weekly release 2.6dev
[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
5f850735
TH
800 function test_is_valid_plugin_name() {
801 $this->assertTrue(is_valid_plugin_name('forum'));
802 $this->assertTrue(is_valid_plugin_name('forum2'));
803 $this->assertTrue(is_valid_plugin_name('online_users'));
804 $this->assertTrue(is_valid_plugin_name('blond_online_users'));
805 $this->assertFalse(is_valid_plugin_name('online__users'));
806 $this->assertFalse(is_valid_plugin_name('forum '));
807 $this->assertFalse(is_valid_plugin_name('forum.old'));
808 $this->assertFalse(is_valid_plugin_name('xx-yy'));
809 $this->assertFalse(is_valid_plugin_name('2xx'));
810 $this->assertFalse(is_valid_plugin_name('Xx'));
811 $this->assertFalse(is_valid_plugin_name('_xx'));
812 $this->assertFalse(is_valid_plugin_name('xx_'));
813 }
814
a3d5830a
PS
815 function test_clean_param_plugin() {
816 // please note the cleaning of plugin names is very strict, no guessing here
817 $this->assertSame(clean_param('forum', PARAM_PLUGIN), 'forum');
818 $this->assertSame(clean_param('forum2', PARAM_PLUGIN), 'forum2');
819 $this->assertSame(clean_param('online_users', PARAM_PLUGIN), 'online_users');
820 $this->assertSame(clean_param('blond_online_users', PARAM_PLUGIN), 'blond_online_users');
821 $this->assertSame(clean_param('online__users', PARAM_PLUGIN), '');
822 $this->assertSame(clean_param('forum ', PARAM_PLUGIN), '');
823 $this->assertSame(clean_param('forum.old', PARAM_PLUGIN), '');
824 $this->assertSame(clean_param('xx-yy', PARAM_PLUGIN), '');
825 $this->assertSame(clean_param('2xx', PARAM_PLUGIN), '');
826 $this->assertSame(clean_param('Xx', PARAM_PLUGIN), '');
827 $this->assertSame(clean_param('_xx', PARAM_PLUGIN), '');
828 $this->assertSame(clean_param('xx_', PARAM_PLUGIN), '');
829 }
830
831 function test_clean_param_area() {
832 // please note the cleaning of area names is very strict, no guessing here
833 $this->assertSame(clean_param('something', PARAM_AREA), 'something');
834 $this->assertSame(clean_param('something2', PARAM_AREA), 'something2');
835 $this->assertSame(clean_param('some_thing', PARAM_AREA), 'some_thing');
836 $this->assertSame(clean_param('some_thing_xx', PARAM_AREA), 'some_thing_xx');
837 $this->assertSame(clean_param('_something', PARAM_AREA), '');
838 $this->assertSame(clean_param('something_', PARAM_AREA), '');
839 $this->assertSame(clean_param('2something', PARAM_AREA), '');
840 $this->assertSame(clean_param('Something', PARAM_AREA), '');
841 $this->assertSame(clean_param('some-thing', PARAM_AREA), '');
842 $this->assertSame(clean_param('somethííng', PARAM_AREA), '');
843 $this->assertSame(clean_param('something.x', PARAM_AREA), '');
844 }
845
846 function test_clean_param_text() {
847 $this->assertEquals(PARAM_TEXT, PARAM_MULTILANG);
848 //standard
849 $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>');
850 $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>');
851 $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>');
852 //malformed
853 $this->assertEquals(clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT), '<span lang="en" class="multilang">aa</span>');
854 $this->assertEquals(clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT), 'aa');
855 $this->assertEquals(clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT), 'aa');
856 $this->assertEquals(clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT), 'aa');
857 $this->assertEquals(clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT), 'aa');
858 $this->assertEquals(clean_param('a<em>b</em>c', PARAM_TEXT), 'abc');
859 $this->assertEquals(clean_param('a><xx >c>', PARAM_TEXT), 'a>c>'); // standard strip_tags() behaviour
860 $this->assertEquals(clean_param('a<b', PARAM_TEXT), 'a');
861 $this->assertEquals(clean_param('a>b', PARAM_TEXT), 'a>b');
862 $this->assertEquals(clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT), '<lang lang="en">a>a</lang>'); // standard strip_tags() behaviour
863 $this->assertEquals(clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT), 'a');
864 $this->assertEquals(clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT), '<lang lang="en">aa</lang>');
865 }
866
867 function test_clean_param_url() {
868 // Test PARAM_URL and PARAM_LOCALURL a bit
869 $this->assertEquals(clean_param('http://google.com/', PARAM_URL), 'http://google.com/');
870 $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/');
871 $this->assertEquals(clean_param('http://localhost/', PARAM_URL), 'http://localhost/');
872 $this->assertEquals(clean_param('http://0.255.1.1/numericip.php', PARAM_URL), 'http://0.255.1.1/numericip.php');
873 $this->assertEquals(clean_param('/just/a/path', PARAM_URL), '/just/a/path');
874 $this->assertEquals(clean_param('funny:thing', PARAM_URL), '');
875 }
876
877 function test_clean_param_localurl() {
878 global $CFG;
879 $this->assertEquals(clean_param('http://google.com/', PARAM_LOCALURL), '');
880 $this->assertEquals(clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL), '');
881 $this->assertEquals(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
882 $this->assertEquals(clean_param('/just/a/path', PARAM_LOCALURL), '/just/a/path');
883 $this->assertEquals(clean_param('funny:thing', PARAM_LOCALURL), '');
884 $this->assertEquals(clean_param('course/view.php?id=3', PARAM_LOCALURL), 'course/view.php?id=3');
885 }
886
887 function test_clean_param_file() {
888 $this->assertEquals(clean_param('correctfile.txt', PARAM_FILE), 'correctfile.txt');
889 $this->assertEquals(clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE), 'badfile.txt');
caf16a57
FM
890 $this->assertEquals(clean_param('../parentdirfile.txt', PARAM_FILE), '..parentdirfile.txt');
891 $this->assertEquals(clean_param('../../grandparentdirfile.txt', PARAM_FILE), '....grandparentdirfile.txt');
892 $this->assertEquals(clean_param('..\winparentdirfile.txt', PARAM_FILE), '..winparentdirfile.txt');
31a78330 893 $this->assertEquals(clean_param('..\..\wingrandparentdir.txt', PARAM_FILE), '....wingrandparentdir.txt');
caf16a57
FM
894 $this->assertEquals(clean_param('myfile.a.b.txt', PARAM_FILE), 'myfile.a.b.txt');
895 $this->assertEquals(clean_param('myfile..a..b.txt', PARAM_FILE), 'myfile..a..b.txt');
896 $this->assertEquals(clean_param('myfile.a..b...txt', PARAM_FILE), 'myfile.a..b...txt');
897 $this->assertEquals(clean_param('myfile.a.txt', PARAM_FILE), 'myfile.a.txt');
898 $this->assertEquals(clean_param('myfile...txt', PARAM_FILE), 'myfile...txt');
899 $this->assertEquals(clean_param('...jpg', PARAM_FILE), '...jpg');
900 $this->assertEquals(clean_param('.a.b.', PARAM_FILE), '.a.b.');
901 $this->assertEquals(clean_param('.', PARAM_FILE), '');
902 $this->assertEquals(clean_param('..', PARAM_FILE), '');
903 $this->assertEquals(clean_param('...', PARAM_FILE), '...');
904 $this->assertEquals(clean_param('. . . .', PARAM_FILE), '. . . .');
905 $this->assertEquals(clean_param('dontrtrim.me. .. .. . ', PARAM_FILE), 'dontrtrim.me. .. .. . ');
906 $this->assertEquals(clean_param(' . .dontltrim.me', PARAM_FILE), ' . .dontltrim.me');
907 $this->assertEquals(clean_param("here is a tab\t.txt", PARAM_FILE), 'here is a tab.txt');
908 $this->assertEquals(clean_param("here is a line\r\nbreak.txt", PARAM_FILE), 'here is a linebreak.txt');
909
a3d5830a
PS
910 //The following behaviours have been maintained although they seem a little odd
911 $this->assertEquals(clean_param('funny:thing', PARAM_FILE), 'funnything');
912 $this->assertEquals(clean_param('./currentdirfile.txt', PARAM_FILE), '.currentdirfile.txt');
913 $this->assertEquals(clean_param('c:\temp\windowsfile.txt', PARAM_FILE), 'ctempwindowsfile.txt');
914 $this->assertEquals(clean_param('/home/user/linuxfile.txt', PARAM_FILE), 'homeuserlinuxfile.txt');
915 $this->assertEquals(clean_param('~/myfile.txt', PARAM_FILE), '~myfile.txt');
916 }
917
caf16a57
FM
918 function test_clean_param_path() {
919 $this->assertEquals(clean_param('correctfile.txt', PARAM_PATH), 'correctfile.txt');
920 $this->assertEquals(clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH), 'bad/file.txt');
921 $this->assertEquals(clean_param('../parentdirfile.txt', PARAM_PATH), '/parentdirfile.txt');
922 $this->assertEquals(clean_param('../../grandparentdirfile.txt', PARAM_PATH), '/grandparentdirfile.txt');
923 $this->assertEquals(clean_param('..\winparentdirfile.txt', PARAM_PATH), '/winparentdirfile.txt');
31a78330 924 $this->assertEquals(clean_param('..\..\wingrandparentdir.txt', PARAM_PATH), '/wingrandparentdir.txt');
caf16a57
FM
925 $this->assertEquals(clean_param('funny:thing', PARAM_PATH), 'funnything');
926 $this->assertEquals(clean_param('./././here', PARAM_PATH), './here');
927 $this->assertEquals(clean_param('./currentdirfile.txt', PARAM_PATH), './currentdirfile.txt');
928 $this->assertEquals(clean_param('c:\temp\windowsfile.txt', PARAM_PATH), 'c/temp/windowsfile.txt');
929 $this->assertEquals(clean_param('/home/user/linuxfile.txt', PARAM_PATH), '/home/user/linuxfile.txt');
930 $this->assertEquals(clean_param('/home../user ./.linuxfile.txt', PARAM_PATH), '/home../user ./.linuxfile.txt');
931 $this->assertEquals(clean_param('~/myfile.txt', PARAM_PATH), '~/myfile.txt');
932 $this->assertEquals(clean_param('~/../myfile.txt', PARAM_PATH), '~/myfile.txt');
933 $this->assertEquals(clean_param('/..b../.../myfile.txt', PARAM_PATH), '/..b../.../myfile.txt');
934 $this->assertEquals(clean_param('..b../.../myfile.txt', PARAM_PATH), '..b../.../myfile.txt');
935 $this->assertEquals(clean_param('/super//slashes///', PARAM_PATH), '/super/slashes/');
936 }
937
a3d5830a
PS
938 function test_clean_param_username() {
939 global $CFG;
940 $currentstatus = $CFG->extendedusernamechars;
941
942 // Run tests with extended character == FALSE;
943 $CFG->extendedusernamechars = FALSE;
944 $this->assertEquals(clean_param('johndoe123', PARAM_USERNAME), 'johndoe123' );
945 $this->assertEquals(clean_param('john.doe', PARAM_USERNAME), 'john.doe');
946 $this->assertEquals(clean_param('john-doe', PARAM_USERNAME), 'john-doe');
947 $this->assertEquals(clean_param('john- doe', PARAM_USERNAME), 'john-doe');
948 $this->assertEquals(clean_param('john_doe', PARAM_USERNAME), 'john_doe');
949 $this->assertEquals(clean_param('john@doe', PARAM_USERNAME), 'john@doe');
950 $this->assertEquals(clean_param('john~doe', PARAM_USERNAME), 'johndoe');
951 $this->assertEquals(clean_param('john´doe', PARAM_USERNAME), 'johndoe');
952 $this->assertEquals(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
953 $this->assertEquals(clean_param('JOHNdóé ', PARAM_USERNAME), 'johnd');
954 $this->assertEquals(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá\9e?\9eý??\9adoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
955
956
957 // Test success condition, if extendedusernamechars == ENABLE;
958 $CFG->extendedusernamechars = TRUE;
959 $this->assertEquals(clean_param('john_doe', PARAM_USERNAME), 'john_doe');
960 $this->assertEquals(clean_param('john@doe', PARAM_USERNAME), 'john@doe');
961 $this->assertEquals(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john#$%&()+_^');
962 $this->assertEquals(clean_param('john~doe', PARAM_USERNAME), 'john~doe');
963 $this->assertEquals(clean_param('joHN´doe', PARAM_USERNAME), 'john´doe');
964 $this->assertEquals(clean_param('johnDOE', PARAM_USERNAME), 'johndoe');
965 $this->assertEquals(clean_param('johndóé ', PARAM_USERNAME), 'johndóé');
966
967 $CFG->extendedusernamechars = $currentstatus;
968 }
969
970 function test_clean_param_stringid() {
971 // Test string identifiers validation
972 // valid strings:
973 $this->assertEquals(clean_param('validstring', PARAM_STRINGID), 'validstring');
974 $this->assertEquals(clean_param('mod/foobar:valid_capability', PARAM_STRINGID), 'mod/foobar:valid_capability');
975 $this->assertEquals(clean_param('CZ', PARAM_STRINGID), 'CZ');
976 $this->assertEquals(clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID), 'application/vnd.ms-powerpoint');
977 $this->assertEquals(clean_param('grade2', PARAM_STRINGID), 'grade2');
978 // invalid strings:
979 $this->assertEquals(clean_param('trailing ', PARAM_STRINGID), '');
980 $this->assertEquals(clean_param('space bar', PARAM_STRINGID), '');
981 $this->assertEquals(clean_param('0numeric', PARAM_STRINGID), '');
982 $this->assertEquals(clean_param('*', PARAM_STRINGID), '');
983 $this->assertEquals(clean_param(' ', PARAM_STRINGID), '');
984 }
985
986 function test_clean_param_timezone() {
987 // Test timezone validation
988 $testvalues = array (
989 'America/Jamaica' => 'America/Jamaica',
990 'America/Argentina/Cordoba' => 'America/Argentina/Cordoba',
991 'America/Port-au-Prince' => 'America/Port-au-Prince',
992 'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
993 'PST8PDT' => 'PST8PDT',
994 'Wrong.Value' => '',
995 'Wrong/.Value' => '',
996 'Wrong(Value)' => '',
997 '0' => '0',
998 '0.0' => '0.0',
999 '0.5' => '0.5',
8158ce79
JM
1000 '9.0' => '9.0',
1001 '-9.0' => '-9.0',
1002 '+9.0' => '+9.0',
1003 '9.5' => '9.5',
1004 '-9.5' => '-9.5',
1005 '+9.5' => '+9.5',
1006 '12.0' => '12.0',
1007 '-12.0' => '-12.0',
1008 '+12.0' => '+12.0',
1009 '12.5' => '12.5',
a3d5830a
PS
1010 '-12.5' => '-12.5',
1011 '+12.5' => '+12.5',
8158ce79
JM
1012 '13.0' => '13.0',
1013 '-13.0' => '-13.0',
1014 '+13.0' => '+13.0',
a3d5830a 1015 '13.5' => '',
8158ce79 1016 '+13.5' => '',
a3d5830a
PS
1017 '-13.5' => '',
1018 '0.2' => '');
1019
1020 foreach ($testvalues as $testvalue => $expectedvalue) {
1021 $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
1022 $this->assertEquals($actualvalue, $expectedvalue);
1023 }
1024 }
1025
1026 function test_validate_param() {
1027 try {
1028 $param = validate_param('11a', PARAM_INT);
1029 $this->fail('invalid_parameter_exception expected');
1030 } catch (invalid_parameter_exception $ex) {
1031 $this->assertTrue(true);
1032 }
1033 try {
1034 $param = validate_param('11', PARAM_INT);
1035 $this->assertEquals($param, 11);
1036 } catch (invalid_parameter_exception $ex) {
1037 $this->fail('invalid_parameter_exception not expected');
1038 }
1039 try {
1040 $param = validate_param(null, PARAM_INT, false);
1041 $this->fail('invalid_parameter_exception expected');
1042 } catch (invalid_parameter_exception $ex) {
1043 $this->assertTrue(true);
1044 }
1045 try {
1046 $param = validate_param(null, PARAM_INT, true);
1047 $this->assertTrue($param===null);
1048 } catch (invalid_parameter_exception $ex) {
1049 $this->fail('invalid_parameter_exception expected');
1050 }
1051 try {
1052 $param = validate_param(array(), PARAM_INT);
1053 $this->fail('invalid_parameter_exception expected');
1054 } catch (invalid_parameter_exception $ex) {
1055 $this->assertTrue(true);
1056 }
1057 try {
1058 $param = validate_param(new stdClass, PARAM_INT);
1059 $this->fail('invalid_parameter_exception expected');
1060 } catch (invalid_parameter_exception $ex) {
1061 $this->assertTrue(true);
1062 }
9a97fa5a
PS
1063 try {
1064 $param = validate_param('1.0', PARAM_FLOAT);
1065 $this->assertSame(1.0, $param);
1066
1067 // Make sure valid floats do not cause exception.
1068 validate_param(1.0, PARAM_FLOAT);
1069 validate_param(10, PARAM_FLOAT);
1070 validate_param('0', PARAM_FLOAT);
1071 validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
1072 validate_param('011.1', PARAM_FLOAT);
1073 validate_param('11', PARAM_FLOAT);
1074 validate_param('+.1', PARAM_FLOAT);
1075 validate_param('-.1', PARAM_FLOAT);
1076 validate_param('1e10', PARAM_FLOAT);
1077 validate_param('.1e+10', PARAM_FLOAT);
1078 validate_param('1E-1', PARAM_FLOAT);
1079 $this->assertTrue(true);
1080 } catch (invalid_parameter_exception $ex) {
1081 $this->fail('Valid float notation not accepted');
1082 }
1083 try {
1084 $param = validate_param('1,2', PARAM_FLOAT);
1085 $this->fail('invalid_parameter_exception expected');
1086 } catch (invalid_parameter_exception $ex) {
1087 $this->assertTrue(true);
1088 }
1089 try {
1090 $param = validate_param('', PARAM_FLOAT);
1091 $this->fail('invalid_parameter_exception expected');
1092 } catch (invalid_parameter_exception $ex) {
1093 $this->assertTrue(true);
1094 }
1095 try {
1096 $param = validate_param('.', PARAM_FLOAT);
1097 $this->fail('invalid_parameter_exception expected');
1098 } catch (invalid_parameter_exception $ex) {
1099 $this->assertTrue(true);
1100 }
1101 try {
1102 $param = validate_param('e10', PARAM_FLOAT);
1103 $this->fail('invalid_parameter_exception expected');
1104 } catch (invalid_parameter_exception $ex) {
1105 $this->assertTrue(true);
1106 }
1107 try {
1108 $param = validate_param('abc', PARAM_FLOAT);
1109 $this->fail('invalid_parameter_exception expected');
1110 } catch (invalid_parameter_exception $ex) {
1111 $this->assertTrue(true);
1112 }
a3d5830a
PS
1113 }
1114
4a7cc248
TH
1115 function test_shorten_text_no_tags_already_short_enough() {
1116 // ......12345678901234567890123456.
a3d5830a
PS
1117 $text = "short text already no tags";
1118 $this->assertEquals($text, shorten_text($text));
4a7cc248 1119 }
a3d5830a 1120
4a7cc248
TH
1121 function test_shorten_text_with_tags_already_short_enough() {
1122 // .........123456...7890....12345678.......901234567.
a3d5830a
PS
1123 $text = "<p>short <b>text</b> already</p><p>with tags</p>";
1124 $this->assertEquals($text, shorten_text($text));
4a7cc248 1125 }
a3d5830a 1126
4a7cc248
TH
1127 function test_shorten_text_no_tags_needs_shortening() {
1128 // Default truncation is after 30 chars, but allowing 3 for the final '...'.
1129 // ......12345678901234567890123456789023456789012345678901234.
a3d5830a
PS
1130 $text = "long text without any tags blah de blah blah blah what";
1131 $this->assertEquals('long text without any tags ...', shorten_text($text));
4a7cc248 1132 }
a3d5830a 1133
4a7cc248
TH
1134 function test_shorten_text_with_tags_needs_shortening() {
1135 // .......................................123456789012345678901234567890...
a3d5830a
PS
1136 $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
1137 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
1138 $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
1139 "tags that ...</blockquote></p></div>", shorten_text($text));
4a7cc248 1140 }
a3d5830a 1141
4a7cc248
TH
1142 function test_shorten_text_with_entities() {
1143 // Remember to allow 3 chars for the final '...'.
1144 // ......123456789012345678901234567_____890...
a3d5830a
PS
1145 $text = "some text which shouldn't &nbsp; break there";
1146 $this->assertEquals("some text which shouldn't &nbsp; ...",
1147 shorten_text($text, 31));
4a7cc248 1148 $this->assertEquals("some text which shouldn't &nbsp;...",
a3d5830a 1149 shorten_text($text, 30));
4a7cc248
TH
1150 $this->assertEquals("some text which shouldn't ...",
1151 shorten_text($text, 29));
1152 }
a3d5830a 1153
4a7cc248 1154 function test_shorten_text_known_tricky_case() {
a3d5830a 1155 // This case caused a bug up to 1.9.5
4a7cc248 1156 // ..........123456789012345678901234567890123456789.....0_____1___2___...
a3d5830a
PS
1157 $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
1158 $this->assertEquals("<h3>standard 'break-out' sub groups in ...</h3>",
4a7cc248
TH
1159 shorten_text($text, 41));
1160 $this->assertEquals("<h3>standard 'break-out' sub groups in TGs?...</h3>",
1161 shorten_text($text, 42));
1162 $this->assertEquals("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
a3d5830a 1163 shorten_text($text, 43));
4a7cc248 1164 }
a3d5830a 1165
4a7cc248
TH
1166 function test_shorten_text_no_spaces() {
1167 // ..........123456789.
1168 $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
a3d5830a
PS
1169 $this->assertEquals("<h1>12345...</h1>",
1170 shorten_text($text, 8));
4a7cc248 1171 }
a3d5830a 1172
4a7cc248
TH
1173 function test_shorten_text_utf8_european() {
1174 // Text without tags.
1175 // ......123456789012345678901234567.
a3d5830a 1176 $text = "Žluťoučký koníček přeskočil";
4a7cc248 1177 $this->assertEquals($text, shorten_text($text)); // 30 chars by default.
a3d5830a
PS
1178 $this->assertEquals("Žluťoučký koníče...", shorten_text($text, 19, true));
1179 $this->assertEquals("Žluťoučký ...", shorten_text($text, 19, false));
4a7cc248 1180 // And try it with 2-less (that are, in bytes, the middle of a sequence).
a3d5830a
PS
1181 $this->assertEquals("Žluťoučký koní...", shorten_text($text, 17, true));
1182 $this->assertEquals("Žluťoučký ...", shorten_text($text, 17, false));
1183
4a7cc248 1184 // .........123456789012345678...901234567....89012345.
a3d5830a
PS
1185 $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
1186 $this->assertEquals($text, shorten_text($text, 60));
1187 $this->assertEquals("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
1188 $this->assertEquals("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
1189 $this->assertEquals("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
4a7cc248 1190 // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
a3d5830a
PS
1191 $this->assertEquals("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
1192 $this->assertEquals("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
4a7cc248 1193 // And try over one tag (start/end), it does proper text len.
a3d5830a
PS
1194 $this->assertEquals("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
1195 $this->assertEquals("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
4a7cc248 1196 // And in the middle of one tag.
a3d5830a 1197 $this->assertEquals("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
4a7cc248 1198 }
a3d5830a 1199
4a7cc248 1200 function test_shorten_text_utf8_oriental() {
a3d5830a 1201 // Japanese
4a7cc248
TH
1202 // text without tags
1203 // ......123456789012345678901234.
a3d5830a
PS
1204 $text = '言語設定言語設定abcdefghijkl';
1205 $this->assertEquals($text, shorten_text($text)); // 30 chars by default
1206 $this->assertEquals("言語設定言語...", shorten_text($text, 9, true));
1207 $this->assertEquals("言語設定言語...", shorten_text($text, 9, false));
1208 $this->assertEquals("言語設定言語設定ab...", shorten_text($text, 13, true));
1209 $this->assertEquals("言語設定言語設定...", shorten_text($text, 13, false));
1210
1211 // Chinese
4a7cc248
TH
1212 // text without tags
1213 // ......123456789012345678901234.
a3d5830a
PS
1214 $text = '简体中文简体中文abcdefghijkl';
1215 $this->assertEquals($text, shorten_text($text)); // 30 chars by default
1216 $this->assertEquals("简体中文简体...", shorten_text($text, 9, true));
1217 $this->assertEquals("简体中文简体...", shorten_text($text, 9, false));
1218 $this->assertEquals("简体中文简体中文ab...", shorten_text($text, 13, true));
1219 $this->assertEquals("简体中文简体中文...", shorten_text($text, 13, false));
4a7cc248 1220 }
a3d5830a 1221
4a7cc248
TH
1222 function test_shorten_text_multilang() {
1223 // This is not necessaryily specific to multilang. The issue is really
1224 // tags with attributes, where before we were generating invalid HTML
1225 // output like shorten_text('<span id="x" class="y">A</span> B', 1);
1226 // returning '<span id="x" ...</span>'. It is just that multilang
1227 // requires the sort of HTML that is quite likely to trigger this.
1228 // ........................................1...
1229 $text = '<span lang="en" class="multilang">A</span>' .
1230 '<span lang="fr" class="multilang">B</span>';
1231 $this->assertEquals('<span lang="en" class="multilang">...</span>',
1232 shorten_text($text, 1));
a3d5830a
PS
1233 }
1234
1235 function test_usergetdate() {
1236 global $USER, $CFG, $DB;
1237
1238 //Check if forcetimezone is set then save it and set it to use user timezone
1239 $cfgforcetimezone = null;
1240 if (isset($CFG->forcetimezone)) {
1241 $cfgforcetimezone = $CFG->forcetimezone;
1242 $CFG->forcetimezone = 99; //get user default timezone.
1243 }
1244
1245 $olduser = $USER;
1246 $USER = $DB->get_record('user', array('id'=>2)); //admin
1247
1248 $userstimezone = $USER->timezone;
1249 $USER->timezone = 2;//set the timezone to a known state
1250
1251 // The string version of date comes from server locale setting and does
1252 // not respect user language, so it is necessary to reset that.
1253 $oldlocale = setlocale(LC_TIME, '0');
1254 setlocale(LC_TIME, 'en_AU.UTF-8');
1255
1256 $ts = 1261540267; //the time this function was created
1257
1258 $arr = usergetdate($ts,1);//specify the timezone as an argument
1259 $arr = array_values($arr);
1260
1261 list($seconds,$minutes,$hours,$mday,$wday,$mon,$year,$yday,$weekday,$month) = $arr;
03764014
EL
1262 $this->assertSame($seconds, 7);
1263 $this->assertSame($minutes, 51);
1264 $this->assertSame($hours, 4);
1265 $this->assertSame($mday, 23);
1266 $this->assertSame($wday, 3);
1267 $this->assertSame($mon, 12);
1268 $this->assertSame($year, 2009);
1269 $this->assertSame($yday, 356);
1270 $this->assertSame($weekday, 'Wednesday');
1271 $this->assertSame($month, 'December');
a3d5830a
PS
1272 $arr = usergetdate($ts);//gets the timezone from the $USER object
1273 $arr = array_values($arr);
1274
1275 list($seconds,$minutes,$hours,$mday,$wday,$mon,$year,$yday,$weekday,$month) = $arr;
03764014
EL
1276 $this->assertSame($seconds, 7);
1277 $this->assertSame($minutes, 51);
1278 $this->assertSame($hours, 5);
1279 $this->assertSame($mday, 23);
1280 $this->assertSame($wday, 3);
1281 $this->assertSame($mon, 12);
1282 $this->assertSame($year, 2009);
1283 $this->assertSame($yday, 356);
1284 $this->assertSame($weekday, 'Wednesday');
1285 $this->assertSame($month, 'December');
a3d5830a
PS
1286 //set the timezone back to what it was
1287 $USER->timezone = $userstimezone;
1288
1289 //restore forcetimezone if changed.
1290 if (!is_null($cfgforcetimezone)) {
1291 $CFG->forcetimezone = $cfgforcetimezone;
1292 }
1293
1294 setlocale(LC_TIME, $oldlocale);
1295
1296 $USER = $olduser;
1297 }
1298
1299 public function test_normalize_component() {
1300
1301 // moodle core
1302 $this->assertEquals(normalize_component('moodle'), array('core', null));
1303 $this->assertEquals(normalize_component('core'), array('core', null));
1304
1305 // moodle core subsystems
1306 $this->assertEquals(normalize_component('admin'), array('core', 'admin'));
1307 $this->assertEquals(normalize_component('core_admin'), array('core', 'admin'));
1308
1309 // activity modules and their subplugins
1310 $this->assertEquals(normalize_component('workshop'), array('mod', 'workshop'));
1311 $this->assertEquals(normalize_component('mod_workshop'), array('mod', 'workshop'));
1312 $this->assertEquals(normalize_component('workshopform_accumulative'), array('workshopform', 'accumulative'));
1313 $this->assertEquals(normalize_component('quiz'), array('mod', 'quiz'));
1314 $this->assertEquals(normalize_component('quiz_grading'), array('quiz', 'grading'));
1315 $this->assertEquals(normalize_component('data'), array('mod', 'data'));
1316 $this->assertEquals(normalize_component('datafield_checkbox'), array('datafield', 'checkbox'));
1317
1318 // other plugin types
1319 $this->assertEquals(normalize_component('auth_mnet'), array('auth', 'mnet'));
1320 $this->assertEquals(normalize_component('enrol_self'), array('enrol', 'self'));
1321 $this->assertEquals(normalize_component('block_html'), array('block', 'html'));
1322 $this->assertEquals(normalize_component('block_mnet_hosts'), array('block', 'mnet_hosts'));
1323 $this->assertEquals(normalize_component('local_amos'), array('local', 'amos'));
1324
1325 // unknown components are supposed to be activity modules
1326 $this->assertEquals(normalize_component('whothefuckwouldcomewithsuchastupidnameofcomponent'),
1327 array('mod', 'whothefuckwouldcomewithsuchastupidnameofcomponent'));
1328 $this->assertEquals(normalize_component('whothefuck_wouldcomewithsuchastupidnameofcomponent'),
1329 array('mod', 'whothefuck_wouldcomewithsuchastupidnameofcomponent'));
1330 $this->assertEquals(normalize_component('whothefuck_would_come_withsuchastupidnameofcomponent'),
1331 array('mod', 'whothefuck_would_come_withsuchastupidnameofcomponent'));
1332 }
1333
1334 protected function get_fake_preference_test_userid() {
1335 global $DB;
1336
1337 // we need some nonexistent user id
1338 $id = 2147483647 - 666;
1339 if ($DB->get_records('user', array('id'=>$id))) {
1340 //weird!
1341 return false;
1342 }
1343 return $id;
1344 }
1345
1346 public function test_mark_user_preferences_changed() {
1347 $this->resetAfterTest(true);
1348 if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1349 $this->fail('Can not find unused user id for the preferences test');
1350 return;
1351 }
1352
1353 set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
1354 mark_user_preferences_changed($otheruserid);
1355
1356 $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1357 set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
1358 }
1359
1360 public function test_check_user_preferences_loaded() {
1361 global $DB;
1362 $this->resetAfterTest(true);
1363
1364 if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1365 $this->fail('Can not find unused user id for the preferences test');
1366 return;
1367 }
1368
1369 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1370 set_cache_flag('userpreferenceschanged', $otheruserid, NULL);
1371
1372 $user = new stdClass();
1373 $user->id = $otheruserid;
1374
1375 // load
1376 check_user_preferences_loaded($user);
1377 $this->assertTrue(isset($user->preference));
1378 $this->assertTrue(is_array($user->preference));
1379 $this->assertTrue(isset($user->preference['_lastloaded']));
1380 $this->assertEquals(count($user->preference), 1);
1381
1382 // add preference via direct call
1383 $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1384
1385 // no cache reload yet
1386 check_user_preferences_loaded($user);
1387 $this->assertEquals(count($user->preference), 1);
1388
1389 // forced reloading of cache
1390 unset($user->preference);
1391 check_user_preferences_loaded($user);
1392 $this->assertEquals(count($user->preference), 2);
1393 $this->assertEquals($user->preference['xxx'], 'yyy');
1394
1395 // add preference via direct call
1396 $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1397
1398 // test timeouts and modifications from different session
1399 set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1400 $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1401 check_user_preferences_loaded($user);
1402 $this->assertEquals(count($user->preference), 2);
1403 check_user_preferences_loaded($user, 10);
1404 $this->assertEquals(count($user->preference), 3);
1405 $this->assertEquals($user->preference['aaa'], 'bbb');
1406 set_cache_flag('userpreferenceschanged', $user->id, null);
1407 }
1408
1409 public function test_set_user_preference() {
1410 global $DB, $USER;
1411 $this->resetAfterTest(true);
1412
1413 $olduser = $USER;
1414 $USER = $DB->get_record('user', array('id'=>2)); //admin
1415
1416 if (!$otheruserid = $this->get_fake_preference_test_userid()) {
1417 $this->fail('Can not find unused user id for the preferences test');
1418 return;
1419 }
1420
1421 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1422 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1423
1424 $user = new stdClass();
1425 $user->id = $otheruserid;
1426
1427 set_user_preference('aaa', 'bbb', $otheruserid);
1428 $this->assertEquals('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1429 $this->assertEquals('bbb', get_user_preferences('aaa', null, $otheruserid));
1430
1431 set_user_preference('xxx', 'yyy', $user);
1432 $this->assertEquals('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1433 $this->assertEquals('yyy', get_user_preferences('xxx', null, $otheruserid));
1434 $this->assertTrue(is_array($user->preference));
1435 $this->assertEquals($user->preference['aaa'], 'bbb');
1436 $this->assertEquals($user->preference['xxx'], 'yyy');
1437
1438 set_user_preference('xxx', NULL, $user);
1439 $this->assertSame(false, $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1440 $this->assertSame(null, get_user_preferences('xxx', null, $otheruserid));
1441
1442 set_user_preference('ooo', true, $user);
1443 $prefs = get_user_preferences(null, null, $otheruserid);
1444 $this->assertSame($prefs['aaa'], $user->preference['aaa']);
1445 $this->assertSame($prefs['ooo'], $user->preference['ooo']);
1446 $this->assertSame($prefs['ooo'], '1');
1447
1448 set_user_preference('null', 0, $user);
1449 $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1450
1451 $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1452
1453 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1454 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1455
1456 // test $USER default
1457 set_user_preference('_test_user_preferences_pref', 'ok');
1458 $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1459 unset_user_preference('_test_user_preferences_pref');
1460 $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1461
1462 // Test 1333 char values (no need for unicode, there are already tests for that in DB tests)
1463 $longvalue = str_repeat('a', 1333);
1464 set_user_preference('_test_long_user_preference', $longvalue);
1465 $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1466 $this->assertEquals($longvalue,
1467 $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1468
1469 // Test > 1333 char values, coding_exception expected
1470 $longvalue = str_repeat('a', 1334);
1471 try {
1472 set_user_preference('_test_long_user_preference', $longvalue);
17222a4a
MN
1473 $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1474 } catch (coding_exception $ex) {
1475 $this->assertTrue(true);
a3d5830a
PS
1476 }
1477
1478 //test invalid params
1479 try {
1480 set_user_preference('_test_user_preferences_pref', array());
17222a4a
MN
1481 $this->fail('Exception expected - array not valid preference value');
1482 } catch (coding_exception $ex) {
a3d5830a
PS
1483 $this->assertTrue(true);
1484 }
1485 try {
1486 set_user_preference('_test_user_preferences_pref', new stdClass);
17222a4a
MN
1487 $this->fail('Exception expected - class not valid preference value');
1488 } catch (coding_exception $ex) {
a3d5830a
PS
1489 $this->assertTrue(true);
1490 }
1491 try {
17222a4a
MN
1492 set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1493 $this->fail('Exception expected - user instance expected');
1494 } catch (coding_exception $ex) {
a3d5830a
PS
1495 $this->assertTrue(true);
1496 }
1497 try {
1498 set_user_preference('_test_user_preferences_pref', 1, 'abc');
17222a4a
MN
1499 $this->fail('Exception expected - user instance expected');
1500 } catch (coding_exception $ex) {
a3d5830a
PS
1501 $this->assertTrue(true);
1502 }
1503 try {
1504 set_user_preference('', 1);
17222a4a
MN
1505 $this->fail('Exception expected - invalid name accepted');
1506 } catch (coding_exception $ex) {
a3d5830a
PS
1507 $this->assertTrue(true);
1508 }
1509 try {
1510 set_user_preference('1', 1);
17222a4a
MN
1511 $this->fail('Exception expected - invalid name accepted');
1512 } catch (coding_exception $ex) {
a3d5830a
PS
1513 $this->assertTrue(true);
1514 }
1515
1516 $USER = $olduser;
1517 }
1518
1519 public function test_get_extra_user_fields() {
1520 global $CFG, $USER, $DB;
1521 $oldshowuseridentity = $CFG->showuseridentity;
1522
1523 $olduser = $USER;
1524 $USER = $DB->get_record('user', array('id'=>2)); //admin
1525
1526 // It would be really nice if there were a way to 'mock' has_capability
1527 // checks (either to return true or false) but as there is not, this
1528 // test doesn't test the capability check. Presumably, anyone running
1529 // unit tests will have the capability.
1530 $context = context_system::instance();
1531
1532 // No fields
1533 $CFG->showuseridentity = '';
1534 $this->assertEquals(array(), get_extra_user_fields($context));
1535
1536 // One field
1537 $CFG->showuseridentity = 'frog';
1538 $this->assertEquals(array('frog'), get_extra_user_fields($context));
1539
1540 // Two fields
1541 $CFG->showuseridentity = 'frog,zombie';
1542 $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1543
1544 // No fields, except
1545 $CFG->showuseridentity = '';
1546 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1547
1548 // One field
1549 $CFG->showuseridentity = 'frog';
1550 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1551
1552 // Two fields
1553 $CFG->showuseridentity = 'frog,zombie';
1554 $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1555
1556 // As long as this test passes, the value will be set back. This is only
1557 // in-memory anyhow
1558 $CFG->showuseridentity = $oldshowuseridentity;
1559
1560 $USER = $olduser;
1561 }
1562
1563 public function test_get_extra_user_fields_sql() {
1564 global $CFG, $USER, $DB;
1565
1566 $olduser = $USER;
1567 $USER = $DB->get_record('user', array('id'=>2)); //admin
1568
1569 $oldshowuseridentity = $CFG->showuseridentity;
1570 $context = context_system::instance();
1571
1572 // No fields
1573 $CFG->showuseridentity = '';
1574 $this->assertEquals('', get_extra_user_fields_sql($context));
1575
1576 // One field
1577 $CFG->showuseridentity = 'frog';
1578 $this->assertEquals(', frog', get_extra_user_fields_sql($context));
1579
1580 // Two fields with table prefix
1581 $CFG->showuseridentity = 'frog,zombie';
1582 $this->assertEquals(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1583
1584 // Two fields with field prefix
1585 $CFG->showuseridentity = 'frog,zombie';
1586 $this->assertEquals(', frog AS u_frog, zombie AS u_zombie',
1587 get_extra_user_fields_sql($context, '', 'u_'));
1588
1589 // One field excluded
1590 $CFG->showuseridentity = 'frog';
1591 $this->assertEquals('', get_extra_user_fields_sql($context, '', '', array('frog')));
1592
1593 // Two fields, one excluded, table+field prefix
1594 $CFG->showuseridentity = 'frog,zombie';
1595 $this->assertEquals(', u1.zombie AS u_zombie',
1596 get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1597
1598 // As long as this test passes, the value will be set back. This is only
1599 // in-memory anyhow
1600 $CFG->showuseridentity = $oldshowuseridentity;
1601 $USER = $olduser;
1602 }
1603
d506f422
EL
1604 /**
1605 * Test some critical TZ/DST.
1606 *
1607 * This method tests some special TZ/DST combinations that were fixed
1608 * by MDL-38999. The tests are done by comparing the results of the
1609 * output using Moodle TZ/DST support and PHP native one.
1610 *
1611 * Note: If you don't trust PHP TZ/DST support, can verify the
1612 * harcoded expectations below with:
1613 * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1614 */
1615 public function test_some_moodle_special_dst() {
1616 $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1617
1618 // In Europe/Tallinn it was 2013/04/08 05:00:00.
1619 $expectation = '2013/04/08 05:00:00';
1620 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1621 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1622 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1623 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1624 $this->assertSame($expectation, $phpres);
1625 $this->assertSame($expectation, $moodleres);
1626
1627 // In St. Johns it was 2013/04/07 23:30:00.
1628 $expectation = '2013/04/07 23:30:00';
1629 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1630 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1631 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1632 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1633 $this->assertSame($expectation, $phpres);
1634 $this->assertSame($expectation, $moodleres);
1635
1636 $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1637
1638 // In Europe/Tallinn it was 2013/11/08 04:00:00.
1639 $expectation = '2013/11/08 04:00:00';
1640 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1641 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1642 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1643 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1644 $this->assertSame($expectation, $phpres);
1645 $this->assertSame($expectation, $moodleres);
1646
1647 // In St. Johns it was 2013/11/07 22:30:00.
1648 $expectation = '2013/11/07 22:30:00';
1649 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1650 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1651 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1652 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1653 $this->assertSame($expectation, $phpres);
1654 $this->assertSame($expectation, $moodleres);
1655 }
1656
a3d5830a
PS
1657 public function test_userdate() {
1658 global $USER, $CFG, $DB;
1659
1660 $olduser = $USER;
1661 $USER = $DB->get_record('user', array('id'=>2)); //admin
1662
1663 $testvalues = array(
1664 array(
1665 'time' => '1309514400',
1666 'usertimezone' => 'America/Moncton',
1667 'timezone' => '0.0', //no dst offset
1668 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1669 ),
1670 array(
1671 'time' => '1309514400',
1672 'usertimezone' => 'America/Moncton',
1673 'timezone' => '99', //dst offset and timezone offset.
1674 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1675 ),
1676 array(
1677 'time' => '1309514400',
1678 'usertimezone' => 'America/Moncton',
1679 'timezone' => 'America/Moncton', //dst offset and timezone offset.
1680 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1681 ),
1682 array(
1683 'time' => '1293876000 ',
1684 'usertimezone' => 'America/Moncton',
1685 'timezone' => '0.0', //no dst offset
1686 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1687 ),
1688 array(
1689 'time' => '1293876000 ',
1690 'usertimezone' => 'America/Moncton',
1691 'timezone' => '99', //no dst offset in jan, so just timezone offset.
1692 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1693 ),
1694 array(
1695 'time' => '1293876000 ',
1696 'usertimezone' => 'America/Moncton',
1697 'timezone' => 'America/Moncton', //no dst offset in jan
1698 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1699 ),
1700 array(
1701 'time' => '1293876000 ',
1702 'usertimezone' => '2',
1703 'timezone' => '99', //take user timezone
1704 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1705 ),
1706 array(
1707 'time' => '1293876000 ',
1708 'usertimezone' => '-2',
1709 'timezone' => '99', //take user timezone
1710 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1711 ),
1712 array(
1713 'time' => '1293876000 ',
1714 'usertimezone' => '-10',
1715 'timezone' => '2', //take this timezone
1716 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1717 ),
1718 array(
1719 'time' => '1293876000 ',
1720 'usertimezone' => '-10',
1721 'timezone' => '-2', //take this timezone
1722 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1723 ),
1724 array(
1725 'time' => '1293876000 ',
1726 'usertimezone' => '-10',
1727 'timezone' => 'random/time', //this should show server time
1728 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1729 ),
1730 array(
1731 'time' => '1293876000 ',
1732 'usertimezone' => '14', //server time zone
1733 'timezone' => '99', //this should show user time
1734 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1735 ),
1736 );
1737
1738 //Check if forcetimezone is set then save it and set it to use user timezone
1739 $cfgforcetimezone = null;
1740 if (isset($CFG->forcetimezone)) {
1741 $cfgforcetimezone = $CFG->forcetimezone;
1742 $CFG->forcetimezone = 99; //get user default timezone.
1743 }
1744 //store user default timezone to restore later
1745 $userstimezone = $USER->timezone;
1746
1747 // The string version of date comes from server locale setting and does
1748 // not respect user language, so it is necessary to reset that.
1749 $oldlocale = setlocale(LC_TIME, '0');
1750 setlocale(LC_TIME, 'en_AU.UTF-8');
1751
1752 //set default timezone to Australia/Perth, else time calculated
1753 //will not match expected values. Before that save system defaults.
1754 $systemdefaulttimezone = date_default_timezone_get();
1755 date_default_timezone_set('Australia/Perth');
1756
1757 foreach ($testvalues as $vals) {
1758 $USER->timezone = $vals['usertimezone'];
1759 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1760
1761 //On different systems case of AM PM changes so compare case insensitive
1762 $vals['expectedoutput'] = textlib::strtolower($vals['expectedoutput']);
1763 $actualoutput = textlib::strtolower($actualoutput);
1764
1765 $this->assertEquals($vals['expectedoutput'], $actualoutput,
1766 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1767 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1768 }
1769
1770 //restore user timezone back to what it was
1771 $USER->timezone = $userstimezone;
1772
1773 //restore forcetimezone
1774 if (!is_null($cfgforcetimezone)) {
1775 $CFG->forcetimezone = $cfgforcetimezone;
1776 }
1777
1778 //restore system default values.
1779 date_default_timezone_set($systemdefaulttimezone);
1780 setlocale(LC_TIME, $oldlocale);
1781
1782 $USER = $olduser;
1783 }
1784
1785 public function test_make_timestamp() {
1786 global $USER, $CFG, $DB;
1787
1788 $olduser = $USER;
1789 $USER = $DB->get_record('user', array('id'=>2)); //admin
1790
1791 $testvalues = array(
1792 array(
1793 'usertimezone' => 'America/Moncton',
1794 'year' => '2011',
1795 'month' => '7',
1796 'day' => '1',
1797 'hour' => '10',
1798 'minutes' => '00',
1799 'seconds' => '00',
7b05e146
FM
1800 'timezone' => '0.0',
1801 'applydst' => false, //no dst offset
1802 'expectedoutput' => '1309514400' // 6pm at UTC+0
a3d5830a
PS
1803 ),
1804 array(
1805 'usertimezone' => 'America/Moncton',
1806 'year' => '2011',
1807 'month' => '7',
1808 'day' => '1',
1809 'hour' => '10',
1810 'minutes' => '00',
1811 'seconds' => '00',
1812 'timezone' => '99', //user default timezone
1813 'applydst' => false, //don't apply dst
1814 'expectedoutput' => '1309528800'
1815 ),
1816 array(
1817 'usertimezone' => 'America/Moncton',
1818 'year' => '2011',
1819 'month' => '7',
1820 'day' => '1',
1821 'hour' => '10',
1822 'minutes' => '00',
1823 'seconds' => '00',
1824 'timezone' => '99', //user default timezone
1825 'applydst' => true, //apply dst
1826 'expectedoutput' => '1309525200'
1827 ),
1828 array(
1829 'usertimezone' => 'America/Moncton',
1830 'year' => '2011',
1831 'month' => '7',
1832 'day' => '1',
1833 'hour' => '10',
1834 'minutes' => '00',
1835 'seconds' => '00',
1836 'timezone' => 'America/Moncton', //string timezone
1837 'applydst' => true, //apply dst
1838 'expectedoutput' => '1309525200'
1839 ),
1840 array(
1841 'usertimezone' => '2',//no dst applyed
1842 'year' => '2011',
1843 'month' => '7',
1844 'day' => '1',
1845 'hour' => '10',
1846 'minutes' => '00',
1847 'seconds' => '00',
1848 'timezone' => '99', //take user timezone
1849 'applydst' => true, //apply dst
1850 'expectedoutput' => '1309507200'
1851 ),
1852 array(
1853 'usertimezone' => '-2',//no dst applyed
1854 'year' => '2011',
1855 'month' => '7',
1856 'day' => '1',
1857 'hour' => '10',
1858 'minutes' => '00',
1859 'seconds' => '00',
1860 'timezone' => '99', //take usertimezone
1861 'applydst' => true, //apply dst
1862 'expectedoutput' => '1309521600'
1863 ),
1864 array(
1865 'usertimezone' => '-10',//no dst applyed
1866 'year' => '2011',
1867 'month' => '7',
1868 'day' => '1',
1869 'hour' => '10',
1870 'minutes' => '00',
1871 'seconds' => '00',
1872 'timezone' => '2', //take this timezone
1873 'applydst' => true, //apply dst
1874 'expectedoutput' => '1309507200'
1875 ),
1876 array(
1877 'usertimezone' => '-10',//no dst applyed
1878 'year' => '2011',
1879 'month' => '7',
1880 'day' => '1',
1881 'hour' => '10',
1882 'minutes' => '00',
1883 'seconds' => '00',
1884 'timezone' => '-2', //take this timezone
1885 'applydst' => true, //apply dst,
1886 'expectedoutput' => '1309521600'
1887 ),
1888 array(
1889 'usertimezone' => '-10',//no dst applyed
1890 'year' => '2011',
1891 'month' => '7',
1892 'day' => '1',
1893 'hour' => '10',
1894 'minutes' => '00',
1895 'seconds' => '00',
1896 'timezone' => 'random/time', //This should show server time
1897 'applydst' => true, //apply dst,
1898 'expectedoutput' => '1309485600'
1899 ),
1900 array(
1901 'usertimezone' => '14',//server time
1902 'year' => '2011',
1903 'month' => '7',
1904 'day' => '1',
1905 'hour' => '10',
1906 'minutes' => '00',
1907 'seconds' => '00',
1908 'timezone' => '99', //get user time
1909 'applydst' => true, //apply dst,
1910 'expectedoutput' => '1309485600'
1911 )
1912 );
1913
1914 //Check if forcetimezone is set then save it and set it to use user timezone
1915 $cfgforcetimezone = null;
1916 if (isset($CFG->forcetimezone)) {
1917 $cfgforcetimezone = $CFG->forcetimezone;
1918 $CFG->forcetimezone = 99; //get user default timezone.
1919 }
1920
1921 //store user default timezone to restore later
1922 $userstimezone = $USER->timezone;
1923
1924 // The string version of date comes from server locale setting and does
1925 // not respect user language, so it is necessary to reset that.
1926 $oldlocale = setlocale(LC_TIME, '0');
1927 setlocale(LC_TIME, 'en_AU.UTF-8');
1928
1929 //set default timezone to Australia/Perth, else time calulated
1930 //will not match expected values. Before that save system defaults.
1931 $systemdefaulttimezone = date_default_timezone_get();
1932 date_default_timezone_set('Australia/Perth');
1933
1934 //Test make_timestamp with all testvals and assert if anything wrong.
1935 foreach ($testvalues as $vals) {
1936 $USER->timezone = $vals['usertimezone'];
1937 $actualoutput = make_timestamp(
1938 $vals['year'],
1939 $vals['month'],
1940 $vals['day'],
1941 $vals['hour'],
1942 $vals['minutes'],
1943 $vals['seconds'],
1944 $vals['timezone'],
1945 $vals['applydst']
1946 );
1947
1948 //On different systems case of AM PM changes so compare case insenitive
1949 $vals['expectedoutput'] = textlib::strtolower($vals['expectedoutput']);
1950 $actualoutput = textlib::strtolower($actualoutput);
1951
1952 $this->assertEquals($vals['expectedoutput'], $actualoutput,
1953 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1954 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1955 }
1956
1957 //restore user timezone back to what it was
1958 $USER->timezone = $userstimezone;
1959
1960 //restore forcetimezone
1961 if (!is_null($cfgforcetimezone)) {
1962 $CFG->forcetimezone = $cfgforcetimezone;
1963 }
1964
1965 //restore system default values.
1966 date_default_timezone_set($systemdefaulttimezone);
1967 setlocale(LC_TIME, $oldlocale);
1968
1969 $USER = $olduser;
1970 }
1971
1972 /**
1973 * Test get_string and most importantly the implementation of the lang_string
1974 * object.
1975 */
1976 public function test_get_string() {
1977 global $COURSE;
1978
1979 // Make sure we are using English
1980 $originallang = $COURSE->lang;
1981 $COURSE->lang = 'en';
1982
1983 $yes = get_string('yes');
1984 $yesexpected = 'Yes';
1985 $this->assertEquals(getType($yes), 'string');
1986 $this->assertEquals($yes, $yesexpected);
1987
1988 $yes = get_string('yes', 'moodle');
1989 $this->assertEquals(getType($yes), 'string');
1990 $this->assertEquals($yes, $yesexpected);
1991
1992 $yes = get_string('yes', 'core');
1993 $this->assertEquals(getType($yes), 'string');
1994 $this->assertEquals($yes, $yesexpected);
1995
1996 $yes = get_string('yes', '');
1997 $this->assertEquals(getType($yes), 'string');
1998 $this->assertEquals($yes, $yesexpected);
1999
2000 $yes = get_string('yes', null);
2001 $this->assertEquals(getType($yes), 'string');
2002 $this->assertEquals($yes, $yesexpected);
2003
2004 $yes = get_string('yes', null, 1);
2005 $this->assertEquals(getType($yes), 'string');
2006 $this->assertEquals($yes, $yesexpected);
2007
2008 $days = 1;
2009 $numdays = get_string('numdays', 'core', '1');
2010 $numdaysexpected = $days.' days';
2011 $this->assertEquals(getType($numdays), 'string');
2012 $this->assertEquals($numdays, $numdaysexpected);
2013
2014 $yes = get_string('yes', null, null, true);
2015 $this->assertEquals(get_class($yes), 'lang_string');
2016 $this->assertEquals((string)$yes, $yesexpected);
2017
2018 // Test using a lang_string object as the $a argument for a normal
2019 // get_string call (returning string)
2020 $test = new lang_string('yes', null, null, true);
2021 $testexpected = get_string('numdays', 'core', get_string('yes'));
2022 $testresult = get_string('numdays', null, $test);
2023 $this->assertEquals(getType($testresult), 'string');
2024 $this->assertEquals($testresult, $testexpected);
2025
2026 // Test using a lang_string object as the $a argument for an object
2027 // get_string call (returning lang_string)
2028 $test = new lang_string('yes', null, null, true);
2029 $testexpected = get_string('numdays', 'core', get_string('yes'));
2030 $testresult = get_string('numdays', null, $test, true);
2031 $this->assertEquals(get_class($testresult), 'lang_string');
2032 $this->assertEquals("$testresult", $testexpected);
2033
2034 // Make sure that object properties that can't be converted don't cause
2035 // errors
2036 // Level one: This is as deep as current language processing goes
2037 $test = new stdClass;
2038 $test->one = 'here';
2039 $string = get_string('yes', null, $test, true);
2040 $this->assertEquals($string, $yesexpected);
2041
2042 // Make sure that object properties that can't be converted don't cause
2043 // errors.
2044 // Level two: Language processing doesn't currently reach this deep.
2045 // only immediate scalar properties are worked with.
2046 $test = new stdClass;
2047 $test->one = new stdClass;
2048 $test->one->two = 'here';
2049 $string = get_string('yes', null, $test, true);
2050 $this->assertEquals($string, $yesexpected);
2051
2052 // Make sure that object properties that can't be converted don't cause
2053 // errors.
2054 // Level three: It should never ever go this deep, but we're making sure
2055 // it doesn't cause any probs anyway.
2056 $test = new stdClass;
2057 $test->one = new stdClass;
2058 $test->one->two = new stdClass;
2059 $test->one->two->three = 'here';
2060 $string = get_string('yes', null, $test, true);
2061 $this->assertEquals($string, $yesexpected);
2062
2063 // Make sure that object properties that can't be converted don't cause
2064 // errors and check lang_string properties.
2065 // Level one: This is as deep as current language processing goes
2066 $test = new stdClass;
2067 $test->one = new lang_string('yes');
2068 $string = get_string('yes', null, $test, true);
2069 $this->assertEquals($string, $yesexpected);
2070
2071 // Make sure that object properties that can't be converted don't cause
2072 // errors and check lang_string properties.
2073 // Level two: Language processing doesn't currently reach this deep.
2074 // only immediate scalar properties are worked with.
2075 $test = new stdClass;
2076 $test->one = new stdClass;
2077 $test->one->two = new lang_string('yes');
2078 $string = get_string('yes', null, $test, true);
2079 $this->assertEquals($string, $yesexpected);
2080
2081 // Make sure that object properties that can't be converted don't cause
2082 // errors and check lang_string properties.
2083 // Level three: It should never ever go this deep, but we're making sure
2084 // it doesn't cause any probs anyway.
2085 $test = new stdClass;
2086 $test->one = new stdClass;
2087 $test->one->two = new stdClass;
2088 $test->one->two->three = new lang_string('yes');
2089 $string = get_string('yes', null, $test, true);
2090 $this->assertEquals($string, $yesexpected);
2091
2092 // Make sure that array properties that can't be converted don't cause
2093 // errors
2094 $test = array();
2095 $test['one'] = new stdClass;
2096 $test['one']->two = 'here';
2097 $string = get_string('yes', null, $test, true);
2098 $this->assertEquals($string, $yesexpected);
2099
2100 // Same thing but as above except using an object... this is allowed :P
2101 $string = get_string('yes', null, null, true);
2102 $object = new stdClass;
2103 $object->$string = 'Yes';
2104 $this->assertEquals($string, $yesexpected);
2105 $this->assertEquals($object->$string, $yesexpected);
2106
2107 // Reset the language
2108 $COURSE->lang = $originallang;
2109 }
2110
2111 /**
2112 * @expectedException PHPUnit_Framework_Error_Warning
2113 * @return void
2114 */
2115 public function test_get_string_limitation() {
2116 // This is one of the limitations to the lang_string class. It can't be
2117 // used as a key
2118 $array = array(get_string('yes', null, null, true) => 'yes');
2119 }
637da99e 2120
2121 /**
2122 * Test localised float formatting.
2123 */
2124 public function test_format_float() {
2125 global $SESSION, $CFG;
2126
2127 // Special case for null
2128 $this->assertEquals('', format_float(null));
2129
2130 // Default 1 decimal place
2131 $this->assertEquals('5.4', format_float(5.43));
2132 $this->assertEquals('5.0', format_float(5.001));
2133
2134 // Custom number of decimal places
2135 $this->assertEquals('5.43000', format_float(5.43, 5));
2136
2137 // Option to strip ending zeros after rounding
2138 $this->assertEquals('5.43', format_float(5.43, 5, true, true));
2139 $this->assertEquals('5', format_float(5.0001, 3, true, true));
2140
2141 // It is not possible to directly change the result of get_string in
2142 // a unit test. Instead, we create a language pack for language 'xx' in
2143 // dataroot and make langconfig.php with the string we need to change.
2144 // The example separator used here is 'X'; on PHP 5.3 and before this
2145 // must be a single byte character due to PHP bug/limitation in
2146 // number_format, so you can't use UTF-8 characters.
2147 $SESSION->lang = 'xx';
2148 $langconfig = "<?php\n\$string['decsep'] = 'X';";
2149 $langfolder = $CFG->dataroot . '/lang/xx';
2150 check_dir_exists($langfolder);
2151 file_put_contents($langfolder . '/langconfig.php', $langconfig);
2152
2153 // Localisation on (default)
2154 $this->assertEquals('5X43000', format_float(5.43, 5));
2155 $this->assertEquals('5X43', format_float(5.43, 5, true, true));
2156
2157 // Localisation off
2158 $this->assertEquals('5.43000', format_float(5.43, 5, false));
2159 $this->assertEquals('5.43', format_float(5.43, 5, false, true));
2160 }
4366ce80
PS
2161
2162 /**
2163 * Test deleting of users.
2164 */
2165 public function test_delete_user() {
2166 global $DB, $CFG;
2167
2168 $this->resetAfterTest();
2169
2170 $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
2171 $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
2172 $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
2173
2174 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2175 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2176
2177 $result = delete_user($user);
2178 $this->assertTrue($result);
2179 $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
2180 $this->assertEquals(1, $deluser->deleted);
2181 $this->assertEquals(0, $deluser->picture);
2182 $this->assertSame('', $deluser->idnumber);
2183 $this->assertSame(md5($user->username), $deluser->email);
2184 $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
2185
2186 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2187
2188 // Try invalid params.
2189
2190 $record = new stdClass();
2191 $record->grrr = 1;
2192 try {
2193 delete_user($record);
2194 $this->fail('Expecting exception for invalid delete_user() $user parameter');
2195 } catch (coding_exception $e) {
2196 $this->assertTrue(true);
2197 }
2198 $record->id = 1;
2199 try {
2200 delete_user($record);
2201 $this->fail('Expecting exception for invalid delete_user() $user parameter');
2202 } catch (coding_exception $e) {
2203 $this->assertTrue(true);
2204 }
2205
4366ce80
PS
2206 $record = new stdClass();
2207 $record->id = 666;
2208 $record->username = 'xx';
2209 $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2210 $result = delete_user($record);
2211 $this->assertFalse($result);
2212
2213 $result = delete_user($guest);
2214 $this->assertFalse($result);
2215
2216 $result = delete_user($admin);
2217 $this->assertFalse($result);
a3b6e311
PS
2218
2219 $this->resetDebugging();
4366ce80 2220 }
7b444a96
MG
2221
2222 /**
2223 * Test function convert_to_array()
2224 */
2225 public function test_convert_to_array() {
2226 // check that normal classes are converted to arrays the same way as (array) would do
2227 $obj = new stdClass();
2228 $obj->prop1 = 'hello';
2229 $obj->prop2 = array('first', 'second', 13);
2230 $obj->prop3 = 15;
2231 $this->assertEquals(convert_to_array($obj), (array)$obj);
2232
2233 // check that context object (with iterator) is converted to array properly
2234 $obj = get_system_context();
2235 $ar = array(
2236 'id' => $obj->id,
2237 'contextlevel' => $obj->contextlevel,
2238 'instanceid' => $obj->instanceid,
2239 'path' => $obj->path,
2240 'depth' => $obj->depth
2241 );
2242 $this->assertEquals(convert_to_array($obj), $ar);
2243 }
15396bba
FM
2244
2245 /**
2246 * Test the function date_format_string().
2247 */
2248 function test_date_format_string() {
73d20f36
PS
2249 global $CFG;
2250
15396bba
FM
2251 // Forcing locale and timezone.
2252 $oldlocale = setlocale(LC_TIME, '0');
73d20f36
PS
2253 if ($CFG->ostype == 'WINDOWS') {
2254 setlocale(LC_TIME, 'English_Australia.1252');
2255 } else {
2256 setlocale(LC_TIME, 'en_AU.UTF-8');
2257 }
15396bba
FM
2258 $systemdefaulttimezone = date_default_timezone_get();
2259 date_default_timezone_set('Australia/Perth');
2260
a8397303
FM
2261 $tests = array(
2262 array(
2263 'tz' => 99,
2264 'str' => '%A, %d %B %Y, %I:%M %p',
2265 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2266 ),
2267 array(
2268 'tz' => 0,
2269 'str' => '%A, %d %B %Y, %I:%M %p',
2270 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2271 ),
2272 array(
2273 'tz' => -12,
2274 'str' => '%A, %d %B %Y, %I:%M %p',
2275 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2276 ),
73d20f36
PS
2277 // Following tests pass on Windows only because en lang pack does
2278 // not contain localewincharset, in real life lang pack maintainers
2279 // may use only characters that are present in localewincharset
2280 // in format strings!
a8397303
FM
2281 array(
2282 'tz' => 99,
2283 'str' => 'Žluťoučký koníček %A',
2284 'expected' => 'Žluťoučký koníček Saturday'
2285 ),
2286 array(
2287 'tz' => 99,
2288 'str' => '言語設定言語 %A',
2289 'expected' => '言語設定言語 Saturday'
2290 ),
2291 array(
2292 'tz' => 99,
2293 'str' => '简体中文简体 %A',
2294 'expected' => '简体中文简体 Saturday'
2295 ),
2296 );
2297
15396bba
FM
2298 // Note: date_format_string() uses the timezone only to differenciate
2299 // the server time from the UTC time. It does not modify the timestamp.
2300 // Hence similar results for timezones <= 13.
a8397303
FM
2301 // On different systems case of AM PM changes so compare case insensitive.
2302 foreach ($tests as $test) {
2303 $str = date_format_string(1293876000, $test['str'], $test['tz']);
2304 $this->assertEquals(textlib::strtolower($test['expected']), textlib::strtolower($str));
2305 }
15396bba
FM
2306
2307 // Restore system default values.
2308 date_default_timezone_set($systemdefaulttimezone);
2309 setlocale(LC_TIME, $oldlocale);
2310 }
7f30a644
SH
2311
2312 public function test_get_config() {
2313 global $CFG;
2314
2315 $this->resetAfterTest();
2316
2317 // Preparation.
2318 set_config('phpunit_test_get_config_1', 'test 1');
2319 set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2320 if (!is_array($CFG->config_php_settings)) {
2321 $CFG->config_php_settings = array();
2322 }
2323 $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2324
2325 if (!is_array($CFG->forced_plugin_settings)) {
2326 $CFG->forced_plugin_settings = array();
2327 }
2328 if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2329 $CFG->forced_plugin_settings['mod_forum'] = array();
2330 }
2331 $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2332 $CFG->phpunit_test_get_config_5 = 'test 5';
2333
2334 // Testing.
2335 $this->assertEquals('test 1', get_config('core', 'phpunit_test_get_config_1'));
2336 $this->assertEquals('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2337 $this->assertEquals('test 3', get_config('core', 'phpunit_test_get_config_3'));
2338 $this->assertEquals('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2339 $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2340 $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2341 $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2342
2343 // Test config we know to exist.
2344 $this->assertEquals($CFG->dataroot, get_config('core', 'dataroot'));
2345 $this->assertEquals($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2346 $this->assertEquals($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2347 $this->assertEquals(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2348
2349 // Test setting a config var that already exists.
2350 set_config('phpunit_test_get_config_1', 'test a');
2351 $this->assertEquals('test a', $CFG->phpunit_test_get_config_1);
2352 $this->assertEquals('test a', get_config('core', 'phpunit_test_get_config_1'));
2353
2354 // Test cache invalidation.
2355 $cache = cache::make('core', 'config');
2356 $this->assertInternalType('array', $cache->get('core'));
2357 $this->assertInternalType('array', $cache->get('mod_forum'));
2358 set_config('phpunit_test_get_config_1', 'test b');
2359 $this->assertFalse($cache->get('core'));
2360 set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2361 $this->assertFalse($cache->get('mod_forum'));
2362 }
6b219310
DW
2363
2364 function test_get_max_upload_sizes() {
2365 // Test with very low limits so we are not affected by php upload limits.
2366 // Test activity limit smallest.
2367 $sitebytes = 102400;
2368 $coursebytes = 51200;
2369 $modulebytes = 10240;
2370 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2371
2372 $this->assertEquals('Activity upload limit (10KB)', $result['0']);
2373 $this->assertEquals(2, count($result));
2374
2375 // Test course limit smallest.
2376 $sitebytes = 102400;
2377 $coursebytes = 10240;
2378 $modulebytes = 51200;
2379 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2380
2381 $this->assertEquals('Course upload limit (10KB)', $result['0']);
2382 $this->assertEquals(2, count($result));
2383
2384 // Test site limit smallest.
2385 $sitebytes = 10240;
2386 $coursebytes = 102400;
2387 $modulebytes = 51200;
2388 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2389
2390 $this->assertEquals('Site upload limit (10KB)', $result['0']);
2391 $this->assertEquals(2, count($result));
2392
2393 // Test site limit not set.
2394 $sitebytes = 0;
2395 $coursebytes = 102400;
2396 $modulebytes = 51200;
2397 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2398
2399 $this->assertEquals('Activity upload limit (50KB)', $result['0']);
2400 $this->assertEquals(3, count($result));
2401
2402 $sitebytes = 0;
2403 $coursebytes = 51200;
2404 $modulebytes = 102400;
2405 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2406
2407 $this->assertEquals('Course upload limit (50KB)', $result['0']);
2408 $this->assertEquals(3, count($result));
2409
6b219310
DW
2410 // Test custom bytes in range.
2411 $sitebytes = 102400;
2412 $coursebytes = 51200;
2413 $modulebytes = 51200;
2414 $custombytes = 10240;
2415 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2416
2417 $this->assertEquals(3, count($result));
2418
2419 // Test custom bytes in range but non-standard.
2420 $sitebytes = 102400;
2421 $coursebytes = 51200;
2422 $modulebytes = 51200;
2423 $custombytes = 25600;
2424 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2425
2426 $this->assertEquals(4, count($result));
2427
2428 // Test custom bytes out of range.
2429 $sitebytes = 102400;
2430 $coursebytes = 51200;
2431 $modulebytes = 51200;
2432 $custombytes = 102400;
2433 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2434
2435 $this->assertEquals(3, count($result));
2436
2437 // Test custom bytes out of range and non-standard.
2438 $sitebytes = 102400;
2439 $coursebytes = 51200;
2440 $modulebytes = 51200;
2441 $custombytes = 256000;
2442 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2443
2444 $this->assertEquals(3, count($result));
f869cb23
PS
2445
2446 // Test site limit only.
2447 $sitebytes = 51200;
2448 $result = get_max_upload_sizes($sitebytes);
2449
2450 $this->assertEquals('Site upload limit (50KB)', $result['0']);
2451 $this->assertEquals('50KB', $result['51200']);
2452 $this->assertEquals('10KB', $result['10240']);
2453 $this->assertCount(3, $result);
2454
2455 // Test no limit.
2456 $result = get_max_upload_sizes();
2457 $this->assertArrayHasKey('0', $result);
2458 $this->assertArrayHasKey(get_max_upload_file_size(), $result);
6b219310 2459 }
1e7db9fe 2460
ec2d8ceb
SC
2461 /**
2462 * Test function password_is_legacy_hash().
2463 */
2464 public function test_password_is_legacy_hash() {
2465 // Well formed md5s should be matched.
2466 foreach (array('some', 'strings', 'to_check!') as $string) {
2467 $md5 = md5($string);
2468 $this->assertTrue(password_is_legacy_hash($md5));
2469 }
2470 // Strings that are not md5s should not be matched.
2471 foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2472 $this->assertFalse(password_is_legacy_hash($notmd5));
2473 }
2474 }
2475
2476 /**
2477 * Test function validate_internal_user_password().
2478 */
2479 public function test_validate_internal_user_password() {
2480 if (password_compat_not_supported()) {
2481 // If bcrypt is not properly supported test legacy md5 hashes instead.
2482 // Can't hardcode these as we don't know the site's password salt.
2483 $validhashes = array(
2484 'pw' => hash_internal_user_password('pw'),
2485 'abc' => hash_internal_user_password('abc'),
2486 'C0mP1eX_&}<?@*&%` |\"' => hash_internal_user_password('C0mP1eX_&}<?@*&%` |\"'),
2487 'ĩńťėŕňăţĩōŋāĹ' => hash_internal_user_password('ĩńťėŕňăţĩōŋāĹ')
2488 );
2489 } else {
2490 // Otherwise test bcrypt hashes.
2491 $validhashes = array(
2492 'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2493 'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2494 'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2495 'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2496 );
2497 }
2498
2499 foreach ($validhashes as $password => $hash) {
2500 $user = new stdClass();
2501 $user->auth = 'manual';
2502 $user->password = $hash;
2503 // The correct password should be validated.
2504 $this->assertTrue(validate_internal_user_password($user, $password));
2505 // An incorrect password should not be validated.
2506 $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2507 }
2508 }
2509
2510 /**
2511 * Test function hash_internal_user_password().
2512 */
2513 public function test_hash_internal_user_password() {
2514 $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2515
2516 // Check that some passwords that we convert to hashes can
2517 // be validated.
2518 foreach ($passwords as $password) {
2519 $hash = hash_internal_user_password($password);
2520 $fasthash = hash_internal_user_password($password, true);
2521 $user = new stdClass();
2522 $user->auth = 'manual';
2523 $user->password = $hash;
2524 $this->assertTrue(validate_internal_user_password($user, $password));
2525
2526 if (password_compat_not_supported()) {
2527 // If bcrypt is not properly supported make sure the passwords are in md5 format.
2528 $this->assertTrue(password_is_legacy_hash($hash));
2529 } else {
2530 // Otherwise they should not be in md5 format.
2531 $this->assertFalse(password_is_legacy_hash($hash));
2532
2533 // Check that cost factor in hash is correctly set.
2534 $this->assertRegExp('/\$10\$/', $hash);
2535 $this->assertRegExp('/\$04\$/', $fasthash);
2536 }
2537 }
2538 }
2539
2540 /**
2541 * Test function update_internal_user_password().
2542 */
2543 public function test_update_internal_user_password() {
2544 global $DB;
2545 $this->resetAfterTest();
2546 $passwords = array('password', '1234', 'changeme', '****');
2547 foreach ($passwords as $password) {
2548 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2549 update_internal_user_password($user, $password);
2550 // The user object should have been updated.
2551 $this->assertTrue(validate_internal_user_password($user, $password));
2552 // The database field for the user should also have been updated to the
2553 // same value.
2554 $this->assertEquals($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2555 }
2556
2557 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2558 // Manually set the user's password to the md5 of the string 'password'.
2559 $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2560
2561 // Update the password.
2562 update_internal_user_password($user, 'password');
2563
2564 if (password_compat_not_supported()) {
2565 // If bcrypt not properly supported the password should remain as an md5 hash.
2566 $expected_hash = hash_internal_user_password('password', true);
2567 $this->assertEquals($user->password, $expected_hash);
2568 $this->assertTrue(password_is_legacy_hash($user->password));
2569 } else {
2570 // Otherwise password should have been updated to a bcrypt hash.
2571 $this->assertFalse(password_is_legacy_hash($user->password));
2572 }
2573 }
a3d5830a 2574}