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