[BUGFIX] isValidUrl() idna converts whole URI
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Tests / Unit / Utility / GeneralUtilityTest.php
1 <?php
2 namespace TYPO3\CMS\Core\Tests\Unit\Utility;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2009-2013 Ingo Renner <ingo@typo3.org>
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 *
19 * This script is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * This copyright notice MUST APPEAR in all copies of the script!
25 ***************************************************************/
26
27 use TYPO3\CMS\Core\Utility;
28 use \org\bovigo\vfs\vfsStreamDirectory;
29 use \org\bovigo\vfs\vfsStreamWrapper;
30
31 /**
32 * Testcase for class \TYPO3\CMS\Core\Utility\GeneralUtility
33 *
34 * @author Ingo Renner <ingo@typo3.org>
35 * @author Oliver Klee <typo3-coding@oliverklee.de>
36 */
37 class GeneralUtilityTest extends \TYPO3\CMS\Core\Tests\UnitTestCase {
38
39 /**
40 * @var array Files, directories and links to be deleted after a test
41 */
42 protected $testFilesToDelete = array();
43
44 /**
45 * @var array A backup of registered singleton instances
46 */
47 protected $singletonInstances = array();
48
49 public function setUp() {
50 $this->singletonInstances = Utility\GeneralUtility::getSingletonInstances();
51 }
52
53 public function tearDown() {
54 Utility\GeneralUtility::resetSingletonInstances($this->singletonInstances);
55 foreach ($this->testFilesToDelete as $absoluteFileName) {
56 Utility\GeneralUtility::rmdir($absoluteFileName, TRUE);
57 }
58 }
59
60 /**
61 * Helper method to test for an existing internet connection.
62 * Some tests are skipped if there is no working uplink.
63 *
64 * @return boolean $isConnected
65 */
66 public function isConnected() {
67 $isConnected = FALSE;
68 $connected = @fsockopen('typo3.org', 80);
69 if ($connected) {
70 $isConnected = TRUE;
71 fclose($connected);
72 }
73 return $isConnected;
74 }
75
76 ///////////////////////////
77 // Tests concerning _GP
78 ///////////////////////////
79 /**
80 * @test
81 * @dataProvider gpDataProvider
82 */
83 public function canRetrieveValueWithGP($key, $get, $post, $expected) {
84 $_GET = $get;
85 $_POST = $post;
86 $this->assertSame($expected, Utility\GeneralUtility::_GP($key));
87 }
88
89 /**
90 * Data provider for canRetrieveValueWithGP.
91 * All test values also check whether slashes are stripped properly.
92 *
93 * @return array
94 */
95 public function gpDataProvider() {
96 return array(
97 'No key parameter' => array(NULL, array(), array(), NULL),
98 'Key not found' => array('cake', array(), array(), NULL),
99 'Value only in GET' => array('cake', array('cake' => 'li\\e'), array(), 'lie'),
100 'Value only in POST' => array('cake', array(), array('cake' => 'l\\ie'), 'lie'),
101 'Value from POST preferred over GET' => array('cake', array('cake' => 'is a'), array('cake' => '\\lie'), 'lie'),
102 'Value can be an array' => array(
103 'cake',
104 array('cake' => array('is a' => 'l\\ie')),
105 array(),
106 array('is a' => 'lie')
107 )
108 );
109 }
110
111 ///////////////////////////
112 // Tests concerning _GPmerged
113 ///////////////////////////
114 /**
115 * @test
116 * @dataProvider gpMergedDataProvider
117 */
118 public function gpMergedWillMergeArraysFromGetAndPost($get, $post, $expected) {
119 $_POST = $post;
120 $_GET = $get;
121 $this->assertEquals($expected, Utility\GeneralUtility::_GPmerged('cake'));
122 }
123
124 /**
125 * Data provider for gpMergedWillMergeArraysFromGetAndPost
126 *
127 * @return array
128 */
129 public function gpMergedDataProvider() {
130 $fullDataArray = array('cake' => array('a' => 'is a', 'b' => 'lie'));
131 $postPartData = array('cake' => array('b' => 'lie'));
132 $getPartData = array('cake' => array('a' => 'is a'));
133 $getPartDataModified = array('cake' => array('a' => 'is not a'));
134 return array(
135 'Key doesn\' exist' => array(array('foo'), array('bar'), array()),
136 'No POST data' => array($fullDataArray, array(), $fullDataArray['cake']),
137 'No GET data' => array(array(), $fullDataArray, $fullDataArray['cake']),
138 'POST and GET are merged' => array($getPartData, $postPartData, $fullDataArray['cake']),
139 'POST is preferred over GET' => array($getPartDataModified, $fullDataArray, $fullDataArray['cake'])
140 );
141 }
142
143 ///////////////////////////////
144 // Tests concerning _GET / _POST
145 ///////////////////////////////
146 /**
147 * Data provider for canRetrieveGlobalInputsThroughGet
148 * and canRetrieveGlobalInputsThroughPost
149 *
150 * @return array
151 */
152 public function getAndPostDataProvider() {
153 return array(
154 'Requested input data doesn\'t exist' => array('cake', array(), NULL),
155 'No key will return entire input data' => array(NULL, array('cake' => 'l\\ie'), array('cake' => 'lie')),
156 'Can retrieve specific input' => array('cake', array('cake' => 'li\\e', 'foo'), 'lie'),
157 'Can retrieve nested input data' => array('cake', array('cake' => array('is a' => 'l\\ie')), array('is a' => 'lie'))
158 );
159 }
160
161 /**
162 * @test
163 * @dataProvider getAndPostDataProvider
164 */
165 public function canRetrieveGlobalInputsThroughGet($key, $get, $expected) {
166 $_GET = $get;
167 $this->assertSame($expected, Utility\GeneralUtility::_GET($key));
168 }
169
170 /**
171 * @test
172 * @dataProvider getAndPostDataProvider
173 */
174 public function canRetrieveGlobalInputsThroughPost($key, $post, $expected) {
175 $_POST = $post;
176 $this->assertSame($expected, Utility\GeneralUtility::_POST($key));
177 }
178
179 ///////////////////////////////
180 // Tests concerning _GETset
181 ///////////////////////////////
182 /**
183 * @test
184 * @dataProvider getSetDataProvider
185 */
186 public function canSetNewGetInputValues($input, $key, $expected, $getPreset = array()) {
187 $_GET = $getPreset;
188 Utility\GeneralUtility::_GETset($input, $key);
189 $this->assertSame($expected, $_GET);
190 }
191
192 /**
193 * Data provider for canSetNewGetInputValues
194 *
195 * @return array
196 */
197 public function getSetDataProvider() {
198 return array(
199 'No input data used without target key' => array(NULL, NULL, array()),
200 'No input data used with target key' => array(NULL, 'cake', array('cake' => '')),
201 'No target key used with string input data' => array('data', NULL, array()),
202 'No target key used with array input data' => array(array('cake' => 'lie'), NULL, array('cake' => 'lie')),
203 'Target key and string input data' => array('lie', 'cake', array('cake' => 'lie')),
204 'Replace existing GET data' => array('lie', 'cake', array('cake' => 'lie'), array('cake' => 'is a lie')),
205 'Target key pointing to sublevels and string input data' => array('lie', 'cake|is', array('cake' => array('is' => 'lie'))),
206 'Target key pointing to sublevels and array input data' => array(array('a' => 'lie'), 'cake|is', array('cake' => array('is' => array('a' => 'lie'))))
207 );
208 }
209
210 ///////////////////////////////
211 // Tests concerning gif_compress
212 ///////////////////////////////
213 /**
214 * @test
215 */
216 public function gifCompressFixesPermissionOfConvertedFileIfUsingImagemagick() {
217 if (TYPO3_OS == 'WIN') {
218 $this->markTestSkipped('gifCompressFixesPermissionOfConvertedFileIfUsingImagemagick() test not available on Windows.');
219 }
220 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] || !$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']) {
221 $this->markTestSkipped('gifCompressFixesPermissionOfConvertedFileIfUsingImagemagick() test not available without imagemagick setup.');
222 }
223 $fixtureGifFile = __DIR__ . '/Fixtures/clear.gif';
224 $GLOBALS['TYPO3_CONF_VARS']['GFX']['gif_compress'] = TRUE;
225 // Copy file to unique filename in typo3temp, set target permissions and run method
226 $testFilename = PATH_site . 'typo3temp/' . uniqid('test_') . '.gif';
227 $this->testFilesToDelete[] = $testFilename;
228 @copy($fixtureGifFile, $testFilename);
229 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
230 Utility\GeneralUtility::gif_compress($testFilename, 'IM');
231 clearstatcache();
232 $this->assertEquals('0777', substr(decoct(fileperms($testFilename)), 2));
233 }
234
235 /**
236 * @test
237 */
238 public function gifCompressFixesPermissionOfConvertedFileIfUsingGd() {
239 if (TYPO3_OS == 'WIN') {
240 $this->markTestSkipped('gifCompressFixesPermissionOfConvertedFileIfUsingImagemagick() test not available on Windows.');
241 }
242 $fixtureGifFile = __DIR__ . '/Fixtures/clear.gif';
243 $GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib'] = TRUE;
244 $GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib_png'] = FALSE;
245 $GLOBALS['TYPO3_CONF_VARS']['GFX']['gif_compress'] = TRUE;
246 // Copy file to unique filename in typo3temp, set target permissions and run method
247 $testFilename = PATH_site . 'typo3temp/' . uniqid('test_') . '.gif';
248 @copy($fixtureGifFile, $testFilename);
249 $this->testFilesToDelete[] = $testFilename;
250 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
251 Utility\GeneralUtility::gif_compress($testFilename, 'GD');
252 clearstatcache();
253 $this->assertEquals('0777', substr(decoct(fileperms($testFilename)), 2));
254 }
255
256 ///////////////////////////////
257 // Tests concerning png_to_gif_by_imagemagick
258 ///////////////////////////////
259 /**
260 * @test
261 */
262 public function pngToGifByImagemagickFixesPermissionsOfConvertedFile() {
263 if (TYPO3_OS == 'WIN') {
264 $this->markTestSkipped('pngToGifByImagemagickFixesPermissionsOfConvertedFile() test not available on Windows.');
265 }
266 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] || !$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']) {
267 $this->markTestSkipped('pngToGifByImagemagickFixesPermissionsOfConvertedFile() test not available without imagemagick setup.');
268 }
269 $fixturePngFile = __DIR__ . '/Fixtures/clear.png';
270 $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] = TRUE;
271 // Copy file to unique filename in typo3temp, set target permissions and run method
272 $testFilename = PATH_site . 'typo3temp/' . uniqid('test_') . '.png';
273 @copy($fixturePngFile, $testFilename);
274 $this->testFilesToDelete[] = $testFilename;
275 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
276 $newGifFile = Utility\GeneralUtility::png_to_gif_by_imagemagick($testFilename);
277 clearstatcache();
278 $this->assertEquals('0777', substr(decoct(fileperms($newGifFile)), 2));
279 }
280
281 ///////////////////////////////
282 // Tests concerning read_png_gif
283 ///////////////////////////////
284 /**
285 * @test
286 */
287 public function readPngGifFixesPermissionsOfConvertedFile() {
288 if (TYPO3_OS == 'WIN') {
289 $this->markTestSkipped('readPngGifFixesPermissionsOfConvertedFile() test not available on Windows.');
290 }
291 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) {
292 $this->markTestSkipped('readPngGifFixesPermissionsOfConvertedFile() test not available without imagemagick setup.');
293 }
294 $testGifFile = __DIR__ . '/Fixtures/clear.gif';
295 // Set target permissions and run method
296 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
297 $newPngFile = Utility\GeneralUtility::read_png_gif($testGifFile, TRUE);
298 $this->testFilesToDelete[] = $newPngFile;
299 clearstatcache();
300 $this->assertEquals(substr(decoct(fileperms($newPngFile)), 2), '0777');
301 }
302
303 ///////////////////////////
304 // Tests concerning cmpIPv4
305 ///////////////////////////
306 /**
307 * Data provider for cmpIPv4ReturnsTrueForMatchingAddress
308 *
309 * @return array Data sets
310 */
311 static public function cmpIPv4DataProviderMatching() {
312 return array(
313 'host with full IP address' => array('127.0.0.1', '127.0.0.1'),
314 'host with two wildcards at the end' => array('127.0.0.1', '127.0.*.*'),
315 'host with wildcard at third octet' => array('127.0.0.1', '127.0.*.1'),
316 'host with wildcard at second octet' => array('127.0.0.1', '127.*.0.1'),
317 '/8 subnet' => array('127.0.0.1', '127.1.1.1/8'),
318 '/32 subnet (match only name)' => array('127.0.0.1', '127.0.0.1/32'),
319 '/30 subnet' => array('10.10.3.1', '10.10.3.3/30'),
320 'host with wildcard in list with IPv4/IPv6 addresses' => array('192.168.1.1', '127.0.0.1, 1234:5678::/126, 192.168.*'),
321 'host in list with IPv4/IPv6 addresses' => array('192.168.1.1', '::1, 1234:5678::/126, 192.168.1.1'),
322 );
323 }
324
325 /**
326 * @test
327 * @dataProvider cmpIPv4DataProviderMatching
328 */
329 public function cmpIPv4ReturnsTrueForMatchingAddress($ip, $list) {
330 $this->assertTrue(Utility\GeneralUtility::cmpIPv4($ip, $list));
331 }
332
333 /**
334 * Data provider for cmpIPv4ReturnsFalseForNotMatchingAddress
335 *
336 * @return array Data sets
337 */
338 static public function cmpIPv4DataProviderNotMatching() {
339 return array(
340 'single host' => array('127.0.0.1', '127.0.0.2'),
341 'single host with wildcard' => array('127.0.0.1', '127.*.1.1'),
342 'single host with /32 subnet mask' => array('127.0.0.1', '127.0.0.2/32'),
343 '/31 subnet' => array('127.0.0.1', '127.0.0.2/31'),
344 'list with IPv4/IPv6 addresses' => array('127.0.0.1', '10.0.2.3, 192.168.1.1, ::1'),
345 'list with only IPv6 addresses' => array('10.20.30.40', '::1, 1234:5678::/127')
346 );
347 }
348
349 /**
350 * @test
351 * @dataProvider cmpIPv4DataProviderNotMatching
352 */
353 public function cmpIPv4ReturnsFalseForNotMatchingAddress($ip, $list) {
354 $this->assertFalse(Utility\GeneralUtility::cmpIPv4($ip, $list));
355 }
356
357 ///////////////////////////
358 // Tests concerning cmpIPv6
359 ///////////////////////////
360 /**
361 * Data provider for cmpIPv6ReturnsTrueForMatchingAddress
362 *
363 * @return array Data sets
364 */
365 static public function cmpIPv6DataProviderMatching() {
366 return array(
367 'empty address' => array('::', '::'),
368 'empty with netmask in list' => array('::', '::/0'),
369 'empty with netmask 0 and host-bits set in list' => array('::', '::123/0'),
370 'localhost' => array('::1', '::1'),
371 'localhost with leading zero blocks' => array('::1', '0:0::1'),
372 'host with submask /128' => array('::1', '0:0::1/128'),
373 '/16 subnet' => array('1234::1', '1234:5678::/16'),
374 '/126 subnet' => array('1234:5678::3', '1234:5678::/126'),
375 '/126 subnet with host-bits in list set' => array('1234:5678::3', '1234:5678::2/126'),
376 'list with IPv4/IPv6 addresses' => array('1234:5678::3', '::1, 127.0.0.1, 1234:5678::/126, 192.168.1.1')
377 );
378 }
379
380 /**
381 * @test
382 * @dataProvider cmpIPv6DataProviderMatching
383 */
384 public function cmpIPv6ReturnsTrueForMatchingAddress($ip, $list) {
385 $this->assertTrue(Utility\GeneralUtility::cmpIPv6($ip, $list));
386 }
387
388 /**
389 * Data provider for cmpIPv6ReturnsFalseForNotMatchingAddress
390 *
391 * @return array Data sets
392 */
393 static public function cmpIPv6DataProviderNotMatching() {
394 return array(
395 'empty against localhost' => array('::', '::1'),
396 'empty against localhost with /128 netmask' => array('::', '::1/128'),
397 'localhost against different host' => array('::1', '::2'),
398 'localhost against host with prior bits set' => array('::1', '::1:1'),
399 'host against different /17 subnet' => array('1234::1', '1234:f678::/17'),
400 'host against different /127 subnet' => array('1234:5678::3', '1234:5678::/127'),
401 'host against IPv4 address list' => array('1234:5678::3', '127.0.0.1, 192.168.1.1'),
402 'host against mixed list with IPv6 host in different subnet' => array('1234:5678::3', '::1, 1234:5678::/127')
403 );
404 }
405
406 /**
407 * @test
408 * @dataProvider cmpIPv6DataProviderNotMatching
409 */
410 public function cmpIPv6ReturnsFalseForNotMatchingAddress($ip, $list) {
411 $this->assertFalse(Utility\GeneralUtility::cmpIPv6($ip, $list));
412 }
413
414 ///////////////////////////////
415 // Tests concerning IPv6Hex2Bin
416 ///////////////////////////////
417 /**
418 * Data provider for IPv6Hex2BinCorrect
419 *
420 * @return array Data sets
421 */
422 static public function IPv6Hex2BinDataProviderCorrect() {
423 return array(
424 'empty 1' => array('::', str_pad('', 16, "\x00")),
425 'empty 2, already normalized' => array('0000:0000:0000:0000:0000:0000:0000:0000', str_pad('', 16, "\x00")),
426 'already normalized' => array('0102:0304:0000:0000:0000:0000:0506:0078', "\x01\x02\x03\x04" . str_pad('', 8, "\x00") . "\x05\x06\x00\x78"),
427 'expansion in middle 1' => array('1::2', "\x00\x01" . str_pad('', 12, "\x00") . "\x00\x02"),
428 'expansion in middle 2' => array('beef::fefa', "\xbe\xef" . str_pad('', 12, "\x00") . "\xfe\xfa"),
429 );
430 }
431
432 /**
433 * @test
434 * @dataProvider IPv6Hex2BinDataProviderCorrect
435 */
436 public function IPv6Hex2BinCorrectlyConvertsAddresses($hex, $binary) {
437 $this->assertTrue(Utility\GeneralUtility::IPv6Hex2Bin($hex) === $binary);
438 }
439
440 ///////////////////////////////
441 // Tests concerning IPv6Bin2Hex
442 ///////////////////////////////
443 /**
444 * Data provider for IPv6Bin2HexCorrect
445 *
446 * @return array Data sets
447 */
448 static public function IPv6Bin2HexDataProviderCorrect() {
449 return array(
450 'empty' => array(str_pad('', 16, "\x00"), '::'),
451 'non-empty front' => array("\x01" . str_pad('', 15, "\x00"), '100::'),
452 'non-empty back' => array(str_pad('', 15, "\x00") . "\x01", '::1'),
453 'normalized' => array("\x01\x02\x03\x04" . str_pad('', 8, "\x00") . "\x05\x06\x00\x78", '102:304::506:78'),
454 'expansion in middle 1' => array("\x00\x01" . str_pad('', 12, "\x00") . "\x00\x02", '1::2'),
455 'expansion in middle 2' => array("\xbe\xef" . str_pad('', 12, "\x00") . "\xfe\xfa", 'beef::fefa'),
456 );
457 }
458
459 /**
460 * @test
461 * @dataProvider IPv6Bin2HexDataProviderCorrect
462 */
463 public function IPv6Bin2HexCorrectlyConvertsAddresses($binary, $hex) {
464 $this->assertEquals(Utility\GeneralUtility::IPv6Bin2Hex($binary), $hex);
465 }
466
467 ////////////////////////////////////////////////
468 // Tests concerning normalizeIPv6 / compressIPv6
469 ////////////////////////////////////////////////
470 /**
471 * Data provider for normalizeIPv6ReturnsCorrectlyNormalizedFormat
472 *
473 * @return array Data sets
474 */
475 static public function normalizeCompressIPv6DataProviderCorrect() {
476 return array(
477 'empty' => array('::', '0000:0000:0000:0000:0000:0000:0000:0000'),
478 'localhost' => array('::1', '0000:0000:0000:0000:0000:0000:0000:0001'),
479 'expansion in middle 1' => array('1::2', '0001:0000:0000:0000:0000:0000:0000:0002'),
480 'expansion in middle 2' => array('1:2::3', '0001:0002:0000:0000:0000:0000:0000:0003'),
481 'expansion in middle 3' => array('1::2:3', '0001:0000:0000:0000:0000:0000:0002:0003'),
482 'expansion in middle 4' => array('1:2::3:4:5', '0001:0002:0000:0000:0000:0003:0004:0005')
483 );
484 }
485
486 /**
487 * @test
488 * @dataProvider normalizeCompressIPv6DataProviderCorrect
489 */
490 public function normalizeIPv6CorrectlyNormalizesAddresses($compressed, $normalized) {
491 $this->assertEquals($normalized, Utility\GeneralUtility::normalizeIPv6($compressed));
492 }
493
494 /**
495 * @test
496 * @dataProvider normalizeCompressIPv6DataProviderCorrect
497 */
498 public function compressIPv6CorrectlyCompressesAdresses($compressed, $normalized) {
499 $this->assertEquals($compressed, Utility\GeneralUtility::compressIPv6($normalized));
500 }
501
502 /**
503 * @test
504 */
505 public function compressIPv6CorrectlyCompressesAdressWithSomeAddressOnRightSide() {
506 if (strtolower(PHP_OS) === 'darwin') {
507 $this->markTestSkipped('This test does not work on OSX / Darwin OS.');
508 }
509 $this->assertEquals('::f0f', Utility\GeneralUtility::compressIPv6('0000:0000:0000:0000:0000:0000:0000:0f0f'));
510 }
511
512 ///////////////////////////////
513 // Tests concerning validIP
514 ///////////////////////////////
515 /**
516 * Data provider for checkValidIpReturnsTrueForValidIp
517 *
518 * @return array Data sets
519 */
520 static public function validIpDataProvider() {
521 return array(
522 '0.0.0.0' => array('0.0.0.0'),
523 'private IPv4 class C' => array('192.168.0.1'),
524 'private IPv4 class A' => array('10.0.13.1'),
525 'private IPv6' => array('fe80::daa2:5eff:fe8b:7dfb')
526 );
527 }
528
529 /**
530 * @test
531 * @dataProvider validIpDataProvider
532 */
533 public function validIpReturnsTrueForValidIp($ip) {
534 $this->assertTrue(Utility\GeneralUtility::validIP($ip));
535 }
536
537 /**
538 * Data provider for checkValidIpReturnsFalseForInvalidIp
539 *
540 * @return array Data sets
541 */
542 static public function invalidIpDataProvider() {
543 return array(
544 'null' => array(NULL),
545 'zero' => array(0),
546 'string' => array('test'),
547 'string empty' => array(''),
548 'string NULL' => array('NULL'),
549 'out of bounds IPv4' => array('300.300.300.300'),
550 'dotted decimal notation with only two dots' => array('127.0.1')
551 );
552 }
553
554 /**
555 * @test
556 * @dataProvider invalidIpDataProvider
557 */
558 public function validIpReturnsFalseForInvalidIp($ip) {
559 $this->assertFalse(Utility\GeneralUtility::validIP($ip));
560 }
561
562 ///////////////////////////////
563 // Tests concerning cmpFQDN
564 ///////////////////////////////
565 /**
566 * Data provider for cmpFqdnReturnsTrue
567 *
568 * @return array Data sets
569 */
570 static public function cmpFqdnValidDataProvider() {
571 return array(
572 'localhost should usually resolve, IPv4' => array('127.0.0.1', '*'),
573 'localhost should usually resolve, IPv6' => array('::1', '*'),
574 // other testcases with resolving not possible since it would
575 // require a working IPv4/IPv6-connectivity
576 'aaa.bbb.ccc.ddd.eee, full' => array('aaa.bbb.ccc.ddd.eee', 'aaa.bbb.ccc.ddd.eee'),
577 'aaa.bbb.ccc.ddd.eee, wildcard first' => array('aaa.bbb.ccc.ddd.eee', '*.ccc.ddd.eee'),
578 'aaa.bbb.ccc.ddd.eee, wildcard last' => array('aaa.bbb.ccc.ddd.eee', 'aaa.bbb.ccc.*'),
579 'aaa.bbb.ccc.ddd.eee, wildcard middle' => array('aaa.bbb.ccc.ddd.eee', 'aaa.*.eee'),
580 'list-matches, 1' => array('aaa.bbb.ccc.ddd.eee', 'xxx, yyy, zzz, aaa.*.eee'),
581 'list-matches, 2' => array('aaa.bbb.ccc.ddd.eee', '127:0:0:1,,aaa.*.eee,::1')
582 );
583 }
584
585 /**
586 * @test
587 * @dataProvider cmpFqdnValidDataProvider
588 */
589 public function cmpFqdnReturnsTrue($baseHost, $list) {
590 $this->assertTrue(Utility\GeneralUtility::cmpFQDN($baseHost, $list));
591 }
592
593 /**
594 * Data provider for cmpFqdnReturnsFalse
595 *
596 * @return array Data sets
597 */
598 static public function cmpFqdnInvalidDataProvider() {
599 return array(
600 'num-parts of hostname to check can only be less or equal than hostname, 1' => array('aaa.bbb.ccc.ddd.eee', 'aaa.bbb.ccc.ddd.eee.fff'),
601 'num-parts of hostname to check can only be less or equal than hostname, 2' => array('aaa.bbb.ccc.ddd.eee', 'aaa.*.bbb.ccc.ddd.eee')
602 );
603 }
604
605 /**
606 * @test
607 * @dataProvider cmpFqdnInvalidDataProvider
608 */
609 public function cmpFqdnReturnsFalse($baseHost, $list) {
610 $this->assertFalse(Utility\GeneralUtility::cmpFQDN($baseHost, $list));
611 }
612
613 ///////////////////////////////
614 // Tests concerning inList
615 ///////////////////////////////
616 /**
617 * @test
618 * @param string $haystack
619 * @dataProvider inListForItemContainedReturnsTrueDataProvider
620 */
621 public function inListForItemContainedReturnsTrue($haystack) {
622 $this->assertTrue(Utility\GeneralUtility::inList($haystack, 'findme'));
623 }
624
625 /**
626 * Data provider for inListForItemContainedReturnsTrue.
627 *
628 * @return array
629 */
630 public function inListForItemContainedReturnsTrueDataProvider() {
631 return array(
632 'Element as second element of four items' => array('one,findme,three,four'),
633 'Element at beginning of list' => array('findme,one,two'),
634 'Element at end of list' => array('one,two,findme'),
635 'One item list' => array('findme')
636 );
637 }
638
639 /**
640 * @test
641 * @param string $haystack
642 * @dataProvider inListForItemNotContainedReturnsFalseDataProvider
643 */
644 public function inListForItemNotContainedReturnsFalse($haystack) {
645 $this->assertFalse(Utility\GeneralUtility::inList($haystack, 'findme'));
646 }
647
648 /**
649 * Data provider for inListForItemNotContainedReturnsFalse.
650 *
651 * @return array
652 */
653 public function inListForItemNotContainedReturnsFalseDataProvider() {
654 return array(
655 'Four item list' => array('one,two,three,four'),
656 'One item list' => array('one'),
657 'Empty list' => array('')
658 );
659 }
660
661 ///////////////////////////////
662 // Tests concerning rmFromList
663 ///////////////////////////////
664 /**
665 * @test
666 * @param string $initialList
667 * @param string $listWithElementRemoved
668 * @dataProvider rmFromListRemovesElementsFromCommaSeparatedListDataProvider
669 */
670 public function rmFromListRemovesElementsFromCommaSeparatedList($initialList, $listWithElementRemoved) {
671 $this->assertSame($listWithElementRemoved, Utility\GeneralUtility::rmFromList('removeme', $initialList));
672 }
673
674 /**
675 * Data provider for rmFromListRemovesElementsFromCommaSeparatedList
676 *
677 * @return array
678 */
679 public function rmFromListRemovesElementsFromCommaSeparatedListDataProvider() {
680 return array(
681 'Element as second element of three' => array('one,removeme,two', 'one,two'),
682 'Element at beginning of list' => array('removeme,one,two', 'one,two'),
683 'Element at end of list' => array('one,two,removeme', 'one,two'),
684 'One item list' => array('removeme', ''),
685 'Element not contained in list' => array('one,two,three', 'one,two,three'),
686 'Empty list' => array('', '')
687 );
688 }
689
690 ///////////////////////////////
691 // Tests concerning expandList
692 ///////////////////////////////
693 /**
694 * @test
695 * @param string $list
696 * @param string $expectation
697 * @dataProvider expandListExpandsIntegerRangesDataProvider
698 */
699 public function expandListExpandsIntegerRanges($list, $expectation) {
700 $this->assertSame($expectation, Utility\GeneralUtility::expandList($list));
701 }
702
703 /**
704 * Data provider for expandListExpandsIntegerRangesDataProvider
705 *
706 * @return array
707 */
708 public function expandListExpandsIntegerRangesDataProvider() {
709 return array(
710 'Expand for the same number' => array('1,2-2,7', '1,2,7'),
711 'Small range expand with parameters reversed ignores reversed items' => array('1,5-3,7', '1,7'),
712 'Small range expand' => array('1,3-5,7', '1,3,4,5,7'),
713 'Expand at beginning' => array('3-5,1,7', '3,4,5,1,7'),
714 'Expand at end' => array('1,7,3-5', '1,7,3,4,5'),
715 'Multiple small range expands' => array('1,3-5,7-10,12', '1,3,4,5,7,8,9,10,12'),
716 'One item list' => array('1-5', '1,2,3,4,5'),
717 'Nothing to expand' => array('1,2,3,4', '1,2,3,4'),
718 'Empty list' => array('', '')
719 );
720 }
721
722 /**
723 * @test
724 */
725 public function expandListExpandsForTwoThousandElementsExpandsOnlyToThousandElementsMaximum() {
726 $list = Utility\GeneralUtility::expandList('1-2000');
727 $this->assertSame(1000, count(explode(',', $list)));
728 }
729
730 ///////////////////////////////
731 // Tests concerning uniqueList
732 ///////////////////////////////
733 /**
734 * @test
735 * @param string $initialList
736 * @param string $unifiedList
737 * @dataProvider uniqueListUnifiesCommaSeparatedListDataProvider
738 */
739 public function uniqueListUnifiesCommaSeparatedList($initialList, $unifiedList) {
740 $this->assertSame($unifiedList, Utility\GeneralUtility::uniqueList($initialList));
741 }
742
743 /**
744 * Data provider for uniqueListUnifiesCommaSeparatedList
745 *
746 * @return array
747 */
748 public function uniqueListUnifiesCommaSeparatedListDataProvider() {
749 return array(
750 'List without duplicates' => array('one,two,three', 'one,two,three'),
751 'List with two consecutive duplicates' => array('one,two,two,three,three', 'one,two,three'),
752 'List with non-consecutive duplicates' => array('one,two,three,two,three', 'one,two,three'),
753 'One item list' => array('one', 'one'),
754 'Empty list' => array('', '')
755 );
756 }
757
758 ///////////////////////////////
759 // Tests concerning isFirstPartOfStr
760 ///////////////////////////////
761 /**
762 * Data provider for isFirstPartOfStrReturnsTrueForMatchingFirstParts
763 *
764 * @return array
765 */
766 public function isFirstPartOfStrReturnsTrueForMatchingFirstPartDataProvider() {
767 return array(
768 'match first part of string' => array('hello world', 'hello'),
769 'match whole string' => array('hello', 'hello'),
770 'integer is part of string with same number' => array('24', 24),
771 'string is part of integer with same number' => array(24, '24'),
772 'integer is part of string starting with same number' => array('24 beer please', 24)
773 );
774 }
775
776 /**
777 * @test
778 * @dataProvider isFirstPartOfStrReturnsTrueForMatchingFirstPartDataProvider
779 */
780 public function isFirstPartOfStrReturnsTrueForMatchingFirstPart($string, $part) {
781 $this->assertTrue(Utility\GeneralUtility::isFirstPartOfStr($string, $part));
782 }
783
784 /**
785 * Data provider for checkIsFirstPartOfStrReturnsFalseForNotMatchingFirstParts
786 *
787 * @return array
788 */
789 public function isFirstPartOfStrReturnsFalseForNotMatchingFirstPartDataProvider() {
790 return array(
791 'no string match' => array('hello', 'bye'),
792 'no case sensitive string match' => array('hello world', 'Hello'),
793 'array is not part of string' => array('string', array()),
794 'string is not part of array' => array(array(), 'string'),
795 'NULL is not part of string' => array('string', NULL),
796 'string is not part of NULL' => array(NULL, 'string'),
797 'NULL is not part of array' => array(array(), NULL),
798 'array is not part of NULL' => array(NULL, array()),
799 'empty string is not part of empty string' => array('', ''),
800 'NULL is not part of empty string' => array('', NULL),
801 'false is not part of empty string' => array('', FALSE),
802 'empty string is not part of NULL' => array(NULL, ''),
803 'empty string is not part of false' => array(FALSE, ''),
804 'empty string is not part of zero integer' => array(0, ''),
805 'zero integer is not part of NULL' => array(NULL, 0),
806 'zero integer is not part of empty string' => array('', 0)
807 );
808 }
809
810 /**
811 * @test
812 * @dataProvider isFirstPartOfStrReturnsFalseForNotMatchingFirstPartDataProvider
813 */
814 public function isFirstPartOfStrReturnsFalseForNotMatchingFirstPart($string, $part) {
815 $this->assertFalse(Utility\GeneralUtility::isFirstPartOfStr($string, $part));
816 }
817
818 ///////////////////////////////
819 // Tests concerning formatSize
820 ///////////////////////////////
821 /**
822 * @test
823 * @dataProvider formatSizeDataProvider
824 */
825 public function formatSizeTranslatesBytesToHigherOrderRepresentation($size, $label, $expected) {
826 $this->assertEquals($expected, Utility\GeneralUtility::formatSize($size, $label));
827 }
828
829 /**
830 * Data provider for formatSizeTranslatesBytesToHigherOrderRepresentation
831 *
832 * @return array
833 */
834 public function formatSizeDataProvider() {
835 return array(
836 'Bytes keep beeing bytes (min)' => array(1, '', '1 '),
837 'Bytes keep beeing bytes (max)' => array(899, '', '899 '),
838 'Kilobytes are detected' => array(1024, '', '1.0 K'),
839 'Megabytes are detected' => array(1048576, '', '1.0 M'),
840 'Gigabytes are detected' => array(1073741824, '', '1.0 G'),
841 'Decimal is omitted for large kilobytes' => array(31080, '', '30 K'),
842 'Decimal is omitted for large megabytes' => array(31458000, '', '30 M'),
843 'Decimal is omitted for large gigabytes' => array(32212254720, '', '30 G'),
844 'Label for bytes can be exchanged' => array(1, ' Foo|||', '1 Foo'),
845 'Label for kilobytes can be exchanged' => array(1024, '| Foo||', '1.0 Foo'),
846 'Label for megabyes can be exchanged' => array(1048576, '|| Foo|', '1.0 Foo'),
847 'Label for gigabytes can be exchanged' => array(1073741824, '||| Foo', '1.0 Foo')
848 );
849 }
850
851 ///////////////////////////////
852 // Tests concerning splitCalc
853 ///////////////////////////////
854 /**
855 * Data provider for splitCalc
856 *
857 * @return array expected values, arithmetic expression
858 */
859 public function splitCalcDataProvider() {
860 return array(
861 'empty string returns empty array' => array(
862 array(),
863 ''
864 ),
865 'number without operator returns array with plus and number' => array(
866 array(array('+', 42)),
867 '42'
868 ),
869 'two numbers with asterisk return first number with plus and second number with asterisk' => array(
870 array(array('+', 42), array('*', 31)),
871 '42 * 31'
872 )
873 );
874 }
875
876 /**
877 * @test
878 * @dataProvider splitCalcDataProvider
879 */
880 public function splitCalcCorrectlySplitsExpression($expected, $expression) {
881 $this->assertEquals($expected, Utility\GeneralUtility::splitCalc($expression, '+-*/'));
882 }
883
884 ///////////////////////////////
885 // Tests concerning htmlspecialchars_decode
886 ///////////////////////////////
887 /**
888 * @test
889 */
890 public function htmlspecialcharsDecodeReturnsDecodedString() {
891 $string = '<typo3 version="6.0">&nbsp;</typo3>';
892 $encoded = htmlspecialchars($string);
893 $decoded = Utility\GeneralUtility::htmlspecialchars_decode($encoded);
894 $this->assertEquals($string, $decoded);
895 }
896
897 ///////////////////////////////
898 // Tests concerning deHSCentities
899 ///////////////////////////////
900 /**
901 * @test
902 * @dataProvider deHSCentitiesReturnsDecodedStringDataProvider
903 */
904 public function deHSCentitiesReturnsDecodedString($input, $expected) {
905 $this->assertEquals($expected, Utility\GeneralUtility::deHSCentities($input));
906 }
907
908 /**
909 * Data provider for deHSCentitiesReturnsDecodedString
910 *
911 * @return array
912 */
913 public function deHSCentitiesReturnsDecodedStringDataProvider() {
914 return array(
915 'Empty string' => array('', ''),
916 'Double encoded &' => array('&amp;amp;', '&amp;'),
917 'Double encoded numeric entity' => array('&amp;#1234;', '&#1234;'),
918 'Double encoded hexadecimal entity' => array('&amp;#x1b;', '&#x1b;'),
919 'Single encoded entities are not touched' => array('&amp; &#1234; &#x1b;', '&amp; &#1234; &#x1b;')
920 );
921 }
922
923 //////////////////////////////////
924 // Tests concerning slashJS
925 //////////////////////////////////
926 /**
927 * @test
928 * @dataProvider slashJsDataProvider
929 */
930 public function slashJsEscapesSingleQuotesAndSlashes($input, $extended, $expected) {
931 $this->assertEquals($expected, Utility\GeneralUtility::slashJS($input, $extended));
932 }
933
934 /**
935 * Data provider for slashJsEscapesSingleQuotesAndSlashes
936 *
937 * @return array
938 */
939 public function slashJsDataProvider() {
940 return array(
941 'Empty string is not changed' => array('', FALSE, ''),
942 'Normal string is not changed' => array('The cake is a lie √', FALSE, 'The cake is a lie √'),
943 'String with single quotes' => array('The \'cake\' is a lie', FALSE, 'The \\\'cake\\\' is a lie'),
944 'String with single quotes and backslashes - just escape single quotes' => array('The \\\'cake\\\' is a lie', FALSE, 'The \\\\\'cake\\\\\' is a lie'),
945 'String with single quotes and backslashes - escape both' => array('The \\\'cake\\\' is a lie', TRUE, 'The \\\\\\\'cake\\\\\\\' is a lie')
946 );
947 }
948
949 //////////////////////////////////
950 // Tests concerning rawUrlEncodeJS
951 //////////////////////////////////
952 /**
953 * @test
954 */
955 public function rawUrlEncodeJsPreservesWhitespaces() {
956 $input = 'Encode \'me\', but leave my spaces √';
957 $expected = 'Encode %27me%27%2C but leave my spaces %E2%88%9A';
958 $this->assertEquals($expected, Utility\GeneralUtility::rawUrlEncodeJS($input));
959 }
960
961 //////////////////////////////////
962 // Tests concerning rawUrlEncodeJS
963 //////////////////////////////////
964 /**
965 * @test
966 */
967 public function rawUrlEncodeFpPreservesSlashes() {
968 $input = 'Encode \'me\', but leave my / √';
969 $expected = 'Encode%20%27me%27%2C%20but%20leave%20my%20/%20%E2%88%9A';
970 $this->assertEquals($expected, Utility\GeneralUtility::rawUrlEncodeFP($input));
971 }
972
973 //////////////////////////////////
974 // Tests concerning strtoupper / strtolower
975 //////////////////////////////////
976 /**
977 * Data provider for strtoupper and strtolower
978 *
979 * @return array
980 */
981 public function strtouppperDataProvider() {
982 return array(
983 'Empty string' => array('', ''),
984 'String containing only latin characters' => array('the cake is a lie.', 'THE CAKE IS A LIE.'),
985 'String with umlauts and accent characters' => array('the càkê is ä lie.', 'THE CàKê IS ä LIE.')
986 );
987 }
988
989 /**
990 * @test
991 * @dataProvider strtouppperDataProvider
992 */
993 public function strtoupperConvertsOnlyLatinCharacters($input, $expected) {
994 $this->assertEquals($expected, Utility\GeneralUtility::strtoupper($input));
995 }
996
997 /**
998 * @test
999 * @dataProvider strtouppperDataProvider
1000 */
1001 public function strtolowerConvertsOnlyLatinCharacters($expected, $input) {
1002 $this->assertEquals($expected, Utility\GeneralUtility::strtolower($input));
1003 }
1004
1005 //////////////////////////////////
1006 // Tests concerning validEmail
1007 //////////////////////////////////
1008 /**
1009 * Data provider for valid validEmail's
1010 *
1011 * @return array Valid email addresses
1012 */
1013 public function validEmailValidDataProvider() {
1014 return array(
1015 'short mail address' => array('a@b.c'),
1016 'simple mail address' => array('test@example.com'),
1017 'uppercase characters' => array('QWERTYUIOPASDFGHJKLZXCVBNM@QWERTYUIOPASDFGHJKLZXCVBNM.NET'),
1018 // Fix / change if TYPO3 php requirement changed: Address ok with 5.2.6 and 5.3.2 but fails with 5.3.0 on windows
1019 // 'equal sign in local part' => array('test=mail@example.com'),
1020 'dash in local part' => array('test-mail@example.com'),
1021 'plus in local part' => array('test+mail@example.com'),
1022 // Fix / change if TYPO3 php requirement changed: Address ok with 5.2.6 and 5.3.2 but fails with 5.3.0 on windows
1023 // 'question mark in local part' => array('test?mail@example.com'),
1024 'slash in local part' => array('foo/bar@example.com'),
1025 'hash in local part' => array('foo#bar@example.com'),
1026 // Fix / change if TYPO3 php requirement changed: Address ok with 5.2.6 and 5.3.2 but fails with 5.3.0 on windows
1027 // 'dot in local part' => array('firstname.lastname@employee.2something.com'),
1028 // Fix / change if TYPO3 php requirement changed: Address ok with 5.2.6, but not ok with 5.3.2
1029 // 'dash as local part' => array('-@foo.com'),
1030 'umlauts in domain part' => array('foo@äöüfoo.com')
1031 );
1032 }
1033
1034 /**
1035 * @test
1036 * @dataProvider validEmailValidDataProvider
1037 */
1038 public function validEmailReturnsTrueForValidMailAddress($address) {
1039 $this->assertTrue(Utility\GeneralUtility::validEmail($address));
1040 }
1041
1042 /**
1043 * Data provider for invalid validEmail's
1044 *
1045 * @return array Invalid email addresses
1046 */
1047 public function validEmailInvalidDataProvider() {
1048 return array(
1049 'empty string' => array(''),
1050 'empty array' => array(array()),
1051 'integer' => array(42),
1052 'float' => array(42.23),
1053 'array' => array(array('foo')),
1054 'object' => array(new \stdClass()),
1055 '@ sign only' => array('@'),
1056 'string longer than 320 characters' => array(str_repeat('0123456789', 33)),
1057 'duplicate @' => array('test@@example.com'),
1058 'duplicate @ combined with further special characters in local part' => array('test!.!@#$%^&*@example.com'),
1059 'opening parenthesis in local part' => array('foo(bar@example.com'),
1060 'closing parenthesis in local part' => array('foo)bar@example.com'),
1061 'opening square bracket in local part' => array('foo[bar@example.com'),
1062 'closing square bracket as local part' => array(']@example.com'),
1063 // Fix / change if TYPO3 php requirement changed: Address ok with 5.2.6, but not ok with 5.3.2
1064 // 'top level domain only' => array('test@com'),
1065 'dash as second level domain' => array('foo@-.com'),
1066 'domain part starting with dash' => array('foo@-foo.com'),
1067 'domain part ending with dash' => array('foo@foo-.com'),
1068 'number as top level domain' => array('foo@bar.123'),
1069 // Fix / change if TYPO3 php requirement changed: Address not ok with 5.2.6, but ok with 5.3.2 (?)
1070 // 'dash as top level domain' => array('foo@bar.-'),
1071 'dot at beginning of domain part' => array('test@.com'),
1072 // Fix / change if TYPO3 php requirement changed: Address ok with 5.2.6, but not ok with 5.3.2
1073 // 'local part ends with dot' => array('e.x.a.m.p.l.e.@example.com'),
1074 'umlauts in local part' => array('äöüfoo@bar.com'),
1075 'trailing whitespace' => array('test@example.com '),
1076 'trailing carriage return' => array('test@example.com' . CR),
1077 'trailing linefeed' => array('test@example.com' . LF),
1078 'trailing carriage return linefeed' => array('test@example.com' . CRLF),
1079 'trailing tab' => array('test@example.com' . TAB)
1080 );
1081 }
1082
1083 /**
1084 * @test
1085 * @dataProvider validEmailInvalidDataProvider
1086 */
1087 public function validEmailReturnsFalseForInvalidMailAddress($address) {
1088 $this->assertFalse(Utility\GeneralUtility::validEmail($address));
1089 }
1090
1091 //////////////////////////////////
1092 // Tests concerning inArray
1093 //////////////////////////////////
1094 /**
1095 * @test
1096 * @dataProvider inArrayDataProvider
1097 */
1098 public function inArrayChecksStringExistenceWithinArray($array, $item, $expected) {
1099 $this->assertEquals($expected, Utility\GeneralUtility::inArray($array, $item));
1100 }
1101
1102 /**
1103 * Data provider for inArrayChecksStringExistenceWithinArray
1104 *
1105 * @return array
1106 */
1107 public function inArrayDataProvider() {
1108 return array(
1109 'Empty array' => array(array(), 'search', FALSE),
1110 'One item array no match' => array(array('one'), 'two', FALSE),
1111 'One item array match' => array(array('one'), 'one', TRUE),
1112 'Multiple items array no match' => array(array('one', 2, 'three', 4), 'four', FALSE),
1113 'Multiple items array match' => array(array('one', 2, 'three', 4), 'three', TRUE),
1114 'Integer search items can match string values' => array(array('0', '1', '2'), 1, TRUE),
1115 'Search item is not casted to integer for a match' => array(array(4), '4a', FALSE),
1116 'Empty item won\'t match - in contrast to the php-builtin ' => array(array(0, 1, 2), '', FALSE)
1117 );
1118 }
1119
1120 //////////////////////////////////
1121 // Tests concerning intExplode
1122 //////////////////////////////////
1123 /**
1124 * @test
1125 */
1126 public function intExplodeConvertsStringsToInteger() {
1127 $testString = '1,foo,2';
1128 $expectedArray = array(1, 0, 2);
1129 $actualArray = Utility\GeneralUtility::intExplode(',', $testString);
1130 $this->assertEquals($expectedArray, $actualArray);
1131 }
1132
1133 //////////////////////////////////
1134 // Tests concerning keepItemsInArray
1135 //////////////////////////////////
1136 /**
1137 * @test
1138 * @dataProvider keepItemsInArrayWorksWithOneArgumentDataProvider
1139 */
1140 public function keepItemsInArrayWorksWithOneArgument($search, $array, $expected) {
1141 $this->assertEquals($expected, Utility\GeneralUtility::keepItemsInArray($array, $search));
1142 }
1143
1144 /**
1145 * Data provider for keepItemsInArrayWorksWithOneArgument
1146 *
1147 * @return array
1148 */
1149 public function keepItemsInArrayWorksWithOneArgumentDataProvider() {
1150 $array = array(
1151 'one' => 'one',
1152 'two' => 'two',
1153 'three' => 'three'
1154 );
1155 return array(
1156 'Empty argument will match "all" elements' => array(NULL, $array, $array),
1157 'No match' => array('four', $array, array()),
1158 'One match' => array('two', $array, array('two' => 'two')),
1159 'Multiple matches' => array('two,one', $array, array('one' => 'one', 'two' => 'two')),
1160 'Argument can be an array' => array(array('three'), $array, array('three' => 'three'))
1161 );
1162 }
1163
1164 /**
1165 * Shows the exmaple from the doc comment where
1166 * a function is used to reduce the sub arrays to one item which
1167 * is then used for the matching.
1168 *
1169 * @test
1170 */
1171 public function keepItemsInArrayCanUseCallbackOnSearchArray() {
1172 $array = array(
1173 'aa' => array('first', 'second'),
1174 'bb' => array('third', 'fourth'),
1175 'cc' => array('fifth', 'sixth')
1176 );
1177 $expected = array('bb' => array('third', 'fourth'));
1178 $keepItems = 'third';
1179 $getValueFunc = create_function('$value', 'return $value[0];');
1180 $match = Utility\GeneralUtility::keepItemsInArray($array, $keepItems, $getValueFunc);
1181 $this->assertEquals($expected, $match);
1182 }
1183
1184 /**
1185 * Similar to keepItemsInArrayCanUseCallbackOnSearchArray(),
1186 * but uses a closure instead of create_function()
1187 *
1188 * @test
1189 */
1190 public function keepItemsInArrayCanUseClosure() {
1191 $array = array(
1192 'aa' => array('first', 'second'),
1193 'bb' => array('third', 'fourth'),
1194 'cc' => array('fifth', 'sixth')
1195 );
1196 $expected = array('bb' => array('third', 'fourth'));
1197 $keepItems = 'third';
1198 $match = Utility\GeneralUtility::keepItemsInArray(
1199 $array,
1200 $keepItems,
1201 function ($value) {
1202 return $value[0];
1203 }
1204 );
1205 $this->assertEquals($expected, $match);
1206 }
1207
1208 //////////////////////////////////
1209 // Tests concerning implodeArrayForUrl / explodeUrl2Array
1210 //////////////////////////////////
1211 /**
1212 * Data provider for implodeArrayForUrlBuildsValidParameterString and
1213 * explodeUrl2ArrayTransformsParameterStringToArray
1214 *
1215 * @return array
1216 */
1217 public function implodeArrayForUrlDataProvider() {
1218 $valueArray = array('one' => '√', 'two' => 2);
1219 return array(
1220 'Empty input' => array('foo', array(), ''),
1221 'String parameters' => array('foo', $valueArray, '&foo[one]=%E2%88%9A&foo[two]=2'),
1222 'Nested array parameters' => array('foo', array($valueArray), '&foo[0][one]=%E2%88%9A&foo[0][two]=2'),
1223 'Keep blank parameters' => array('foo', array('one' => '√', ''), '&foo[one]=%E2%88%9A&foo[0]=')
1224 );
1225 }
1226
1227 /**
1228 * @test
1229 * @dataProvider implodeArrayForUrlDataProvider
1230 */
1231 public function implodeArrayForUrlBuildsValidParameterString($name, $input, $expected) {
1232 $this->assertSame($expected, Utility\GeneralUtility::implodeArrayForUrl($name, $input));
1233 }
1234
1235 /**
1236 * @test
1237 */
1238 public function implodeArrayForUrlCanSkipEmptyParameters() {
1239 $input = array('one' => '√', '');
1240 $expected = '&foo[one]=%E2%88%9A';
1241 $this->assertSame($expected, Utility\GeneralUtility::implodeArrayForUrl('foo', $input, '', TRUE));
1242 }
1243
1244 /**
1245 * @test
1246 */
1247 public function implodeArrayForUrlCanUrlEncodeKeyNames() {
1248 $input = array('one' => '√', '');
1249 $expected = '&foo%5Bone%5D=%E2%88%9A&foo%5B0%5D=';
1250 $this->assertSame($expected, Utility\GeneralUtility::implodeArrayForUrl('foo', $input, '', FALSE, TRUE));
1251 }
1252
1253 /**
1254 * @test
1255 * @dataProvider implodeArrayForUrlDataProvider
1256 */
1257 public function explodeUrl2ArrayTransformsParameterStringToNestedArray($name, $array, $input) {
1258 $expected = $array ? array($name => $array) : array();
1259 $this->assertEquals($expected, Utility\GeneralUtility::explodeUrl2Array($input, TRUE));
1260 }
1261
1262 /**
1263 * @test
1264 * @dataProvider explodeUrl2ArrayDataProvider
1265 */
1266 public function explodeUrl2ArrayTransformsParameterStringToFlatArray($input, $expected) {
1267 $this->assertEquals($expected, Utility\GeneralUtility::explodeUrl2Array($input, FALSE));
1268 }
1269
1270 /**
1271 * Data provider for explodeUrl2ArrayTransformsParameterStringToFlatArray
1272 *
1273 * @return array
1274 */
1275 public function explodeUrl2ArrayDataProvider() {
1276 return array(
1277 'Empty string' => array('', array()),
1278 'Simple parameter string' => array('&one=%E2%88%9A&two=2', array('one' => '√', 'two' => 2)),
1279 'Nested parameter string' => array('&foo[one]=%E2%88%9A&two=2', array('foo[one]' => '√', 'two' => 2))
1280 );
1281 }
1282
1283 //////////////////////////////////
1284 // Tests concerning compileSelectedGetVarsFromArray
1285 //////////////////////////////////
1286 /**
1287 * @test
1288 */
1289 public function compileSelectedGetVarsFromArrayFiltersIncomingData() {
1290 $filter = 'foo,bar';
1291 $getArray = array('foo' => 1, 'cake' => 'lie');
1292 $expected = array('foo' => 1);
1293 $result = Utility\GeneralUtility::compileSelectedGetVarsFromArray($filter, $getArray, FALSE);
1294 $this->assertSame($expected, $result);
1295 }
1296
1297 /**
1298 * @test
1299 */
1300 public function compileSelectedGetVarsFromArrayUsesGetPostDataFallback() {
1301 $_GET['bar'] = '2';
1302 $filter = 'foo,bar';
1303 $getArray = array('foo' => 1, 'cake' => 'lie');
1304 $expected = array('foo' => 1, 'bar' => '2');
1305 $result = Utility\GeneralUtility::compileSelectedGetVarsFromArray($filter, $getArray, TRUE);
1306 $this->assertSame($expected, $result);
1307 }
1308
1309 //////////////////////////////////
1310 // Tests concerning remapArrayKeys
1311 //////////////////////////////////
1312 /**
1313 * @test
1314 */
1315 public function remapArrayKeysExchangesKeysWithGivenMapping() {
1316 $array = array(
1317 'one' => 'one',
1318 'two' => 'two',
1319 'three' => 'three'
1320 );
1321 $keyMapping = array(
1322 'one' => '1',
1323 'two' => '2'
1324 );
1325 $expected = array(
1326 '1' => 'one',
1327 '2' => 'two',
1328 'three' => 'three'
1329 );
1330 Utility\GeneralUtility::remapArrayKeys($array, $keyMapping);
1331 $this->assertEquals($expected, $array);
1332 }
1333
1334 //////////////////////////////////
1335 // Tests concerning array_merge
1336 //////////////////////////////////
1337 /**
1338 * Test demonstrating array_merge. This is actually
1339 * a native PHP operator, therefore this test is mainly used to
1340 * show how this function can be used.
1341 *
1342 * @test
1343 */
1344 public function arrayMergeKeepsIndexesAfterMerge() {
1345 $array1 = array(10 => 'FOO', '20' => 'BAR');
1346 $array2 = array('5' => 'PLONK');
1347 $expected = array('5' => 'PLONK', 10 => 'FOO', '20' => 'BAR');
1348 $this->assertEquals($expected, Utility\GeneralUtility::array_merge($array1, $array2));
1349 }
1350
1351 //////////////////////////////////
1352 // Tests concerning revExplode
1353 //////////////////////////////////
1354 /**
1355 * @test
1356 */
1357 public function revExplodeExplodesString() {
1358 $testString = 'my:words:here';
1359 $expectedArray = array('my:words', 'here');
1360 $actualArray = Utility\GeneralUtility::revExplode(':', $testString, 2);
1361 $this->assertEquals($expectedArray, $actualArray);
1362 }
1363
1364 //////////////////////////////////
1365 // Tests concerning trimExplode
1366 //////////////////////////////////
1367 /**
1368 * @test
1369 */
1370 public function checkTrimExplodeTrimsSpacesAtElementStartAndEnd() {
1371 $testString = ' a , b , c ,d ,, e,f,';
1372 $expectedArray = array('a', 'b', 'c', 'd', '', 'e', 'f', '');
1373 $actualArray = Utility\GeneralUtility::trimExplode(',', $testString);
1374 $this->assertEquals($expectedArray, $actualArray);
1375 }
1376
1377 /**
1378 * @test
1379 */
1380 public function checkTrimExplodeRemovesNewLines() {
1381 $testString = ' a , b , ' . LF . ' ,d ,, e,f,';
1382 $expectedArray = array('a', 'b', 'd', 'e', 'f');
1383 $actualArray = Utility\GeneralUtility::trimExplode(',', $testString, TRUE);
1384 $this->assertEquals($expectedArray, $actualArray);
1385 }
1386
1387 /**
1388 * @test
1389 */
1390 public function checkTrimExplodeRemovesEmptyElements() {
1391 $testString = 'a , b , c , ,d ,, ,e,f,';
1392 $expectedArray = array('a', 'b', 'c', 'd', 'e', 'f');
1393 $actualArray = Utility\GeneralUtility::trimExplode(',', $testString, TRUE);
1394 $this->assertEquals($expectedArray, $actualArray);
1395 }
1396
1397 /**
1398 * @test
1399 */
1400 public function checkTrimExplodeKeepsRemainingResultsWithEmptyItemsAfterReachingLimitWithPositiveParameter() {
1401 $testString = ' a , b , c , , d,, ,e ';
1402 $expectedArray = array('a', 'b', 'c,,d,,,e');
1403 // Limiting returns the rest of the string as the last element
1404 $actualArray = Utility\GeneralUtility::trimExplode(',', $testString, FALSE, 3);
1405 $this->assertEquals($expectedArray, $actualArray);
1406 }
1407
1408 /**
1409 * @test
1410 */
1411 public function checkTrimExplodeKeepsRemainingResultsWithoutEmptyItemsAfterReachingLimitWithPositiveParameter() {
1412 $testString = ' a , b , c , , d,, ,e ';
1413 $expectedArray = array('a', 'b', 'c,d,e');
1414 // Limiting returns the rest of the string as the last element
1415 $actualArray = Utility\GeneralUtility::trimExplode(',', $testString, TRUE, 3);
1416 $this->assertEquals($expectedArray, $actualArray);
1417 }
1418
1419 /**
1420 * @test
1421 */
1422 public function checkTrimExplodeKeepsRamainingResultsWithEmptyItemsAfterReachingLimitWithNegativeParameter() {
1423 $testString = ' a , b , c , d, ,e, f , , ';
1424 $expectedArray = array('a', 'b', 'c', 'd', '', 'e');
1425 // limiting returns the rest of the string as the last element
1426 $actualArray = Utility\GeneralUtility::trimExplode(',', $testString, FALSE, -3);
1427 $this->assertEquals($expectedArray, $actualArray);
1428 }
1429
1430 /**
1431 * @test
1432 */
1433 public function checkTrimExplodeKeepsRamainingResultsWithoutEmptyItemsAfterReachingLimitWithNegativeParameter() {
1434 $testString = ' a , b , c , d, ,e, f , , ';
1435 $expectedArray = array('a', 'b', 'c');
1436 // Limiting returns the rest of the string as the last element
1437 $actualArray = Utility\GeneralUtility::trimExplode(',', $testString, TRUE, -3);
1438 $this->assertEquals($expectedArray, $actualArray);
1439 }
1440
1441 /**
1442 * @test
1443 */
1444 public function checkTrimExplodeReturnsExactResultsWithoutReachingLimitWithPositiveParameter() {
1445 $testString = ' a , b , , c , , , ';
1446 $expectedArray = array('a', 'b', 'c');
1447 // Limiting returns the rest of the string as the last element
1448 $actualArray = Utility\GeneralUtility::trimExplode(',', $testString, TRUE, 4);
1449 $this->assertEquals($expectedArray, $actualArray);
1450 }
1451
1452 /**
1453 * @test
1454 */
1455 public function checkTrimExplodeKeepsZeroAsString() {
1456 $testString = 'a , b , c , ,d ,, ,e,f, 0 ,';
1457 $expectedArray = array('a', 'b', 'c', 'd', 'e', 'f', '0');
1458 $actualArray = Utility\GeneralUtility::trimExplode(',', $testString, TRUE);
1459 $this->assertEquals($expectedArray, $actualArray);
1460 }
1461
1462 //////////////////////////////////
1463 // Tests concerning removeArrayEntryByValue
1464 //////////////////////////////////
1465 /**
1466 * @test
1467 */
1468 public function checkRemoveArrayEntryByValueRemovesEntriesFromOneDimensionalArray() {
1469 $inputArray = array(
1470 '0' => 'test1',
1471 '1' => 'test2',
1472 '2' => 'test3',
1473 '3' => 'test2'
1474 );
1475 $compareValue = 'test2';
1476 $expectedResult = array(
1477 '0' => 'test1',
1478 '2' => 'test3'
1479 );
1480 $actualResult = Utility\GeneralUtility::removeArrayEntryByValue($inputArray, $compareValue);
1481 $this->assertEquals($expectedResult, $actualResult);
1482 }
1483
1484 /**
1485 * @test
1486 */
1487 public function checkRemoveArrayEntryByValueRemovesEntriesFromMultiDimensionalArray() {
1488 $inputArray = array(
1489 '0' => 'foo',
1490 '1' => array(
1491 '10' => 'bar'
1492 ),
1493 '2' => 'bar'
1494 );
1495 $compareValue = 'bar';
1496 $expectedResult = array(
1497 '0' => 'foo',
1498 '1' => array()
1499 );
1500 $actualResult = Utility\GeneralUtility::removeArrayEntryByValue($inputArray, $compareValue);
1501 $this->assertEquals($expectedResult, $actualResult);
1502 }
1503
1504 /**
1505 * @test
1506 */
1507 public function checkRemoveArrayEntryByValueRemovesEntryWithEmptyString() {
1508 $inputArray = array(
1509 '0' => 'foo',
1510 '1' => '',
1511 '2' => 'bar'
1512 );
1513 $compareValue = '';
1514 $expectedResult = array(
1515 '0' => 'foo',
1516 '2' => 'bar'
1517 );
1518 $actualResult = Utility\GeneralUtility::removeArrayEntryByValue($inputArray, $compareValue);
1519 $this->assertEquals($expectedResult, $actualResult);
1520 }
1521
1522 //////////////////////////////////
1523 // Tests concerning getBytesFromSizeMeasurement
1524 //////////////////////////////////
1525 /**
1526 * Data provider for getBytesFromSizeMeasurement
1527 *
1528 * @return array expected value, input string
1529 */
1530 public function getBytesFromSizeMeasurementDataProvider() {
1531 return array(
1532 '100 kilo Bytes' => array('102400', '100k'),
1533 '100 mega Bytes' => array('104857600', '100m'),
1534 '100 giga Bytes' => array('107374182400', '100g')
1535 );
1536 }
1537
1538 /**
1539 * @test
1540 * @dataProvider getBytesFromSizeMeasurementDataProvider
1541 */
1542 public function getBytesFromSizeMeasurementCalculatesCorrectByteValue($expected, $byteString) {
1543 $this->assertEquals($expected, Utility\GeneralUtility::getBytesFromSizeMeasurement($byteString));
1544 }
1545
1546 //////////////////////////////////
1547 // Tests concerning getIndpEnv
1548 //////////////////////////////////
1549 /**
1550 * @test
1551 */
1552 public function getIndpEnvTypo3SitePathReturnNonEmptyString() {
1553 $this->assertTrue(strlen(Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_PATH')) >= 1);
1554 }
1555
1556 /**
1557 * @test
1558 */
1559 public function getIndpEnvTypo3SitePathReturnsStringStartingWithSlash() {
1560 $result = Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
1561 $this->assertEquals('/', $result[0]);
1562 }
1563
1564 /**
1565 * @test
1566 */
1567 public function getIndpEnvTypo3SitePathReturnsStringEndingWithSlash() {
1568 $result = Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
1569 $this->assertEquals('/', $result[strlen($result) - 1]);
1570 }
1571
1572 /**
1573 * @return array
1574 */
1575 static public function hostnameAndPortDataProvider() {
1576 return array(
1577 'localhost ipv4 without port' => array('127.0.0.1', '127.0.0.1', ''),
1578 'localhost ipv4 with port' => array('127.0.0.1:81', '127.0.0.1', '81'),
1579 'localhost ipv6 without port' => array('[::1]', '[::1]', ''),
1580 'localhost ipv6 with port' => array('[::1]:81', '[::1]', '81'),
1581 'ipv6 without port' => array('[2001:DB8::1]', '[2001:DB8::1]', ''),
1582 'ipv6 with port' => array('[2001:DB8::1]:81', '[2001:DB8::1]', '81'),
1583 'hostname without port' => array('lolli.did.this', 'lolli.did.this', ''),
1584 'hostname with port' => array('lolli.did.this:42', 'lolli.did.this', '42')
1585 );
1586 }
1587
1588 /**
1589 * @test
1590 * @dataProvider hostnameAndPortDataProvider
1591 */
1592 public function getIndpEnvTypo3HostOnlyParsesHostnamesAndIpAdresses($httpHost, $expectedIp) {
1593 $_SERVER['HTTP_HOST'] = $httpHost;
1594 $this->assertEquals($expectedIp, Utility\GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'));
1595 }
1596
1597 /**
1598 * @test
1599 * @dataProvider hostnameAndPortDataProvider
1600 */
1601 public function getIndpEnvTypo3PortParsesHostnamesAndIpAdresses($httpHost, $dummy, $expectedPort) {
1602 $_SERVER['HTTP_HOST'] = $httpHost;
1603 $this->assertEquals($expectedPort, Utility\GeneralUtility::getIndpEnv('TYPO3_PORT'));
1604 }
1605
1606 //////////////////////////////////
1607 // Tests concerning underscoredToUpperCamelCase
1608 //////////////////////////////////
1609 /**
1610 * Data provider for underscoredToUpperCamelCase
1611 *
1612 * @return array expected, input string
1613 */
1614 public function underscoredToUpperCamelCaseDataProvider() {
1615 return array(
1616 'single word' => array('Blogexample', 'blogexample'),
1617 'multiple words' => array('BlogExample', 'blog_example')
1618 );
1619 }
1620
1621 /**
1622 * @test
1623 * @dataProvider underscoredToUpperCamelCaseDataProvider
1624 */
1625 public function underscoredToUpperCamelCase($expected, $inputString) {
1626 $this->assertEquals($expected, Utility\GeneralUtility::underscoredToUpperCamelCase($inputString));
1627 }
1628
1629 //////////////////////////////////
1630 // Tests concerning underscoredToLowerCamelCase
1631 //////////////////////////////////
1632 /**
1633 * Data provider for underscoredToLowerCamelCase
1634 *
1635 * @return array expected, input string
1636 */
1637 public function underscoredToLowerCamelCaseDataProvider() {
1638 return array(
1639 'single word' => array('minimalvalue', 'minimalvalue'),
1640 'multiple words' => array('minimalValue', 'minimal_value')
1641 );
1642 }
1643
1644 /**
1645 * @test
1646 * @dataProvider underscoredToLowerCamelCaseDataProvider
1647 */
1648 public function underscoredToLowerCamelCase($expected, $inputString) {
1649 $this->assertEquals($expected, Utility\GeneralUtility::underscoredToLowerCamelCase($inputString));
1650 }
1651
1652 //////////////////////////////////
1653 // Tests concerning camelCaseToLowerCaseUnderscored
1654 //////////////////////////////////
1655 /**
1656 * Data provider for camelCaseToLowerCaseUnderscored
1657 *
1658 * @return array expected, input string
1659 */
1660 public function camelCaseToLowerCaseUnderscoredDataProvider() {
1661 return array(
1662 'single word' => array('blogexample', 'blogexample'),
1663 'single word starting upper case' => array('blogexample', 'Blogexample'),
1664 'two words starting lower case' => array('minimal_value', 'minimalValue'),
1665 'two words starting upper case' => array('blog_example', 'BlogExample')
1666 );
1667 }
1668
1669 /**
1670 * @test
1671 * @dataProvider camelCaseToLowerCaseUnderscoredDataProvider
1672 */
1673 public function camelCaseToLowerCaseUnderscored($expected, $inputString) {
1674 $this->assertEquals($expected, Utility\GeneralUtility::camelCaseToLowerCaseUnderscored($inputString));
1675 }
1676
1677 //////////////////////////////////
1678 // Tests concerning lcFirst
1679 //////////////////////////////////
1680 /**
1681 * Data provider for lcFirst
1682 *
1683 * @return array expected, input string
1684 */
1685 public function lcfirstDataProvider() {
1686 return array(
1687 'single word' => array('blogexample', 'blogexample'),
1688 'single Word starting upper case' => array('blogexample', 'Blogexample'),
1689 'two words' => array('blogExample', 'BlogExample')
1690 );
1691 }
1692
1693 /**
1694 * @test
1695 * @dataProvider lcfirstDataProvider
1696 */
1697 public function lcFirst($expected, $inputString) {
1698 $this->assertEquals($expected, Utility\GeneralUtility::lcfirst($inputString));
1699 }
1700
1701 //////////////////////////////////
1702 // Tests concerning encodeHeader
1703 //////////////////////////////////
1704 /**
1705 * @test
1706 */
1707 public function encodeHeaderEncodesWhitespacesInQuotedPrintableMailHeader() {
1708 $this->assertEquals('=?utf-8?Q?We_test_whether_the_copyright_character_=C2=A9_is_encoded_correctly?=', Utility\GeneralUtility::encodeHeader('We test whether the copyright character © is encoded correctly', 'quoted-printable', 'utf-8'));
1709 }
1710
1711 /**
1712 * @test
1713 */
1714 public function encodeHeaderEncodesQuestionmarksInQuotedPrintableMailHeader() {
1715 $this->assertEquals('=?utf-8?Q?Is_the_copyright_character_=C2=A9_really_encoded_correctly=3F_Really=3F?=', Utility\GeneralUtility::encodeHeader('Is the copyright character © really encoded correctly? Really?', 'quoted-printable', 'utf-8'));
1716 }
1717
1718 //////////////////////////////////
1719 // Tests concerning isValidUrl
1720 //////////////////////////////////
1721 /**
1722 * Data provider for valid isValidUrl's
1723 *
1724 * @return array Valid resource
1725 */
1726 public function validUrlValidResourceDataProvider() {
1727 return array(
1728 'http' => array('http://www.example.org/'),
1729 'http without trailing slash' => array('http://qwe'),
1730 'http directory with trailing slash' => array('http://www.example/img/dir/'),
1731 'http directory without trailing slash' => array('http://www.example/img/dir'),
1732 'http index.html' => array('http://example.com/index.html'),
1733 'http index.php' => array('http://www.example.com/index.php'),
1734 'http test.png' => array('http://www.example/img/test.png'),
1735 'http username password querystring and ancher' => array('https://user:pw@www.example.org:80/path?arg=value#fragment'),
1736 'file' => array('file:///tmp/test.c'),
1737 'file directory' => array('file://foo/bar'),
1738 'ftp directory' => array('ftp://ftp.example.com/tmp/'),
1739 'mailto' => array('mailto:foo@bar.com'),
1740 'news' => array('news:news.php.net'),
1741 'telnet' => array('telnet://192.0.2.16:80/'),
1742 'ldap' => array('ldap://[2001:db8::7]/c=GB?objectClass?one'),
1743 'http punycode domain name' => array('http://www.xn--bb-eka.at'),
1744 'http punicode subdomain' => array('http://xn--h-zfa.oebb.at'),
1745 'http domain-name umlauts' => array('http://www.öbb.at'),
1746 'http subdomain umlauts' => array('http://äh.oebb.at'),
1747 );
1748 }
1749
1750 /**
1751 * @test
1752 * @dataProvider validUrlValidResourceDataProvider
1753 */
1754 public function validURLReturnsTrueForValidResource($url) {
1755 $this->assertTrue(Utility\GeneralUtility::isValidUrl($url));
1756 }
1757
1758 /**
1759 * Data provider for invalid isValidUrl's
1760 *
1761 * @return array Invalid ressource
1762 */
1763 public function isValidUrlInvalidRessourceDataProvider() {
1764 return array(
1765 'http missing colon' => array('http//www.example/wrong/url/'),
1766 'http missing slash' => array('http:/www.example'),
1767 'hostname only' => array('www.example.org/'),
1768 'file missing protocol specification' => array('/tmp/test.c'),
1769 'slash only' => array('/'),
1770 'string http://' => array('http://'),
1771 'string http:/' => array('http:/'),
1772 'string http:' => array('http:'),
1773 'string http' => array('http'),
1774 'empty string' => array(''),
1775 'string -1' => array('-1'),
1776 'string array()' => array('array()'),
1777 'random string' => array('qwe'),
1778 'http directory umlauts' => array('http://www.oebb.at/äöü/'),
1779 );
1780 }
1781
1782 /**
1783 * @test
1784 * @dataProvider isValidUrlInvalidRessourceDataProvider
1785 */
1786 public function validURLReturnsFalseForInvalidRessoure($url) {
1787 $this->assertFalse(Utility\GeneralUtility::isValidUrl($url));
1788 }
1789
1790 //////////////////////////////////
1791 // Tests concerning isOnCurrentHost
1792 //////////////////////////////////
1793 /**
1794 * @test
1795 */
1796 public function isOnCurrentHostReturnsTrueWithCurrentHost() {
1797 $testUrl = Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL');
1798 $this->assertTrue(Utility\GeneralUtility::isOnCurrentHost($testUrl));
1799 }
1800
1801 /**
1802 * Data provider for invalid isOnCurrentHost's
1803 *
1804 * @return array Invalid Hosts
1805 */
1806 public function checkisOnCurrentHostInvalidHosts() {
1807 return array(
1808 'empty string' => array(''),
1809 'arbitrary string' => array('arbitrary string'),
1810 'localhost IP' => array('127.0.0.1'),
1811 'relative path' => array('./relpath/file.txt'),
1812 'absolute path' => array('/abspath/file.txt?arg=value'),
1813 'differnt host' => array(Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . '.example.org')
1814 );
1815 }
1816
1817 ////////////////////////////////////////
1818 // Tests concerning sanitizeLocalUrl
1819 ////////////////////////////////////////
1820 /**
1821 * Data provider for valid sanitizeLocalUrl's
1822 *
1823 * @return array Valid url
1824 */
1825 public function sanitizeLocalUrlValidUrlDataProvider() {
1826 $subDirectory = Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
1827 $typo3SiteUrl = Utility\GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
1828 $typo3RequestHost = Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST');
1829 return array(
1830 'alt_intro.php' => array('alt_intro.php'),
1831 'alt_intro.php?foo=1&bar=2' => array('alt_intro.php?foo=1&bar=2'),
1832 $subDirectory . 'typo3/alt_intro.php' => array($subDirectory . 'typo3/alt_intro.php'),
1833 $subDirectory . 'index.php' => array($subDirectory . 'index.php'),
1834 '../index.php' => array('../index.php'),
1835 '../typo3/alt_intro.php' => array('../typo3/alt_intro.php'),
1836 '../~userDirectory/index.php' => array('../~userDirectory/index.php'),
1837 '../typo3/mod.php?var1=test-case&var2=~user' => array('../typo3/mod.php?var1=test-case&var2=~user'),
1838 PATH_site . 'typo3/alt_intro.php' => array(PATH_site . 'typo3/alt_intro.php'),
1839 $typo3SiteUrl . 'typo3/alt_intro.php' => array($typo3SiteUrl . 'typo3/alt_intro.php'),
1840 $typo3RequestHost . $subDirectory . '/index.php' => array($typo3RequestHost . $subDirectory . '/index.php')
1841 );
1842 }
1843
1844 /**
1845 * @test
1846 * @dataProvider sanitizeLocalUrlValidUrlDataProvider
1847 */
1848 public function sanitizeLocalUrlAcceptsNotEncodedValidUrls($url) {
1849 $this->assertEquals($url, Utility\GeneralUtility::sanitizeLocalUrl($url));
1850 }
1851
1852 /**
1853 * @test
1854 * @dataProvider sanitizeLocalUrlValidUrlDataProvider
1855 */
1856 public function sanitizeLocalUrlAcceptsEncodedValidUrls($url) {
1857 $this->assertEquals(rawurlencode($url), Utility\GeneralUtility::sanitizeLocalUrl(rawurlencode($url)));
1858 }
1859
1860 /**
1861 * Data provider for invalid sanitizeLocalUrl's
1862 *
1863 * @return array Valid url
1864 */
1865 public function sanitizeLocalUrlInvalidDataProvider() {
1866 return array(
1867 'empty string' => array(''),
1868 'http domain' => array('http://www.google.de/'),
1869 'https domain' => array('https://www.google.de/'),
1870 'relative path with XSS' => array('../typo3/whatever.php?argument=javascript:alert(0)')
1871 );
1872 }
1873
1874 /**
1875 * @test
1876 * @dataProvider sanitizeLocalUrlInvalidDataProvider
1877 */
1878 public function sanitizeLocalUrlDeniesPlainInvalidUrls($url) {
1879 $this->assertEquals('', Utility\GeneralUtility::sanitizeLocalUrl($url));
1880 }
1881
1882 /**
1883 * @test
1884 * @dataProvider sanitizeLocalUrlInvalidDataProvider
1885 */
1886 public function sanitizeLocalUrlDeniesEncodedInvalidUrls($url) {
1887 $this->assertEquals('', Utility\GeneralUtility::sanitizeLocalUrl(rawurlencode($url)));
1888 }
1889
1890 ////////////////////////////////////////
1891 // Tests concerning unlink_tempfile
1892 ////////////////////////////////////////
1893
1894 /**
1895 * @test
1896 */
1897 public function unlink_tempfileRemovesValidFileInTypo3temp() {
1898 $fixtureFile = __DIR__ . '/Fixtures/clear.gif';
1899 $testFilename = PATH_site . 'typo3temp/' . uniqid('test_') . '.gif';
1900 @copy($fixtureFile, $testFilename);
1901 Utility\GeneralUtility::unlink_tempfile($testFilename);
1902 $fileExists = file_exists($testFilename);
1903 $this->assertFalse($fileExists);
1904 }
1905
1906 /**
1907 * @test
1908 */
1909 public function unlink_tempfileRemovesHiddenFile() {
1910 $fixtureFile = __DIR__ . '/Fixtures/clear.gif';
1911 $testFilename = PATH_site . 'typo3temp/' . uniqid('.test_') . '.gif';
1912 @copy($fixtureFile, $testFilename);
1913 Utility\GeneralUtility::unlink_tempfile($testFilename);
1914 $fileExists = file_exists($testFilename);
1915 $this->assertFalse($fileExists);
1916 }
1917
1918 /**
1919 * @test
1920 */
1921 public function unlink_tempfileReturnsTrueIfFileWasRemoved() {
1922 $fixtureFile = __DIR__ . '/Fixtures/clear.gif';
1923 $testFilename = PATH_site . 'typo3temp/' . uniqid('test_') . '.gif';
1924 @copy($fixtureFile, $testFilename);
1925 $returnValue = Utility\GeneralUtility::unlink_tempfile($testFilename);
1926 $this->assertTrue($returnValue);
1927 }
1928
1929 /**
1930 * @test
1931 */
1932 public function unlink_tempfileReturnsNullIfFileDoesNotExist() {
1933 $returnValue = Utility\GeneralUtility::unlink_tempfile(PATH_site . 'typo3temp/' . uniqid('i_do_not_exist'));
1934 $this->assertNull($returnValue);
1935 }
1936
1937 /**
1938 * @test
1939 */
1940 public function unlink_tempfileReturnsNullIfFileIsNowWithinTypo3temp() {
1941 $returnValue = Utility\GeneralUtility::unlink_tempfile('/tmp/typo3-unit-test-unlink_tempfile');
1942 $this->assertNull($returnValue);
1943 }
1944
1945 //////////////////////////////////////
1946 // Tests concerning addSlashesOnArray
1947 //////////////////////////////////////
1948 /**
1949 * @test
1950 */
1951 public function addSlashesOnArrayAddsSlashesRecursive() {
1952 $inputArray = array(
1953 'key1' => array(
1954 'key11' => 'val\'ue1',
1955 'key12' => 'val"ue2'
1956 ),
1957 'key2' => 'val\\ue3'
1958 );
1959 $expectedResult = array(
1960 'key1' => array(
1961 'key11' => 'val\\\'ue1',
1962 'key12' => 'val\\"ue2'
1963 ),
1964 'key2' => 'val\\\\ue3'
1965 );
1966 Utility\GeneralUtility::addSlashesOnArray($inputArray);
1967 $this->assertEquals($expectedResult, $inputArray);
1968 }
1969
1970 //////////////////////////////////////
1971 // Tests concerning addSlashesOnArray
1972 //////////////////////////////////////
1973 /**
1974 * @test
1975 */
1976 public function stripSlashesOnArrayStripsSlashesRecursive() {
1977 $inputArray = array(
1978 'key1' => array(
1979 'key11' => 'val\\\'ue1',
1980 'key12' => 'val\\"ue2'
1981 ),
1982 'key2' => 'val\\\\ue3'
1983 );
1984 $expectedResult = array(
1985 'key1' => array(
1986 'key11' => 'val\'ue1',
1987 'key12' => 'val"ue2'
1988 ),
1989 'key2' => 'val\\ue3'
1990 );
1991 Utility\GeneralUtility::stripSlashesOnArray($inputArray);
1992 $this->assertEquals($expectedResult, $inputArray);
1993 }
1994
1995 //////////////////////////////////////
1996 // Tests concerning arrayDiffAssocRecursive
1997 //////////////////////////////////////
1998 /**
1999 * @test
2000 */
2001 public function arrayDiffAssocRecursiveHandlesOneDimensionalArrays() {
2002 $array1 = array(
2003 'key1' => 'value1',
2004 'key2' => 'value2',
2005 'key3' => 'value3'
2006 );
2007 $array2 = array(
2008 'key1' => 'value1',
2009 'key3' => 'value3'
2010 );
2011 $expectedResult = array(
2012 'key2' => 'value2'
2013 );
2014 $actualResult = Utility\GeneralUtility::arrayDiffAssocRecursive($array1, $array2);
2015 $this->assertEquals($expectedResult, $actualResult);
2016 }
2017
2018 /**
2019 * @test
2020 */
2021 public function arrayDiffAssocRecursiveHandlesMultiDimensionalArrays() {
2022 $array1 = array(
2023 'key1' => 'value1',
2024 'key2' => array(
2025 'key21' => 'value21',
2026 'key22' => 'value22',
2027 'key23' => array(
2028 'key231' => 'value231',
2029 'key232' => 'value232'
2030 )
2031 )
2032 );
2033 $array2 = array(
2034 'key1' => 'value1',
2035 'key2' => array(
2036 'key21' => 'value21',
2037 'key23' => array(
2038 'key231' => 'value231'
2039 )
2040 )
2041 );
2042 $expectedResult = array(
2043 'key2' => array(
2044 'key22' => 'value22',
2045 'key23' => array(
2046 'key232' => 'value232'
2047 )
2048 )
2049 );
2050 $actualResult = Utility\GeneralUtility::arrayDiffAssocRecursive($array1, $array2);
2051 $this->assertEquals($expectedResult, $actualResult);
2052 }
2053
2054 /**
2055 * @test
2056 */
2057 public function arrayDiffAssocRecursiveHandlesMixedArrays() {
2058 $array1 = array(
2059 'key1' => array(
2060 'key11' => 'value11',
2061 'key12' => 'value12'
2062 ),
2063 'key2' => 'value2',
2064 'key3' => 'value3'
2065 );
2066 $array2 = array(
2067 'key1' => 'value1',
2068 'key2' => array(
2069 'key21' => 'value21'
2070 )
2071 );
2072 $expectedResult = array(
2073 'key3' => 'value3'
2074 );
2075 $actualResult = Utility\GeneralUtility::arrayDiffAssocRecursive($array1, $array2);
2076 $this->assertEquals($expectedResult, $actualResult);
2077 }
2078
2079 //////////////////////////////////////
2080 // Tests concerning removeDotsFromTS
2081 //////////////////////////////////////
2082 /**
2083 * @test
2084 */
2085 public function removeDotsFromTypoScriptSucceedsWithDottedArray() {
2086 $typoScript = array(
2087 'propertyA.' => array(
2088 'keyA.' => array(
2089 'valueA' => 1
2090 ),
2091 'keyB' => 2
2092 ),
2093 'propertyB' => 3
2094 );
2095 $expectedResult = array(
2096 'propertyA' => array(
2097 'keyA' => array(
2098 'valueA' => 1
2099 ),
2100 'keyB' => 2
2101 ),
2102 'propertyB' => 3
2103 );
2104 $this->assertEquals($expectedResult, Utility\GeneralUtility::removeDotsFromTS($typoScript));
2105 }
2106
2107 /**
2108 * @test
2109 */
2110 public function removeDotsFromTypoScriptOverridesSubArray() {
2111 $typoScript = array(
2112 'propertyA.' => array(
2113 'keyA' => 'getsOverridden',
2114 'keyA.' => array(
2115 'valueA' => 1
2116 ),
2117 'keyB' => 2
2118 ),
2119 'propertyB' => 3
2120 );
2121 $expectedResult = array(
2122 'propertyA' => array(
2123 'keyA' => array(
2124 'valueA' => 1
2125 ),
2126 'keyB' => 2
2127 ),
2128 'propertyB' => 3
2129 );
2130 $this->assertEquals($expectedResult, Utility\GeneralUtility::removeDotsFromTS($typoScript));
2131 }
2132
2133 /**
2134 * @test
2135 */
2136 public function removeDotsFromTypoScriptOverridesWithScalar() {
2137 $typoScript = array(
2138 'propertyA.' => array(
2139 'keyA.' => array(
2140 'valueA' => 1
2141 ),
2142 'keyA' => 'willOverride',
2143 'keyB' => 2
2144 ),
2145 'propertyB' => 3
2146 );
2147 $expectedResult = array(
2148 'propertyA' => array(
2149 'keyA' => 'willOverride',
2150 'keyB' => 2
2151 ),
2152 'propertyB' => 3
2153 );
2154 $this->assertEquals($expectedResult, Utility\GeneralUtility::removeDotsFromTS($typoScript));
2155 }
2156
2157 //////////////////////////////////////
2158 // Tests concerning naturalKeySortRecursive
2159 //////////////////////////////////////
2160 /**
2161 * @test
2162 */
2163 public function naturalKeySortRecursiveReturnsFalseIfInputIsNotAnArray() {
2164 $testValues = array(
2165 1,
2166 'string',
2167 FALSE
2168 );
2169 foreach ($testValues as $testValue) {
2170 $this->assertFalse(Utility\GeneralUtility::naturalKeySortRecursive($testValue));
2171 }
2172 }
2173
2174 /**
2175 * @test
2176 */
2177 public function naturalKeySortRecursiveSortsOneDimensionalArrayByNaturalOrder() {
2178 $testArray = array(
2179 'bb' => 'bb',
2180 'ab' => 'ab',
2181 '123' => '123',
2182 'aaa' => 'aaa',
2183 'abc' => 'abc',
2184 '23' => '23',
2185 'ba' => 'ba',
2186 'bad' => 'bad',
2187 '2' => '2',
2188 'zap' => 'zap',
2189 '210' => '210'
2190 );
2191 $expectedResult = array(
2192 '2',
2193 '23',
2194 '123',
2195 '210',
2196 'aaa',
2197 'ab',
2198 'abc',
2199 'ba',
2200 'bad',
2201 'bb',
2202 'zap'
2203 );
2204 Utility\GeneralUtility::naturalKeySortRecursive($testArray);
2205 $this->assertEquals($expectedResult, array_values($testArray));
2206 }
2207
2208 /**
2209 * @test
2210 */
2211 public function naturalKeySortRecursiveSortsMultiDimensionalArrayByNaturalOrder() {
2212 $testArray = array(
2213 '2' => '2',
2214 'bb' => 'bb',
2215 'ab' => 'ab',
2216 '23' => '23',
2217 'aaa' => array(
2218 'bb' => 'bb',
2219 'ab' => 'ab',
2220 '123' => '123',
2221 'aaa' => 'aaa',
2222 '2' => '2',
2223 'abc' => 'abc',
2224 'ba' => 'ba',
2225 '23' => '23',
2226 'bad' => array(
2227 'bb' => 'bb',
2228 'ab' => 'ab',
2229 '123' => '123',
2230 'aaa' => 'aaa',
2231 'abc' => 'abc',
2232 '23' => '23',
2233 'ba' => 'ba',
2234 'bad' => 'bad',
2235 '2' => '2',
2236 'zap' => 'zap',
2237 '210' => '210'
2238 ),
2239 '210' => '210',
2240 'zap' => 'zap'
2241 ),
2242 'abc' => 'abc',
2243 'ba' => 'ba',
2244 '210' => '210',
2245 'bad' => 'bad',
2246 '123' => '123',
2247 'zap' => 'zap'
2248 );
2249 $expectedResult = array(
2250 '2',
2251 '23',
2252 '123',
2253 '210',
2254 'aaa',
2255 'ab',
2256 'abc',
2257 'ba',
2258 'bad',
2259 'bb',
2260 'zap'
2261 );
2262 Utility\GeneralUtility::naturalKeySortRecursive($testArray);
2263 $this->assertEquals($expectedResult, array_values(array_keys($testArray['aaa']['bad'])));
2264 $this->assertEquals($expectedResult, array_values(array_keys($testArray['aaa'])));
2265 $this->assertEquals($expectedResult, array_values(array_keys($testArray)));
2266 }
2267
2268 //////////////////////////////////////
2269 // Tests concerning get_dirs
2270 //////////////////////////////////////
2271 /**
2272 * @test
2273 */
2274 public function getDirsReturnsArrayOfDirectoriesFromGivenDirectory() {
2275 $path = PATH_typo3conf;
2276 $directories = Utility\GeneralUtility::get_dirs($path);
2277 $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $directories);
2278 }
2279
2280 /**
2281 * @test
2282 */
2283 public function getDirsReturnsStringErrorOnPathFailure() {
2284 $path = 'foo';
2285 $result = Utility\GeneralUtility::get_dirs($path);
2286 $expectedResult = 'error';
2287 $this->assertEquals($expectedResult, $result);
2288 }
2289
2290 //////////////////////////////////
2291 // Tests concerning hmac
2292 //////////////////////////////////
2293 /**
2294 * @test
2295 */
2296 public function hmacReturnsHashOfProperLength() {
2297 $hmac = Utility\GeneralUtility::hmac('message');
2298 $this->assertTrue(!empty($hmac) && is_string($hmac));
2299 $this->assertTrue(strlen($hmac) == 40);
2300 }
2301
2302 /**
2303 * @test
2304 */
2305 public function hmacReturnsEqualHashesForEqualInput() {
2306 $msg0 = 'message';
2307 $msg1 = 'message';
2308 $this->assertEquals(Utility\GeneralUtility::hmac($msg0), Utility\GeneralUtility::hmac($msg1));
2309 }
2310
2311 /**
2312 * @test
2313 */
2314 public function hmacReturnsNoEqualHashesForNonEqualInput() {
2315 $msg0 = 'message0';
2316 $msg1 = 'message1';
2317 $this->assertNotEquals(Utility\GeneralUtility::hmac($msg0), Utility\GeneralUtility::hmac($msg1));
2318 }
2319
2320 //////////////////////////////////
2321 // Tests concerning quoteJSvalue
2322 //////////////////////////////////
2323 /**
2324 * Data provider for quoteJSvalueTest.
2325 *
2326 * @return array
2327 */
2328 public function quoteJsValueDataProvider() {
2329 return array(
2330 'Immune characters are returned as is' => array(
2331 '._,',
2332 '._,'
2333 ),
2334 'Alphanumerical characters are returned as is' => array(
2335 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
2336 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
2337 ),
2338 'Angel brackets and ampersand are encoded' => array(
2339 '<>&',
2340 '\\x3C\\x3E\\x26'
2341 ),
2342 'Quotes and slashes are encoded' => array(
2343 '"\'\\/',
2344 '\\x22\\x27\\x5C\\x2F'
2345 ),
2346 'Empty string stays empty' => array(
2347 '',
2348 ''
2349 ),
2350 'Exclamation mark and space are properly encoded' => array(
2351 'Hello World!',
2352 'Hello\\x20World\\x21'
2353 ),
2354 'Whitespaces are properly encoded' => array(
2355 TAB . LF . CR . ' ',
2356 '\\x09\\x0A\\x0D\\x20'
2357 ),
2358 'Null byte is properly encoded' => array(
2359 chr(0),
2360 '\\x00'
2361 ),
2362 'Umlauts are properly encoded' => array(
2363 'ÜüÖöÄä',
2364 '\\xDC\\xFC\\xD6\\xF6\\xC4\\xE4'
2365 )
2366 );
2367 }
2368
2369 /**
2370 * @test
2371 * @param string $input
2372 * @param string $expected
2373 * @dataProvider quoteJsValueDataProvider
2374 */
2375 public function quoteJsValueTest($input, $expected) {
2376 $this->assertSame('\'' . $expected . '\'', Utility\GeneralUtility::quoteJSvalue($input));
2377 }
2378
2379 //////////////////////////////////
2380 // Tests concerning readLLfile
2381 //////////////////////////////////
2382 /**
2383 * @test
2384 */
2385 public function readLLfileHandlesLocallangXMLOverride() {
2386 $unique = uniqid('locallangXMLOverrideTest');
2387 $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
2388 <T3locallang>
2389 <data type="array">
2390 <languageKey index="default" type="array">
2391 <label index="buttons.logout">EXIT</label>
2392 </languageKey>
2393 </data>
2394 </T3locallang>';
2395 $file = PATH_site . 'typo3temp/' . $unique . '.xml';
2396 Utility\GeneralUtility::writeFileToTypo3tempDir($file, $xml);
2397 // Make sure there is no cached version of the label
2398 $GLOBALS['typo3CacheManager']->getCache('t3lib_l10n')->flush();
2399 // Get default value
2400 $defaultLL = Utility\GeneralUtility::readLLfile('EXT:lang/locallang_core.xlf', 'default');
2401 // Clear language cache again
2402 $GLOBALS['typo3CacheManager']->getCache('t3lib_l10n')->flush();
2403 // Set override file
2404 $GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride']['EXT:lang/locallang_core.xlf'][$unique] = $file;
2405 /** @var $store \TYPO3\CMS\Core\Localization\LanguageStore */
2406 $store = Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Localization\\LanguageStore');
2407 $store->flushData('EXT:lang/locallang_core.xlf');
2408 // Get override value
2409 $overrideLL = Utility\GeneralUtility::readLLfile('EXT:lang/locallang_core.xlf', 'default');
2410 // Clean up again
2411 unlink($file);
2412 $this->assertNotEquals($overrideLL['default']['buttons.logout'][0]['target'], '');
2413 $this->assertNotEquals($defaultLL['default']['buttons.logout'][0]['target'], $overrideLL['default']['buttons.logout'][0]['target']);
2414 $this->assertEquals($overrideLL['default']['buttons.logout'][0]['target'], 'EXIT');
2415 }
2416
2417 ///////////////////////////////
2418 // Tests concerning _GETset()
2419 ///////////////////////////////
2420 /**
2421 * @test
2422 */
2423 public function getSetWritesArrayToGetSystemVariable() {
2424 $_GET = array();
2425 $GLOBALS['HTTP_GET_VARS'] = array();
2426 $getParameters = array('foo' => 'bar');
2427 Utility\GeneralUtility::_GETset($getParameters);
2428 $this->assertSame($getParameters, $_GET);
2429 }
2430
2431 /**
2432 * @test
2433 */
2434 public function getSetWritesArrayToGlobalsHttpGetVars() {
2435 $_GET = array();
2436 $GLOBALS['HTTP_GET_VARS'] = array();
2437 $getParameters = array('foo' => 'bar');
2438 Utility\GeneralUtility::_GETset($getParameters);
2439 $this->assertSame($getParameters, $GLOBALS['HTTP_GET_VARS']);
2440 }
2441
2442 /**
2443 * @test
2444 */
2445 public function getSetForArrayDropsExistingValues() {
2446 $_GET = array();
2447 $GLOBALS['HTTP_GET_VARS'] = array();
2448 Utility\GeneralUtility::_GETset(array('foo' => 'bar'));
2449 Utility\GeneralUtility::_GETset(array('oneKey' => 'oneValue'));
2450 $this->assertEquals(array('oneKey' => 'oneValue'), $GLOBALS['HTTP_GET_VARS']);
2451 }
2452
2453 /**
2454 * @test
2455 */
2456 public function getSetAssignsOneValueToOneKey() {
2457 $_GET = array();
2458 $GLOBALS['HTTP_GET_VARS'] = array();
2459 Utility\GeneralUtility::_GETset('oneValue', 'oneKey');
2460 $this->assertEquals('oneValue', $GLOBALS['HTTP_GET_VARS']['oneKey']);
2461 }
2462
2463 /**
2464 * @test
2465 */
2466 public function getSetForOneValueDoesNotDropUnrelatedValues() {
2467 $_GET = array();
2468 $GLOBALS['HTTP_GET_VARS'] = array();
2469 Utility\GeneralUtility::_GETset(array('foo' => 'bar'));
2470 Utility\GeneralUtility::_GETset('oneValue', 'oneKey');
2471 $this->assertEquals(array('foo' => 'bar', 'oneKey' => 'oneValue'), $GLOBALS['HTTP_GET_VARS']);
2472 }
2473
2474 /**
2475 * @test
2476 */
2477 public function getSetCanAssignsAnArrayToASpecificArrayElement() {
2478 $_GET = array();
2479 $GLOBALS['HTTP_GET_VARS'] = array();
2480 Utility\GeneralUtility::_GETset(array('childKey' => 'oneValue'), 'parentKey');
2481 $this->assertEquals(array('parentKey' => array('childKey' => 'oneValue')), $GLOBALS['HTTP_GET_VARS']);
2482 }
2483
2484 /**
2485 * @test
2486 */
2487 public function getSetCanAssignAStringValueToASpecificArrayChildElement() {
2488 $_GET = array();
2489 $GLOBALS['HTTP_GET_VARS'] = array();
2490 Utility\GeneralUtility::_GETset('oneValue', 'parentKey|childKey');
2491 $this->assertEquals(array('parentKey' => array('childKey' => 'oneValue')), $GLOBALS['HTTP_GET_VARS']);
2492 }
2493
2494 /**
2495 * @test
2496 */
2497 public function getSetCanAssignAnArrayToASpecificArrayChildElement() {
2498 $_GET = array();
2499 $GLOBALS['HTTP_GET_VARS'] = array();
2500 Utility\GeneralUtility::_GETset(array('key1' => 'value1', 'key2' => 'value2'), 'parentKey|childKey');
2501 $this->assertEquals(array(
2502 'parentKey' => array(
2503 'childKey' => array('key1' => 'value1', 'key2' => 'value2')
2504 )
2505 ), $GLOBALS['HTTP_GET_VARS']);
2506 }
2507
2508 ///////////////////////////
2509 // Tests concerning minifyJavaScript
2510 ///////////////////////////
2511 /**
2512 * @test
2513 */
2514 public function minifyJavaScriptReturnsInputStringIfNoHookIsRegistered() {
2515 unset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript']);
2516 $testString = uniqid('string');
2517 $this->assertSame($testString, Utility\GeneralUtility::minifyJavaScript($testString));
2518 }
2519
2520 /**
2521 * Create an own hook callback class, register as hook, and check
2522 * if given string to compress is given to hook method
2523 *
2524 * @test
2525 */
2526 public function minifyJavaScriptCallsRegisteredHookWithInputString() {
2527 $hookClassName = uniqid('tx_coretest');
2528 $minifyHookMock = $this->getMock('stdClass', array('minify'), array(), $hookClassName);
2529 $functionName = '&' . $hookClassName . '->minify';
2530 $GLOBALS['T3_VAR']['callUserFunction'][$functionName] = array();
2531 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['obj'] = $minifyHookMock;
2532 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['method'] = 'minify';
2533 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'][] = $functionName;
2534 $minifyHookMock->expects($this->once())->method('minify')->will($this->returnCallback(array($this, 'isMinifyJavaScriptHookCalledCallback')));
2535 Utility\GeneralUtility::minifyJavaScript('foo');
2536 }
2537
2538 /**
2539 * Callback function used in minifyJavaScriptCallsRegisteredHookWithInputString test
2540 *
2541 * @param array $params
2542 */
2543 public function isMinifyJavaScriptHookCalledCallback(array $params) {
2544 // We can not throw an exception here, because that would be caught by the
2545 // minifyJavaScript method under test itself. Thus, we just die if the
2546 // input string is not ok.
2547 if ($params['script'] !== 'foo') {
2548 die('broken');
2549 }
2550 }
2551
2552 /**
2553 * Create a hook callback, use callback to throw an exception and check
2554 * if the exception is given as error parameter to the calling method.
2555 *
2556 * @test
2557 */
2558 public function minifyJavaScriptReturnsErrorStringOfHookException() {
2559 $hookClassName = uniqid('tx_coretest');
2560 $minifyHookMock = $this->getMock('stdClass', array('minify'), array(), $hookClassName);
2561 $functionName = '&' . $hookClassName . '->minify';
2562 $GLOBALS['T3_VAR']['callUserFunction'][$functionName] = array();
2563 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['obj'] = $minifyHookMock;
2564 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['method'] = 'minify';
2565 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'][] = $functionName;
2566 $minifyHookMock->expects($this->any())->method('minify')->will($this->returnCallback(array($this, 'minifyJavaScriptErroneousCallback')));
2567 $error = '';
2568 Utility\GeneralUtility::minifyJavaScript('string to compress', $error);
2569 $this->assertSame('Error minifying java script: foo', $error);
2570 }
2571
2572 /**
2573 * Check if the error message that is returned by the hook callback
2574 * is logged to \TYPO3\CMS\Core\Utility\GeneralUtility::devLog.
2575 *
2576 * @test
2577 */
2578 public function minifyJavaScriptWritesExceptionMessageToDevLog() {
2579 $t3libDivMock = uniqid('GeneralUtility');
2580 eval('namespace ' . __NAMESPACE__ . '; class ' . $t3libDivMock . ' extends \\TYPO3\\CMS\\Core\\Utility\\GeneralUtility {' . ' public static function devLog($errorMessage) {' . ' if (!($errorMessage === \'Error minifying java script: foo\')) {' . ' throw new \\UnexpectedValue(\'broken\');' . ' }' . ' throw new \\RuntimeException();' . ' }' . '}');
2581 $t3libDivMock = __NAMESPACE__ . '\\' . $t3libDivMock;
2582 $hookClassName = uniqid('tx_coretest');
2583 $minifyHookMock = $this->getMock('stdClass', array('minify'), array(), $hookClassName);
2584 $functionName = '&' . $hookClassName . '->minify';
2585 $GLOBALS['T3_VAR']['callUserFunction'][$functionName] = array();
2586 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['obj'] = $minifyHookMock;
2587 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['method'] = 'minify';
2588 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'][] = $functionName;
2589 $minifyHookMock->expects($this->any())->method('minify')->will($this->returnCallback(array($this, 'minifyJavaScriptErroneousCallback')));
2590 $this->setExpectedException('\\RuntimeException');
2591 $t3libDivMock::minifyJavaScript('string to compress');
2592 }
2593
2594 /**
2595 * Callback function used in
2596 * minifyJavaScriptReturnsErrorStringOfHookException and
2597 * minifyJavaScriptWritesExceptionMessageToDevLog
2598 *
2599 * @throws \RuntimeException
2600 */
2601 public function minifyJavaScriptErroneousCallback() {
2602 throw new \RuntimeException('foo', 1344888548);
2603 }
2604
2605 ///////////////////////////
2606 // Tests concerning getUrl
2607 ///////////////////////////
2608
2609 /**
2610 * @test
2611 */
2612 public function getUrlWithAdditionalRequestHeadersProvidesHttpHeaderOnError() {
2613 if (!$this->isConnected()) {
2614 $this->markTestSkipped('No internet connection detected');
2615 }
2616 $url = 'http://typo3.org/i-do-not-exist-' . time();
2617 $report = array();
2618 Utility\GeneralUtility::getUrl($url, 0, array(), $report);
2619 $this->assertContains('404', $report['message']);
2620 }
2621
2622 /**
2623 * @test
2624 */
2625 public function getUrlProvidesWithoutAdditionalRequestHeadersHttpHeaderOnError() {
2626 if (!$this->isConnected()) {
2627 $this->markTestSkipped('No internet connection detected');
2628 }
2629 $url = 'http://typo3.org/i-do-not-exist-' . time();
2630 $report = array();
2631 Utility\GeneralUtility::getUrl($url, 0, FALSE, $report);
2632 $this->assertContains('404', $report['message'], 'Did not provide the HTTP response header when requesting a failing URL.');
2633 }
2634
2635 ///////////////////////////////
2636 // Tests concerning fixPermissions
2637 ///////////////////////////////
2638 /**
2639 * @test
2640 */
2641 public function fixPermissionsSetsGroup() {
2642 if (TYPO3_OS == 'WIN') {
2643 $this->markTestSkipped('fixPermissionsSetsGroup() tests not available on Windows');
2644 }
2645 if (!function_exists('posix_getegid')) {
2646 $this->markTestSkipped('Function posix_getegid() not available, fixPermissionsSetsGroup() tests skipped');
2647 }
2648 if (posix_getegid() === -1) {
2649 $this->markTestSkipped('The fixPermissionsSetsGroup() is not available on Mac OS because posix_getegid() always returns -1 on Mac OS.');
2650 }
2651 // Create and prepare test file
2652 $filename = PATH_site . 'typo3temp/' . uniqid('test_');
2653 Utility\GeneralUtility::writeFileToTypo3tempDir($filename, '42');
2654 $this->testFilesToDelete[] = $filename;
2655 $currentGroupId = posix_getegid();
2656 // Set target group and run method
2657 $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'] = $currentGroupId;
2658 Utility\GeneralUtility::fixPermissions($filename);
2659 clearstatcache();
2660 $this->assertEquals($currentGroupId, filegroup($filename));
2661 }
2662
2663 /**
2664 * @test
2665 */
2666 public function fixPermissionsSetsPermissionsToFile() {
2667 if (TYPO3_OS == 'WIN') {
2668 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2669 }
2670 // Create and prepare test file
2671 $filename = PATH_site . 'typo3temp/' . uniqid('test_');
2672 Utility\GeneralUtility::writeFileToTypo3tempDir($filename, '42');
2673 $this->testFilesToDelete[] = $filename;
2674 chmod($filename, 482);
2675 // Set target permissions and run method
2676 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2677 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($filename);
2678 clearstatcache();
2679 $this->assertTrue($fixPermissionsResult);
2680 $this->assertEquals('0660', substr(decoct(fileperms($filename)), 2));
2681 }
2682
2683 /**
2684 * @test
2685 */
2686 public function fixPermissionsSetsPermissionsToHiddenFile() {
2687 if (TYPO3_OS == 'WIN') {
2688 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2689 }
2690 // Create and prepare test file
2691 $filename = PATH_site . 'typo3temp/' . uniqid('.test_');
2692 Utility\GeneralUtility::writeFileToTypo3tempDir($filename, '42');
2693 $this->testFilesToDelete[] = $filename;
2694 chmod($filename, 482);
2695 // Set target permissions and run method
2696 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2697 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($filename);
2698 clearstatcache();
2699 $this->assertTrue($fixPermissionsResult);
2700 $this->assertEquals('0660', substr(decoct(fileperms($filename)), 2));
2701 }
2702
2703 /**
2704 * @test
2705 */
2706 public function fixPermissionsSetsPermissionsToDirectory() {
2707 if (TYPO3_OS == 'WIN') {
2708 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2709 }
2710 // Create and prepare test directory
2711 $directory = PATH_site . 'typo3temp/' . uniqid('test_');
2712 Utility\GeneralUtility::mkdir($directory);
2713 $this->testFilesToDelete[] = $directory;
2714 chmod($directory, 1551);
2715 // Set target permissions and run method
2716 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = '0770';
2717 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($directory);
2718 clearstatcache();
2719 $this->assertTrue($fixPermissionsResult);
2720 $this->assertEquals('0770', substr(decoct(fileperms($directory)), 1));
2721 }
2722
2723 /**
2724 * @test
2725 */
2726 public function fixPermissionsSetsPermissionsToDirectoryWithTrailingSlash() {
2727 if (TYPO3_OS == 'WIN') {
2728 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2729 }
2730 // Create and prepare test directory
2731 $directory = PATH_site . 'typo3temp/' . uniqid('test_');
2732 Utility\GeneralUtility::mkdir($directory);
2733 $this->testFilesToDelete[] = $directory;
2734 chmod($directory, 1551);
2735 // Set target permissions and run method
2736 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = '0770';
2737 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($directory . '/');
2738 // Get actual permissions and clean up
2739 clearstatcache();
2740 $this->assertTrue($fixPermissionsResult);
2741 $this->assertEquals('0770', substr(decoct(fileperms($directory)), 1));
2742 }
2743
2744 /**
2745 * @test
2746 */
2747 public function fixPermissionsSetsPermissionsToHiddenDirectory() {
2748 if (TYPO3_OS == 'WIN') {
2749 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2750 }
2751 // Create and prepare test directory
2752 $directory = PATH_site . 'typo3temp/' . uniqid('.test_');
2753 Utility\GeneralUtility::mkdir($directory);
2754 $this->testFilesToDelete[] = $directory;
2755 chmod($directory, 1551);
2756 // Set target permissions and run method
2757 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = '0770';
2758 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($directory);
2759 // Get actual permissions and clean up
2760 clearstatcache();
2761 $this->assertTrue($fixPermissionsResult);
2762 $this->assertEquals('0770', substr(decoct(fileperms($directory)), 1));
2763 }
2764
2765 /**
2766 * @test
2767 */
2768 public function fixPermissionsCorrectlySetsPermissionsRecursive() {
2769 if (TYPO3_OS == 'WIN') {
2770 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2771 }
2772 // Create and prepare test directory and file structure
2773 $baseDirectory = PATH_site . 'typo3temp/' . uniqid('test_');
2774 Utility\GeneralUtility::mkdir($baseDirectory);
2775 $this->testFilesToDelete[] = $baseDirectory;
2776 chmod($baseDirectory, 1751);
2777 Utility\GeneralUtility::writeFileToTypo3tempDir($baseDirectory . '/file', '42');
2778 chmod($baseDirectory . '/file', 482);
2779 Utility\GeneralUtility::mkdir($baseDirectory . '/foo');
2780 chmod($baseDirectory . '/foo', 1751);
2781 Utility\GeneralUtility::writeFileToTypo3tempDir($baseDirectory . '/foo/file', '42');
2782 chmod($baseDirectory . '/foo/file', 482);
2783 Utility\GeneralUtility::mkdir($baseDirectory . '/.bar');
2784 chmod($baseDirectory . '/.bar', 1751);
2785 // Use this if writeFileToTypo3tempDir is fixed to create hidden files in subdirectories
2786 // \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($baseDirectory . '/.bar/.file', '42');
2787 // \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($baseDirectory . '/.bar/..file2', '42');
2788 touch($baseDirectory . '/.bar/.file', '42');
2789 chmod($baseDirectory . '/.bar/.file', 482);
2790 touch($baseDirectory . '/.bar/..file2', '42');
2791 chmod($baseDirectory . '/.bar/..file2', 482);
2792 // Set target permissions and run method
2793 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2794 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = '0770';
2795 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($baseDirectory, TRUE);
2796 // Get actual permissions
2797 clearstatcache();
2798 $resultBaseDirectoryPermissions = substr(decoct(fileperms($baseDirectory)), 1);
2799 $resultBaseFilePermissions = substr(decoct(fileperms($baseDirectory . '/file')), 2);
2800 $resultFooDirectoryPermissions = substr(decoct(fileperms($baseDirectory . '/foo')), 1);
2801 $resultFooFilePermissions = substr(decoct(fileperms($baseDirectory . '/foo/file')), 2);
2802 $resultBarDirectoryPermissions = substr(decoct(fileperms($baseDirectory . '/.bar')), 1);
2803 $resultBarFilePermissions = substr(decoct(fileperms($baseDirectory . '/.bar/.file')), 2);
2804 $resultBarFile2Permissions = substr(decoct(fileperms($baseDirectory . '/.bar/..file2')), 2);
2805 // Test if everything was ok
2806 $this->assertTrue($fixPermissionsResult);
2807 $this->assertEquals('0770', $resultBaseDirectoryPermissions);
2808 $this->assertEquals('0660', $resultBaseFilePermissions);
2809 $this->assertEquals('0770', $resultFooDirectoryPermissions);
2810 $this->assertEquals('0660', $resultFooFilePermissions);
2811 $this->assertEquals('0770', $resultBarDirectoryPermissions);
2812 $this->assertEquals('0660', $resultBarFilePermissions);
2813 $this->assertEquals('0660', $resultBarFile2Permissions);
2814 }
2815
2816 /**
2817 * @test
2818 */
2819 public function fixPermissionsDoesNotSetPermissionsToNotAllowedPath() {
2820 if (TYPO3_OS == 'WIN') {
2821 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2822 }
2823 // Create and prepare test file
2824 $filename = PATH_site . 'typo3temp/../typo3temp/' . uniqid('test_');
2825 $this->testFilesToDelete[] = $filename;
2826 touch($filename);
2827 chmod($filename, 482);
2828 // Set target permissions and run method
2829 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2830 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($filename);
2831 clearstatcache();
2832 $this->assertFalse($fixPermissionsResult);
2833 }
2834
2835 /**
2836 * @test
2837 */
2838 public function fixPermissionsSetsPermissionsWithRelativeFileReference() {
2839 if (TYPO3_OS == 'WIN') {
2840 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2841 }
2842 $filename = 'typo3temp/' . uniqid('test_');
2843 Utility\GeneralUtility::writeFileToTypo3tempDir(PATH_site . $filename, '42');
2844 $this->testFilesToDelete[] = PATH_site . $filename;
2845 chmod(PATH_site . $filename, 482);
2846 // Set target permissions and run method
2847 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2848 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($filename);
2849 clearstatcache();
2850 $this->assertTrue($fixPermissionsResult);
2851 $this->assertEquals('0660', substr(decoct(fileperms(PATH_site . $filename)), 2));
2852 }
2853
2854 /**
2855 * @test
2856 */
2857 public function fixPermissionsSetsDefaultPermissionsToFile() {
2858 if (TYPO3_OS == 'WIN') {
2859 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2860 }
2861 $filename = PATH_site . 'typo3temp/' . uniqid('test_');
2862 Utility\GeneralUtility::writeFileToTypo3tempDir($filename, '42');
2863 $this->testFilesToDelete[] = $filename;
2864 chmod($filename, 482);
2865 unset($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']);
2866 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($filename);
2867 clearstatcache();
2868 $this->assertTrue($fixPermissionsResult);
2869 $this->assertEquals('0644', substr(decoct(fileperms($filename)), 2));
2870 }
2871
2872 /**
2873 * @test
2874 */
2875 public function fixPermissionsSetsDefaultPermissionsToDirectory() {
2876 if (TYPO3_OS == 'WIN') {
2877 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2878 }
2879 $directory = PATH_site . 'typo3temp/' . uniqid('test_');
2880 Utility\GeneralUtility::mkdir($directory);
2881 $this->testFilesToDelete[] = $directory;
2882 chmod($directory, 1551);
2883 unset($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']);
2884 $fixPermissionsResult = Utility\GeneralUtility::fixPermissions($directory);
2885 clearstatcache();
2886 $this->assertTrue($fixPermissionsResult);
2887 $this->assertEquals('0755', substr(decoct(fileperms($directory)), 1));
2888 }
2889
2890 ///////////////////////////////
2891 // Tests concerning mkdir
2892 ///////////////////////////////
2893 /**
2894 * @test