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