MDL-37894 Amend tests with new openclose rule.
[moodle.git] / lib / tests / moodlelib_test.php
blobfef75b5f895a1a0a2bcb0cbfc745860e70d5db0b
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Unit tests for (some of) ../moodlelib.php.
20 * @package core
21 * @category phpunit
22 * @copyright &copy; 2006 The Open University
23 * @author T.J.Hunt@open.ac.uk
24 * @author nicolas@moodle.com
27 defined('MOODLE_INTERNAL') || die();
29 global $CFG;
30 require_once($CFG->libdir . '/moodlelib.php');
33 class moodlelib_testcase extends advanced_testcase {
35 public static $includecoverage = array('lib/moodlelib.php');
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))'),
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 '3.6' => array('Linux' => 'Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/3.6'),
55 '11.0' => array('Windows' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko Firefox/11.0'),
56 '15.0a2' => array('Windows' => 'Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2'),
57 '18.0' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:18.0) Gecko/18.0 Firefox/18.0'),
59 'SeaMonkey' => array(
60 '2.0' => array('Windows' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1b3pre) Gecko/20081208 SeaMonkey/2.0'),
61 '2.1' => array('Linux' => 'Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20110609 Firefox/4.0.1 SeaMonkey/2.1'),
62 '2.3' => array('FreeBSD' => 'Mozilla/5.0 (X11; FreeBSD amd64; rv:6.0) Gecko/20110818 Firefox/6.0 SeaMonkey/2.3'),
64 'Safari' => array(
65 '312' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312'),
66 '412' => array('Mac OS X' => 'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412 (KHTML, like Gecko) Safari/412')
68 'Safari iOS' => array(
69 '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'),
70 '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'),
72 'WebKit Android' => array(
73 '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'),
74 '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'),
76 'Chrome' => array(
77 '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'),
79 'Opera' => array(
80 '8.51' => array('Windows XP' => 'Opera/8.51 (Windows NT 5.1; U; en)'),
81 '9.0' => array('Windows XP' => 'Opera/9.0 (Windows NT 5.1; U; en)',
82 'Debian Linux' => 'Opera/9.01 (X11; Linux i686; U; en)')
86 function test_cleanremoteaddr() {
87 //IPv4
88 $this->assertEquals(cleanremoteaddr('1023.121.234.1'), null);
89 $this->assertEquals(cleanremoteaddr('123.121.234.01 '), '123.121.234.1');
91 //IPv6
92 $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:0:0:0'), null);
93 $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:0:abh'), null);
94 $this->assertEquals(cleanremoteaddr('0:0:0:::0:0:1'), null);
95 $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:0:0', true), '::');
96 $this->assertEquals(cleanremoteaddr('0:0:0:0:0:0:1:1', true), '::1:1');
97 $this->assertEquals(cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true), 'abcd:ef::');
98 $this->assertEquals(cleanremoteaddr('1:0:0:0:0:0:0:1', true), '1::1');
99 $this->assertEquals(cleanremoteaddr('::10:1', false), '0:0:0:0:0:0:10:1');
100 $this->assertEquals(cleanremoteaddr('01:1::', false), '1:1:0:0:0:0:0:0');
101 $this->assertEquals(cleanremoteaddr('10::10', false), '10:0:0:0:0:0:0:10');
102 $this->assertEquals(cleanremoteaddr('::ffff:192.168.1.1', true), '::ffff:c0a8:11');
105 function test_address_in_subnet() {
106 /// 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
107 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32'));
108 $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32'));
109 $this->assertTrue(address_in_subnet('10.10.10.100', '123.121.23.45/0'));
110 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24'));
111 $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24'));
112 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30'));
113 $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30'));
114 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
115 $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128'));
116 $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0'));
117 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
118 $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120'));
119 $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120'));
120 $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112'));
121 $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112'));
122 $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112'));
124 // fixed input
125 $this->assertTrue(address_in_subnet('123.121.23.1 ', ' 123.121.23.0 / 24'));
126 $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126'));
128 // incorrect input
129 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2'));
130 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64'));
131 $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24'));
132 $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24'));
133 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0'));
134 $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0'));
135 $this->assertFalse(address_in_subnet('::1', '::aa:0/-5'));
136 $this->assertFalse(address_in_subnet('::1', '::aa:0/130'));
137 $this->assertFalse(address_in_subnet('x:1', '::aa:0/130'));
138 $this->assertFalse(address_in_subnet('::1', '::ax:0/130'));
141 /// 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)
142 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14'));
143 $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14'));
144 $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14'));
145 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14'));
146 $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14'));
147 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14'));
148 $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14'));
149 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe'));
150 $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe'));
151 $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe'));
152 $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe'));
153 $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe'));
154 $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe'));
155 $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe'));
157 // fixed input
158 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 '));
159 $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe '));
161 // incorrect input
162 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14'));
163 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256'));
164 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256'));
167 /// 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
168 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12'));
169 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13'));
170 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.'));
171 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234'));
172 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121'));
173 $this->assertTrue(address_in_subnet('123.121.234.12', '123'));
174 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.'));
175 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234'));
176 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab'));
177 $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc'));
178 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba'));
179 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:'));
180 $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:'));
183 /// multiple subnets
184 $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30'));
185 $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30'));
186 $this->assertTrue(address_in_subnet('::2', '::1/64, 124., 123.121.234.10-30'));
187 $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30'));
190 /// other incorrect input
191 $this->assertFalse(address_in_subnet('123.123.123.123', ''));
195 * Modifies $_SERVER['HTTP_USER_AGENT'] manually to check if check_browser_version
196 * works as expected.
198 function test_check_browser_version()
200 global $CFG;
202 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari']['412']['Mac OS X'];
203 $this->assertTrue(check_browser_version('Safari'));
204 $this->assertTrue(check_browser_version('WebKit'));
205 $this->assertTrue(check_browser_version('Safari', '312'));
206 $this->assertFalse(check_browser_version('Safari', '500'));
207 $this->assertFalse(check_browser_version('Chrome'));
208 $this->assertFalse(check_browser_version('Safari iOS'));
210 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari iOS']['528']['iPhone'];
211 $this->assertTrue(check_browser_version('Safari iOS'));
212 $this->assertTrue(check_browser_version('WebKit'));
213 $this->assertTrue(check_browser_version('Safari iOS', '527'));
214 $this->assertFalse(check_browser_version('Safari iOS', 590));
215 $this->assertFalse(check_browser_version('Safari', '312'));
216 $this->assertFalse(check_browser_version('Safari', '500'));
217 $this->assertFalse(check_browser_version('Chrome'));
219 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['WebKit Android']['530']['Nexus'];
220 $this->assertTrue(check_browser_version('WebKit'));
221 $this->assertTrue(check_browser_version('WebKit Android', '527'));
222 $this->assertFalse(check_browser_version('WebKit Android', 590));
223 $this->assertFalse(check_browser_version('Safari'));
224 $this->assertFalse(check_browser_version('Chrome'));
226 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X'];
227 $this->assertTrue(check_browser_version('Chrome'));
228 $this->assertTrue(check_browser_version('WebKit'));
229 $this->assertTrue(check_browser_version('Chrome', 8));
230 $this->assertFalse(check_browser_version('Chrome', 10));
231 $this->assertFalse(check_browser_version('Safari', '1'));
233 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Opera']['9.0']['Windows XP'];
234 $this->assertTrue(check_browser_version('Opera'));
235 $this->assertTrue(check_browser_version('Opera', '8.0'));
236 $this->assertFalse(check_browser_version('Opera', '10.0'));
238 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['6.0']['Windows XP SP2'];
239 $this->assertTrue(check_browser_version('MSIE'));
240 $this->assertTrue(check_browser_version('MSIE', '5.0'));
241 $this->assertFalse(check_browser_version('MSIE', '7.0'));
243 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['5.0']['Windows 98'];
244 $this->assertFalse(check_browser_version('MSIE'));
245 $this->assertTrue(check_browser_version('MSIE', 0));
246 $this->assertTrue(check_browser_version('MSIE', '5.0'));
247 $this->assertFalse(check_browser_version('MSIE', '7.0'));
249 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['9.0']['Windows 7'];
250 $this->assertTrue(check_browser_version('MSIE'));
251 $this->assertTrue(check_browser_version('MSIE', 0));
252 $this->assertTrue(check_browser_version('MSIE', '5.0'));
253 $this->assertTrue(check_browser_version('MSIE', '9.0'));
254 $this->assertFalse(check_browser_version('MSIE', '10'));
256 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP'];
257 $this->assertTrue(check_browser_version('Firefox'));
258 $this->assertTrue(check_browser_version('Firefox', '1.5'));
259 $this->assertFalse(check_browser_version('Firefox', '3.0'));
260 $this->assertTrue(check_browser_version('Gecko', '2'));
261 $this->assertTrue(check_browser_version('Gecko', 20030516));
262 $this->assertTrue(check_browser_version('Gecko', 20051106));
263 $this->assertTrue(check_browser_version('Gecko', 2006010100));
265 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['1.0.6']['Windows XP'];
266 $this->assertTrue(check_browser_version('Firefox'));
267 $this->assertTrue(check_browser_version('Gecko', '1'));
268 $this->assertFalse(check_browser_version('Gecko', 20030516));
269 $this->assertFalse(check_browser_version('Gecko', 20051106));
270 $this->assertFalse(check_browser_version('Gecko', 2006010100));
271 $this->assertFalse(check_browser_version('Firefox', '1.5'));
272 $this->assertFalse(check_browser_version('Firefox', '3.0'));
273 $this->assertFalse(check_browser_version('Gecko', '2'));
275 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP'];
276 $this->assertTrue(check_browser_version('Firefox'));
277 $this->assertTrue(check_browser_version('Firefox', '1.5'));
278 $this->assertTrue(check_browser_version('Gecko', '1'));
279 $this->assertTrue(check_browser_version('Gecko', '2'));
280 $this->assertTrue(check_browser_version('Gecko', 20030516));
281 $this->assertTrue(check_browser_version('Gecko', 20051106));
282 $this->assertTrue(check_browser_version('Gecko', 2006010100));
283 $this->assertFalse(check_browser_version('Firefox', '3.0'));
285 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['3.6']['Linux'];
286 $this->assertTrue(check_browser_version('Firefox'));
287 $this->assertTrue(check_browser_version('Firefox', '1.5'));
288 $this->assertTrue(check_browser_version('Firefox', '3.0'));
289 $this->assertTrue(check_browser_version('Gecko', '2'));
290 $this->assertTrue(check_browser_version('Gecko', '3.6'));
291 $this->assertTrue(check_browser_version('Gecko', 20030516));
292 $this->assertTrue(check_browser_version('Gecko', 20051106));
293 $this->assertTrue(check_browser_version('Gecko', 2006010100));
294 $this->assertFalse(check_browser_version('Firefox', '4'));
295 $this->assertFalse(check_browser_version('Firefox', '10'));
297 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['3.6']['Linux'];
298 $this->assertTrue(check_browser_version('Firefox'));
299 $this->assertTrue(check_browser_version('Firefox', '1.5'));
300 $this->assertTrue(check_browser_version('Firefox', '3.0'));
301 $this->assertTrue(check_browser_version('Gecko', '2'));
302 $this->assertTrue(check_browser_version('Gecko', '3.6'));
303 $this->assertTrue(check_browser_version('Gecko', 20030516));
304 $this->assertTrue(check_browser_version('Gecko', 20051106));
305 $this->assertTrue(check_browser_version('Gecko', 2006010100));
306 $this->assertFalse(check_browser_version('Firefox', '4'));
307 $this->assertFalse(check_browser_version('Firefox', '10'));
308 $this->assertFalse(check_browser_version('Firefox', '18'));
309 $this->assertFalse(check_browser_version('Gecko', '4'));
311 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['15.0a2']['Windows'];
312 $this->assertTrue(check_browser_version('Firefox'));
313 $this->assertTrue(check_browser_version('Firefox', '1.5'));
314 $this->assertTrue(check_browser_version('Firefox', '3.0'));
315 $this->assertTrue(check_browser_version('Gecko', '2'));
316 $this->assertTrue(check_browser_version('Gecko', '3.6'));
317 $this->assertTrue(check_browser_version('Gecko', '15.0'));
318 $this->assertTrue(check_browser_version('Gecko', 20030516));
319 $this->assertTrue(check_browser_version('Gecko', 20051106));
320 $this->assertTrue(check_browser_version('Gecko', 2006010100));
321 $this->assertTrue(check_browser_version('Firefox', '4'));
322 $this->assertTrue(check_browser_version('Firefox', '10'));
323 $this->assertTrue(check_browser_version('Firefox', '15'));
324 $this->assertFalse(check_browser_version('Firefox', '18'));
325 $this->assertFalse(check_browser_version('Gecko', '18'));
327 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['18.0']['Mac OS X'];
328 $this->assertTrue(check_browser_version('Firefox'));
329 $this->assertTrue(check_browser_version('Firefox', '1.5'));
330 $this->assertTrue(check_browser_version('Firefox', '3.0'));
331 $this->assertTrue(check_browser_version('Gecko', '2'));
332 $this->assertTrue(check_browser_version('Gecko', '3.6'));
333 $this->assertTrue(check_browser_version('Gecko', '15.0'));
334 $this->assertTrue(check_browser_version('Gecko', '18.0'));
335 $this->assertTrue(check_browser_version('Gecko', 20030516));
336 $this->assertTrue(check_browser_version('Gecko', 20051106));
337 $this->assertTrue(check_browser_version('Gecko', 2006010100));
338 $this->assertTrue(check_browser_version('Firefox', '4'));
339 $this->assertTrue(check_browser_version('Firefox', '10'));
340 $this->assertTrue(check_browser_version('Firefox', '15'));
341 $this->assertTrue(check_browser_version('Firefox', '18'));
342 $this->assertFalse(check_browser_version('Firefox', '19'));
343 $this->assertFalse(check_browser_version('Gecko', '19'));
345 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['SeaMonkey']['2.0']['Windows'];
347 $this->assertTrue(check_browser_version('Gecko', '2'));
348 $this->assertTrue(check_browser_version('Gecko', 20030516));
349 $this->assertTrue(check_browser_version('Gecko', 20051106));
350 $this->assertTrue(check_browser_version('Gecko', 2006010100));
351 $this->assertFalse(check_browser_version('Gecko', '3.6'));
352 $this->assertFalse(check_browser_version('Gecko', '4.0'));
353 $this->assertFalse(check_browser_version('Firefox'));
355 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['SeaMonkey']['2.1']['Linux'];
356 $this->assertTrue(check_browser_version('Gecko', '2'));
357 $this->assertTrue(check_browser_version('Gecko', '3.6'));
358 $this->assertTrue(check_browser_version('Gecko', '4.0'));
359 $this->assertTrue(check_browser_version('Gecko', 20030516));
360 $this->assertTrue(check_browser_version('Gecko', 20051106));
361 $this->assertTrue(check_browser_version('Gecko', 2006010100));
362 $this->assertTrue(check_browser_version('Firefox'));
363 $this->assertTrue(check_browser_version('Firefox', 4.0));
364 $this->assertFalse(check_browser_version('Firefox', 5));
365 $this->assertFalse(check_browser_version('Gecko', '18.0'));
369 function test_get_browser_version_classes() {
370 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari']['412']['Mac OS X'];
371 $this->assertEquals(array('safari'), get_browser_version_classes());
373 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X'];
374 $this->assertEquals(array('safari'), get_browser_version_classes());
376 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Safari iOS']['528']['iPhone'];
377 $this->assertEquals(array('safari', 'ios'), get_browser_version_classes());
379 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['WebKit Android']['530']['Nexus'];
380 $this->assertEquals(array('safari', 'android'), get_browser_version_classes());
382 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Chrome']['8']['Mac OS X'];
383 $this->assertEquals(array('safari'), get_browser_version_classes());
385 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Opera']['9.0']['Windows XP'];
386 $this->assertEquals(array('opera'), get_browser_version_classes());
388 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['6.0']['Windows XP SP2'];
389 $this->assertEquals(array('ie', 'ie6'), get_browser_version_classes());
391 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['7.0']['Windows XP SP2'];
392 $this->assertEquals(array('ie', 'ie7'), get_browser_version_classes());
394 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['MSIE']['8.0']['Windows Vista'];
395 $this->assertEquals(array('ie', 'ie8'), get_browser_version_classes());
397 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['2.0']['Windows XP'];
398 $this->assertEquals(array('gecko', 'gecko18'), get_browser_version_classes());
400 $_SERVER['HTTP_USER_AGENT'] = $this->user_agents['Firefox']['3.0.6']['SUSE'];
401 $this->assertEquals(array('gecko', 'gecko19'), get_browser_version_classes());
404 function test_get_device_type() {
405 // IE8 (common pattern ~1.5% of IE7/8 users have embedded IE6 agent))
406 $_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)';
407 $this->assertEquals('default', get_device_type());
408 // Genuine IE6
409 $_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)';
410 $this->assertEquals('legacy', get_device_type());
413 function test_fix_utf8() {
414 // make sure valid data including other types is not changed
415 $this->assertSame(null, fix_utf8(null));
416 $this->assertSame(1, fix_utf8(1));
417 $this->assertSame(1.1, fix_utf8(1.1));
418 $this->assertSame(true, fix_utf8(true));
419 $this->assertSame('', fix_utf8(''));
420 $this->assertSame('abc', fix_utf8('abc'));
421 $array = array('do', 're', 'mi');
422 $this->assertSame($array, fix_utf8($array));
423 $object = new stdClass();
424 $object->a = 'aa';
425 $object->b = 'bb';
426 $this->assertEquals($object, fix_utf8($object));
428 // valid utf8 string
429 $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"));
431 // invalid utf8 string
432 $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
435 function test_optional_param() {
436 global $CFG;
438 $_POST['username'] = 'post_user';
439 $_GET['username'] = 'get_user';
440 $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), $_POST['username']);
442 unset($_POST['username']);
443 $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), $_GET['username']);
445 unset($_GET['username']);
446 $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), 'default_user');
448 // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
449 $_POST['username'] = 'post_user';
450 try {
451 optional_param('username', 'default_user', null);
452 $this->fail('coding_exception expected');
453 } catch (coding_exception $ex) {
454 $this->assertTrue(true);
456 try {
457 @optional_param('username', 'default_user');
458 $this->fail('coding_exception expected');
459 } catch (coding_exception $ex) {
460 $this->assertTrue(true);
462 try {
463 @optional_param('username');
464 $this->fail('coding_exception expected');
465 } catch (coding_exception $ex) {
466 $this->assertTrue(true);
468 try {
469 optional_param('', 'default_user', PARAM_RAW);
470 $this->fail('coding_exception expected');
471 } catch (coding_exception $ex) {
472 $this->assertTrue(true);
475 // make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3
476 $debugging = isset($CFG->debug) ? $CFG->debug : null;
477 $debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null;
478 $CFG->debug = DEBUG_DEVELOPER;
479 $CFG->debugdisplay = true;
481 ob_start();
482 $this->assertSame(optional_param('username', 'default_user', PARAM_RAW), $_POST['username']);
483 $d = ob_end_clean();
484 $this->assertTrue($d !== '');
486 if ($debugging !== null) {
487 $CFG->debug = $debugging;
488 } else {
489 unset($CFG->debug);
491 if ($debugdisplay !== null) {
492 $CFG->debugdisplay = $debugdisplay;
493 } else {
494 unset($CFG->debugdisplay);
498 function test_optional_param_array() {
499 global $CFG;
501 $_POST['username'] = array('a'=>'post_user');
502 $_GET['username'] = array('a'=>'get_user');
503 $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), $_POST['username']);
505 unset($_POST['username']);
506 $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), $_GET['username']);
508 unset($_GET['username']);
509 $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), array('a'=>'default_user'));
511 // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
512 $_POST['username'] = array('a'=>'post_user');
513 try {
514 optional_param_array('username', array('a'=>'default_user'), null);
515 $this->fail('coding_exception expected');
516 } catch (coding_exception $ex) {
517 $this->assertTrue(true);
519 try {
520 @optional_param_array('username', array('a'=>'default_user'));
521 $this->fail('coding_exception expected');
522 } catch (coding_exception $ex) {
523 $this->assertTrue(true);
525 try {
526 @optional_param_array('username');
527 $this->fail('coding_exception expected');
528 } catch (coding_exception $ex) {
529 $this->assertTrue(true);
531 try {
532 optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
533 $this->fail('coding_exception expected');
534 } catch (coding_exception $ex) {
535 $this->assertTrue(true);
538 // do not allow nested arrays
539 try {
540 $_POST['username'] = array('a'=>array('b'=>'post_user'));
541 optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
542 $this->fail('coding_exception expected');
543 } catch (coding_exception $ex) {
544 $this->assertTrue(true);
547 // do not allow non-arrays
548 $debugging = isset($CFG->debug) ? $CFG->debug : null;
549 $debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null;
550 $CFG->debug = DEBUG_DEVELOPER;
551 $CFG->debugdisplay = true;
553 ob_start();
554 $_POST['username'] = 'post_user';
555 $this->assertSame(optional_param_array('username', array('a'=>'default_user'), PARAM_RAW), array('a'=>'default_user'));
556 $d = ob_end_clean();
557 $this->assertTrue($d !== '');
559 // make sure array keys are sanitised
560 ob_start();
561 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
562 $this->assertSame(optional_param_array('username', array(), PARAM_RAW), array('a1_-'=>'post_user'));
563 $d = ob_end_clean();
564 $this->assertTrue($d !== '');
566 if ($debugging !== null) {
567 $CFG->debug = $debugging;
568 } else {
569 unset($CFG->debug);
571 if ($debugdisplay !== null) {
572 $CFG->debugdisplay = $debugdisplay;
573 } else {
574 unset($CFG->debugdisplay);
578 function test_required_param() {
579 global $CFG;
581 $_POST['username'] = 'post_user';
582 $_GET['username'] = 'get_user';
583 $this->assertSame(required_param('username', PARAM_RAW), 'post_user');
585 unset($_POST['username']);
586 $this->assertSame(required_param('username', PARAM_RAW), 'get_user');
588 unset($_GET['username']);
589 try {
590 $this->assertSame(required_param('username', PARAM_RAW), 'default_user');
591 $this->fail('moodle_exception expected');
592 } catch (moodle_exception $ex) {
593 $this->assertTrue(true);
596 // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
597 $_POST['username'] = 'post_user';
598 try {
599 @required_param('username');
600 $this->fail('coding_exception expected');
601 } catch (coding_exception $ex) {
602 $this->assertTrue(true);
604 try {
605 required_param('username', '');
606 $this->fail('coding_exception expected');
607 } catch (coding_exception $ex) {
608 $this->assertTrue(true);
610 try {
611 required_param('', PARAM_RAW);
612 $this->fail('coding_exception expected');
613 } catch (coding_exception $ex) {
614 $this->assertTrue(true);
617 // make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3
618 $debugging = isset($CFG->debug) ? $CFG->debug : null;
619 $debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null;
620 $CFG->debug = DEBUG_DEVELOPER;
621 $CFG->debugdisplay = true;
623 ob_start();
624 $this->assertSame(required_param('username', PARAM_RAW), $_POST['username']);
625 $d = ob_end_clean();
626 $this->assertTrue($d !== '');
628 if ($debugging !== null) {
629 $CFG->debug = $debugging;
630 } else {
631 unset($CFG->debug);
633 if ($debugdisplay !== null) {
634 $CFG->debugdisplay = $debugdisplay;
635 } else {
636 unset($CFG->debugdisplay);
640 function test_required_param_array() {
641 global $CFG;
643 $_POST['username'] = array('a'=>'post_user');
644 $_GET['username'] = array('a'=>'get_user');
645 $this->assertSame(required_param_array('username', PARAM_RAW), $_POST['username']);
647 unset($_POST['username']);
648 $this->assertSame(required_param_array('username', PARAM_RAW), $_GET['username']);
650 // make sure exception is triggered when some params are missing, hide error notices here - new in 2.2
651 $_POST['username'] = array('a'=>'post_user');
652 try {
653 required_param_array('username', null);
654 $this->fail('coding_exception expected');
655 } catch (coding_exception $ex) {
656 $this->assertTrue(true);
658 try {
659 @required_param_array('username');
660 $this->fail('coding_exception expected');
661 } catch (coding_exception $ex) {
662 $this->assertTrue(true);
664 try {
665 required_param_array('', PARAM_RAW);
666 $this->fail('coding_exception expected');
667 } catch (coding_exception $ex) {
668 $this->assertTrue(true);
671 // do not allow nested arrays
672 try {
673 $_POST['username'] = array('a'=>array('b'=>'post_user'));
674 required_param_array('username', PARAM_RAW);
675 $this->fail('coding_exception expected');
676 } catch (coding_exception $ex) {
677 $this->assertTrue(true);
680 // do not allow non-arrays
681 try {
682 $_POST['username'] = 'post_user';
683 required_param_array('username', PARAM_RAW);
684 $this->fail('moodle_exception expected');
685 } catch (moodle_exception $ex) {
686 $this->assertTrue(true);
689 // do not allow non-arrays
690 $debugging = isset($CFG->debug) ? $CFG->debug : null;
691 $debugdisplay = isset($CFG->debugdisplay) ? $CFG->debugdisplay : null;
692 $CFG->debug = DEBUG_DEVELOPER;
693 $CFG->debugdisplay = true;
695 // make sure array keys are sanitised
696 ob_start();
697 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
698 $this->assertSame(required_param_array('username', PARAM_RAW), array('a1_-'=>'post_user'));
699 $d = ob_end_clean();
700 $this->assertTrue($d !== '');
702 if ($debugging !== null) {
703 $CFG->debug = $debugging;
704 } else {
705 unset($CFG->debug);
707 if ($debugdisplay !== null) {
708 $CFG->debugdisplay = $debugdisplay;
709 } else {
710 unset($CFG->debugdisplay);
714 function test_clean_param() {
715 // forbid objects and arrays
716 try {
717 clean_param(array('x', 'y'), PARAM_RAW);
718 $this->fail('coding_exception expected');
719 } catch (coding_exception $ex) {
720 $this->assertTrue(true);
722 try {
723 $param = new stdClass();
724 $param->id = 1;
725 clean_param($param, PARAM_RAW);
726 $this->fail('coding_exception expected');
727 } catch (coding_exception $ex) {
728 $this->assertTrue(true);
731 // require correct type
732 try {
733 clean_param('x', 'xxxxxx');
734 $this->fail('moodle_exception expected');
735 } catch (moodle_exception $ex) {
736 $this->assertTrue(true);
738 try {
739 @clean_param('x');
740 $this->fail('moodle_exception expected');
741 } catch (moodle_exception $ex) {
742 $this->assertTrue(true);
747 function test_clean_param_array() {
748 $this->assertSame(clean_param_array(null, PARAM_RAW), array());
749 $this->assertSame(clean_param_array(array('a', 'b'), PARAM_RAW), array('a', 'b'));
750 $this->assertSame(clean_param_array(array('a', array('b')), PARAM_RAW, true), array('a', array('b')));
752 // require correct type
753 try {
754 clean_param_array(array('x'), 'xxxxxx');
755 $this->fail('moodle_exception expected');
756 } catch (moodle_exception $ex) {
757 $this->assertTrue(true);
759 try {
760 @clean_param_array(array('x'));
761 $this->fail('moodle_exception expected');
762 } catch (moodle_exception $ex) {
763 $this->assertTrue(true);
766 try {
767 clean_param_array(array('x', array('y')), PARAM_RAW);
768 $this->fail('coding_exception expected');
769 } catch (coding_exception $ex) {
770 $this->assertTrue(true);
773 // test recursive
776 function test_clean_param_raw() {
777 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW),
778 '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)');
781 function test_clean_param_trim() {
782 $this->assertEquals(clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED), 'Frog toad');
785 function test_clean_param_clean() {
786 // PARAM_CLEAN is an ugly hack, do not use in new code (skodak)
787 // instead use more specific type, or submit sothing that can be verified properly
788 $this->assertEquals(clean_param('xx<script>', PARAM_CLEAN), 'xx');
791 function test_clean_param_alpha() {
792 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA),
793 'DSFMOSDJ');
796 function test_clean_param_alphanum() {
797 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM),
798 '978942897DSFMOSDJ');
801 function test_clean_param_alphaext() {
802 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT),
803 'DSFMOSDJ');
806 function test_clean_param_sequence() {
807 $this->assertEquals(clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE),
808 ',9789,42897');
811 function test_clean_param_component() {
812 // please note the cleaning of component names is very strict, no guessing here
813 $this->assertSame(clean_param('mod_forum', PARAM_COMPONENT), 'mod_forum');
814 $this->assertSame(clean_param('block_online_users', PARAM_COMPONENT), 'block_online_users');
815 $this->assertSame(clean_param('block_blond_online_users', PARAM_COMPONENT), 'block_blond_online_users');
816 $this->assertSame(clean_param('mod_something2', PARAM_COMPONENT), 'mod_something2');
817 $this->assertSame(clean_param('forum', PARAM_COMPONENT), 'forum');
818 $this->assertSame(clean_param('user', PARAM_COMPONENT), 'user');
819 $this->assertSame(clean_param('rating', PARAM_COMPONENT), 'rating');
820 $this->assertSame(clean_param('mod_2something', PARAM_COMPONENT), '');
821 $this->assertSame(clean_param('2mod_something', PARAM_COMPONENT), '');
822 $this->assertSame(clean_param('mod_something_xx', PARAM_COMPONENT), '');
823 $this->assertSame(clean_param('auth_something__xx', PARAM_COMPONENT), '');
824 $this->assertSame(clean_param('mod_Something', PARAM_COMPONENT), '');
825 $this->assertSame(clean_param('mod_somethíng', PARAM_COMPONENT), '');
826 $this->assertSame(clean_param('auth_xx-yy', PARAM_COMPONENT), '');
827 $this->assertSame(clean_param('_auth_xx', PARAM_COMPONENT), '');
828 $this->assertSame(clean_param('a2uth_xx', PARAM_COMPONENT), '');
829 $this->assertSame(clean_param('auth_xx_', PARAM_COMPONENT), '');
830 $this->assertSame(clean_param('auth_xx.old', PARAM_COMPONENT), '');
831 $this->assertSame(clean_param('_user', PARAM_COMPONENT), '');
832 $this->assertSame(clean_param('2rating', PARAM_COMPONENT), '');
833 $this->assertSame(clean_param('user_', PARAM_COMPONENT), '');
836 function test_clean_param_plugin() {
837 // please note the cleaning of plugin names is very strict, no guessing here
838 $this->assertSame(clean_param('forum', PARAM_PLUGIN), 'forum');
839 $this->assertSame(clean_param('forum2', PARAM_PLUGIN), 'forum2');
840 $this->assertSame(clean_param('online_users', PARAM_PLUGIN), 'online_users');
841 $this->assertSame(clean_param('blond_online_users', PARAM_PLUGIN), 'blond_online_users');
842 $this->assertSame(clean_param('online__users', PARAM_PLUGIN), '');
843 $this->assertSame(clean_param('forum ', PARAM_PLUGIN), '');
844 $this->assertSame(clean_param('forum.old', PARAM_PLUGIN), '');
845 $this->assertSame(clean_param('xx-yy', PARAM_PLUGIN), '');
846 $this->assertSame(clean_param('2xx', PARAM_PLUGIN), '');
847 $this->assertSame(clean_param('Xx', PARAM_PLUGIN), '');
848 $this->assertSame(clean_param('_xx', PARAM_PLUGIN), '');
849 $this->assertSame(clean_param('xx_', PARAM_PLUGIN), '');
852 function test_clean_param_area() {
853 // please note the cleaning of area names is very strict, no guessing here
854 $this->assertSame(clean_param('something', PARAM_AREA), 'something');
855 $this->assertSame(clean_param('something2', PARAM_AREA), 'something2');
856 $this->assertSame(clean_param('some_thing', PARAM_AREA), 'some_thing');
857 $this->assertSame(clean_param('some_thing_xx', PARAM_AREA), 'some_thing_xx');
858 $this->assertSame(clean_param('_something', PARAM_AREA), '');
859 $this->assertSame(clean_param('something_', PARAM_AREA), '');
860 $this->assertSame(clean_param('2something', PARAM_AREA), '');
861 $this->assertSame(clean_param('Something', PARAM_AREA), '');
862 $this->assertSame(clean_param('some-thing', PARAM_AREA), '');
863 $this->assertSame(clean_param('somethííng', PARAM_AREA), '');
864 $this->assertSame(clean_param('something.x', PARAM_AREA), '');
867 function test_clean_param_text() {
868 $this->assertEquals(PARAM_TEXT, PARAM_MULTILANG);
869 //standard
870 $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>');
871 $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>');
872 $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>');
873 //malformed
874 $this->assertEquals(clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT), '<span lang="en" class="multilang">aa</span>');
875 $this->assertEquals(clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT), 'aa');
876 $this->assertEquals(clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT), 'aa');
877 $this->assertEquals(clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT), 'aa');
878 $this->assertEquals(clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT), 'aa');
879 $this->assertEquals(clean_param('a<em>b</em>c', PARAM_TEXT), 'abc');
880 $this->assertEquals(clean_param('a><xx >c>', PARAM_TEXT), 'a>c>'); // standard strip_tags() behaviour
881 $this->assertEquals(clean_param('a<b', PARAM_TEXT), 'a');
882 $this->assertEquals(clean_param('a>b', PARAM_TEXT), 'a>b');
883 $this->assertEquals(clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT), '<lang lang="en">a>a</lang>'); // standard strip_tags() behaviour
884 $this->assertEquals(clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT), 'a');
885 $this->assertEquals(clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT), '<lang lang="en">aa</lang>');
888 function test_clean_param_url() {
889 // Test PARAM_URL and PARAM_LOCALURL a bit
890 $this->assertEquals(clean_param('http://google.com/', PARAM_URL), 'http://google.com/');
891 $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/');
892 $this->assertEquals(clean_param('http://localhost/', PARAM_URL), 'http://localhost/');
893 $this->assertEquals(clean_param('http://0.255.1.1/numericip.php', PARAM_URL), 'http://0.255.1.1/numericip.php');
894 $this->assertEquals(clean_param('/just/a/path', PARAM_URL), '/just/a/path');
895 $this->assertEquals(clean_param('funny:thing', PARAM_URL), '');
898 function test_clean_param_localurl() {
899 global $CFG;
900 $this->assertEquals(clean_param('http://google.com/', PARAM_LOCALURL), '');
901 $this->assertEquals(clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL), '');
902 $this->assertEquals(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
903 $this->assertEquals(clean_param('/just/a/path', PARAM_LOCALURL), '/just/a/path');
904 $this->assertEquals(clean_param('funny:thing', PARAM_LOCALURL), '');
905 $this->assertEquals(clean_param('course/view.php?id=3', PARAM_LOCALURL), 'course/view.php?id=3');
908 function test_clean_param_file() {
909 $this->assertEquals(clean_param('correctfile.txt', PARAM_FILE), 'correctfile.txt');
910 $this->assertEquals(clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE), 'badfile.txt');
911 $this->assertEquals(clean_param('../parentdirfile.txt', PARAM_FILE), 'parentdirfile.txt');
912 //The following behaviours have been maintained although they seem a little odd
913 $this->assertEquals(clean_param('funny:thing', PARAM_FILE), 'funnything');
914 $this->assertEquals(clean_param('./currentdirfile.txt', PARAM_FILE), '.currentdirfile.txt');
915 $this->assertEquals(clean_param('c:\temp\windowsfile.txt', PARAM_FILE), 'ctempwindowsfile.txt');
916 $this->assertEquals(clean_param('/home/user/linuxfile.txt', PARAM_FILE), 'homeuserlinuxfile.txt');
917 $this->assertEquals(clean_param('~/myfile.txt', PARAM_FILE), '~myfile.txt');
920 function test_clean_param_username() {
921 global $CFG;
922 $currentstatus = $CFG->extendedusernamechars;
924 // Run tests with extended character == FALSE;
925 $CFG->extendedusernamechars = FALSE;
926 $this->assertEquals(clean_param('johndoe123', PARAM_USERNAME), 'johndoe123' );
927 $this->assertEquals(clean_param('john.doe', PARAM_USERNAME), 'john.doe');
928 $this->assertEquals(clean_param('john-doe', PARAM_USERNAME), 'john-doe');
929 $this->assertEquals(clean_param('john- doe', PARAM_USERNAME), 'john-doe');
930 $this->assertEquals(clean_param('john_doe', PARAM_USERNAME), 'john_doe');
931 $this->assertEquals(clean_param('john@doe', PARAM_USERNAME), 'john@doe');
932 $this->assertEquals(clean_param('john~doe', PARAM_USERNAME), 'johndoe');
933 $this->assertEquals(clean_param('john´doe', PARAM_USERNAME), 'johndoe');
934 $this->assertEquals(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
935 $this->assertEquals(clean_param('JOHNdóé ', PARAM_USERNAME), 'johnd');
936 $this->assertEquals(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýáž?žý??šdoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
939 // Test success condition, if extendedusernamechars == ENABLE;
940 $CFG->extendedusernamechars = TRUE;
941 $this->assertEquals(clean_param('john_doe', PARAM_USERNAME), 'john_doe');
942 $this->assertEquals(clean_param('john@doe', PARAM_USERNAME), 'john@doe');
943 $this->assertEquals(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john#$%&()+_^');
944 $this->assertEquals(clean_param('john~doe', PARAM_USERNAME), 'john~doe');
945 $this->assertEquals(clean_param('joHN´doe', PARAM_USERNAME), 'john´doe');
946 $this->assertEquals(clean_param('johnDOE', PARAM_USERNAME), 'johndoe');
947 $this->assertEquals(clean_param('johndóé ', PARAM_USERNAME), 'johndóé');
949 $CFG->extendedusernamechars = $currentstatus;
952 function test_clean_param_stringid() {
953 // Test string identifiers validation
954 // valid strings:
955 $this->assertEquals(clean_param('validstring', PARAM_STRINGID), 'validstring');
956 $this->assertEquals(clean_param('mod/foobar:valid_capability', PARAM_STRINGID), 'mod/foobar:valid_capability');
957 $this->assertEquals(clean_param('CZ', PARAM_STRINGID), 'CZ');
958 $this->assertEquals(clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID), 'application/vnd.ms-powerpoint');
959 $this->assertEquals(clean_param('grade2', PARAM_STRINGID), 'grade2');
960 // invalid strings:
961 $this->assertEquals(clean_param('trailing ', PARAM_STRINGID), '');
962 $this->assertEquals(clean_param('space bar', PARAM_STRINGID), '');
963 $this->assertEquals(clean_param('0numeric', PARAM_STRINGID), '');
964 $this->assertEquals(clean_param('*', PARAM_STRINGID), '');
965 $this->assertEquals(clean_param(' ', PARAM_STRINGID), '');
968 function test_clean_param_timezone() {
969 // Test timezone validation
970 $testvalues = array (
971 'America/Jamaica' => 'America/Jamaica',
972 'America/Argentina/Cordoba' => 'America/Argentina/Cordoba',
973 'America/Port-au-Prince' => 'America/Port-au-Prince',
974 'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
975 'PST8PDT' => 'PST8PDT',
976 'Wrong.Value' => '',
977 'Wrong/.Value' => '',
978 'Wrong(Value)' => '',
979 '0' => '0',
980 '0.0' => '0.0',
981 '0.5' => '0.5',
982 '9.0' => '9.0',
983 '-9.0' => '-9.0',
984 '+9.0' => '+9.0',
985 '9.5' => '9.5',
986 '-9.5' => '-9.5',
987 '+9.5' => '+9.5',
988 '12.0' => '12.0',
989 '-12.0' => '-12.0',
990 '+12.0' => '+12.0',
991 '12.5' => '12.5',
992 '-12.5' => '-12.5',
993 '+12.5' => '+12.5',
994 '13.0' => '13.0',
995 '-13.0' => '-13.0',
996 '+13.0' => '+13.0',
997 '13.5' => '',
998 '+13.5' => '',
999 '-13.5' => '',
1000 '0.2' => '');
1002 foreach ($testvalues as $testvalue => $expectedvalue) {
1003 $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
1004 $this->assertEquals($actualvalue, $expectedvalue);
1008 function test_validate_param() {
1009 try {
1010 $param = validate_param('11a', PARAM_INT);
1011 $this->fail('invalid_parameter_exception expected');
1012 } catch (invalid_parameter_exception $ex) {
1013 $this->assertTrue(true);
1015 try {
1016 $param = validate_param('11', PARAM_INT);
1017 $this->assertEquals($param, 11);
1018 } catch (invalid_parameter_exception $ex) {
1019 $this->fail('invalid_parameter_exception not expected');
1021 try {
1022 $param = validate_param(null, PARAM_INT, false);
1023 $this->fail('invalid_parameter_exception expected');
1024 } catch (invalid_parameter_exception $ex) {
1025 $this->assertTrue(true);
1027 try {
1028 $param = validate_param(null, PARAM_INT, true);
1029 $this->assertTrue($param===null);
1030 } catch (invalid_parameter_exception $ex) {
1031 $this->fail('invalid_parameter_exception expected');
1033 try {
1034 $param = validate_param(array(), PARAM_INT);
1035 $this->fail('invalid_parameter_exception expected');
1036 } catch (invalid_parameter_exception $ex) {
1037 $this->assertTrue(true);
1039 try {
1040 $param = validate_param(new stdClass, PARAM_INT);
1041 $this->fail('invalid_parameter_exception expected');
1042 } catch (invalid_parameter_exception $ex) {
1043 $this->assertTrue(true);
1045 try {
1046 $param = validate_param('1.0', PARAM_FLOAT);
1047 $this->assertSame(1.0, $param);
1049 // Make sure valid floats do not cause exception.
1050 validate_param(1.0, PARAM_FLOAT);
1051 validate_param(10, PARAM_FLOAT);
1052 validate_param('0', PARAM_FLOAT);
1053 validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
1054 validate_param('011.1', PARAM_FLOAT);
1055 validate_param('11', PARAM_FLOAT);
1056 validate_param('+.1', PARAM_FLOAT);
1057 validate_param('-.1', PARAM_FLOAT);
1058 validate_param('1e10', PARAM_FLOAT);
1059 validate_param('.1e+10', PARAM_FLOAT);
1060 validate_param('1E-1', PARAM_FLOAT);
1061 $this->assertTrue(true);
1062 } catch (invalid_parameter_exception $ex) {
1063 $this->fail('Valid float notation not accepted');
1065 try {
1066 $param = validate_param('1,2', PARAM_FLOAT);
1067 $this->fail('invalid_parameter_exception expected');
1068 } catch (invalid_parameter_exception $ex) {
1069 $this->assertTrue(true);
1071 try {
1072 $param = validate_param('', PARAM_FLOAT);
1073 $this->fail('invalid_parameter_exception expected');
1074 } catch (invalid_parameter_exception $ex) {
1075 $this->assertTrue(true);
1077 try {
1078 $param = validate_param('.', PARAM_FLOAT);
1079 $this->fail('invalid_parameter_exception expected');
1080 } catch (invalid_parameter_exception $ex) {
1081 $this->assertTrue(true);
1083 try {
1084 $param = validate_param('e10', PARAM_FLOAT);
1085 $this->fail('invalid_parameter_exception expected');
1086 } catch (invalid_parameter_exception $ex) {
1087 $this->assertTrue(true);
1089 try {
1090 $param = validate_param('abc', PARAM_FLOAT);
1091 $this->fail('invalid_parameter_exception expected');
1092 } catch (invalid_parameter_exception $ex) {
1093 $this->assertTrue(true);
1097 function test_shorten_text() {
1098 $text = "short text already no tags";
1099 $this->assertEquals($text, shorten_text($text));
1101 $text = "<p>short <b>text</b> already</p><p>with tags</p>";
1102 $this->assertEquals($text, shorten_text($text));
1104 $text = "long text without any tags blah de blah blah blah what";
1105 $this->assertEquals('long text without any tags ...', shorten_text($text));
1107 $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
1108 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
1109 $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
1110 "tags that ...</blockquote></p></div>", shorten_text($text));
1112 $text = "some text which shouldn't &nbsp; break there";
1113 $this->assertEquals("some text which shouldn't &nbsp; ...",
1114 shorten_text($text, 31));
1115 $this->assertEquals("some text which shouldn't ...",
1116 shorten_text($text, 30));
1118 // This case caused a bug up to 1.9.5
1119 $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
1120 $this->assertEquals("<h3>standard 'break-out' sub groups in ...</h3>",
1121 shorten_text($text, 43));
1123 $text = "<h1>123456789</h1>";//a string with no convenient breaks
1124 $this->assertEquals("<h1>12345...</h1>",
1125 shorten_text($text, 8));
1127 // ==== this must work with UTF-8 too! ======
1129 // text without tags
1130 $text = "Žluťoučký koníček přeskočil";
1131 $this->assertEquals($text, shorten_text($text)); // 30 chars by default
1132 $this->assertEquals("Žluťoučký koníče...", shorten_text($text, 19, true));
1133 $this->assertEquals("Žluťoučký ...", shorten_text($text, 19, false));
1134 // And try it with 2-less (that are, in bytes, the middle of a sequence)
1135 $this->assertEquals("Žluťoučký koní...", shorten_text($text, 17, true));
1136 $this->assertEquals("Žluťoučký ...", shorten_text($text, 17, false));
1138 $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
1139 $this->assertEquals($text, shorten_text($text, 60));
1140 $this->assertEquals("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
1141 $this->assertEquals("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
1142 $this->assertEquals("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
1143 // And try it with 2-less (that are, in bytes, the middle of a sequence)
1144 $this->assertEquals("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
1145 $this->assertEquals("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
1146 // And try over one tag (start/end), it does proper text len
1147 $this->assertEquals("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
1148 $this->assertEquals("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
1149 // And in the middle of one tag
1150 $this->assertEquals("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
1152 // Japanese
1153 $text = '言語設定言語設定abcdefghijkl';
1154 $this->assertEquals($text, shorten_text($text)); // 30 chars by default
1155 $this->assertEquals("言語設定言語...", shorten_text($text, 9, true));
1156 $this->assertEquals("言語設定言語...", shorten_text($text, 9, false));
1157 $this->assertEquals("言語設定言語設定ab...", shorten_text($text, 13, true));
1158 $this->assertEquals("言語設定言語設定...", shorten_text($text, 13, false));
1160 // Chinese
1161 $text = '简体中文简体中文abcdefghijkl';
1162 $this->assertEquals($text, shorten_text($text)); // 30 chars by default
1163 $this->assertEquals("简体中文简体...", shorten_text($text, 9, true));
1164 $this->assertEquals("简体中文简体...", shorten_text($text, 9, false));
1165 $this->assertEquals("简体中文简体中文ab...", shorten_text($text, 13, true));
1166 $this->assertEquals("简体中文简体中文...", shorten_text($text, 13, false));
1170 function test_usergetdate() {
1171 global $USER, $CFG, $DB;
1173 //Check if forcetimezone is set then save it and set it to use user timezone
1174 $cfgforcetimezone = null;
1175 if (isset($CFG->forcetimezone)) {
1176 $cfgforcetimezone = $CFG->forcetimezone;
1177 $CFG->forcetimezone = 99; //get user default timezone.
1180 $olduser = $USER;
1181 $USER = $DB->get_record('user', array('id'=>2)); //admin
1183 $userstimezone = $USER->timezone;
1184 $USER->timezone = 2;//set the timezone to a known state
1186 // The string version of date comes from server locale setting and does
1187 // not respect user language, so it is necessary to reset that.
1188 $oldlocale = setlocale(LC_TIME, '0');
1189 setlocale(LC_TIME, 'en_AU.UTF-8');
1191 $ts = 1261540267; //the time this function was created
1193 $arr = usergetdate($ts,1);//specify the timezone as an argument
1194 $arr = array_values($arr);
1196 list($seconds,$minutes,$hours,$mday,$wday,$mon,$year,$yday,$weekday,$month) = $arr;
1197 $this->assertSame($seconds, 7);
1198 $this->assertSame($minutes, 51);
1199 $this->assertSame($hours, 4);
1200 $this->assertSame($mday, 23);
1201 $this->assertSame($wday, 3);
1202 $this->assertSame($mon, 12);
1203 $this->assertSame($year, 2009);
1204 $this->assertSame($yday, 356);
1205 $this->assertSame($weekday, 'Wednesday');
1206 $this->assertSame($month, 'December');
1207 $arr = usergetdate($ts);//gets the timezone from the $USER object
1208 $arr = array_values($arr);
1210 list($seconds,$minutes,$hours,$mday,$wday,$mon,$year,$yday,$weekday,$month) = $arr;
1211 $this->assertSame($seconds, 7);
1212 $this->assertSame($minutes, 51);
1213 $this->assertSame($hours, 5);
1214 $this->assertSame($mday, 23);
1215 $this->assertSame($wday, 3);
1216 $this->assertSame($mon, 12);
1217 $this->assertSame($year, 2009);
1218 $this->assertSame($yday, 356);
1219 $this->assertSame($weekday, 'Wednesday');
1220 $this->assertSame($month, 'December');
1221 //set the timezone back to what it was
1222 $USER->timezone = $userstimezone;
1224 //restore forcetimezone if changed.
1225 if (!is_null($cfgforcetimezone)) {
1226 $CFG->forcetimezone = $cfgforcetimezone;
1229 setlocale(LC_TIME, $oldlocale);
1231 $USER = $olduser;
1234 public function test_normalize_component() {
1236 // moodle core
1237 $this->assertEquals(normalize_component('moodle'), array('core', null));
1238 $this->assertEquals(normalize_component('core'), array('core', null));
1240 // moodle core subsystems
1241 $this->assertEquals(normalize_component('admin'), array('core', 'admin'));
1242 $this->assertEquals(normalize_component('core_admin'), array('core', 'admin'));
1244 // activity modules and their subplugins
1245 $this->assertEquals(normalize_component('workshop'), array('mod', 'workshop'));
1246 $this->assertEquals(normalize_component('mod_workshop'), array('mod', 'workshop'));
1247 $this->assertEquals(normalize_component('workshopform_accumulative'), array('workshopform', 'accumulative'));
1248 $this->assertEquals(normalize_component('quiz'), array('mod', 'quiz'));
1249 $this->assertEquals(normalize_component('quiz_grading'), array('quiz', 'grading'));
1250 $this->assertEquals(normalize_component('data'), array('mod', 'data'));
1251 $this->assertEquals(normalize_component('datafield_checkbox'), array('datafield', 'checkbox'));
1253 // other plugin types
1254 $this->assertEquals(normalize_component('auth_mnet'), array('auth', 'mnet'));
1255 $this->assertEquals(normalize_component('enrol_self'), array('enrol', 'self'));
1256 $this->assertEquals(normalize_component('block_html'), array('block', 'html'));
1257 $this->assertEquals(normalize_component('block_mnet_hosts'), array('block', 'mnet_hosts'));
1258 $this->assertEquals(normalize_component('local_amos'), array('local', 'amos'));
1260 // unknown components are supposed to be activity modules
1261 $this->assertEquals(normalize_component('whothefuckwouldcomewithsuchastupidnameofcomponent'),
1262 array('mod', 'whothefuckwouldcomewithsuchastupidnameofcomponent'));
1263 $this->assertEquals(normalize_component('whothefuck_wouldcomewithsuchastupidnameofcomponent'),
1264 array('mod', 'whothefuck_wouldcomewithsuchastupidnameofcomponent'));
1265 $this->assertEquals(normalize_component('whothefuck_would_come_withsuchastupidnameofcomponent'),
1266 array('mod', 'whothefuck_would_come_withsuchastupidnameofcomponent'));
1269 protected function get_fake_preference_test_userid() {
1270 global $DB;
1272 // we need some nonexistent user id
1273 $id = 2147483647 - 666;
1274 if ($DB->get_records('user', array('id'=>$id))) {
1275 //weird!
1276 return false;
1278 return $id;
1281 public function test_mark_user_preferences_changed() {
1282 $this->resetAfterTest(true);
1283 if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1284 $this->fail('Can not find unused user id for the preferences test');
1285 return;
1288 set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
1289 mark_user_preferences_changed($otheruserid);
1291 $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1292 set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
1295 public function test_check_user_preferences_loaded() {
1296 global $DB;
1297 $this->resetAfterTest(true);
1299 if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1300 $this->fail('Can not find unused user id for the preferences test');
1301 return;
1304 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1305 set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
1307 $user = new stdClass();
1308 $user->id = $otheruserid;
1310 // load
1311 check_user_preferences_loaded($user);
1312 $this->assertTrue(isset($user->preference));
1313 $this->assertTrue(is_array($user->preference));
1314 $this->assertTrue(isset($user->preference['_lastloaded']));
1315 $this->assertEquals(count($user->preference), 1);
1317 // add preference via direct call
1318 $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1320 // no cache reload yet
1321 check_user_preferences_loaded($user);
1322 $this->assertEquals(count($user->preference), 1);
1324 // forced reloading of cache
1325 unset($user->preference);
1326 check_user_preferences_loaded($user);
1327 $this->assertEquals(count($user->preference), 2);
1328 $this->assertEquals($user->preference['xxx'], 'yyy');
1330 // add preference via direct call
1331 $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1333 // test timeouts and modifications from different session
1334 set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1335 $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1336 check_user_preferences_loaded($user);
1337 $this->assertEquals(count($user->preference), 2);
1338 check_user_preferences_loaded($user, 10);
1339 $this->assertEquals(count($user->preference), 3);
1340 $this->assertEquals($user->preference['aaa'], 'bbb');
1341 set_cache_flag('userpreferenceschanged', $user->id, null);
1344 public function test_set_user_preference() {
1345 global $DB, $USER;
1346 $this->resetAfterTest(true);
1348 $olduser = $USER;
1349 $USER = $DB->get_record('user', array('id'=>2)); //admin
1351 if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1352 $this->fail('Can not find unused user id for the preferences test');
1353 return;
1356 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1357 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1359 $user = new stdClass();
1360 $user->id = $otheruserid;
1362 set_user_preference('aaa', 'bbb', $otheruserid);
1363 $this->assertEquals('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1364 $this->assertEquals('bbb', get_user_preferences('aaa', null, $otheruserid));
1366 set_user_preference('xxx', 'yyy', $user);
1367 $this->assertEquals('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1368 $this->assertEquals('yyy', get_user_preferences('xxx', null, $otheruserid));
1369 $this->assertTrue(is_array($user->preference));
1370 $this->assertEquals($user->preference['aaa'], 'bbb');
1371 $this->assertEquals($user->preference['xxx'], 'yyy');
1373 set_user_preference('xxx', NULL, $user);
1374 $this->assertSame(false, $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1375 $this->assertSame(null, get_user_preferences('xxx', null, $otheruserid));
1377 set_user_preference('ooo', true, $user);
1378 $prefs = get_user_preferences(null, null, $otheruserid);
1379 $this->assertSame($prefs['aaa'], $user->preference['aaa']);
1380 $this->assertSame($prefs['ooo'], $user->preference['ooo']);
1381 $this->assertSame($prefs['ooo'], '1');
1383 set_user_preference('null', 0, $user);
1384 $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1386 $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1388 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1389 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1391 // test $USER default
1392 set_user_preference('_test_user_preferences_pref', 'ok');
1393 $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1394 unset_user_preference('_test_user_preferences_pref');
1395 $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1397 // Test 1333 char values (no need for unicode, there are already tests for that in DB tests)
1398 $longvalue = str_repeat('a', 1333);
1399 set_user_preference('_test_long_user_preference', $longvalue);
1400 $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1401 $this->assertEquals($longvalue,
1402 $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1404 // Test > 1333 char values, coding_exception expected
1405 $longvalue = str_repeat('a', 1334);
1406 try {
1407 set_user_preference('_test_long_user_preference', $longvalue);
1408 $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1409 } catch (coding_exception $ex) {
1410 $this->assertTrue(true);
1413 //test invalid params
1414 try {
1415 set_user_preference('_test_user_preferences_pref', array());
1416 $this->fail('Exception expected - array not valid preference value');
1417 } catch (coding_exception $ex) {
1418 $this->assertTrue(true);
1420 try {
1421 set_user_preference('_test_user_preferences_pref', new stdClass);
1422 $this->fail('Exception expected - class not valid preference value');
1423 } catch (coding_exception $ex) {
1424 $this->assertTrue(true);
1426 try {
1427 set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1428 $this->fail('Exception expected - user instance expected');
1429 } catch (coding_exception $ex) {
1430 $this->assertTrue(true);
1432 try {
1433 set_user_preference('_test_user_preferences_pref', 1, 'abc');
1434 $this->fail('Exception expected - user instance expected');
1435 } catch (coding_exception $ex) {
1436 $this->assertTrue(true);
1438 try {
1439 set_user_preference('', 1);
1440 $this->fail('Exception expected - invalid name accepted');
1441 } catch (coding_exception $ex) {
1442 $this->assertTrue(true);
1444 try {
1445 set_user_preference('1', 1);
1446 $this->fail('Exception expected - invalid name accepted');
1447 } catch (coding_exception $ex) {
1448 $this->assertTrue(true);
1451 $USER = $olduser;
1454 public function test_get_extra_user_fields() {
1455 global $CFG, $USER, $DB;
1456 $oldshowuseridentity = $CFG->showuseridentity;
1458 $olduser = $USER;
1459 $USER = $DB->get_record('user', array('id'=>2)); //admin
1461 // It would be really nice if there were a way to 'mock' has_capability
1462 // checks (either to return true or false) but as there is not, this
1463 // test doesn't test the capability check. Presumably, anyone running
1464 // unit tests will have the capability.
1465 $context = context_system::instance();
1467 // No fields
1468 $CFG->showuseridentity = '';
1469 $this->assertEquals(array(), get_extra_user_fields($context));
1471 // One field
1472 $CFG->showuseridentity = 'frog';
1473 $this->assertEquals(array('frog'), get_extra_user_fields($context));
1475 // Two fields
1476 $CFG->showuseridentity = 'frog,zombie';
1477 $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1479 // No fields, except
1480 $CFG->showuseridentity = '';
1481 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1483 // One field
1484 $CFG->showuseridentity = 'frog';
1485 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1487 // Two fields
1488 $CFG->showuseridentity = 'frog,zombie';
1489 $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1491 // As long as this test passes, the value will be set back. This is only
1492 // in-memory anyhow
1493 $CFG->showuseridentity = $oldshowuseridentity;
1495 $USER = $olduser;
1498 public function test_get_extra_user_fields_sql() {
1499 global $CFG, $USER, $DB;
1501 $olduser = $USER;
1502 $USER = $DB->get_record('user', array('id'=>2)); //admin
1504 $oldshowuseridentity = $CFG->showuseridentity;
1505 $context = context_system::instance();
1507 // No fields
1508 $CFG->showuseridentity = '';
1509 $this->assertEquals('', get_extra_user_fields_sql($context));
1511 // One field
1512 $CFG->showuseridentity = 'frog';
1513 $this->assertEquals(', frog', get_extra_user_fields_sql($context));
1515 // Two fields with table prefix
1516 $CFG->showuseridentity = 'frog,zombie';
1517 $this->assertEquals(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1519 // Two fields with field prefix
1520 $CFG->showuseridentity = 'frog,zombie';
1521 $this->assertEquals(', frog AS u_frog, zombie AS u_zombie',
1522 get_extra_user_fields_sql($context, '', 'u_'));
1524 // One field excluded
1525 $CFG->showuseridentity = 'frog';
1526 $this->assertEquals('', get_extra_user_fields_sql($context, '', '', array('frog')));
1528 // Two fields, one excluded, table+field prefix
1529 $CFG->showuseridentity = 'frog,zombie';
1530 $this->assertEquals(', u1.zombie AS u_zombie',
1531 get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1533 // As long as this test passes, the value will be set back. This is only
1534 // in-memory anyhow
1535 $CFG->showuseridentity = $oldshowuseridentity;
1536 $USER = $olduser;
1539 public function test_userdate() {
1540 global $USER, $CFG, $DB;
1542 $olduser = $USER;
1543 $USER = $DB->get_record('user', array('id'=>2)); //admin
1545 $testvalues = array(
1546 array(
1547 'time' => '1309514400',
1548 'usertimezone' => 'America/Moncton',
1549 'timezone' => '0.0', //no dst offset
1550 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1552 array(
1553 'time' => '1309514400',
1554 'usertimezone' => 'America/Moncton',
1555 'timezone' => '99', //dst offset and timezone offset.
1556 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1558 array(
1559 'time' => '1309514400',
1560 'usertimezone' => 'America/Moncton',
1561 'timezone' => 'America/Moncton', //dst offset and timezone offset.
1562 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1564 array(
1565 'time' => '1293876000 ',
1566 'usertimezone' => 'America/Moncton',
1567 'timezone' => '0.0', //no dst offset
1568 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1570 array(
1571 'time' => '1293876000 ',
1572 'usertimezone' => 'America/Moncton',
1573 'timezone' => '99', //no dst offset in jan, so just timezone offset.
1574 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1576 array(
1577 'time' => '1293876000 ',
1578 'usertimezone' => 'America/Moncton',
1579 'timezone' => 'America/Moncton', //no dst offset in jan
1580 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1582 array(
1583 'time' => '1293876000 ',
1584 'usertimezone' => '2',
1585 'timezone' => '99', //take user timezone
1586 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1588 array(
1589 'time' => '1293876000 ',
1590 'usertimezone' => '-2',
1591 'timezone' => '99', //take user timezone
1592 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1594 array(
1595 'time' => '1293876000 ',
1596 'usertimezone' => '-10',
1597 'timezone' => '2', //take this timezone
1598 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1600 array(
1601 'time' => '1293876000 ',
1602 'usertimezone' => '-10',
1603 'timezone' => '-2', //take this timezone
1604 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1606 array(
1607 'time' => '1293876000 ',
1608 'usertimezone' => '-10',
1609 'timezone' => 'random/time', //this should show server time
1610 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1612 array(
1613 'time' => '1293876000 ',
1614 'usertimezone' => '14', //server time zone
1615 'timezone' => '99', //this should show user time
1616 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1620 //Check if forcetimezone is set then save it and set it to use user timezone
1621 $cfgforcetimezone = null;
1622 if (isset($CFG->forcetimezone)) {
1623 $cfgforcetimezone = $CFG->forcetimezone;
1624 $CFG->forcetimezone = 99; //get user default timezone.
1626 //store user default timezone to restore later
1627 $userstimezone = $USER->timezone;
1629 // The string version of date comes from server locale setting and does
1630 // not respect user language, so it is necessary to reset that.
1631 $oldlocale = setlocale(LC_TIME, '0');
1632 setlocale(LC_TIME, 'en_AU.UTF-8');
1634 //set default timezone to Australia/Perth, else time calculated
1635 //will not match expected values. Before that save system defaults.
1636 $systemdefaulttimezone = date_default_timezone_get();
1637 date_default_timezone_set('Australia/Perth');
1639 foreach ($testvalues as $vals) {
1640 $USER->timezone = $vals['usertimezone'];
1641 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1643 //On different systems case of AM PM changes so compare case insensitive
1644 $vals['expectedoutput'] = textlib::strtolower($vals['expectedoutput']);
1645 $actualoutput = textlib::strtolower($actualoutput);
1647 $this->assertEquals($vals['expectedoutput'], $actualoutput,
1648 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1649 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1652 //restore user timezone back to what it was
1653 $USER->timezone = $userstimezone;
1655 //restore forcetimezone
1656 if (!is_null($cfgforcetimezone)) {
1657 $CFG->forcetimezone = $cfgforcetimezone;
1660 //restore system default values.
1661 date_default_timezone_set($systemdefaulttimezone);
1662 setlocale(LC_TIME, $oldlocale);
1664 $USER = $olduser;
1667 public function test_make_timestamp() {
1668 global $USER, $CFG, $DB;
1670 $olduser = $USER;
1671 $USER = $DB->get_record('user', array('id'=>2)); //admin
1673 $testvalues = array(
1674 array(
1675 'usertimezone' => 'America/Moncton',
1676 'year' => '2011',
1677 'month' => '7',
1678 'day' => '1',
1679 'hour' => '10',
1680 'minutes' => '00',
1681 'seconds' => '00',
1682 'timezone' => '0.0',
1683 'applydst' => false, //no dst offset
1684 'expectedoutput' => '1309514400' // 6pm at UTC+0
1686 array(
1687 'usertimezone' => 'America/Moncton',
1688 'year' => '2011',
1689 'month' => '7',
1690 'day' => '1',
1691 'hour' => '10',
1692 'minutes' => '00',
1693 'seconds' => '00',
1694 'timezone' => '99', //user default timezone
1695 'applydst' => false, //don't apply dst
1696 'expectedoutput' => '1309528800'
1698 array(
1699 'usertimezone' => 'America/Moncton',
1700 'year' => '2011',
1701 'month' => '7',
1702 'day' => '1',
1703 'hour' => '10',
1704 'minutes' => '00',
1705 'seconds' => '00',
1706 'timezone' => '99', //user default timezone
1707 'applydst' => true, //apply dst
1708 'expectedoutput' => '1309525200'
1710 array(
1711 'usertimezone' => 'America/Moncton',
1712 'year' => '2011',
1713 'month' => '7',
1714 'day' => '1',
1715 'hour' => '10',
1716 'minutes' => '00',
1717 'seconds' => '00',
1718 'timezone' => 'America/Moncton', //string timezone
1719 'applydst' => true, //apply dst
1720 'expectedoutput' => '1309525200'
1722 array(
1723 'usertimezone' => '2',//no dst applyed
1724 'year' => '2011',
1725 'month' => '7',
1726 'day' => '1',
1727 'hour' => '10',
1728 'minutes' => '00',
1729 'seconds' => '00',
1730 'timezone' => '99', //take user timezone
1731 'applydst' => true, //apply dst
1732 'expectedoutput' => '1309507200'
1734 array(
1735 'usertimezone' => '-2',//no dst applyed
1736 'year' => '2011',
1737 'month' => '7',
1738 'day' => '1',
1739 'hour' => '10',
1740 'minutes' => '00',
1741 'seconds' => '00',
1742 'timezone' => '99', //take usertimezone
1743 'applydst' => true, //apply dst
1744 'expectedoutput' => '1309521600'
1746 array(
1747 'usertimezone' => '-10',//no dst applyed
1748 'year' => '2011',
1749 'month' => '7',
1750 'day' => '1',
1751 'hour' => '10',
1752 'minutes' => '00',
1753 'seconds' => '00',
1754 'timezone' => '2', //take this timezone
1755 'applydst' => true, //apply dst
1756 'expectedoutput' => '1309507200'
1758 array(
1759 'usertimezone' => '-10',//no dst applyed
1760 'year' => '2011',
1761 'month' => '7',
1762 'day' => '1',
1763 'hour' => '10',
1764 'minutes' => '00',
1765 'seconds' => '00',
1766 'timezone' => '-2', //take this timezone
1767 'applydst' => true, //apply dst,
1768 'expectedoutput' => '1309521600'
1770 array(
1771 'usertimezone' => '-10',//no dst applyed
1772 'year' => '2011',
1773 'month' => '7',
1774 'day' => '1',
1775 'hour' => '10',
1776 'minutes' => '00',
1777 'seconds' => '00',
1778 'timezone' => 'random/time', //This should show server time
1779 'applydst' => true, //apply dst,
1780 'expectedoutput' => '1309485600'
1782 array(
1783 'usertimezone' => '14',//server time
1784 'year' => '2011',
1785 'month' => '7',
1786 'day' => '1',
1787 'hour' => '10',
1788 'minutes' => '00',
1789 'seconds' => '00',
1790 'timezone' => '99', //get user time
1791 'applydst' => true, //apply dst,
1792 'expectedoutput' => '1309485600'
1796 //Check if forcetimezone is set then save it and set it to use user timezone
1797 $cfgforcetimezone = null;
1798 if (isset($CFG->forcetimezone)) {
1799 $cfgforcetimezone = $CFG->forcetimezone;
1800 $CFG->forcetimezone = 99; //get user default timezone.
1803 //store user default timezone to restore later
1804 $userstimezone = $USER->timezone;
1806 // The string version of date comes from server locale setting and does
1807 // not respect user language, so it is necessary to reset that.
1808 $oldlocale = setlocale(LC_TIME, '0');
1809 setlocale(LC_TIME, 'en_AU.UTF-8');
1811 //set default timezone to Australia/Perth, else time calulated
1812 //will not match expected values. Before that save system defaults.
1813 $systemdefaulttimezone = date_default_timezone_get();
1814 date_default_timezone_set('Australia/Perth');
1816 //Test make_timestamp with all testvals and assert if anything wrong.
1817 foreach ($testvalues as $vals) {
1818 $USER->timezone = $vals['usertimezone'];
1819 $actualoutput = make_timestamp(
1820 $vals['year'],
1821 $vals['month'],
1822 $vals['day'],
1823 $vals['hour'],
1824 $vals['minutes'],
1825 $vals['seconds'],
1826 $vals['timezone'],
1827 $vals['applydst']
1830 //On different systems case of AM PM changes so compare case insenitive
1831 $vals['expectedoutput'] = textlib::strtolower($vals['expectedoutput']);
1832 $actualoutput = textlib::strtolower($actualoutput);
1834 $this->assertEquals($vals['expectedoutput'], $actualoutput,
1835 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1836 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1839 //restore user timezone back to what it was
1840 $USER->timezone = $userstimezone;
1842 //restore forcetimezone
1843 if (!is_null($cfgforcetimezone)) {
1844 $CFG->forcetimezone = $cfgforcetimezone;
1847 //restore system default values.
1848 date_default_timezone_set($systemdefaulttimezone);
1849 setlocale(LC_TIME, $oldlocale);
1851 $USER = $olduser;
1855 * Test get_string and most importantly the implementation of the lang_string
1856 * object.
1858 public function test_get_string() {
1859 global $COURSE;
1861 // Make sure we are using English
1862 $originallang = $COURSE->lang;
1863 $COURSE->lang = 'en';
1865 $yes = get_string('yes');
1866 $yesexpected = 'Yes';
1867 $this->assertEquals(getType($yes), 'string');
1868 $this->assertEquals($yes, $yesexpected);
1870 $yes = get_string('yes', 'moodle');
1871 $this->assertEquals(getType($yes), 'string');
1872 $this->assertEquals($yes, $yesexpected);
1874 $yes = get_string('yes', 'core');
1875 $this->assertEquals(getType($yes), 'string');
1876 $this->assertEquals($yes, $yesexpected);
1878 $yes = get_string('yes', '');
1879 $this->assertEquals(getType($yes), 'string');
1880 $this->assertEquals($yes, $yesexpected);
1882 $yes = get_string('yes', null);
1883 $this->assertEquals(getType($yes), 'string');
1884 $this->assertEquals($yes, $yesexpected);
1886 $yes = get_string('yes', null, 1);
1887 $this->assertEquals(getType($yes), 'string');
1888 $this->assertEquals($yes, $yesexpected);
1890 $days = 1;
1891 $numdays = get_string('numdays', 'core', '1');
1892 $numdaysexpected = $days.' days';
1893 $this->assertEquals(getType($numdays), 'string');
1894 $this->assertEquals($numdays, $numdaysexpected);
1896 $yes = get_string('yes', null, null, true);
1897 $this->assertEquals(get_class($yes), 'lang_string');
1898 $this->assertEquals((string)$yes, $yesexpected);
1900 // Test using a lang_string object as the $a argument for a normal
1901 // get_string call (returning string)
1902 $test = new lang_string('yes', null, null, true);
1903 $testexpected = get_string('numdays', 'core', get_string('yes'));
1904 $testresult = get_string('numdays', null, $test);
1905 $this->assertEquals(getType($testresult), 'string');
1906 $this->assertEquals($testresult, $testexpected);
1908 // Test using a lang_string object as the $a argument for an object
1909 // get_string call (returning lang_string)
1910 $test = new lang_string('yes', null, null, true);
1911 $testexpected = get_string('numdays', 'core', get_string('yes'));
1912 $testresult = get_string('numdays', null, $test, true);
1913 $this->assertEquals(get_class($testresult), 'lang_string');
1914 $this->assertEquals("$testresult", $testexpected);
1916 // Make sure that object properties that can't be converted don't cause
1917 // errors
1918 // Level one: This is as deep as current language processing goes
1919 $test = new stdClass;
1920 $test->one = 'here';
1921 $string = get_string('yes', null, $test, true);
1922 $this->assertEquals($string, $yesexpected);
1924 // Make sure that object properties that can't be converted don't cause
1925 // errors.
1926 // Level two: Language processing doesn't currently reach this deep.
1927 // only immediate scalar properties are worked with.
1928 $test = new stdClass;
1929 $test->one = new stdClass;
1930 $test->one->two = 'here';
1931 $string = get_string('yes', null, $test, true);
1932 $this->assertEquals($string, $yesexpected);
1934 // Make sure that object properties that can't be converted don't cause
1935 // errors.
1936 // Level three: It should never ever go this deep, but we're making sure
1937 // it doesn't cause any probs anyway.
1938 $test = new stdClass;
1939 $test->one = new stdClass;
1940 $test->one->two = new stdClass;
1941 $test->one->two->three = 'here';
1942 $string = get_string('yes', null, $test, true);
1943 $this->assertEquals($string, $yesexpected);
1945 // Make sure that object properties that can't be converted don't cause
1946 // errors and check lang_string properties.
1947 // Level one: This is as deep as current language processing goes
1948 $test = new stdClass;
1949 $test->one = new lang_string('yes');
1950 $string = get_string('yes', null, $test, true);
1951 $this->assertEquals($string, $yesexpected);
1953 // Make sure that object properties that can't be converted don't cause
1954 // errors and check lang_string properties.
1955 // Level two: Language processing doesn't currently reach this deep.
1956 // only immediate scalar properties are worked with.
1957 $test = new stdClass;
1958 $test->one = new stdClass;
1959 $test->one->two = new lang_string('yes');
1960 $string = get_string('yes', null, $test, true);
1961 $this->assertEquals($string, $yesexpected);
1963 // Make sure that object properties that can't be converted don't cause
1964 // errors and check lang_string properties.
1965 // Level three: It should never ever go this deep, but we're making sure
1966 // it doesn't cause any probs anyway.
1967 $test = new stdClass;
1968 $test->one = new stdClass;
1969 $test->one->two = new stdClass;
1970 $test->one->two->three = new lang_string('yes');
1971 $string = get_string('yes', null, $test, true);
1972 $this->assertEquals($string, $yesexpected);
1974 // Make sure that array properties that can't be converted don't cause
1975 // errors
1976 $test = array();
1977 $test['one'] = new stdClass;
1978 $test['one']->two = 'here';
1979 $string = get_string('yes', null, $test, true);
1980 $this->assertEquals($string, $yesexpected);
1982 // Same thing but as above except using an object... this is allowed :P
1983 $string = get_string('yes', null, null, true);
1984 $object = new stdClass;
1985 $object->$string = 'Yes';
1986 $this->assertEquals($string, $yesexpected);
1987 $this->assertEquals($object->$string, $yesexpected);
1989 // Reset the language
1990 $COURSE->lang = $originallang;
1994 * @expectedException PHPUnit_Framework_Error_Warning
1995 * @return void
1997 public function test_get_string_limitation() {
1998 // This is one of the limitations to the lang_string class. It can't be
1999 // used as a key
2000 $array = array(get_string('yes', null, null, true) => 'yes');
2004 * Test localised float formatting.
2006 public function test_format_float() {
2007 global $SESSION, $CFG;
2009 // Special case for null
2010 $this->assertEquals('', format_float(null));
2012 // Default 1 decimal place
2013 $this->assertEquals('5.4', format_float(5.43));
2014 $this->assertEquals('5.0', format_float(5.001));
2016 // Custom number of decimal places
2017 $this->assertEquals('5.43000', format_float(5.43, 5));
2019 // Option to strip ending zeros after rounding
2020 $this->assertEquals('5.43', format_float(5.43, 5, true, true));
2021 $this->assertEquals('5', format_float(5.0001, 3, true, true));
2023 // It is not possible to directly change the result of get_string in
2024 // a unit test. Instead, we create a language pack for language 'xx' in
2025 // dataroot and make langconfig.php with the string we need to change.
2026 // The example separator used here is 'X'; on PHP 5.3 and before this
2027 // must be a single byte character due to PHP bug/limitation in
2028 // number_format, so you can't use UTF-8 characters.
2029 $SESSION->lang = 'xx';
2030 $langconfig = "<?php\n\$string['decsep'] = 'X';";
2031 $langfolder = $CFG->dataroot . '/lang/xx';
2032 check_dir_exists($langfolder);
2033 file_put_contents($langfolder . '/langconfig.php', $langconfig);
2035 // Localisation on (default)
2036 $this->assertEquals('5X43000', format_float(5.43, 5));
2037 $this->assertEquals('5X43', format_float(5.43, 5, true, true));
2039 // Localisation off
2040 $this->assertEquals('5.43000', format_float(5.43, 5, false));
2041 $this->assertEquals('5.43', format_float(5.43, 5, false, true));
2045 * Test deleting of users.
2047 public function test_delete_user() {
2048 global $DB, $CFG;
2050 $this->resetAfterTest();
2052 $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
2053 $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
2054 $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
2056 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2057 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2059 $result = delete_user($user);
2060 $this->assertTrue($result);
2061 $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
2062 $this->assertEquals(1, $deluser->deleted);
2063 $this->assertEquals(0, $deluser->picture);
2064 $this->assertSame('', $deluser->idnumber);
2065 $this->assertSame(md5($user->username), $deluser->email);
2066 $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
2068 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2070 // Try invalid params.
2072 $record = new stdClass();
2073 $record->grrr = 1;
2074 try {
2075 delete_user($record);
2076 $this->fail('Expecting exception for invalid delete_user() $user parameter');
2077 } catch (coding_exception $e) {
2078 $this->assertTrue(true);
2080 $record->id = 1;
2081 try {
2082 delete_user($record);
2083 $this->fail('Expecting exception for invalid delete_user() $user parameter');
2084 } catch (coding_exception $e) {
2085 $this->assertTrue(true);
2088 $CFG->debug = DEBUG_MINIMAL; // Prevent standard debug warnings.
2090 $record = new stdClass();
2091 $record->id = 666;
2092 $record->username = 'xx';
2093 $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2094 $result = delete_user($record);
2095 $this->assertFalse($result);
2097 $result = delete_user($guest);
2098 $this->assertFalse($result);
2100 $result = delete_user($admin);
2101 $this->assertFalse($result);
2105 * Test function convert_to_array()
2107 public function test_convert_to_array() {
2108 // check that normal classes are converted to arrays the same way as (array) would do
2109 $obj = new stdClass();
2110 $obj->prop1 = 'hello';
2111 $obj->prop2 = array('first', 'second', 13);
2112 $obj->prop3 = 15;
2113 $this->assertEquals(convert_to_array($obj), (array)$obj);
2115 // check that context object (with iterator) is converted to array properly
2116 $obj = get_system_context();
2117 $ar = array(
2118 'id' => $obj->id,
2119 'contextlevel' => $obj->contextlevel,
2120 'instanceid' => $obj->instanceid,
2121 'path' => $obj->path,
2122 'depth' => $obj->depth
2124 $this->assertEquals(convert_to_array($obj), $ar);
2128 * Test the function date_format_string().
2130 function test_date_format_string() {
2131 // Forcing locale and timezone.
2132 $oldlocale = setlocale(LC_TIME, '0');
2133 setlocale(LC_TIME, 'en_AU.UTF-8');
2134 $systemdefaulttimezone = date_default_timezone_get();
2135 date_default_timezone_set('Australia/Perth');
2137 $tests = array(
2138 array(
2139 'tz' => 99,
2140 'str' => '%A, %d %B %Y, %I:%M %p',
2141 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2143 array(
2144 'tz' => 0,
2145 'str' => '%A, %d %B %Y, %I:%M %p',
2146 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2148 array(
2149 'tz' => -12,
2150 'str' => '%A, %d %B %Y, %I:%M %p',
2151 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2153 array(
2154 'tz' => 99,
2155 'str' => 'Žluťoučký koníček %A',
2156 'expected' => 'Žluťoučký koníček Saturday'
2158 array(
2159 'tz' => 99,
2160 'str' => '言語設定言語 %A',
2161 'expected' => '言語設定言語 Saturday'
2163 array(
2164 'tz' => 99,
2165 'str' => '简体中文简体 %A',
2166 'expected' => '简体中文简体 Saturday'
2170 // Note: date_format_string() uses the timezone only to differenciate
2171 // the server time from the UTC time. It does not modify the timestamp.
2172 // Hence similar results for timezones <= 13.
2173 // On different systems case of AM PM changes so compare case insensitive.
2174 foreach ($tests as $test) {
2175 $str = date_format_string(1293876000, $test['str'], $test['tz']);
2176 $this->assertEquals(textlib::strtolower($test['expected']), textlib::strtolower($str));
2179 // Restore system default values.
2180 date_default_timezone_set($systemdefaulttimezone);
2181 setlocale(LC_TIME, $oldlocale);