MDL-35469 fix Gecko based browser checks
[moodle.git] / lib / tests / moodlelib_test.php
CommitLineData
a3d5830a
PS
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Unit tests for (some of) ../moodlelib.php.
19 *
20 * @package core
21 * @category phpunit
22 * @copyright &copy; 2006 The Open University
23 * @author T.J.Hunt@open.ac.uk
24 * @author nicolas@moodle.com
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
29global $CFG;
30require_once($CFG->libdir . '/moodlelib.php');
31
32
4b027431 33class moodlelib_testcase extends advanced_testcase {
a3d5830a
PS
34
35 public static $includecoverage = array('lib/moodlelib.php');
36
37 var $user_agents = array(
38 'MSIE' => array(
39 '5.0' => array('Windows 98' => 'Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)'),
40 '5.5' => array('Windows 2000' => 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)'),
41 '6.0' => array('Windows XP SP2' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'),
42 '7.0' => array('Windows XP SP2' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; YPC 3.0.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)'),
43 '8.0' => array('Windows Vista' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)'),
44 '9.0' => array('Windows 7' => 'Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))'),
45
46 ),
47 'Firefox' => array(
48 '1.0.6' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6'),
49 '1.5' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; nl; rv:1.8) Gecko/20051107 Firefox/1.5'),
50 '1.5.0.1' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1'),
51 '2.0' => array('Windows XP' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1',
52 'Ubuntu Linux AMD64' => 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1) Gecko/20060601 Firefox/2.0 (Ubuntu-edgy)'),
53 '3.0.6' => array('SUSE' => 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.6) Gecko/2009012700 SUSE/3.0.6-1.4 Firefox/3.0.6'),
54 ),
55 'Safari' => array(
56 '312' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312'),
57 '412' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412 (KHTML, like Gecko) Safari/412')
58 ),
59 'Safari iOS' => array(
60 '528' => array('iPhone' => 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_1_2 like Mac OS X; cs-cz) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7D11 Safari/528.16'),
61 '533' => array('iPad' => 'Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5'),
62 ),
63 'WebKit Android' => array(
64 '525' => array('G1 Phone' => 'Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2 – G1 Phone'),
65 '530' => array('Nexus' => 'Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17 –Nexus'),
66 ),
67 'Chrome' => array(
68 '8' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.215 Safari/534.10'),
69 ),
70 'Opera' => array(
71 '8.51' => array('Windows XP' => 'Opera/8.51 (Windows NT 5.1; U; en)'),
72 '9.0' => array('Windows XP' => 'Opera/9.0 (Windows NT 5.1; U; en)',
73 'Debian Linux' => 'Opera/9.01 (X11; Linux i686; U; en)')
74 )
75 );
76
77 function test_cleanremoteaddr() {
78 //IPv4
79 $this->assertEquals(cleanremoteaddr('1023.121.234.1'), null);
80 $this->assertEquals(cleanremoteaddr('123.121.234.01 '), '123.121.234.1');
81
82 //IPv6
83 $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:0:0:0'), null);
84 $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:0:abh'), null);
85 $this->assertEquals(cleanremoteaddr('0:0:0:::0:0:1'), null);
86 $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:0:0', true), '::');
87 $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:1:1', true), '::1:1');
88 $this->assertEquals(cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true), 'abcd:ef::');
89 $this->assertEquals(cleanremoteaddr('1:0:0:0:0:0:0:1', true), '1::1');
90 $this->assertEquals(cleanremoteaddr('::10:1', false), '0:0:0:0:0:0:10:1');
91 $this->assertEquals(cleanremoteaddr('01:1::', false), '1:1:0:0:0:0:0:0');
92 $this->assertEquals(cleanremoteaddr('10::10', false), '10:0:0:0:0:0:0:10');
93 $this->assertEquals(cleanremoteaddr('::ffff:192.168.1.1', true), '::ffff:c0a8:11');
94 }
95
96 function test_address_in_subnet() {
97 /// 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
98 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32'));
99 $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32'));
100 $this->assertTrue(address_in_subnet('10.10.10.100', '123.121.23.45/0'));
101 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24'));
102 $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24'));
103 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30'));
104 $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30'));
105 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
106 $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128'));
107 $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0'));
108 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
109 $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120'));
110 $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120'));
111 $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112'));
112 $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112'));
113 $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112'));
114
115 // fixed input
116 $this->assertTrue(address_in_subnet('123.121.23.1 ', ' 123.121.23.0 / 24'));
117 $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126'));
118
119 // incorrect input
120 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2'));
121 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64'));
122 $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24'));
123 $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24'));
124 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0'));
125 $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0'));
126 $this->assertFalse(address_in_subnet('::1', '::aa:0/-5'));
127 $this->assertFalse(address_in_subnet('::1', '::aa:0/130'));
128 $this->assertFalse(address_in_subnet('x:1', '::aa:0/130'));
129 $this->assertFalse(address_in_subnet('::1', '::ax:0/130'));
130
131
132 /// 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)
133 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14'));
134 $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14'));
135 $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14'));
136 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14'));
137 $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14'));
138 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14'));
139 $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14'));
140 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe'));
141 $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe'));
142 $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe'));
143 $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe'));
144 $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe'));
145 $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe'));
146 $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe'));
147
148 // fixed input
149 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 '));
150 $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe '));
151
152 // incorrect input
153 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14'));
154 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256'));
155 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256'));
156
157
158 /// 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
159 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12'));
160 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13'));
161 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.'));
162 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234'));
163 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121'));
164 $this->assertTrue(address_in_subnet('123.121.234.12', '123'));
165 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.'));
166 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234'));
167 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab'));
168 $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc'));
169 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba'));
170 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:'));
171 $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:'));
172
173
174 /// multiple subnets
175 $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30'));
176 $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30'));
177 $this->assertTrue(address_in_subnet('::2', '::1/64, 124., 123.121.234.10-30'));
178 $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30'));
179
180
181 /// other incorrect input
182 $this->assertFalse(address_in_subnet('123.123.123.123', ''));
183 }
184
185 /**
186 * Modifies $_SERVER['HTTP_USER_AGENT'] manually to check if check_browser_version
187 * works as expected.
188 */
189 function test_check_browser_version()
190 {
191 global $CFG;
192
193 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari']['412']['Mac OS X'];
194 $this->assertTrue(check_browser_version('Safari'));
195 $this->assertTrue(check_browser_version('WebKit'));
196 $this->assertTrue(check_browser_version('Safari', '312'));
197 $this->assertFalse(check_browser_version('Safari', '500'));
198 $this->assertFalse(check_browser_version('Chrome'));
199 $this->assertFalse(check_browser_version('Safari iOS'));
200
201 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari iOS']['528']['iPhone'];
202 $this->assertTrue(check_browser_version('Safari iOS'));
203 $this->assertTrue(check_browser_version('WebKit'));
204 $this->assertTrue(check_browser_version('Safari iOS', '527'));
205 $this->assertFalse(check_browser_version('Safari iOS', 590));
206 $this->assertFalse(check_browser_version('Safari', '312'));
207 $this->assertFalse(check_browser_version('Safari', '500'));
208 $this->assertFalse(check_browser_version('Chrome'));
209
210 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['WebKit Android']['530']['Nexus'];
211 $this->assertTrue(check_browser_version('WebKit'));
212 $this->assertTrue(check_browser_version('WebKit Android', '527'));
213 $this->assertFalse(check_browser_version('WebKit Android', 590));
214 $this->assertFalse(check_browser_version('Safari'));
215 $this->assertFalse(check_browser_version('Chrome'));
216
217 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X'];
218 $this->assertTrue(check_browser_version('Chrome'));
219 $this->assertTrue(check_browser_version('WebKit'));
220 $this->assertTrue(check_browser_version('Chrome', 8));
221 $this->assertFalse(check_browser_version('Chrome', 10));
222 $this->assertFalse(check_browser_version('Safari', '1'));
223
224 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Opera']['9.0']['Windows XP'];
225 $this->assertTrue(check_browser_version('Opera'));
226 $this->assertTrue(check_browser_version('Opera', '8.0'));
227 $this->assertFalse(check_browser_version('Opera', '10.0'));
228
229 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['6.0']['Windows XP SP2'];
230 $this->assertTrue(check_browser_version('MSIE'));
231 $this->assertTrue(check_browser_version('MSIE', '5.0'));
232 $this->assertFalse(check_browser_version('MSIE', '7.0'));
233
234 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['5.0']['Windows 98'];
235 $this->assertFalse(check_browser_version('MSIE'));
236 $this->assertTrue(check_browser_version('MSIE', 0));
237 $this->assertTrue(check_browser_version('MSIE', '5.0'));
238 $this->assertFalse(check_browser_version('MSIE', '7.0'));
239
240 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['9.0']['Windows 7'];
241 $this->assertTrue(check_browser_version('MSIE'));
242 $this->assertTrue(check_browser_version('MSIE', 0));
243 $this->assertTrue(check_browser_version('MSIE', '5.0'));
244 $this->assertTrue(check_browser_version('MSIE', '9.0'));
245 $this->assertFalse(check_browser_version('MSIE', '10'));
246
247 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP'];
248 $this->assertTrue(check_browser_version('Firefox'));
249 $this->assertTrue(check_browser_version('Firefox', '1.5'));
250 $this->assertFalse(check_browser_version('Firefox', '3.0'));
251 }
252
253 function test_get_browser_version_classes() {
254 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari']['412']['Mac OS X'];
255 $this->assertEquals(array('safari'), get_browser_version_classes());
256
257 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X'];
258 $this->assertEquals(array('safari'), get_browser_version_classes());
259
260 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari iOS']['528']['iPhone'];
261 $this->assertEquals(array('safari', 'ios'), get_browser_version_classes());
262
263 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['WebKit Android']['530']['Nexus'];
264 $this->assertEquals(array('safari', 'android'), get_browser_version_classes());
265
266 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X'];
267 $this->assertEquals(array('safari'), get_browser_version_classes());
268
269 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Opera']['9.0']['Windows XP'];
270 $this->assertEquals(array('opera'), get_browser_version_classes());
271
272 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['6.0']['Windows XP SP2'];
273 $this->assertEquals(array('ie', 'ie6'), get_browser_version_classes());
274
275 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['7.0']['Windows XP SP2'];
276 $this->assertEquals(array('ie', 'ie7'), get_browser_version_classes());
277
278 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['8.0']['Windows Vista'];
279 $this->assertEquals(array('ie', 'ie8'), get_browser_version_classes());
280
281 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP'];
282 $this->assertEquals(array('gecko', 'gecko18'), get_browser_version_classes());
283
284 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['3.0.6']['SUSE'];
285 $this->assertEquals(array('gecko', 'gecko19'), get_browser_version_classes());
286 }
287
288 function test_get_device_type() {
289 // IE8 (common pattern ~1.5% of IE7/8 users have embedded IE6 agent))
290 $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; BT Openworld BB; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; Hotbar 10.2.197.0; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727)';
291 $this->assertEquals('default', get_device_type());
292 // Genuine IE6
293 $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 6.0; AOL 9.0; Windows NT 5.1; SV1; FunWebProducts; .NET CLR 1.0.3705; Media Center PC 2.8)';
294 $this->assertEquals('legacy', get_device_type());
295 }
296
297 function test_fix_utf8() {
298 // make sure valid data including other types is not changed
299 $this->assertSame(null, fix_utf8(null));
300 $this->assertSame(1, fix_utf8(1));
301 $this->assertSame(1.1, fix_utf8(1.1));
302 $this->assertSame(true, fix_utf8(true));
303 $this->assertSame('', fix_utf8(''));
0aff15c2 304 $this->assertSame('abc', fix_utf8('abc'));
a3d5830a
PS
305 $array = array('do', 're', 'mi');
306 $this->assertSame($array, fix_utf8($array));
307 $object = new stdClass();
308 $object->a = 'aa';
309 $object->b = 'bb';
310 $this->assertEquals($object, fix_utf8($object));
311
312 // valid utf8 string
313 $this->assertSame("žlutý koníček přeskočil potůček \n\t\r\0", fix_utf8("žlutý koníček přeskočil potůček \n\t\r\0"));
314
315 // invalid utf8 string
0aff15c2 316 $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
a3d5830a
PS
317 }
318
319 function test_optional_param() {
320 global $CFG;
321
322 $_POST['username'] = 'post_user';
323 $_GET['username'] = 'get_user';
324 $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), $_POST['username']);
325
326 unset($_POST['username']);
327 $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), $_GET['username']);
328
329 unset($_GET['username']);
330 $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), 'default_user');
331
332 // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
333 $_POST['username'] = 'post_user';
334 try {
335 optional_param('username', 'default_user', null);
336 $this->fail('coding_exception expected');
337 } catch (coding_exception $ex) {
338 $this->assertTrue(true);
339 }
340 try {
341 @optional_param('username', 'default_user');
342 $this->fail('coding_exception expected');
343 } catch (coding_exception $ex) {
344 $this->assertTrue(true);
345 }
346 try {
347 @optional_param('username');
348 $this->fail('coding_exception expected');
349 } catch (coding_exception $ex) {
350 $this->assertTrue(true);
351 }
352 try {
353 optional_param('', 'default_user', PARAM_RAW);
354 $this->fail('coding_exception expected');
355 } catch (coding_exception $ex) {
356 $this->assertTrue(true);
357 }
358
359 // make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3
c8bc6c15 360 $_POST['username'] = array('a'=>'a');
a3d5830a 361 $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), $_POST['username']);
c8bc6c15 362 $this->assertDebuggingCalled();
a3d5830a
PS
363 }
364
365 function test_optional_param_array() {
366 global $CFG;
367
368 $_POST['username'] = array('a'=>'post_user');
369 $_GET['username'] = array('a'=>'get_user');
370 $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), $_POST['username']);
371
372 unset($_POST['username']);
373 $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), $_GET['username']);
374
375 unset($_GET['username']);
376 $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), array('a'=>'default_user'));
377
378 // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
379 $_POST['username'] = array('a'=>'post_user');
380 try {
381 optional_param_array('username', array('a'=>'default_user'), null);
382 $this->fail('coding_exception expected');
383 } catch (coding_exception $ex) {
384 $this->assertTrue(true);
385 }
386 try {
387 @optional_param_array('username', array('a'=>'default_user'));
388 $this->fail('coding_exception expected');
389 } catch (coding_exception $ex) {
390 $this->assertTrue(true);
391 }
392 try {
393 @optional_param_array('username');
394 $this->fail('coding_exception expected');
395 } catch (coding_exception $ex) {
396 $this->assertTrue(true);
397 }
398 try {
399 optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
400 $this->fail('coding_exception expected');
401 } catch (coding_exception $ex) {
402 $this->assertTrue(true);
403 }
404
405 // do not allow nested arrays
406 try {
407 $_POST['username'] = array('a'=>array('b'=>'post_user'));
408 optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
409 $this->fail('coding_exception expected');
410 } catch (coding_exception $ex) {
411 $this->assertTrue(true);
412 }
413
414 // do not allow non-arrays
a3d5830a
PS
415 $_POST['username'] = 'post_user';
416 $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), array('a'=>'default_user'));
c8bc6c15 417 $this->assertDebuggingCalled();
a3d5830a
PS
418
419 // make sure array keys are sanitised
a3d5830a
PS
420 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
421 $this->assertSame(optional_param_array('username', array(), PARAM_RAW), array('a1_-'=>'post_user'));
c8bc6c15 422 $this->assertDebuggingCalled();
a3d5830a
PS
423 }
424
425 function test_required_param() {
426 global $CFG;
427
428 $_POST['username'] = 'post_user';
429 $_GET['username'] = 'get_user';
430 $this->assertSame(required_param('username', PARAM_RAW), 'post_user');
431
432 unset($_POST['username']);
433 $this->assertSame(required_param('username', PARAM_RAW), 'get_user');
434
435 unset($_GET['username']);
436 try {
437 $this->assertSame(required_param('username', PARAM_RAW), 'default_user');
438 $this->fail('moodle_exception expected');
439 } catch (moodle_exception $ex) {
440 $this->assertTrue(true);
441 }
442
443 // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
444 $_POST['username'] = 'post_user';
445 try {
446 @required_param('username');
447 $this->fail('coding_exception expected');
448 } catch (coding_exception $ex) {
449 $this->assertTrue(true);
450 }
451 try {
452 required_param('username', '');
453 $this->fail('coding_exception expected');
454 } catch (coding_exception $ex) {
455 $this->assertTrue(true);
456 }
457 try {
458 required_param('', PARAM_RAW);
459 $this->fail('coding_exception expected');
460 } catch (coding_exception $ex) {
461 $this->assertTrue(true);
462 }
463
464 // make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3
c8bc6c15 465 $_POST['username'] = array('a'=>'a');
a3d5830a 466 $this->assertSame(required_param('username', PARAM_RAW), $_POST['username']);
c8bc6c15 467 $this->assertDebuggingCalled();
a3d5830a
PS
468 }
469
470 function test_required_param_array() {
471 global $CFG;
472
473 $_POST['username'] = array('a'=>'post_user');
474 $_GET['username'] = array('a'=>'get_user');
475 $this->assertSame(required_param_array('username', PARAM_RAW), $_POST['username']);
476
477 unset($_POST['username']);
478 $this->assertSame(required_param_array('username', PARAM_RAW), $_GET['username']);
479
480 // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
481 $_POST['username'] = array('a'=>'post_user');
482 try {
483 required_param_array('username', null);
484 $this->fail('coding_exception expected');
485 } catch (coding_exception $ex) {
486 $this->assertTrue(true);
487 }
488 try {
489 @required_param_array('username');
490 $this->fail('coding_exception expected');
491 } catch (coding_exception $ex) {
492 $this->assertTrue(true);
493 }
494 try {
495 required_param_array('', PARAM_RAW);
496 $this->fail('coding_exception expected');
497 } catch (coding_exception $ex) {
498 $this->assertTrue(true);
499 }
500
501 // do not allow nested arrays
502 try {
503 $_POST['username'] = array('a'=>array('b'=>'post_user'));
504 required_param_array('username', PARAM_RAW);
505 $this->fail('coding_exception expected');
506 } catch (coding_exception $ex) {
507 $this->assertTrue(true);
508 }
509
510 // do not allow non-arrays
511 try {
512 $_POST['username'] = 'post_user';
513 required_param_array('username', PARAM_RAW);
514 $this->fail('moodle_exception expected');
515 } catch (moodle_exception $ex) {
516 $this->assertTrue(true);
517 }
518
a3d5830a 519 // make sure array keys are sanitised
a3d5830a
PS
520 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
521 $this->assertSame(required_param_array('username', PARAM_RAW), array('a1_-'=>'post_user'));
c8bc6c15 522 $this->assertDebuggingCalled();
a3d5830a
PS
523 }
524
525 function test_clean_param() {
526 // forbid objects and arrays
527 try {
528 clean_param(array('x', 'y'), PARAM_RAW);
529 $this->fail('coding_exception expected');
530 } catch (coding_exception $ex) {
531 $this->assertTrue(true);
532 }
533 try {
534 $param = new stdClass();
535 $param->id = 1;
536 clean_param($param, PARAM_RAW);
537 $this->fail('coding_exception expected');
538 } catch (coding_exception $ex) {
539 $this->assertTrue(true);
540 }
541
542 // require correct type
543 try {
544 clean_param('x', 'xxxxxx');
545 $this->fail('moodle_exception expected');
546 } catch (moodle_exception $ex) {
547 $this->assertTrue(true);
548 }
549 try {
550 @clean_param('x');
551 $this->fail('moodle_exception expected');
552 } catch (moodle_exception $ex) {
553 $this->assertTrue(true);
554 }
555
556 }
557
558 function test_clean_param_array() {
559 $this->assertSame(clean_param_array(null, PARAM_RAW), array());
560 $this->assertSame(clean_param_array(array('a', 'b'), PARAM_RAW), array('a', 'b'));
561 $this->assertSame(clean_param_array(array('a', array('b')), PARAM_RAW, true), array('a', array('b')));
562
563 // require correct type
564 try {
565 clean_param_array(array('x'), 'xxxxxx');
566 $this->fail('moodle_exception expected');
567 } catch (moodle_exception $ex) {
568 $this->assertTrue(true);
569 }
570 try {
571 @clean_param_array(array('x'));
572 $this->fail('moodle_exception expected');
573 } catch (moodle_exception $ex) {
574 $this->assertTrue(true);
575 }
576
577 try {
578 clean_param_array(array('x', array('y')), PARAM_RAW);
579 $this->fail('coding_exception expected');
580 } catch (coding_exception $ex) {
581 $this->assertTrue(true);
582 }
583
584 // test recursive
585 }
586
587 function test_clean_param_raw() {
588 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW),
589 '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)');
590 }
591
592 function test_clean_param_trim() {
593 $this->assertEquals(clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED), 'Frog toad');
594 }
595
596 function test_clean_param_clean() {
597 // PARAM_CLEAN is an ugly hack, do not use in new code (skodak)
598 // instead use more specific type, or submit sothing that can be verified properly
599 $this->assertEquals(clean_param('xx<script>', PARAM_CLEAN), 'xx');
600 }
601
602 function test_clean_param_alpha() {
603 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA),
604 'DSFMOSDJ');
605 }
606
607 function test_clean_param_alphanum() {
608 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM),
609 '978942897DSFMOSDJ');
610 }
611
612 function test_clean_param_alphaext() {
613 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT),
614 'DSFMOSDJ');
615 }
616
617 function test_clean_param_sequence() {
618 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE),
619 ',9789,42897');
620 }
621
622 function test_clean_param_component() {
623 // please note the cleaning of component names is very strict, no guessing here
624 $this->assertSame(clean_param('mod_forum', PARAM_COMPONENT), 'mod_forum');
625 $this->assertSame(clean_param('block_online_users', PARAM_COMPONENT), 'block_online_users');
626 $this->assertSame(clean_param('block_blond_online_users', PARAM_COMPONENT), 'block_blond_online_users');
627 $this->assertSame(clean_param('mod_something2', PARAM_COMPONENT), 'mod_something2');
628 $this->assertSame(clean_param('forum', PARAM_COMPONENT), 'forum');
629 $this->assertSame(clean_param('user', PARAM_COMPONENT), 'user');
630 $this->assertSame(clean_param('rating', PARAM_COMPONENT), 'rating');
631 $this->assertSame(clean_param('mod_2something', PARAM_COMPONENT), '');
632 $this->assertSame(clean_param('2mod_something', PARAM_COMPONENT), '');
633 $this->assertSame(clean_param('mod_something_xx', PARAM_COMPONENT), '');
634 $this->assertSame(clean_param('auth_something__xx', PARAM_COMPONENT), '');
635 $this->assertSame(clean_param('mod_Something', PARAM_COMPONENT), '');
636 $this->assertSame(clean_param('mod_somethíng', PARAM_COMPONENT), '');
637 $this->assertSame(clean_param('auth_xx-yy', PARAM_COMPONENT), '');
638 $this->assertSame(clean_param('_auth_xx', PARAM_COMPONENT), '');
639 $this->assertSame(clean_param('a2uth_xx', PARAM_COMPONENT), '');
640 $this->assertSame(clean_param('auth_xx_', PARAM_COMPONENT), '');
641 $this->assertSame(clean_param('auth_xx.old', PARAM_COMPONENT), '');
642 $this->assertSame(clean_param('_user', PARAM_COMPONENT), '');
643 $this->assertSame(clean_param('2rating', PARAM_COMPONENT), '');
644 $this->assertSame(clean_param('user_', PARAM_COMPONENT), '');
645 }
646
647 function test_clean_param_plugin() {
648 // please note the cleaning of plugin names is very strict, no guessing here
649 $this->assertSame(clean_param('forum', PARAM_PLUGIN), 'forum');
650 $this->assertSame(clean_param('forum2', PARAM_PLUGIN), 'forum2');
651 $this->assertSame(clean_param('online_users', PARAM_PLUGIN), 'online_users');
652 $this->assertSame(clean_param('blond_online_users', PARAM_PLUGIN), 'blond_online_users');
653 $this->assertSame(clean_param('online__users', PARAM_PLUGIN), '');
654 $this->assertSame(clean_param('forum ', PARAM_PLUGIN), '');
655 $this->assertSame(clean_param('forum.old', PARAM_PLUGIN), '');
656 $this->assertSame(clean_param('xx-yy', PARAM_PLUGIN), '');
657 $this->assertSame(clean_param('2xx', PARAM_PLUGIN), '');
658 $this->assertSame(clean_param('Xx', PARAM_PLUGIN), '');
659 $this->assertSame(clean_param('_xx', PARAM_PLUGIN), '');
660 $this->assertSame(clean_param('xx_', PARAM_PLUGIN), '');
661 }
662
663 function test_clean_param_area() {
664 // please note the cleaning of area names is very strict, no guessing here
665 $this->assertSame(clean_param('something', PARAM_AREA), 'something');
666 $this->assertSame(clean_param('something2', PARAM_AREA), 'something2');
667 $this->assertSame(clean_param('some_thing', PARAM_AREA), 'some_thing');
668 $this->assertSame(clean_param('some_thing_xx', PARAM_AREA), 'some_thing_xx');
669 $this->assertSame(clean_param('_something', PARAM_AREA), '');
670 $this->assertSame(clean_param('something_', PARAM_AREA), '');
671 $this->assertSame(clean_param('2something', PARAM_AREA), '');
672 $this->assertSame(clean_param('Something', PARAM_AREA), '');
673 $this->assertSame(clean_param('some-thing', PARAM_AREA), '');
674 $this->assertSame(clean_param('somethííng', PARAM_AREA), '');
675 $this->assertSame(clean_param('something.x', PARAM_AREA), '');
676 }
677
678 function test_clean_param_text() {
679 $this->assertEquals(PARAM_TEXT, PARAM_MULTILANG);
680 //standard
681 $this->assertEquals(clean_param('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', PARAM_TEXT), 'xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>');
682 $this->assertEquals(clean_param('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', PARAM_TEXT), '<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>');
683 $this->assertEquals(clean_param('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', PARAM_TEXT), 'xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>');
684 //malformed
685 $this->assertEquals(clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT), '<span lang="en" class="multilang">aa</span>');
686 $this->assertEquals(clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT), 'aa');
687 $this->assertEquals(clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT), 'aa');
688 $this->assertEquals(clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT), 'aa');
689 $this->assertEquals(clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT), 'aa');
690 $this->assertEquals(clean_param('a<em>b</em>c', PARAM_TEXT), 'abc');
691 $this->assertEquals(clean_param('a><xx >c>', PARAM_TEXT), 'a>c>'); // standard strip_tags() behaviour
692 $this->assertEquals(clean_param('a<b', PARAM_TEXT), 'a');
693 $this->assertEquals(clean_param('a>b', PARAM_TEXT), 'a>b');
694 $this->assertEquals(clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT), '<lang lang="en">a>a</lang>'); // standard strip_tags() behaviour
695 $this->assertEquals(clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT), 'a');
696 $this->assertEquals(clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT), '<lang lang="en">aa</lang>');
697 }
698
699 function test_clean_param_url() {
700 // Test PARAM_URL and PARAM_LOCALURL a bit
701 $this->assertEquals(clean_param('http://google.com/', PARAM_URL), 'http://google.com/');
702 $this->assertEquals(clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_URL), 'http://some.very.long.and.silly.domain/with/a/path/');
703 $this->assertEquals(clean_param('http://localhost/', PARAM_URL), 'http://localhost/');
704 $this->assertEquals(clean_param('http://0.255.1.1/numericip.php', PARAM_URL), 'http://0.255.1.1/numericip.php');
705 $this->assertEquals(clean_param('/just/a/path', PARAM_URL), '/just/a/path');
706 $this->assertEquals(clean_param('funny:thing', PARAM_URL), '');
707 }
708
709 function test_clean_param_localurl() {
710 global $CFG;
711 $this->assertEquals(clean_param('http://google.com/', PARAM_LOCALURL), '');
712 $this->assertEquals(clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL), '');
713 $this->assertEquals(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
714 $this->assertEquals(clean_param('/just/a/path', PARAM_LOCALURL), '/just/a/path');
715 $this->assertEquals(clean_param('funny:thing', PARAM_LOCALURL), '');
716 $this->assertEquals(clean_param('course/view.php?id=3', PARAM_LOCALURL), 'course/view.php?id=3');
717 }
718
719 function test_clean_param_file() {
720 $this->assertEquals(clean_param('correctfile.txt', PARAM_FILE), 'correctfile.txt');
721 $this->assertEquals(clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE), 'badfile.txt');
722 $this->assertEquals(clean_param('../parentdirfile.txt', PARAM_FILE), 'parentdirfile.txt');
723 //The following behaviours have been maintained although they seem a little odd
724 $this->assertEquals(clean_param('funny:thing', PARAM_FILE), 'funnything');
725 $this->assertEquals(clean_param('./currentdirfile.txt', PARAM_FILE), '.currentdirfile.txt');
726 $this->assertEquals(clean_param('c:\temp\windowsfile.txt', PARAM_FILE), 'ctempwindowsfile.txt');
727 $this->assertEquals(clean_param('/home/user/linuxfile.txt', PARAM_FILE), 'homeuserlinuxfile.txt');
728 $this->assertEquals(clean_param('~/myfile.txt', PARAM_FILE), '~myfile.txt');
729 }
730
731 function test_clean_param_username() {
732 global $CFG;
733 $currentstatus = $CFG->extendedusernamechars;
734
735 // Run tests with extended character == FALSE;
736 $CFG->extendedusernamechars = FALSE;
737 $this->assertEquals(clean_param('johndoe123', PARAM_USERNAME), 'johndoe123' );
738 $this->assertEquals(clean_param('john.doe', PARAM_USERNAME), 'john.doe');
739 $this->assertEquals(clean_param('john-doe', PARAM_USERNAME), 'john-doe');
740 $this->assertEquals(clean_param('john- doe', PARAM_USERNAME), 'john-doe');
741 $this->assertEquals(clean_param('john_doe', PARAM_USERNAME), 'john_doe');
742 $this->assertEquals(clean_param('john@doe', PARAM_USERNAME), 'john@doe');
743 $this->assertEquals(clean_param('john~doe', PARAM_USERNAME), 'johndoe');
744 $this->assertEquals(clean_param('john´doe', PARAM_USERNAME), 'johndoe');
745 $this->assertEquals(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
746 $this->assertEquals(clean_param('JOHNdóé ', PARAM_USERNAME), 'johnd');
747 $this->assertEquals(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá\9e?\9eý??\9adoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
748
749
750 // Test success condition, if extendedusernamechars == ENABLE;
751 $CFG->extendedusernamechars = TRUE;
752 $this->assertEquals(clean_param('john_doe', PARAM_USERNAME), 'john_doe');
753 $this->assertEquals(clean_param('john@doe', PARAM_USERNAME), 'john@doe');
754 $this->assertEquals(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john#$%&()+_^');
755 $this->assertEquals(clean_param('john~doe', PARAM_USERNAME), 'john~doe');
756 $this->assertEquals(clean_param('joHN´doe', PARAM_USERNAME), 'john´doe');
757 $this->assertEquals(clean_param('johnDOE', PARAM_USERNAME), 'johndoe');
758 $this->assertEquals(clean_param('johndóé ', PARAM_USERNAME), 'johndóé');
759
760 $CFG->extendedusernamechars = $currentstatus;
761 }
762
763 function test_clean_param_stringid() {
764 // Test string identifiers validation
765 // valid strings:
766 $this->assertEquals(clean_param('validstring', PARAM_STRINGID), 'validstring');
767 $this->assertEquals(clean_param('mod/foobar:valid_capability', PARAM_STRINGID), 'mod/foobar:valid_capability');
768 $this->assertEquals(clean_param('CZ', PARAM_STRINGID), 'CZ');
769 $this->assertEquals(clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID), 'application/vnd.ms-powerpoint');
770 $this->assertEquals(clean_param('grade2', PARAM_STRINGID), 'grade2');
771 // invalid strings:
772 $this->assertEquals(clean_param('trailing ', PARAM_STRINGID), '');
773 $this->assertEquals(clean_param('space bar', PARAM_STRINGID), '');
774 $this->assertEquals(clean_param('0numeric', PARAM_STRINGID), '');
775 $this->assertEquals(clean_param('*', PARAM_STRINGID), '');
776 $this->assertEquals(clean_param(' ', PARAM_STRINGID), '');
777 }
778
779 function test_clean_param_timezone() {
780 // Test timezone validation
781 $testvalues = array (
782 'America/Jamaica' => 'America/Jamaica',
783 'America/Argentina/Cordoba' => 'America/Argentina/Cordoba',
784 'America/Port-au-Prince' => 'America/Port-au-Prince',
785 'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
786 'PST8PDT' => 'PST8PDT',
787 'Wrong.Value' => '',
788 'Wrong/.Value' => '',
789 'Wrong(Value)' => '',
790 '0' => '0',
791 '0.0' => '0.0',
792 '0.5' => '0.5',
793 '-12.5' => '-12.5',
794 '+12.5' => '+12.5',
795 '13.5' => '',
796 '-13.5' => '',
797 '0.2' => '');
798
799 foreach ($testvalues as $testvalue => $expectedvalue) {
800 $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
801 $this->assertEquals($actualvalue, $expectedvalue);
802 }
803 }
804
805 function test_validate_param() {
806 try {
807 $param = validate_param('11a', PARAM_INT);
808 $this->fail('invalid_parameter_exception expected');
809 } catch (invalid_parameter_exception $ex) {
810 $this->assertTrue(true);
811 }
812 try {
813 $param = validate_param('11', PARAM_INT);
814 $this->assertEquals($param, 11);
815 } catch (invalid_parameter_exception $ex) {
816 $this->fail('invalid_parameter_exception not expected');
817 }
818 try {
819 $param = validate_param(null, PARAM_INT, false);
820 $this->fail('invalid_parameter_exception expected');
821 } catch (invalid_parameter_exception $ex) {
822 $this->assertTrue(true);
823 }
824 try {
825 $param = validate_param(null, PARAM_INT, true);
826 $this->assertTrue($param===null);
827 } catch (invalid_parameter_exception $ex) {
828 $this->fail('invalid_parameter_exception expected');
829 }
830 try {
831 $param = validate_param(array(), PARAM_INT);
832 $this->fail('invalid_parameter_exception expected');
833 } catch (invalid_parameter_exception $ex) {
834 $this->assertTrue(true);
835 }
836 try {
837 $param = validate_param(new stdClass, PARAM_INT);
838 $this->fail('invalid_parameter_exception expected');
839 } catch (invalid_parameter_exception $ex) {
840 $this->assertTrue(true);
841 }
9a97fa5a
PS
842 try {
843 $param = validate_param('1.0', PARAM_FLOAT);
844 $this->assertSame(1.0, $param);
845
846 // Make sure valid floats do not cause exception.
847 validate_param(1.0, PARAM_FLOAT);
848 validate_param(10, PARAM_FLOAT);
849 validate_param('0', PARAM_FLOAT);
850 validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
851 validate_param('011.1', PARAM_FLOAT);
852 validate_param('11', PARAM_FLOAT);
853 validate_param('+.1', PARAM_FLOAT);
854 validate_param('-.1', PARAM_FLOAT);
855 validate_param('1e10', PARAM_FLOAT);
856 validate_param('.1e+10', PARAM_FLOAT);
857 validate_param('1E-1', PARAM_FLOAT);
858 $this->assertTrue(true);
859 } catch (invalid_parameter_exception $ex) {
860 $this->fail('Valid float notation not accepted');
861 }
862 try {
863 $param = validate_param('1,2', PARAM_FLOAT);
864 $this->fail('invalid_parameter_exception expected');
865 } catch (invalid_parameter_exception $ex) {
866 $this->assertTrue(true);
867 }
868 try {
869 $param = validate_param('', PARAM_FLOAT);
870 $this->fail('invalid_parameter_exception expected');
871 } catch (invalid_parameter_exception $ex) {
872 $this->assertTrue(true);
873 }
874 try {
875 $param = validate_param('.', PARAM_FLOAT);
876 $this->fail('invalid_parameter_exception expected');
877 } catch (invalid_parameter_exception $ex) {
878 $this->assertTrue(true);
879 }
880 try {
881 $param = validate_param('e10', PARAM_FLOAT);
882 $this->fail('invalid_parameter_exception expected');
883 } catch (invalid_parameter_exception $ex) {
884 $this->assertTrue(true);
885 }
886 try {
887 $param = validate_param('abc', PARAM_FLOAT);
888 $this->fail('invalid_parameter_exception expected');
889 } catch (invalid_parameter_exception $ex) {
890 $this->assertTrue(true);
891 }
a3d5830a
PS
892 }
893
894 function test_shorten_text() {
895 $text = "short text already no tags";
896 $this->assertEquals($text, shorten_text($text));
897
898 $text = "<p>short <b>text</b> already</p><p>with tags</p>";
899 $this->assertEquals($text, shorten_text($text));
900
901 $text = "long text without any tags blah de blah blah blah what";
902 $this->assertEquals('long text without any tags ...', shorten_text($text));
903
904 $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
905 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
906 $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
907 "tags that ...</blockquote></p></div>", shorten_text($text));
908
909 $text = "some text which shouldn't &nbsp; break there";
910 $this->assertEquals("some text which shouldn't &nbsp; ...",
911 shorten_text($text, 31));
912 $this->assertEquals("some text which shouldn't ...",
913 shorten_text($text, 30));
914
915 // This case caused a bug up to 1.9.5
916 $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
917 $this->assertEquals("<h3>standard 'break-out' sub groups in ...</h3>",
918 shorten_text($text, 43));
919
920 $text = "<h1>123456789</h1>";//a string with no convenient breaks
921 $this->assertEquals("<h1>12345...</h1>",
922 shorten_text($text, 8));
923
924 // ==== this must work with UTF-8 too! ======
925
926 // text without tags
927 $text = "Žluťoučký koníček přeskočil";
928 $this->assertEquals($text, shorten_text($text)); // 30 chars by default
929 $this->assertEquals("Žluťoučký koníče...", shorten_text($text, 19, true));
930 $this->assertEquals("Žluťoučký ...", shorten_text($text, 19, false));
931 // And try it with 2-less (that are, in bytes, the middle of a sequence)
932 $this->assertEquals("Žluťoučký koní...", shorten_text($text, 17, true));
933 $this->assertEquals("Žluťoučký ...", shorten_text($text, 17, false));
934
935 $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
936 $this->assertEquals($text, shorten_text($text, 60));
937 $this->assertEquals("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
938 $this->assertEquals("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
939 $this->assertEquals("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
940 // And try it with 2-less (that are, in bytes, the middle of a sequence)
941 $this->assertEquals("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
942 $this->assertEquals("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
943 // And try over one tag (start/end), it does proper text len
944 $this->assertEquals("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
945 $this->assertEquals("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
946 // And in the middle of one tag
947 $this->assertEquals("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
948
949 // Japanese
950 $text = '言語設定言語設定abcdefghijkl';
951 $this->assertEquals($text, shorten_text($text)); // 30 chars by default
952 $this->assertEquals("言語設定言語...", shorten_text($text, 9, true));
953 $this->assertEquals("言語設定言語...", shorten_text($text, 9, false));
954 $this->assertEquals("言語設定言語設定ab...", shorten_text($text, 13, true));
955 $this->assertEquals("言語設定言語設定...", shorten_text($text, 13, false));
956
957 // Chinese
958 $text = '简体中文简体中文abcdefghijkl';
959 $this->assertEquals($text, shorten_text($text)); // 30 chars by default
960 $this->assertEquals("简体中文简体...", shorten_text($text, 9, true));
961 $this->assertEquals("简体中文简体...", shorten_text($text, 9, false));
962 $this->assertEquals("简体中文简体中文ab...", shorten_text($text, 13, true));
963 $this->assertEquals("简体中文简体中文...", shorten_text($text, 13, false));
964
965 }
966
967 function test_usergetdate() {
968 global $USER, $CFG, $DB;
969
970 //Check if forcetimezone is set then save it and set it to use user timezone
971 $cfgforcetimezone = null;
972 if (isset($CFG->forcetimezone)) {
973 $cfgforcetimezone = $CFG->forcetimezone;
974 $CFG->forcetimezone = 99; //get user default timezone.
975 }
976
977 $olduser = $USER;
978 $USER = $DB->get_record('user', array('id'=>2)); //admin
979
980 $userstimezone = $USER->timezone;
981 $USER->timezone = 2;//set the timezone to a known state
982
983 // The string version of date comes from server locale setting and does
984 // not respect user language, so it is necessary to reset that.
985 $oldlocale = setlocale(LC_TIME, '0');
986 setlocale(LC_TIME, 'en_AU.UTF-8');
987
988 $ts = 1261540267; //the time this function was created
989
990 $arr = usergetdate($ts,1);//specify the timezone as an argument
991 $arr = array_values($arr);
992
993 list($seconds,$minutes,$hours,$mday,$wday,$mon,$year,$yday,$weekday,$month) = $arr;
03764014
EL
994 $this->assertSame($seconds, 7);
995 $this->assertSame($minutes, 51);
996 $this->assertSame($hours, 4);
997 $this->assertSame($mday, 23);
998 $this->assertSame($wday, 3);
999 $this->assertSame($mon, 12);
1000 $this->assertSame($year, 2009);
1001 $this->assertSame($yday, 356);
1002 $this->assertSame($weekday, 'Wednesday');
1003 $this->assertSame($month, 'December');
a3d5830a
PS
1004 $arr = usergetdate($ts);//gets the timezone from the $USER object
1005 $arr = array_values($arr);
1006
1007 list($seconds,$minutes,$hours,$mday,$wday,$mon,$year,$yday,$weekday,$month) = $arr;
03764014
EL
1008 $this->assertSame($seconds, 7);
1009 $this->assertSame($minutes, 51);
1010 $this->assertSame($hours, 5);
1011 $this->assertSame($mday, 23);
1012 $this->assertSame($wday, 3);
1013 $this->assertSame($mon, 12);
1014 $this->assertSame($year, 2009);
1015 $this->assertSame($yday, 356);
1016 $this->assertSame($weekday, 'Wednesday');
1017 $this->assertSame($month, 'December');
a3d5830a
PS
1018 //set the timezone back to what it was
1019 $USER->timezone = $userstimezone;
1020
1021 //restore forcetimezone if changed.
1022 if (!is_null($cfgforcetimezone)) {
1023 $CFG->forcetimezone = $cfgforcetimezone;
1024 }
1025
1026 setlocale(LC_TIME, $oldlocale);
1027
1028 $USER = $olduser;
1029 }
1030
1031 public function test_normalize_component() {
1032
1033 // moodle core
1034 $this->assertEquals(normalize_component('moodle'), array('core', null));
1035 $this->assertEquals(normalize_component('core'), array('core', null));
1036
1037 // moodle core subsystems
1038 $this->assertEquals(normalize_component('admin'), array('core', 'admin'));
1039 $this->assertEquals(normalize_component('core_admin'), array('core', 'admin'));
1040
1041 // activity modules and their subplugins
1042 $this->assertEquals(normalize_component('workshop'), array('mod', 'workshop'));
1043 $this->assertEquals(normalize_component('mod_workshop'), array('mod', 'workshop'));
1044 $this->assertEquals(normalize_component('workshopform_accumulative'), array('workshopform', 'accumulative'));
1045 $this->assertEquals(normalize_component('quiz'), array('mod', 'quiz'));
1046 $this->assertEquals(normalize_component('quiz_grading'), array('quiz', 'grading'));
1047 $this->assertEquals(normalize_component('data'), array('mod', 'data'));
1048 $this->assertEquals(normalize_component('datafield_checkbox'), array('datafield', 'checkbox'));
1049
1050 // other plugin types
1051 $this->assertEquals(normalize_component('auth_mnet'), array('auth', 'mnet'));
1052 $this->assertEquals(normalize_component('enrol_self'), array('enrol', 'self'));
1053 $this->assertEquals(normalize_component('block_html'), array('block', 'html'));
1054 $this->assertEquals(normalize_component('block_mnet_hosts'), array('block', 'mnet_hosts'));
1055 $this->assertEquals(normalize_component('local_amos'), array('local', 'amos'));
1056
1057 // unknown components are supposed to be activity modules
1058 $this->assertEquals(normalize_component('whothefuckwouldcomewithsuchastupidnameofcomponent'),
1059 array('mod', 'whothefuckwouldcomewithsuchastupidnameofcomponent'));
1060 $this->assertEquals(normalize_component('whothefuck_wouldcomewithsuchastupidnameofcomponent'),
1061 array('mod', 'whothefuck_wouldcomewithsuchastupidnameofcomponent'));
1062 $this->assertEquals(normalize_component('whothefuck_would_come_withsuchastupidnameofcomponent'),
1063 array('mod', 'whothefuck_would_come_withsuchastupidnameofcomponent'));
1064 }
1065
1066 protected function get_fake_preference_test_userid() {
1067 global $DB;
1068
1069 // we need some nonexistent user id
1070 $id = 2147483647 - 666;
1071 if ($DB->get_records('user', array('id'=>$id))) {
1072 //weird!
1073 return false;
1074 }
1075 return $id;
1076 }
1077
1078 public function test_mark_user_preferences_changed() {
1079 $this->resetAfterTest(true);
1080 if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1081 $this->fail('Can not find unused user id for the preferences test');
1082 return;
1083 }
1084
1085 set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
1086 mark_user_preferences_changed($otheruserid);
1087
1088 $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1089 set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
1090 }
1091
1092 public function test_check_user_preferences_loaded() {
1093 global $DB;
1094 $this->resetAfterTest(true);
1095
1096 if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1097 $this->fail('Can not find unused user id for the preferences test');
1098 return;
1099 }
1100
1101 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1102 set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
1103
1104 $user = new stdClass();
1105 $user->id = $otheruserid;
1106
1107 // load
1108 check_user_preferences_loaded($user);
1109 $this->assertTrue(isset($user->preference));
1110 $this->assertTrue(is_array($user->preference));
1111 $this->assertTrue(isset($user->preference['_lastloaded']));
1112 $this->assertEquals(count($user->preference), 1);
1113
1114 // add preference via direct call
1115 $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1116
1117 // no cache reload yet
1118 check_user_preferences_loaded($user);
1119 $this->assertEquals(count($user->preference), 1);
1120
1121 // forced reloading of cache
1122 unset($user->preference);
1123 check_user_preferences_loaded($user);
1124 $this->assertEquals(count($user->preference), 2);
1125 $this->assertEquals($user->preference['xxx'], 'yyy');
1126
1127 // add preference via direct call
1128 $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1129
1130 // test timeouts and modifications from different session
1131 set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1132 $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1133 check_user_preferences_loaded($user);
1134 $this->assertEquals(count($user->preference), 2);
1135 check_user_preferences_loaded($user, 10);
1136 $this->assertEquals(count($user->preference), 3);
1137 $this->assertEquals($user->preference['aaa'], 'bbb');
1138 set_cache_flag('userpreferenceschanged', $user->id, null);
1139 }
1140
1141 public function test_set_user_preference() {
1142 global $DB, $USER;
1143 $this->resetAfterTest(true);
1144
1145 $olduser = $USER;
1146 $USER = $DB->get_record('user', array('id'=>2)); //admin
1147
1148 if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1149 $this->fail('Can not find unused user id for the preferences test');
1150 return;
1151 }
1152
1153 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1154 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1155
1156 $user = new stdClass();
1157 $user->id = $otheruserid;
1158
1159 set_user_preference('aaa', 'bbb', $otheruserid);
1160 $this->assertEquals('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1161 $this->assertEquals('bbb', get_user_preferences('aaa', null, $otheruserid));
1162
1163 set_user_preference('xxx', 'yyy', $user);
1164 $this->assertEquals('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1165 $this->assertEquals('yyy', get_user_preferences('xxx', null, $otheruserid));
1166 $this->assertTrue(is_array($user->preference));
1167 $this->assertEquals($user->preference['aaa'], 'bbb');
1168 $this->assertEquals($user->preference['xxx'], 'yyy');
1169
1170 set_user_preference('xxx', NULL, $user);
1171 $this->assertSame(false, $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1172 $this->assertSame(null, get_user_preferences('xxx', null, $otheruserid));
1173
1174 set_user_preference('ooo', true, $user);
1175 $prefs = get_user_preferences(null, null, $otheruserid);
1176 $this->assertSame($prefs['aaa'], $user->preference['aaa']);
1177 $this->assertSame($prefs['ooo'], $user->preference['ooo']);
1178 $this->assertSame($prefs['ooo'], '1');
1179
1180 set_user_preference('null', 0, $user);
1181 $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1182
1183 $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1184
1185 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1186 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1187
1188 // test $USER default
1189 set_user_preference('_test_user_preferences_pref', 'ok');
1190 $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1191 unset_user_preference('_test_user_preferences_pref');
1192 $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1193
1194 // Test 1333 char values (no need for unicode, there are already tests for that in DB tests)
1195 $longvalue = str_repeat('a', 1333);
1196 set_user_preference('_test_long_user_preference', $longvalue);
1197 $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1198 $this->assertEquals($longvalue,
1199 $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1200
1201 // Test > 1333 char values, coding_exception expected
1202 $longvalue = str_repeat('a', 1334);
1203 try {
1204 set_user_preference('_test_long_user_preference', $longvalue);
1205 $this->assertFail('Exception expected - longer than 1333 chars not allowed as preference value');
1206 } catch (Exception $e) {
1207 $this->assertTrue($e instanceof coding_exception);
1208 }
1209
1210 //test invalid params
1211 try {
1212 set_user_preference('_test_user_preferences_pref', array());
1213 $this->assertFail('Exception expected - array not valid preference value');
1214 } catch (Exception $ex) {
1215 $this->assertTrue(true);
1216 }
1217 try {
1218 set_user_preference('_test_user_preferences_pref', new stdClass);
1219 $this->assertFail('Exception expected - class not valid preference value');
1220 } catch (Exception $ex) {
1221 $this->assertTrue(true);
1222 }
1223 try {
1224 set_user_preference('_test_user_preferences_pref', 1, array('xx'=>1));
1225 $this->assertFail('Exception expected - user instance expected');
1226 } catch (Exception $ex) {
1227 $this->assertTrue(true);
1228 }
1229 try {
1230 set_user_preference('_test_user_preferences_pref', 1, 'abc');
1231 $this->assertFail('Exception expected - user instance expected');
1232 } catch (Exception $ex) {
1233 $this->assertTrue(true);
1234 }
1235 try {
1236 set_user_preference('', 1);
1237 $this->assertFail('Exception expected - invalid name accepted');
1238 } catch (Exception $ex) {
1239 $this->assertTrue(true);
1240 }
1241 try {
1242 set_user_preference('1', 1);
1243 $this->assertFail('Exception expected - invalid name accepted');
1244 } catch (Exception $ex) {
1245 $this->assertTrue(true);
1246 }
1247
1248 $USER = $olduser;
1249 }
1250
1251 public function test_get_extra_user_fields() {
1252 global $CFG, $USER, $DB;
1253 $oldshowuseridentity = $CFG->showuseridentity;
1254
1255 $olduser = $USER;
1256 $USER = $DB->get_record('user', array('id'=>2)); //admin
1257
1258 // It would be really nice if there were a way to 'mock' has_capability
1259 // checks (either to return true or false) but as there is not, this
1260 // test doesn't test the capability check. Presumably, anyone running
1261 // unit tests will have the capability.
1262 $context = context_system::instance();
1263
1264 // No fields
1265 $CFG->showuseridentity = '';
1266 $this->assertEquals(array(), get_extra_user_fields($context));
1267
1268 // One field
1269 $CFG->showuseridentity = 'frog';
1270 $this->assertEquals(array('frog'), get_extra_user_fields($context));
1271
1272 // Two fields
1273 $CFG->showuseridentity = 'frog,zombie';
1274 $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1275
1276 // No fields, except
1277 $CFG->showuseridentity = '';
1278 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1279
1280 // One field
1281 $CFG->showuseridentity = 'frog';
1282 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1283
1284 // Two fields
1285 $CFG->showuseridentity = 'frog,zombie';
1286 $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1287
1288 // As long as this test passes, the value will be set back. This is only
1289 // in-memory anyhow
1290 $CFG->showuseridentity = $oldshowuseridentity;
1291
1292 $USER = $olduser;
1293 }
1294
1295 public function test_get_extra_user_fields_sql() {
1296 global $CFG, $USER, $DB;
1297
1298 $olduser = $USER;
1299 $USER = $DB->get_record('user', array('id'=>2)); //admin
1300
1301 $oldshowuseridentity = $CFG->showuseridentity;
1302 $context = context_system::instance();
1303
1304 // No fields
1305 $CFG->showuseridentity = '';
1306 $this->assertEquals('', get_extra_user_fields_sql($context));
1307
1308 // One field
1309 $CFG->showuseridentity = 'frog';
1310 $this->assertEquals(', frog', get_extra_user_fields_sql($context));
1311
1312 // Two fields with table prefix
1313 $CFG->showuseridentity = 'frog,zombie';
1314 $this->assertEquals(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1315
1316 // Two fields with field prefix
1317 $CFG->showuseridentity = 'frog,zombie';
1318 $this->assertEquals(', frog AS u_frog, zombie AS u_zombie',
1319 get_extra_user_fields_sql($context, '', 'u_'));
1320
1321 // One field excluded
1322 $CFG->showuseridentity = 'frog';
1323 $this->assertEquals('', get_extra_user_fields_sql($context, '', '', array('frog')));
1324
1325 // Two fields, one excluded, table+field prefix
1326 $CFG->showuseridentity = 'frog,zombie';
1327 $this->assertEquals(', u1.zombie AS u_zombie',
1328 get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1329
1330 // As long as this test passes, the value will be set back. This is only
1331 // in-memory anyhow
1332 $CFG->showuseridentity = $oldshowuseridentity;
1333 $USER = $olduser;
1334 }
1335
1336 public function test_userdate() {
1337 global $USER, $CFG, $DB;
1338
1339 $olduser = $USER;
1340 $USER = $DB->get_record('user', array('id'=>2)); //admin
1341
1342 $testvalues = array(
1343 array(
1344 'time' => '1309514400',
1345 'usertimezone' => 'America/Moncton',
1346 'timezone' => '0.0', //no dst offset
1347 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1348 ),
1349 array(
1350 'time' => '1309514400',
1351 'usertimezone' => 'America/Moncton',
1352 'timezone' => '99', //dst offset and timezone offset.
1353 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1354 ),
1355 array(
1356 'time' => '1309514400',
1357 'usertimezone' => 'America/Moncton',
1358 'timezone' => 'America/Moncton', //dst offset and timezone offset.
1359 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1360 ),
1361 array(
1362 'time' => '1293876000 ',
1363 'usertimezone' => 'America/Moncton',
1364 'timezone' => '0.0', //no dst offset
1365 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1366 ),
1367 array(
1368 'time' => '1293876000 ',
1369 'usertimezone' => 'America/Moncton',
1370 'timezone' => '99', //no dst offset in jan, so just timezone offset.
1371 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1372 ),
1373 array(
1374 'time' => '1293876000 ',
1375 'usertimezone' => 'America/Moncton',
1376 'timezone' => 'America/Moncton', //no dst offset in jan
1377 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1378 ),
1379 array(
1380 'time' => '1293876000 ',
1381 'usertimezone' => '2',
1382 'timezone' => '99', //take user timezone
1383 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1384 ),
1385 array(
1386 'time' => '1293876000 ',
1387 'usertimezone' => '-2',
1388 'timezone' => '99', //take user timezone
1389 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1390 ),
1391 array(
1392 'time' => '1293876000 ',
1393 'usertimezone' => '-10',
1394 'timezone' => '2', //take this timezone
1395 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1396 ),
1397 array(
1398 'time' => '1293876000 ',
1399 'usertimezone' => '-10',
1400 'timezone' => '-2', //take this timezone
1401 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1402 ),
1403 array(
1404 'time' => '1293876000 ',
1405 'usertimezone' => '-10',
1406 'timezone' => 'random/time', //this should show server time
1407 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1408 ),
1409 array(
1410 'time' => '1293876000 ',
1411 'usertimezone' => '14', //server time zone
1412 'timezone' => '99', //this should show user time
1413 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1414 ),
1415 );
1416
1417 //Check if forcetimezone is set then save it and set it to use user timezone
1418 $cfgforcetimezone = null;
1419 if (isset($CFG->forcetimezone)) {
1420 $cfgforcetimezone = $CFG->forcetimezone;
1421 $CFG->forcetimezone = 99; //get user default timezone.
1422 }
1423 //store user default timezone to restore later
1424 $userstimezone = $USER->timezone;
1425
1426 // The string version of date comes from server locale setting and does
1427 // not respect user language, so it is necessary to reset that.
1428 $oldlocale = setlocale(LC_TIME, '0');
1429 setlocale(LC_TIME, 'en_AU.UTF-8');
1430
1431 //set default timezone to Australia/Perth, else time calculated
1432 //will not match expected values. Before that save system defaults.
1433 $systemdefaulttimezone = date_default_timezone_get();
1434 date_default_timezone_set('Australia/Perth');
1435
1436 foreach ($testvalues as $vals) {
1437 $USER->timezone = $vals['usertimezone'];
1438 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1439
1440 //On different systems case of AM PM changes so compare case insensitive
1441 $vals['expectedoutput'] = textlib::strtolower($vals['expectedoutput']);
1442 $actualoutput = textlib::strtolower($actualoutput);
1443
1444 $this->assertEquals($vals['expectedoutput'], $actualoutput,
1445 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1446 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1447 }
1448
1449 //restore user timezone back to what it was
1450 $USER->timezone = $userstimezone;
1451
1452 //restore forcetimezone
1453 if (!is_null($cfgforcetimezone)) {
1454 $CFG->forcetimezone = $cfgforcetimezone;
1455 }
1456
1457 //restore system default values.
1458 date_default_timezone_set($systemdefaulttimezone);
1459 setlocale(LC_TIME, $oldlocale);
1460
1461 $USER = $olduser;
1462 }
1463
1464 public function test_make_timestamp() {
1465 global $USER, $CFG, $DB;
1466
1467 $olduser = $USER;
1468 $USER = $DB->get_record('user', array('id'=>2)); //admin
1469
1470 $testvalues = array(
1471 array(
1472 'usertimezone' => 'America/Moncton',
1473 'year' => '2011',
1474 'month' => '7',
1475 'day' => '1',
1476 'hour' => '10',
1477 'minutes' => '00',
1478 'seconds' => '00',
7b05e146
FM
1479 'timezone' => '0.0',
1480 'applydst' => false, //no dst offset
1481 'expectedoutput' => '1309514400' // 6pm at UTC+0
a3d5830a
PS
1482 ),
1483 array(
1484 'usertimezone' => 'America/Moncton',
1485 'year' => '2011',
1486 'month' => '7',
1487 'day' => '1',
1488 'hour' => '10',
1489 'minutes' => '00',
1490 'seconds' => '00',
1491 'timezone' => '99', //user default timezone
1492 'applydst' => false, //don't apply dst
1493 'expectedoutput' => '1309528800'
1494 ),
1495 array(
1496 'usertimezone' => 'America/Moncton',
1497 'year' => '2011',
1498 'month' => '7',
1499 'day' => '1',
1500 'hour' => '10',
1501 'minutes' => '00',
1502 'seconds' => '00',
1503 'timezone' => '99', //user default timezone
1504 'applydst' => true, //apply dst
1505 'expectedoutput' => '1309525200'
1506 ),
1507 array(
1508 'usertimezone' => 'America/Moncton',
1509 'year' => '2011',
1510 'month' => '7',
1511 'day' => '1',
1512 'hour' => '10',
1513 'minutes' => '00',
1514 'seconds' => '00',
1515 'timezone' => 'America/Moncton', //string timezone
1516 'applydst' => true, //apply dst
1517 'expectedoutput' => '1309525200'
1518 ),
1519 array(
1520 'usertimezone' => '2',//no dst applyed
1521 'year' => '2011',
1522 'month' => '7',
1523 'day' => '1',
1524 'hour' => '10',
1525 'minutes' => '00',
1526 'seconds' => '00',
1527 'timezone' => '99', //take user timezone
1528 'applydst' => true, //apply dst
1529 'expectedoutput' => '1309507200'
1530 ),
1531 array(
1532 'usertimezone' => '-2',//no dst applyed
1533 'year' => '2011',
1534 'month' => '7',
1535 'day' => '1',
1536 'hour' => '10',
1537 'minutes' => '00',
1538 'seconds' => '00',
1539 'timezone' => '99', //take usertimezone
1540 'applydst' => true, //apply dst
1541 'expectedoutput' => '1309521600'
1542 ),
1543 array(
1544 'usertimezone' => '-10',//no dst applyed
1545 'year' => '2011',
1546 'month' => '7',
1547 'day' => '1',
1548 'hour' => '10',
1549 'minutes' => '00',
1550 'seconds' => '00',
1551 'timezone' => '2', //take this timezone
1552 'applydst' => true, //apply dst
1553 'expectedoutput' => '1309507200'
1554 ),
1555 array(
1556 'usertimezone' => '-10',//no dst applyed
1557 'year' => '2011',
1558 'month' => '7',
1559 'day' => '1',
1560 'hour' => '10',
1561 'minutes' => '00',
1562 'seconds' => '00',
1563 'timezone' => '-2', //take this timezone
1564 'applydst' => true, //apply dst,
1565 'expectedoutput' => '1309521600'
1566 ),
1567 array(
1568 'usertimezone' => '-10',//no dst applyed
1569 'year' => '2011',
1570 'month' => '7',
1571 'day' => '1',
1572 'hour' => '10',
1573 'minutes' => '00',
1574 'seconds' => '00',
1575 'timezone' => 'random/time', //This should show server time
1576 'applydst' => true, //apply dst,
1577 'expectedoutput' => '1309485600'
1578 ),
1579 array(
1580 'usertimezone' => '14',//server time
1581 'year' => '2011',
1582 'month' => '7',
1583 'day' => '1',
1584 'hour' => '10',
1585 'minutes' => '00',
1586 'seconds' => '00',
1587 'timezone' => '99', //get user time
1588 'applydst' => true, //apply dst,
1589 'expectedoutput' => '1309485600'
1590 )
1591 );
1592
1593 //Check if forcetimezone is set then save it and set it to use user timezone
1594 $cfgforcetimezone = null;
1595 if (isset($CFG->forcetimezone)) {
1596 $cfgforcetimezone = $CFG->forcetimezone;
1597 $CFG->forcetimezone = 99; //get user default timezone.
1598 }
1599
1600 //store user default timezone to restore later
1601 $userstimezone = $USER->timezone;
1602
1603 // The string version of date comes from server locale setting and does
1604 // not respect user language, so it is necessary to reset that.
1605 $oldlocale = setlocale(LC_TIME, '0');
1606 setlocale(LC_TIME, 'en_AU.UTF-8');
1607
1608 //set default timezone to Australia/Perth, else time calulated
1609 //will not match expected values. Before that save system defaults.
1610 $systemdefaulttimezone = date_default_timezone_get();
1611 date_default_timezone_set('Australia/Perth');
1612
1613 //Test make_timestamp with all testvals and assert if anything wrong.
1614 foreach ($testvalues as $vals) {
1615 $USER->timezone = $vals['usertimezone'];
1616 $actualoutput = make_timestamp(
1617 $vals['year'],
1618 $vals['month'],
1619 $vals['day'],
1620 $vals['hour'],
1621 $vals['minutes'],
1622 $vals['seconds'],
1623 $vals['timezone'],
1624 $vals['applydst']
1625 );
1626
1627 //On different systems case of AM PM changes so compare case insenitive
1628 $vals['expectedoutput'] = textlib::strtolower($vals['expectedoutput']);
1629 $actualoutput = textlib::strtolower($actualoutput);
1630
1631 $this->assertEquals($vals['expectedoutput'], $actualoutput,
1632 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1633 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1634 }
1635
1636 //restore user timezone back to what it was
1637 $USER->timezone = $userstimezone;
1638
1639 //restore forcetimezone
1640 if (!is_null($cfgforcetimezone)) {
1641 $CFG->forcetimezone = $cfgforcetimezone;
1642 }
1643
1644 //restore system default values.
1645 date_default_timezone_set($systemdefaulttimezone);
1646 setlocale(LC_TIME, $oldlocale);
1647
1648 $USER = $olduser;
1649 }
1650
1651 /**
1652 * Test get_string and most importantly the implementation of the lang_string
1653 * object.
1654 */
1655 public function test_get_string() {
1656 global $COURSE;
1657
1658 // Make sure we are using English
1659 $originallang = $COURSE->lang;
1660 $COURSE->lang = 'en';
1661
1662 $yes = get_string('yes');
1663 $yesexpected = 'Yes';
1664 $this->assertEquals(getType($yes), 'string');
1665 $this->assertEquals($yes, $yesexpected);
1666
1667 $yes = get_string('yes', 'moodle');
1668 $this->assertEquals(getType($yes), 'string');
1669 $this->assertEquals($yes, $yesexpected);
1670
1671 $yes = get_string('yes', 'core');
1672 $this->assertEquals(getType($yes), 'string');
1673 $this->assertEquals($yes, $yesexpected);
1674
1675 $yes = get_string('yes', '');
1676 $this->assertEquals(getType($yes), 'string');
1677 $this->assertEquals($yes, $yesexpected);
1678
1679 $yes = get_string('yes', null);
1680 $this->assertEquals(getType($yes), 'string');
1681 $this->assertEquals($yes, $yesexpected);
1682
1683 $yes = get_string('yes', null, 1);
1684 $this->assertEquals(getType($yes), 'string');
1685 $this->assertEquals($yes, $yesexpected);
1686
1687 $days = 1;
1688 $numdays = get_string('numdays', 'core', '1');
1689 $numdaysexpected = $days.' days';
1690 $this->assertEquals(getType($numdays), 'string');
1691 $this->assertEquals($numdays, $numdaysexpected);
1692
1693 $yes = get_string('yes', null, null, true);
1694 $this->assertEquals(get_class($yes), 'lang_string');
1695 $this->assertEquals((string)$yes, $yesexpected);
1696
1697 // Test using a lang_string object as the $a argument for a normal
1698 // get_string call (returning string)
1699 $test = new lang_string('yes', null, null, true);
1700 $testexpected = get_string('numdays', 'core', get_string('yes'));
1701 $testresult = get_string('numdays', null, $test);
1702 $this->assertEquals(getType($testresult), 'string');
1703 $this->assertEquals($testresult, $testexpected);
1704
1705 // Test using a lang_string object as the $a argument for an object
1706 // get_string call (returning lang_string)
1707 $test = new lang_string('yes', null, null, true);
1708 $testexpected = get_string('numdays', 'core', get_string('yes'));
1709 $testresult = get_string('numdays', null, $test, true);
1710 $this->assertEquals(get_class($testresult), 'lang_string');
1711 $this->assertEquals("$testresult", $testexpected);
1712
1713 // Make sure that object properties that can't be converted don't cause
1714 // errors
1715 // Level one: This is as deep as current language processing goes
1716 $test = new stdClass;
1717 $test->one = 'here';
1718 $string = get_string('yes', null, $test, true);
1719 $this->assertEquals($string, $yesexpected);
1720
1721 // Make sure that object properties that can't be converted don't cause
1722 // errors.
1723 // Level two: Language processing doesn't currently reach this deep.
1724 // only immediate scalar properties are worked with.
1725 $test = new stdClass;
1726 $test->one = new stdClass;
1727 $test->one->two = 'here';
1728 $string = get_string('yes', null, $test, true);
1729 $this->assertEquals($string, $yesexpected);
1730
1731 // Make sure that object properties that can't be converted don't cause
1732 // errors.
1733 // Level three: It should never ever go this deep, but we're making sure
1734 // it doesn't cause any probs anyway.
1735 $test = new stdClass;
1736 $test->one = new stdClass;
1737 $test->one->two = new stdClass;
1738 $test->one->two->three = 'here';
1739 $string = get_string('yes', null, $test, true);
1740 $this->assertEquals($string, $yesexpected);
1741
1742 // Make sure that object properties that can't be converted don't cause
1743 // errors and check lang_string properties.
1744 // Level one: This is as deep as current language processing goes
1745 $test = new stdClass;
1746 $test->one = new lang_string('yes');
1747 $string = get_string('yes', null, $test, true);
1748 $this->assertEquals($string, $yesexpected);
1749
1750 // Make sure that object properties that can't be converted don't cause
1751 // errors and check lang_string properties.
1752 // Level two: Language processing doesn't currently reach this deep.
1753 // only immediate scalar properties are worked with.
1754 $test = new stdClass;
1755 $test->one = new stdClass;
1756 $test->one->two = new lang_string('yes');
1757 $string = get_string('yes', null, $test, true);
1758 $this->assertEquals($string, $yesexpected);
1759
1760 // Make sure that object properties that can't be converted don't cause
1761 // errors and check lang_string properties.
1762 // Level three: It should never ever go this deep, but we're making sure
1763 // it doesn't cause any probs anyway.
1764 $test = new stdClass;
1765 $test->one = new stdClass;
1766 $test->one->two = new stdClass;
1767 $test->one->two->three = new lang_string('yes');
1768 $string = get_string('yes', null, $test, true);
1769 $this->assertEquals($string, $yesexpected);
1770
1771 // Make sure that array properties that can't be converted don't cause
1772 // errors
1773 $test = array();
1774 $test['one'] = new stdClass;
1775 $test['one']->two = 'here';
1776 $string = get_string('yes', null, $test, true);
1777 $this->assertEquals($string, $yesexpected);
1778
1779 // Same thing but as above except using an object... this is allowed :P
1780 $string = get_string('yes', null, null, true);
1781 $object = new stdClass;
1782 $object->$string = 'Yes';
1783 $this->assertEquals($string, $yesexpected);
1784 $this->assertEquals($object->$string, $yesexpected);
1785
1786 // Reset the language
1787 $COURSE->lang = $originallang;
1788 }
1789
1790 /**
1791 * @expectedException PHPUnit_Framework_Error_Warning
1792 * @return void
1793 */
1794 public function test_get_string_limitation() {
1795 // This is one of the limitations to the lang_string class. It can't be
1796 // used as a key
1797 $array = array(get_string('yes', null, null, true) => 'yes');
1798 }
637da99e 1799
1800 /**
1801 * Test localised float formatting.
1802 */
1803 public function test_format_float() {
1804 global $SESSION, $CFG;
1805
1806 // Special case for null
1807 $this->assertEquals('', format_float(null));
1808
1809 // Default 1 decimal place
1810 $this->assertEquals('5.4', format_float(5.43));
1811 $this->assertEquals('5.0', format_float(5.001));
1812
1813 // Custom number of decimal places
1814 $this->assertEquals('5.43000', format_float(5.43, 5));
1815
1816 // Option to strip ending zeros after rounding
1817 $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1818 $this->assertEquals('5', format_float(5.0001, 3, true, true));
1819
1820 // It is not possible to directly change the result of get_string in
1821 // a unit test. Instead, we create a language pack for language 'xx' in
1822 // dataroot and make langconfig.php with the string we need to change.
1823 // The example separator used here is 'X'; on PHP 5.3 and before this
1824 // must be a single byte character due to PHP bug/limitation in
1825 // number_format, so you can't use UTF-8 characters.
1826 $SESSION->lang = 'xx';
1827 $langconfig = "<?php\n\$string['decsep'] = 'X';";
1828 $langfolder = $CFG->dataroot . '/lang/xx';
1829 check_dir_exists($langfolder);
1830 file_put_contents($langfolder . '/langconfig.php', $langconfig);
1831
1832 // Localisation on (default)
1833 $this->assertEquals('5X43000', format_float(5.43, 5));
1834 $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1835
1836 // Localisation off
1837 $this->assertEquals('5.43000', format_float(5.43, 5, false));
1838 $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1839 }
4366ce80
PS
1840
1841 /**
1842 * Test deleting of users.
1843 */
1844 public function test_delete_user() {
1845 global $DB, $CFG;
1846
1847 $this->resetAfterTest();
1848
1849 $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
1850 $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
1851 $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
1852
1853 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1854 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
1855
1856 $result = delete_user($user);
1857 $this->assertTrue($result);
1858 $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
1859 $this->assertEquals(1, $deluser->deleted);
1860 $this->assertEquals(0, $deluser->picture);
1861 $this->assertSame('', $deluser->idnumber);
1862 $this->assertSame(md5($user->username), $deluser->email);
1863 $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
1864
1865 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
1866
1867 // Try invalid params.
1868
1869 $record = new stdClass();
1870 $record->grrr = 1;
1871 try {
1872 delete_user($record);
1873 $this->fail('Expecting exception for invalid delete_user() $user parameter');
1874 } catch (coding_exception $e) {
1875 $this->assertTrue(true);
1876 }
1877 $record->id = 1;
1878 try {
1879 delete_user($record);
1880 $this->fail('Expecting exception for invalid delete_user() $user parameter');
1881 } catch (coding_exception $e) {
1882 $this->assertTrue(true);
1883 }
1884
4366ce80
PS
1885 $record = new stdClass();
1886 $record->id = 666;
1887 $record->username = 'xx';
1888 $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
1889 $result = delete_user($record);
1890 $this->assertFalse($result);
1891
1892 $result = delete_user($guest);
1893 $this->assertFalse($result);
1894
1895 $result = delete_user($admin);
1896 $this->assertFalse($result);
a3b6e311
PS
1897
1898 $this->resetDebugging();
4366ce80 1899 }
7b444a96
MG
1900
1901 /**
1902 * Test function convert_to_array()
1903 */
1904 public function test_convert_to_array() {
1905 // check that normal classes are converted to arrays the same way as (array) would do
1906 $obj = new stdClass();
1907 $obj->prop1 = 'hello';
1908 $obj->prop2 = array('first', 'second', 13);
1909 $obj->prop3 = 15;
1910 $this->assertEquals(convert_to_array($obj), (array)$obj);
1911
1912 // check that context object (with iterator) is converted to array properly
1913 $obj = get_system_context();
1914 $ar = array(
1915 'id' => $obj->id,
1916 'contextlevel' => $obj->contextlevel,
1917 'instanceid' => $obj->instanceid,
1918 'path' => $obj->path,
1919 'depth' => $obj->depth
1920 );
1921 $this->assertEquals(convert_to_array($obj), $ar);
1922 }
a3d5830a 1923}