2 namespace TYPO3\CMS\Core\Tests\Unit\Utility
;
4 /***************************************************************
7 * (c) 2009-2011 Ingo Renner <ingo@typo3.org>
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.
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
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.
24 * This copyright notice MUST APPEAR in all copies of the script!
25 ***************************************************************/
28 * Testcase for class \TYPO3\CMS\Core\Utility\GeneralUtility
30 * @author Ingo Renner <ingo@typo3.org>
31 * @author Oliver Klee <typo3-coding@oliverklee.de>
35 class GeneralUtilityTest
extends \tx_phpunit_testcase
{
38 * Enable backup of global and system variables
42 protected $backupGlobals = TRUE;
45 * Exclude TYPO3_DB from backup/ restore of $GLOBALS
46 * because resource types cannot be handled during serializing
50 protected $backupGlobalsBlacklist = array('TYPO3_DB');
53 * @var array A backup of registered singleton instances
55 protected $singletonInstances = array();
57 public function setUp() {
58 $this->singletonInstances
= \TYPO3\CMS\Core\Utility\GeneralUtility
::getSingletonInstances();
61 public function tearDown() {
62 \TYPO3\CMS\Core\Utility\GeneralUtility
::resetSingletonInstances($this->singletonInstances
);
65 ///////////////////////////
66 // Tests concerning _GP
67 ///////////////////////////
70 * @dataProvider gpDataProvider
72 public function canRetrieveValueWithGP($key, $get, $post, $expected) {
75 $this->assertSame($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::_GP($key));
79 * Data provider for canRetrieveValueWithGP.
80 * All test values also check whether slashes are stripped properly.
84 public function gpDataProvider() {
86 'No key parameter' => array(NULL, array(), array(), NULL),
87 'Key not found' => array('cake', array(), array(), NULL),
88 'Value only in GET' => array('cake', array('cake' => 'li\\e'), array(), 'lie'),
89 'Value only in POST' => array('cake', array(), array('cake' => 'l\\ie'), 'lie'),
90 'Value from POST preferred over GET' => array('cake', array('cake' => 'is a'), array('cake' => '\\lie'), 'lie'),
91 'Value can be an array' => array(
93 array('cake' => array('is a' => 'l\\ie')),
95 array('is a' => 'lie')
100 ///////////////////////////
101 // Tests concerning _GPmerged
102 ///////////////////////////
105 * @dataProvider gpMergedDataProvider
107 public function gpMergedWillMergeArraysFromGetAndPost($get, $post, $expected) {
110 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::_GPmerged('cake'));
114 * Data provider for gpMergedWillMergeArraysFromGetAndPost
118 public function gpMergedDataProvider() {
119 $fullDataArray = array('cake' => array('a' => 'is a', 'b' => 'lie'));
120 $postPartData = array('cake' => array('b' => 'lie'));
121 $getPartData = array('cake' => array('a' => 'is a'));
122 $getPartDataModified = array('cake' => array('a' => 'is not a'));
124 'Key doesn\' exist' => array(array('foo'), array('bar'), array()),
125 'No POST data' => array($fullDataArray, array(), $fullDataArray['cake']),
126 'No GET data' => array(array(), $fullDataArray, $fullDataArray['cake']),
127 'POST and GET are merged' => array($getPartData, $postPartData, $fullDataArray['cake']),
128 'POST is preferred over GET' => array($getPartDataModified, $fullDataArray, $fullDataArray['cake'])
132 ///////////////////////////////
133 // Tests concerning _GET / _POST
134 ///////////////////////////////
136 * Data provider for canRetrieveGlobalInputsThroughGet
137 * and canRetrieveGlobalInputsThroughPost
141 public function getAndPostDataProvider() {
143 'Requested input data doesn\'t exist' => array('cake', array(), NULL),
144 'No key will return entire input data' => array(NULL, array('cake' => 'l\\ie'), array('cake' => 'lie')),
145 'Can retrieve specific input' => array('cake', array('cake' => 'li\\e', 'foo'), 'lie'),
146 'Can retrieve nested input data' => array('cake', array('cake' => array('is a' => 'l\\ie')), array('is a' => 'lie'))
152 * @dataProvider getAndPostDataProvider
154 public function canRetrieveGlobalInputsThroughGet($key, $get, $expected) {
156 $this->assertSame($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::_GET($key));
161 * @dataProvider getAndPostDataProvider
163 public function canRetrieveGlobalInputsThroughPost($key, $post, $expected) {
165 $this->assertSame($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::_POST($key));
168 ///////////////////////////////
169 // Tests concerning _GETset
170 ///////////////////////////////
173 * @dataProvider getSetDataProvider
175 public function canSetNewGetInputValues($input, $key, $expected, $getPreset = array()) {
177 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset($input, $key);
178 $this->assertSame($expected, $_GET);
182 * Data provider for canSetNewGetInputValues
186 public function getSetDataProvider() {
188 'No input data used without target key' => array(NULL, NULL, array()),
189 'No input data used with target key' => array(NULL, 'cake', array('cake' => '')),
190 'No target key used with string input data' => array('data', NULL, array()),
191 'No target key used with array input data' => array(array('cake' => 'lie'), NULL, array('cake' => 'lie')),
192 'Target key and string input data' => array('lie', 'cake', array('cake' => 'lie')),
193 'Replace existing GET data' => array('lie', 'cake', array('cake' => 'lie'), array('cake' => 'is a lie')),
194 'Target key pointing to sublevels and string input data' => array('lie', 'cake|is', array('cake' => array('is' => 'lie'))),
195 'Target key pointing to sublevels and array input data' => array(array('a' => 'lie'), 'cake|is', array('cake' => array('is' => array('a' => 'lie'))))
199 ///////////////////////////////
200 // Tests concerning gif_compress
201 ///////////////////////////////
205 public function gifCompressFixesPermissionOfConvertedFileIfUsingImagemagick() {
206 if (TYPO3_OS
== 'WIN') {
207 $this->markTestSkipped('gifCompressFixesPermissionOfConvertedFileIfUsingImagemagick() test not available on Windows.');
209 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] ||
!$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']) {
210 $this->markTestSkipped('gifCompressFixesPermissionOfConvertedFileIfUsingImagemagick() test not available without imagemagick setup.');
212 $testFinder = \TYPO3\CMS\Core\Utility\GeneralUtility
::makeInstance('Tx_Phpunit_Service_TestFinder');
213 $fixtureGifFile = $testFinder->getAbsoluteCoreTestsPath() . 'Unit/t3lib/fixtures/clear.gif';
214 $GLOBALS['TYPO3_CONF_VARS']['GFX']['gif_compress'] = TRUE;
215 // Copy file to unique filename in typo3temp, set target permissions and run method
216 $testFilename = ((PATH_site
. 'typo3temp/') . uniqid('test_')) . '.gif';
217 @copy
($fixtureGifFile, $testFilename);
218 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
219 \TYPO3\CMS\Core\Utility\GeneralUtility
::gif_compress($testFilename, 'IM');
220 // Get actual permissions and clean up
222 $resultFilePermissions = substr(decoct(fileperms($testFilename)), 2);
223 \TYPO3\CMS\Core\Utility\GeneralUtility
::unlink_tempfile($testFilename);
224 $this->assertEquals($resultFilePermissions, '0777');
230 public function gifCompressFixesPermissionOfConvertedFileIfUsingGd() {
231 if (TYPO3_OS
== 'WIN') {
232 $this->markTestSkipped('gifCompressFixesPermissionOfConvertedFileIfUsingImagemagick() test not available on Windows.');
234 $testFinder = \TYPO3\CMS\Core\Utility\GeneralUtility
::makeInstance('Tx_Phpunit_Service_TestFinder');
235 $fixtureGifFile = $testFinder->getAbsoluteCoreTestsPath() . 'Unit/t3lib/fixtures/clear.gif';
236 $GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib'] = TRUE;
237 $GLOBALS['TYPO3_CONF_VARS']['GFX']['gdlib_png'] = FALSE;
238 $GLOBALS['TYPO3_CONF_VARS']['GFX']['gif_compress'] = TRUE;
239 // Copy file to unique filename in typo3temp, set target permissions and run method
240 $testFilename = ((PATH_site
. 'typo3temp/') . uniqid('test_')) . '.gif';
241 @copy
($fixtureGifFile, $testFilename);
242 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
243 \TYPO3\CMS\Core\Utility\GeneralUtility
::gif_compress($testFilename, 'GD');
244 // Get actual permissions and clean up
246 $resultFilePermissions = substr(decoct(fileperms($testFilename)), 2);
247 \TYPO3\CMS\Core\Utility\GeneralUtility
::unlink_tempfile($testFilename);
248 $this->assertEquals($resultFilePermissions, '0777');
251 ///////////////////////////////
252 // Tests concerning png_to_gif_by_imagemagick
253 ///////////////////////////////
257 public function pngToGifByImagemagickFixesPermissionsOfConvertedFile() {
258 if (TYPO3_OS
== 'WIN') {
259 $this->markTestSkipped('pngToGifByImagemagickFixesPermissionsOfConvertedFile() test not available on Windows.');
261 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] ||
!$GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']) {
262 $this->markTestSkipped('pngToGifByImagemagickFixesPermissionsOfConvertedFile() test not available without imagemagick setup.');
264 $testFinder = \TYPO3\CMS\Core\Utility\GeneralUtility
::makeInstance('Tx_Phpunit_Service_TestFinder');
265 $fixturePngFile = $testFinder->getAbsoluteCoreTestsPath() . 'Unit/t3lib/fixtures/clear.png';
266 $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] = TRUE;
267 // Copy file to unique filename in typo3temp, set target permissions and run method
268 $testFilename = ((PATH_site
. 'typo3temp/') . uniqid('test_')) . '.png';
269 @copy
($fixturePngFile, $testFilename);
270 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
271 $newGifFile = \TYPO3\CMS\Core\Utility\GeneralUtility
::png_to_gif_by_imagemagick($testFilename);
272 // Get actual permissions and clean up
274 $resultFilePermissions = substr(decoct(fileperms($newGifFile)), 2);
275 \TYPO3\CMS\Core\Utility\GeneralUtility
::unlink_tempfile($newGifFile);
276 $this->assertEquals($resultFilePermissions, '0777');
279 ///////////////////////////////
280 // Tests concerning read_png_gif
281 ///////////////////////////////
285 public function readPngGifFixesPermissionsOfConvertedFile() {
286 if (TYPO3_OS
== 'WIN') {
287 $this->markTestSkipped('readPngGifFixesPermissionsOfConvertedFile() test not available on Windows.');
289 if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['im']) {
290 $this->markTestSkipped('readPngGifFixesPermissionsOfConvertedFile() test not available without imagemagick setup.');
292 $testFinder = \TYPO3\CMS\Core\Utility\GeneralUtility
::makeInstance('Tx_Phpunit_Service_TestFinder');
293 $testGifFile = $testFinder->getAbsoluteCoreTestsPath() . 'Unit/t3lib/fixtures/clear.gif';
294 // Set target permissions and run method
295 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0777';
296 $newPngFile = \TYPO3\CMS\Core\Utility\GeneralUtility
::read_png_gif($testGifFile, TRUE);
297 // Get actual permissions and clean up
299 $resultFilePermissions = substr(decoct(fileperms($newPngFile)), 2);
300 \TYPO3\CMS\Core\Utility\GeneralUtility
::unlink_tempfile($newPngFile);
301 $this->assertEquals($resultFilePermissions, '0777');
304 ///////////////////////////
305 // Tests concerning cmpIPv4
306 ///////////////////////////
308 * Data provider for cmpIPv4ReturnsTrueForMatchingAddress
310 * @return array Data sets
312 static public function cmpIPv4DataProviderMatching() {
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'),
328 * @dataProvider cmpIPv4DataProviderMatching
330 public function cmpIPv4ReturnsTrueForMatchingAddress($ip, $list) {
331 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::cmpIPv4($ip, $list));
335 * Data provider for cmpIPv4ReturnsFalseForNotMatchingAddress
337 * @return array Data sets
339 static public function cmpIPv4DataProviderNotMatching() {
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')
352 * @dataProvider cmpIPv4DataProviderNotMatching
354 public function cmpIPv4ReturnsFalseForNotMatchingAddress($ip, $list) {
355 $this->assertFalse(\TYPO3\CMS\Core\Utility\GeneralUtility
::cmpIPv4($ip, $list));
358 ///////////////////////////
359 // Tests concerning cmpIPv6
360 ///////////////////////////
362 * Data provider for cmpIPv6ReturnsTrueForMatchingAddress
364 * @return array Data sets
366 static public function cmpIPv6DataProviderMatching() {
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')
383 * @dataProvider cmpIPv6DataProviderMatching
385 public function cmpIPv6ReturnsTrueForMatchingAddress($ip, $list) {
386 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::cmpIPv6($ip, $list));
390 * Data provider for cmpIPv6ReturnsFalseForNotMatchingAddress
392 * @return array Data sets
394 static public function cmpIPv6DataProviderNotMatching() {
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')
409 * @dataProvider cmpIPv6DataProviderNotMatching
411 public function cmpIPv6ReturnsFalseForNotMatchingAddress($ip, $list) {
412 $this->assertFalse(\TYPO3\CMS\Core\Utility\GeneralUtility
::cmpIPv6($ip, $list));
415 ///////////////////////////////
416 // Tests concerning IPv6Hex2Bin
417 ///////////////////////////////
419 * Data provider for IPv6Hex2BinCorrect
421 * @return array Data sets
423 static public function IPv6Hex2BinDataProviderCorrect() {
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"),
435 * @dataProvider IPv6Hex2BinDataProviderCorrect
437 public function IPv6Hex2BinCorrectlyConvertsAddresses($hex, $binary) {
438 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::IPv6Hex2Bin($hex) === $binary);
441 ///////////////////////////////
442 // Tests concerning IPv6Bin2Hex
443 ///////////////////////////////
445 * Data provider for IPv6Bin2HexCorrect
447 * @return array Data sets
449 static public function IPv6Bin2HexDataProviderCorrect() {
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'),
462 * @dataProvider IPv6Bin2HexDataProviderCorrect
464 public function IPv6Bin2HexCorrectlyConvertsAddresses($binary, $hex) {
465 if (!class_exists('t3lib_diff')) {
466 $this->markTestSkipped('The current version of phpunit relies on t3lib_diff which is removed in 6.0 and thus this test fails. Move t3lib_diff to phpunit and reenable this test.');
468 $this->assertEquals(\TYPO3\CMS\Core\Utility\GeneralUtility
::IPv6Bin2Hex($binary), $hex);
471 ////////////////////////////////////////////////
472 // Tests concerning normalizeIPv6 / compressIPv6
473 ////////////////////////////////////////////////
475 * Data provider for normalizeIPv6ReturnsCorrectlyNormalizedFormat
477 * @return array Data sets
479 static public function normalizeCompressIPv6DataProviderCorrect() {
481 'empty' => array('::', '0000:0000:0000:0000:0000:0000:0000:0000'),
482 'localhost' => array('::1', '0000:0000:0000:0000:0000:0000:0000:0001'),
483 'some address on right side' => array('::f0f', '0000:0000:0000:0000:0000:0000:0000:0f0f'),
484 'expansion in middle 1' => array('1::2', '0001:0000:0000:0000:0000:0000:0000:0002'),
485 'expansion in middle 2' => array('1:2::3', '0001:0002:0000:0000:0000:0000:0000:0003'),
486 'expansion in middle 3' => array('1::2:3', '0001:0000:0000:0000:0000:0000:0002:0003'),
487 'expansion in middle 4' => array('1:2::3:4:5', '0001:0002:0000:0000:0000:0003:0004:0005')
493 * @dataProvider normalizeCompressIPv6DataProviderCorrect
495 public function normalizeIPv6CorrectlyNormalizesAddresses($compressed, $normalized) {
496 $this->assertEquals(\TYPO3\CMS\Core\Utility\GeneralUtility
::normalizeIPv6($compressed), $normalized);
501 * @dataProvider normalizeCompressIPv6DataProviderCorrect
503 public function compressIPv6CorrectlyCompressesAdresses($compressed, $normalized) {
504 if (!class_exists('t3lib_diff')) {
505 $this->markTestSkipped('The current version of phpunit relies on t3lib_diff which is removed in 6.0 and thus this test fails. Move t3lib_diff to phpunit and reenable this test.');
507 $this->assertEquals(\TYPO3\CMS\Core\Utility\GeneralUtility
::compressIPv6($normalized), $compressed);
510 ///////////////////////////////
511 // Tests concerning validIP
512 ///////////////////////////////
514 * Data provider for checkValidIpReturnsTrueForValidIp
516 * @return array Data sets
518 static public function validIpDataProvider() {
520 '0.0.0.0' => array('0.0.0.0'),
521 'private IPv4 class C' => array('192.168.0.1'),
522 'private IPv4 class A' => array('10.0.13.1'),
523 'private IPv6' => array('fe80::daa2:5eff:fe8b:7dfb')
529 * @dataProvider validIpDataProvider
531 public function validIpReturnsTrueForValidIp($ip) {
532 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::validIP($ip));
536 * Data provider for checkValidIpReturnsFalseForInvalidIp
538 * @return array Data sets
540 static public function invalidIpDataProvider() {
542 'null' => array(NULL),
544 'string' => array('test'),
545 'string empty' => array(''),
546 'string NULL' => array('NULL'),
547 'out of bounds IPv4' => array('300.300.300.300'),
548 'dotted decimal notation with only two dots' => array('127.0.1')
554 * @dataProvider invalidIpDataProvider
556 public function validIpReturnsFalseForInvalidIp($ip) {
557 $this->assertFalse(\TYPO3\CMS\Core\Utility\GeneralUtility
::validIP($ip));
560 ///////////////////////////////
561 // Tests concerning cmpFQDN
562 ///////////////////////////////
564 * Data provider for cmpFqdnReturnsTrue
566 * @return array Data sets
568 static public function cmpFqdnValidDataProvider() {
570 'localhost should usually resolve, IPv4' => array('127.0.0.1', '*'),
571 'localhost should usually resolve, IPv6' => array('::1', '*'),
572 // other testcases with resolving not possible since it would
573 // require a working IPv4/IPv6-connectivity
574 'aaa.bbb.ccc.ddd.eee, full' => array('aaa.bbb.ccc.ddd.eee', 'aaa.bbb.ccc.ddd.eee'),
575 'aaa.bbb.ccc.ddd.eee, wildcard first' => array('aaa.bbb.ccc.ddd.eee', '*.ccc.ddd.eee'),
576 'aaa.bbb.ccc.ddd.eee, wildcard last' => array('aaa.bbb.ccc.ddd.eee', 'aaa.bbb.ccc.*'),
577 'aaa.bbb.ccc.ddd.eee, wildcard middle' => array('aaa.bbb.ccc.ddd.eee', 'aaa.*.eee'),
578 'list-matches, 1' => array('aaa.bbb.ccc.ddd.eee', 'xxx, yyy, zzz, aaa.*.eee'),
579 'list-matches, 2' => array('aaa.bbb.ccc.ddd.eee', '127:0:0:1,,aaa.*.eee,::1')
585 * @dataProvider cmpFqdnValidDataProvider
587 public function cmpFqdnReturnsTrue($baseHost, $list) {
588 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::cmpFQDN($baseHost, $list));
592 * Data provider for cmpFqdnReturnsFalse
594 * @return array Data sets
596 static public function cmpFqdnInvalidDataProvider() {
598 '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'),
599 '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')
605 * @dataProvider cmpFqdnInvalidDataProvider
607 public function cmpFqdnReturnsFalse($baseHost, $list) {
608 $this->assertFalse(\TYPO3\CMS\Core\Utility\GeneralUtility
::cmpFQDN($baseHost, $list));
611 ///////////////////////////////
612 // Tests concerning inList
613 ///////////////////////////////
616 * @param string $haystack
617 * @dataProvider inListForItemContainedReturnsTrueDataProvider
619 public function inListForItemContainedReturnsTrue($haystack) {
620 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::inList($haystack, 'findme'));
624 * Data provider for inListForItemContainedReturnsTrue.
628 public function inListForItemContainedReturnsTrueDataProvider() {
630 'Element as second element of four items' => array('one,findme,three,four'),
631 'Element at beginning of list' => array('findme,one,two'),
632 'Element at end of list' => array('one,two,findme'),
633 'One item list' => array('findme')
639 * @param string $haystack
640 * @dataProvider inListForItemNotContainedReturnsFalseDataProvider
642 public function inListForItemNotContainedReturnsFalse($haystack) {
643 $this->assertFalse(\TYPO3\CMS\Core\Utility\GeneralUtility
::inList($haystack, 'findme'));
647 * Data provider for inListForItemNotContainedReturnsFalse.
651 public function inListForItemNotContainedReturnsFalseDataProvider() {
653 'Four item list' => array('one,two,three,four'),
654 'One item list' => array('one'),
655 'Empty list' => array('')
659 ///////////////////////////////
660 // Tests concerning rmFromList
661 ///////////////////////////////
664 * @param string $initialList
665 * @param string $listWithElementRemoved
666 * @dataProvider rmFromListRemovesElementsFromCommaSeparatedListDataProvider
668 public function rmFromListRemovesElementsFromCommaSeparatedList($initialList, $listWithElementRemoved) {
669 $this->assertSame($listWithElementRemoved, \TYPO3\CMS\Core\Utility\GeneralUtility
::rmFromList('removeme', $initialList));
673 * Data provider for rmFromListRemovesElementsFromCommaSeparatedList
677 public function rmFromListRemovesElementsFromCommaSeparatedListDataProvider() {
679 'Element as second element of three' => array('one,removeme,two', 'one,two'),
680 'Element at beginning of list' => array('removeme,one,two', 'one,two'),
681 'Element at end of list' => array('one,two,removeme', 'one,two'),
682 'One item list' => array('removeme', ''),
683 'Element not contained in list' => array('one,two,three', 'one,two,three'),
684 'Empty list' => array('', '')
688 ///////////////////////////////
689 // Tests concerning expandList
690 ///////////////////////////////
693 * @param string $list
694 * @param string $expectation
695 * @dataProvider expandListExpandsIntegerRangesDataProvider
697 public function expandListExpandsIntegerRanges($list, $expectation) {
698 $this->assertSame($expectation, \TYPO3\CMS\Core\Utility\GeneralUtility
::expandList($list));
702 * Data provider for expandListExpandsIntegerRangesDataProvider
706 public function expandListExpandsIntegerRangesDataProvider() {
708 'Expand for the same number' => array('1,2-2,7', '1,2,7'),
709 'Small range expand with parameters reversed ignores reversed items' => array('1,5-3,7', '1,7'),
710 'Small range expand' => array('1,3-5,7', '1,3,4,5,7'),
711 'Expand at beginning' => array('3-5,1,7', '3,4,5,1,7'),
712 'Expand at end' => array('1,7,3-5', '1,7,3,4,5'),
713 'Multiple small range expands' => array('1,3-5,7-10,12', '1,3,4,5,7,8,9,10,12'),
714 'One item list' => array('1-5', '1,2,3,4,5'),
715 'Nothing to expand' => array('1,2,3,4', '1,2,3,4'),
716 'Empty list' => array('', '')
723 public function expandListExpandsForTwoThousandElementsExpandsOnlyToThousandElementsMaximum() {
724 $list = \TYPO3\CMS\Core\Utility\GeneralUtility
::expandList('1-2000');
725 $this->assertSame(1000, count(explode(',', $list)));
728 ///////////////////////////////
729 // Tests concerning uniqueList
730 ///////////////////////////////
733 * @param string $initialList
734 * @param string $unifiedList
735 * @dataProvider uniqueListUnifiesCommaSeparatedListDataProvider
737 public function uniqueListUnifiesCommaSeparatedList($initialList, $unifiedList) {
738 $this->assertSame($unifiedList, \TYPO3\CMS\Core\Utility\GeneralUtility
::uniqueList($initialList));
742 * Data provider for uniqueListUnifiesCommaSeparatedList
746 public function uniqueListUnifiesCommaSeparatedListDataProvider() {
748 'List without duplicates' => array('one,two,three', 'one,two,three'),
749 'List with two consecutive duplicates' => array('one,two,two,three,three', 'one,two,three'),
750 'List with non-consecutive duplicates' => array('one,two,three,two,three', 'one,two,three'),
751 'One item list' => array('one', 'one'),
752 'Empty list' => array('', '')
756 ///////////////////////////////
757 // Tests concerning isFirstPartOfStr
758 ///////////////////////////////
760 * Data provider for isFirstPartOfStrReturnsTrueForMatchingFirstParts
764 public function isFirstPartOfStrReturnsTrueForMatchingFirstPartDataProvider() {
766 'match first part of string' => array('hello world', 'hello'),
767 'match whole string' => array('hello', 'hello'),
768 'integer is part of string with same number' => array('24', 24),
769 'string is part of integer with same number' => array(24, '24'),
770 'integer is part of string starting with same number' => array('24 beer please', 24)
776 * @dataProvider isFirstPartOfStrReturnsTrueForMatchingFirstPartDataProvider
778 public function isFirstPartOfStrReturnsTrueForMatchingFirstPart($string, $part) {
779 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::isFirstPartOfStr($string, $part));
783 * Data provider for checkIsFirstPartOfStrReturnsFalseForNotMatchingFirstParts
787 public function isFirstPartOfStrReturnsFalseForNotMatchingFirstPartDataProvider() {
789 'no string match' => array('hello', 'bye'),
790 'no case sensitive string match' => array('hello world', 'Hello'),
791 'array is not part of string' => array('string', array()),
792 'string is not part of array' => array(array(), 'string'),
793 'NULL is not part of string' => array('string', NULL),
794 'string is not part of array' => array(NULL, 'string'),
795 'NULL is not part of array' => array(array(), NULL),
796 'array is not part of string' => array(NULL, array()),
797 'empty string is not part of empty string' => array('', ''),
798 'NULL is not part of empty string' => array('', NULL),
799 'false is not part of empty string' => array('', FALSE),
800 'empty string is not part of NULL' => array(NULL, ''),
801 'empty string is not part of false' => array(FALSE, ''),
802 'empty string is not part of zero integer' => array(0, ''),
803 'zero integer is not part of NULL' => array(NULL, 0),
804 'zero integer is not part of empty string' => array('', 0)
810 * @dataProvider isFirstPartOfStrReturnsFalseForNotMatchingFirstPartDataProvider
812 public function isFirstPartOfStrReturnsFalseForNotMatchingFirstPart($string, $part) {
813 $this->assertFalse(\TYPO3\CMS\Core\Utility\GeneralUtility
::isFirstPartOfStr($string, $part));
816 ///////////////////////////////
817 // Tests concerning formatSize
818 ///////////////////////////////
821 * @dataProvider formatSizeDataProvider
823 public function formatSizeTranslatesBytesToHigherOrderRepresentation($size, $label, $expected) {
824 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::formatSize($size, $label));
828 * Data provider for formatSizeTranslatesBytesToHigherOrderRepresentation
832 public function formatSizeDataProvider() {
834 'Bytes keep beeing bytes (min)' => array(1, '', '1 '),
835 'Bytes keep beeing bytes (max)' => array(899, '', '899 '),
836 'Kilobytes are detected' => array(1024, '', '1.0 K'),
837 'Megabytes are detected' => array(1048576, '', '1.0 M'),
838 'Gigabytes are detected' => array(1073741824, '', '1.0 G'),
839 'Decimal is omitted for large kilobytes' => array(31080, '', '30 K'),
840 'Decimal is omitted for large megabytes' => array(31458000, '', '30 M'),
841 'Decimal is omitted for large gigabytes' => array(32212254720, '', '30 G'),
842 'Label for bytes can be exchanged' => array(1, ' Foo|||', '1 Foo'),
843 'Label for kilobytes can be exchanged' => array(1024, '| Foo||', '1.0 Foo'),
844 'Label for megabyes can be exchanged' => array(1048576, '|| Foo|', '1.0 Foo'),
845 'Label for gigabytes can be exchanged' => array(1073741824, '||| Foo', '1.0 Foo')
849 ///////////////////////////////
850 // Tests concerning splitCalc
851 ///////////////////////////////
853 * Data provider for splitCalc
855 * @return array expected values, arithmetic expression
857 public function splitCalcDataProvider() {
859 'empty string returns empty array' => array(
863 'number without operator returns array with plus and number' => array(
864 array(array('+', 42)),
867 'two numbers with asterisk return first number with plus and second number with asterisk' => array(
868 array(array('+', 42), array('*', 31)),
876 * @dataProvider splitCalcDataProvider
878 public function splitCalcCorrectlySplitsExpression($expected, $expression) {
879 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::splitCalc($expression, '+-*/'));
882 ///////////////////////////////
883 // Tests concerning htmlspecialchars_decode
884 ///////////////////////////////
888 public function htmlspecialcharsDecodeReturnsDecodedString() {
889 $string = '<typo3 version="6.0"> </typo3>';
890 $encoded = htmlspecialchars($string);
891 $decoded = \TYPO3\CMS\Core\Utility\GeneralUtility
::htmlspecialchars_decode($encoded);
892 $this->assertEquals($string, $decoded);
895 ///////////////////////////////
896 // Tests concerning deHSCentities
897 ///////////////////////////////
900 * @dataProvider deHSCentitiesReturnsDecodedStringDataProvider
902 public function deHSCentitiesReturnsDecodedString($input, $expected) {
903 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::deHSCentities($input));
907 * Data provider for deHSCentitiesReturnsDecodedString
911 public function deHSCentitiesReturnsDecodedStringDataProvider() {
913 'Empty string' => array('', ''),
914 'Double encoded &' => array('&amp;', '&'),
915 'Double encoded numeric entity' => array('&#1234;', 'Ӓ'),
916 'Double encoded hexadecimal entity' => array('&#x1b;', ''),
917 'Single encoded entities are not touched' => array('& Ӓ ', '& Ӓ ')
921 //////////////////////////////////
922 // Tests concerning slashJS
923 //////////////////////////////////
926 * @dataProvider slashJsDataProvider
928 public function slashJsEscapesSingleQuotesAndSlashes($input, $extended, $expected) {
929 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::slashJS($input, $extended));
933 * Data provider for slashJsEscapesSingleQuotesAndSlashes
937 public function slashJsDataProvider() {
939 'Empty string is not changed' => array('', FALSE, ''),
940 'Normal string is not changed' => array('The cake is a lie √', FALSE, 'The cake is a lie √'),
941 'String with single quotes' => array('The \'cake\' is a lie', FALSE, 'The \\\'cake\\\' is a lie'),
942 'String with single quotes and backslashes - just escape single quotes' => array('The \\\'cake\\\' is a lie', FALSE, 'The \\\\\'cake\\\\\' is a lie'),
943 'String with single quotes and backslashes - escape both' => array('The \\\'cake\\\' is a lie', TRUE, 'The \\\\\\\'cake\\\\\\\' is a lie')
947 //////////////////////////////////
948 // Tests concerning rawUrlEncodeJS
949 //////////////////////////////////
953 public function rawUrlEncodeJsPreservesWhitespaces() {
954 $input = 'Encode \'me\', but leave my spaces √';
955 $expected = 'Encode %27me%27%2C but leave my spaces %E2%88%9A';
956 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::rawUrlEncodeJS($input));
959 //////////////////////////////////
960 // Tests concerning rawUrlEncodeJS
961 //////////////////////////////////
965 public function rawUrlEncodeFpPreservesSlashes() {
966 $input = 'Encode \'me\', but leave my / √';
967 $expected = 'Encode%20%27me%27%2C%20but%20leave%20my%20/%20%E2%88%9A';
968 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::rawUrlEncodeFP($input));
971 //////////////////////////////////
972 // Tests concerning strtoupper / strtolower
973 //////////////////////////////////
975 * Data provider for strtoupper and strtolower
979 public function strtouppperDataProvider() {
981 'Empty string' => array('', ''),
982 'String containing only latin characters' => array('the cake is a lie.', 'THE CAKE IS A LIE.'),
983 'String with umlauts and accent characters' => array('the cà kê is ä lie.', 'THE Cà Kê IS ä LIE.')
989 * @dataProvider strtouppperDataProvider
991 public function strtoupperConvertsOnlyLatinCharacters($input, $expected) {
992 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::strtoupper($input));
997 * @dataProvider strtouppperDataProvider
999 public function strtolowerConvertsOnlyLatinCharacters($expected, $input) {
1000 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::strtolower($input));
1003 //////////////////////////////////
1004 // Tests concerning validEmail
1005 //////////////////////////////////
1007 * Data provider for valid validEmail's
1009 * @return array Valid email addresses
1011 public function validEmailValidDataProvider() {
1013 'short mail address' => array('a@b.c'),
1014 'simple mail address' => array('test@example.com'),
1015 'uppercase characters' => array('QWERTYUIOPASDFGHJKLZXCVBNM@QWERTYUIOPASDFGHJKLZXCVBNM.NET'),
1016 // 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
1017 // 'equal sign in local part' => array('test=mail@example.com'),
1018 'dash in local part' => array('test-mail@example.com'),
1019 'plus in local part' => array('test+mail@example.com'),
1020 // 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
1021 // 'question mark in local part' => array('test?mail@example.com'),
1022 'slash in local part' => array('foo/bar@example.com'),
1023 'hash in local part' => array('foo#bar@example.com'),
1024 // 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
1025 // 'dot in local part' => array('firstname.lastname@employee.2something.com'),
1026 // Fix / change if TYPO3 php requirement changed: Address ok with 5.2.6, but not ok with 5.3.2
1027 // 'dash as local part' => array('-@foo.com'),
1028 'umlauts in local part' => array('äöüfoo@bar.com'),
1029 'umlauts in domain part' => array('foo@äöüfoo.com')
1035 * @dataProvider validEmailValidDataProvider
1037 public function validEmailReturnsTrueForValidMailAddress($address) {
1038 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::validEmail($address));
1042 * Data provider for invalid validEmail's
1044 * @return array Invalid email addresses
1046 public function validEmailInvalidDataProvider() {
1048 '@ sign only' => array('@'),
1049 'duplicate @' => array('test@@example.com'),
1050 'duplicate @ combined with further special characters in local part' => array('test!.!@#$%^&*@example.com'),
1051 'opening parenthesis in local part' => array('foo(bar@example.com'),
1052 'closing parenthesis in local part' => array('foo)bar@example.com'),
1053 'opening square bracket in local part' => array('foo[bar@example.com'),
1054 'closing square bracket as local part' => array(']@example.com'),
1055 // Fix / change if TYPO3 php requirement changed: Address ok with 5.2.6, but not ok with 5.3.2
1056 // 'top level domain only' => array('test@com'),
1057 'dash as second level domain' => array('foo@-.com'),
1058 'domain part starting with dash' => array('foo@-foo.com'),
1059 'domain part ending with dash' => array('foo@foo-.com'),
1060 'number as top level domain' => array('foo@bar.123'),
1061 // Fix / change if TYPO3 php requirement changed: Address not ok with 5.2.6, but ok with 5.3.2 (?)
1062 // 'dash as top level domain' => array('foo@bar.-'),
1063 'dot at beginning of domain part' => array('test@.com'),
1064 // Fix / change if TYPO3 php requirement changed: Address ok with 5.2.6, but not ok with 5.3.2
1065 // 'local part ends with dot' => array('e.x.a.m.p.l.e.@example.com'),
1066 'trailing whitespace' => array('test@example.com '),
1067 'trailing carriage return' => array('test@example.com' . CR
),
1068 'trailing linefeed' => array('test@example.com' . LF
),
1069 'trailing carriage return linefeed' => array('test@example.com' . CRLF
),
1070 'trailing tab' => array('test@example.com' . TAB
)
1076 * @dataProvider validEmailInvalidDataProvider
1078 public function validEmailReturnsFalseForInvalidMailAddress($address) {
1079 $this->assertFalse(\TYPO3\CMS\Core\Utility\GeneralUtility
::validEmail($address));
1082 //////////////////////////////////
1083 // Tests concerning inArray
1084 //////////////////////////////////
1087 * @dataProvider inArrayDataProvider
1089 public function inArrayChecksStringExistenceWithinArray($array, $item, $expected) {
1090 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::inArray($array, $item));
1094 * Data provider for inArrayChecksStringExistenceWithinArray
1098 public function inArrayDataProvider() {
1100 'Empty array' => array(array(), 'search', FALSE),
1101 'One item array no match' => array(array('one'), 'two', FALSE),
1102 'One item array match' => array(array('one'), 'one', TRUE),
1103 'Multiple items array no match' => array(array('one', 2, 'three', 4), 'four', FALSE),
1104 'Multiple items array match' => array(array('one', 2, 'three', 4), 'three', TRUE),
1105 'Integer search items can match string values' => array(array('0', '1', '2'), 1, TRUE),
1106 'Search item is not casted to integer for a match' => array(array(4), '4a', FALSE),
1107 'Empty item won\'t match - in contrast to the php-builtin ' => array(array(0, 1, 2), '', FALSE)
1111 //////////////////////////////////
1112 // Tests concerning intExplode
1113 //////////////////////////////////
1117 public function intExplodeConvertsStringsToInteger() {
1118 $testString = '1,foo,2';
1119 $expectedArray = array(1, 0, 2);
1120 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::intExplode(',', $testString);
1121 $this->assertEquals($expectedArray, $actualArray);
1124 //////////////////////////////////
1125 // Tests concerning keepItemsInArray
1126 //////////////////////////////////
1129 * @dataProvider keepItemsInArrayWorksWithOneArgumentDataProvider
1131 public function keepItemsInArrayWorksWithOneArgument($search, $array, $expected) {
1132 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::keepItemsInArray($array, $search));
1136 * Data provider for keepItemsInArrayWorksWithOneArgument
1140 public function keepItemsInArrayWorksWithOneArgumentDataProvider() {
1147 'Empty argument will match "all" elements' => array(NULL, $array, $array),
1148 'No match' => array('four', $array, array()),
1149 'One match' => array('two', $array, array('two' => 'two')),
1150 'Multiple matches' => array('two,one', $array, array('one' => 'one', 'two' => 'two')),
1151 'Argument can be an array' => array(array('three'), $array, array('three' => 'three'))
1156 * Shows the exmaple from the doc comment where
1157 * a function is used to reduce the sub arrays to one item which
1158 * is then used for the matching.
1162 public function keepItemsInArrayCanUseCallbackOnSearchArray() {
1164 'aa' => array('first', 'second'),
1165 'bb' => array('third', 'fourth'),
1166 'cc' => array('fifth', 'sixth')
1168 $expected = array('bb' => array('third', 'fourth'));
1169 $keepItems = 'third';
1170 $getValueFunc = create_function('$value', 'return $value[0];');
1171 $match = \TYPO3\CMS\Core\Utility\GeneralUtility
::keepItemsInArray($array, $keepItems, $getValueFunc);
1172 $this->assertEquals($expected, $match);
1175 //////////////////////////////////
1176 // Tests concerning implodeArrayForUrl / explodeUrl2Array
1177 //////////////////////////////////
1179 * Data provider for implodeArrayForUrlBuildsValidParameterString and
1180 * explodeUrl2ArrayTransformsParameterStringToArray
1184 public function implodeArrayForUrlDataProvider() {
1185 $valueArray = array('one' => '√', 'two' => 2);
1187 'Empty input' => array('foo', array(), ''),
1188 'String parameters' => array('foo', $valueArray, '&foo[one]=%E2%88%9A&foo[two]=2'),
1189 'Nested array parameters' => array('foo', array($valueArray), '&foo[0][one]=%E2%88%9A&foo[0][two]=2'),
1190 'Keep blank parameters' => array('foo', array('one' => '√', ''), '&foo[one]=%E2%88%9A&foo[0]=')
1196 * @dataProvider implodeArrayForUrlDataProvider
1198 public function implodeArrayForUrlBuildsValidParameterString($name, $input, $expected) {
1199 $this->assertSame($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::implodeArrayForUrl($name, $input));
1205 public function implodeArrayForUrlCanSkipEmptyParameters() {
1206 $input = array('one' => '√', '');
1207 $expected = '&foo[one]=%E2%88%9A';
1208 $this->assertSame($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::implodeArrayForUrl('foo', $input, '', TRUE));
1214 public function implodeArrayForUrlCanUrlEncodeKeyNames() {
1215 $input = array('one' => '√', '');
1216 $expected = '&foo%5Bone%5D=%E2%88%9A&foo%5B0%5D=';
1217 $this->assertSame($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::implodeArrayForUrl('foo', $input, '', FALSE, TRUE));
1222 * @dataProvider implodeArrayForUrlDataProvider
1224 public function explodeUrl2ArrayTransformsParameterStringToNestedArray($name, $array, $input) {
1225 $expected = $array ?
array($name => $array) : array();
1226 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::explodeUrl2Array($input, TRUE));
1231 * @dataProvider explodeUrl2ArrayDataProvider
1233 public function explodeUrl2ArrayTransformsParameterStringToFlatArray($input, $expected) {
1234 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::explodeUrl2Array($input, FALSE));
1238 * Data provider for explodeUrl2ArrayTransformsParameterStringToFlatArray
1242 public function explodeUrl2ArrayDataProvider() {
1244 'Empty string' => array('', array()),
1245 'Simple parameter string' => array('&one=%E2%88%9A&two=2', array('one' => '√', 'two' => 2)),
1246 'Nested parameter string' => array('&foo[one]=%E2%88%9A&two=2', array('foo[one]' => '√', 'two' => 2))
1250 //////////////////////////////////
1251 // Tests concerning compileSelectedGetVarsFromArray
1252 //////////////////////////////////
1256 public function compileSelectedGetVarsFromArrayFiltersIncomingData() {
1257 $filter = 'foo,bar';
1258 $getArray = array('foo' => 1, 'cake' => 'lie');
1259 $expected = array('foo' => 1);
1260 $result = \TYPO3\CMS\Core\Utility\GeneralUtility
::compileSelectedGetVarsFromArray($filter, $getArray, FALSE);
1261 $this->assertSame($expected, $result);
1267 public function compileSelectedGetVarsFromArrayUsesGetPostDataFallback() {
1269 $filter = 'foo,bar';
1270 $getArray = array('foo' => 1, 'cake' => 'lie');
1271 $expected = array('foo' => 1, 'bar' => '2');
1272 $result = \TYPO3\CMS\Core\Utility\GeneralUtility
::compileSelectedGetVarsFromArray($filter, $getArray, TRUE);
1273 $this->assertSame($expected, $result);
1276 //////////////////////////////////
1277 // Tests concerning remapArrayKeys
1278 //////////////////////////////////
1282 public function remapArrayKeysExchangesKeysWithGivenMapping() {
1288 $keyMapping = array(
1297 \TYPO3\CMS\Core\Utility\GeneralUtility
::remapArrayKeys($array, $keyMapping);
1298 $this->assertEquals($expected, $array);
1301 //////////////////////////////////
1302 // Tests concerning array_merge
1303 //////////////////////////////////
1305 * Test demonstrating array_merge. This is actually
1306 * a native PHP operator, therefore this test is mainly used to
1307 * show how this function can be used.
1311 public function arrayMergeKeepsIndexesAfterMerge() {
1312 $array1 = array(10 => 'FOO', '20' => 'BAR');
1313 $array2 = array('5' => 'PLONK');
1314 $expected = array('5' => 'PLONK', 10 => 'FOO', '20' => 'BAR');
1315 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::array_merge($array1, $array2));
1318 //////////////////////////////////
1319 // Tests concerning int_from_ver
1320 //////////////////////////////////
1322 * Data Provider for intFromVerConvertsVersionNumbersToIntegersDataProvider
1326 public function intFromVerConvertsVersionNumbersToIntegersDataProvider() {
1328 array('4003003', '4.3.3'),
1329 array('4012003', '4.12.3'),
1330 array('5000000', '5.0.0'),
1331 array('3008001', '3.8.1'),
1332 array('1012', '0.1.12')
1338 * @dataProvider intFromVerConvertsVersionNumbersToIntegersDataProvider
1340 public function intFromVerConvertsVersionNumbersToIntegers($expected, $version) {
1341 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::int_from_ver($version));
1344 //////////////////////////////////
1345 // Tests concerning revExplode
1346 //////////////////////////////////
1350 public function revExplodeExplodesString() {
1351 $testString = 'my:words:here';
1352 $expectedArray = array('my:words', 'here');
1353 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::revExplode(':', $testString, 2);
1354 $this->assertEquals($expectedArray, $actualArray);
1357 //////////////////////////////////
1358 // Tests concerning trimExplode
1359 //////////////////////////////////
1363 public function checkTrimExplodeTrimsSpacesAtElementStartAndEnd() {
1364 $testString = ' a , b , c ,d ,, e,f,';
1365 $expectedArray = array('a', 'b', 'c', 'd', '', 'e', 'f', '');
1366 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $testString);
1367 $this->assertEquals($expectedArray, $actualArray);
1373 public function checkTrimExplodeRemovesNewLines() {
1374 $testString = (' a , b , ' . LF
) . ' ,d ,, e,f,';
1375 $expectedArray = array('a', 'b', 'd', 'e', 'f');
1376 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $testString, TRUE);
1377 $this->assertEquals($expectedArray, $actualArray);
1383 public function checkTrimExplodeRemovesEmptyElements() {
1384 $testString = 'a , b , c , ,d ,, ,e,f,';
1385 $expectedArray = array('a', 'b', 'c', 'd', 'e', 'f');
1386 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $testString, TRUE);
1387 $this->assertEquals($expectedArray, $actualArray);
1393 public function checkTrimExplodeKeepsRemainingResultsWithEmptyItemsAfterReachingLimitWithPositiveParameter() {
1394 $testString = ' a , b , c , , d,, ,e ';
1395 $expectedArray = array('a', 'b', 'c,,d,,,e');
1396 // Limiting returns the rest of the string as the last element
1397 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $testString, FALSE, 3);
1398 $this->assertEquals($expectedArray, $actualArray);
1404 public function checkTrimExplodeKeepsRemainingResultsWithoutEmptyItemsAfterReachingLimitWithPositiveParameter() {
1405 $testString = ' a , b , c , , d,, ,e ';
1406 $expectedArray = array('a', 'b', 'c,d,e');
1407 // Limiting returns the rest of the string as the last element
1408 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $testString, TRUE, 3);
1409 $this->assertEquals($expectedArray, $actualArray);
1415 public function checkTrimExplodeKeepsRamainingResultsWithEmptyItemsAfterReachingLimitWithNegativeParameter() {
1416 $testString = ' a , b , c , d, ,e, f , , ';
1417 $expectedArray = array('a', 'b', 'c', 'd', '', 'e');
1418 // limiting returns the rest of the string as the last element
1419 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $testString, FALSE, -3);
1420 $this->assertEquals($expectedArray, $actualArray);
1426 public function checkTrimExplodeKeepsRamainingResultsWithoutEmptyItemsAfterReachingLimitWithNegativeParameter() {
1427 $testString = ' a , b , c , d, ,e, f , , ';
1428 $expectedArray = array('a', 'b', 'c');
1429 // Limiting returns the rest of the string as the last element
1430 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $testString, TRUE, -3);
1431 $this->assertEquals($expectedArray, $actualArray);
1437 public function checkTrimExplodeReturnsExactResultsWithoutReachingLimitWithPositiveParameter() {
1438 $testString = ' a , b , , c , , , ';
1439 $expectedArray = array('a', 'b', 'c');
1440 // Limiting returns the rest of the string as the last element
1441 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $testString, TRUE, 4);
1442 $this->assertEquals($expectedArray, $actualArray);
1448 public function checkTrimExplodeKeepsZeroAsString() {
1449 $testString = 'a , b , c , ,d ,, ,e,f, 0 ,';
1450 $expectedArray = array('a', 'b', 'c', 'd', 'e', 'f', '0');
1451 $actualArray = \TYPO3\CMS\Core\Utility\GeneralUtility
::trimExplode(',', $testString, TRUE);
1452 $this->assertEquals($expectedArray, $actualArray);
1455 //////////////////////////////////
1456 // Tests concerning removeArrayEntryByValue
1457 //////////////////////////////////
1461 public function checkRemoveArrayEntryByValueRemovesEntriesFromOneDimensionalArray() {
1462 $inputArray = array(
1468 $compareValue = 'test2';
1469 $expectedResult = array(
1473 $actualResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::removeArrayEntryByValue($inputArray, $compareValue);
1474 $this->assertEquals($expectedResult, $actualResult);
1480 public function checkRemoveArrayEntryByValueRemovesEntriesFromMultiDimensionalArray() {
1481 $inputArray = array(
1488 $compareValue = 'bar';
1489 $expectedResult = array(
1493 $actualResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::removeArrayEntryByValue($inputArray, $compareValue);
1494 $this->assertEquals($expectedResult, $actualResult);
1500 public function checkRemoveArrayEntryByValueRemovesEntryWithEmptyString() {
1501 $inputArray = array(
1507 $expectedResult = array(
1511 $actualResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::removeArrayEntryByValue($inputArray, $compareValue);
1512 $this->assertEquals($expectedResult, $actualResult);
1515 //////////////////////////////////
1516 // Tests concerning getBytesFromSizeMeasurement
1517 //////////////////////////////////
1519 * Data provider for getBytesFromSizeMeasurement
1521 * @return array expected value, input string
1523 public function getBytesFromSizeMeasurementDataProvider() {
1525 '100 kilo Bytes' => array('102400', '100k'),
1526 '100 mega Bytes' => array('104857600', '100m'),
1527 '100 giga Bytes' => array('107374182400', '100g')
1533 * @dataProvider getBytesFromSizeMeasurementDataProvider
1535 public function getBytesFromSizeMeasurementCalculatesCorrectByteValue($expected, $byteString) {
1536 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::getBytesFromSizeMeasurement($byteString));
1539 //////////////////////////////////
1540 // Tests concerning getIndpEnv
1541 //////////////////////////////////
1545 public function getIndpEnvTypo3SitePathReturnNonEmptyString() {
1546 $this->assertTrue(strlen(\TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_SITE_PATH')) >= 1);
1552 public function getIndpEnvTypo3SitePathReturnsStringStartingWithSlash() {
1553 $result = \TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_SITE_PATH');
1554 $this->assertEquals('/', $result[0]);
1560 public function getIndpEnvTypo3SitePathReturnsStringEndingWithSlash() {
1561 $result = \TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_SITE_PATH');
1562 $this->assertEquals('/', $result[strlen($result) - 1]);
1568 static public function hostnameAndPortDataProvider() {
1570 'localhost ipv4 without port' => array('127.0.0.1', '127.0.0.1', ''),
1571 'localhost ipv4 with port' => array('127.0.0.1:81', '127.0.0.1', '81'),
1572 'localhost ipv6 without port' => array('[::1]', '[::1]', ''),
1573 'localhost ipv6 with port' => array('[::1]:81', '[::1]', '81'),
1574 'ipv6 without port' => array('[2001:DB8::1]', '[2001:DB8::1]', ''),
1575 'ipv6 with port' => array('[2001:DB8::1]:81', '[2001:DB8::1]', '81'),
1576 'hostname without port' => array('lolli.did.this', 'lolli.did.this', ''),
1577 'hostname with port' => array('lolli.did.this:42', 'lolli.did.this', '42')
1583 * @dataProvider hostnameAndPortDataProvider
1585 public function getIndpEnvTypo3HostOnlyParsesHostnamesAndIpAdresses($httpHost, $expectedIp) {
1586 $_SERVER['HTTP_HOST'] = $httpHost;
1587 $this->assertEquals($expectedIp, \TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_HOST_ONLY'));
1592 * @dataProvider hostnameAndPortDataProvider
1594 public function getIndpEnvTypo3PortParsesHostnamesAndIpAdresses($httpHost, $dummy, $expectedPort) {
1595 $_SERVER['HTTP_HOST'] = $httpHost;
1596 $this->assertEquals($expectedPort, \TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_PORT'));
1599 //////////////////////////////////
1600 // Tests concerning underscoredToUpperCamelCase
1601 //////////////////////////////////
1603 * Data provider for underscoredToUpperCamelCase
1605 * @return array expected, input string
1607 public function underscoredToUpperCamelCaseDataProvider() {
1609 'single word' => array('Blogexample', 'blogexample'),
1610 'multiple words' => array('BlogExample', 'blog_example')
1616 * @dataProvider underscoredToUpperCamelCaseDataProvider
1618 public function underscoredToUpperCamelCase($expected, $inputString) {
1619 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::underscoredToUpperCamelCase($inputString));
1622 //////////////////////////////////
1623 // Tests concerning underscoredToLowerCamelCase
1624 //////////////////////////////////
1626 * Data provider for underscoredToLowerCamelCase
1628 * @return array expected, input string
1630 public function underscoredToLowerCamelCaseDataProvider() {
1632 'single word' => array('minimalvalue', 'minimalvalue'),
1633 'multiple words' => array('minimalValue', 'minimal_value')
1639 * @dataProvider underscoredToLowerCamelCaseDataProvider
1641 public function underscoredToLowerCamelCase($expected, $inputString) {
1642 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::underscoredToLowerCamelCase($inputString));
1645 //////////////////////////////////
1646 // Tests concerning camelCaseToLowerCaseUnderscored
1647 //////////////////////////////////
1649 * Data provider for camelCaseToLowerCaseUnderscored
1651 * @return array expected, input string
1653 public function camelCaseToLowerCaseUnderscoredDataProvider() {
1655 'single word' => array('blogexample', 'blogexample'),
1656 'single word starting upper case' => array('blogexample', 'Blogexample'),
1657 'two words starting lower case' => array('minimal_value', 'minimalValue'),
1658 'two words starting upper case' => array('blog_example', 'BlogExample')
1664 * @dataProvider camelCaseToLowerCaseUnderscoredDataProvider
1666 public function camelCaseToLowerCaseUnderscored($expected, $inputString) {
1667 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::camelCaseToLowerCaseUnderscored($inputString));
1670 //////////////////////////////////
1671 // Tests concerning lcFirst
1672 //////////////////////////////////
1674 * Data provider for lcFirst
1676 * @return array expected, input string
1678 public function lcfirstDataProvider() {
1680 'single word' => array('blogexample', 'blogexample'),
1681 'single Word starting upper case' => array('blogexample', 'Blogexample'),
1682 'two words' => array('blogExample', 'BlogExample')
1688 * @dataProvider lcfirstDataProvider
1690 public function lcFirst($expected, $inputString) {
1691 $this->assertEquals($expected, \TYPO3\CMS\Core\Utility\GeneralUtility
::lcfirst($inputString));
1694 //////////////////////////////////
1695 // Tests concerning encodeHeader
1696 //////////////////////////////////
1700 public function encodeHeaderEncodesWhitespacesInQuotedPrintableMailHeader() {
1701 $this->assertEquals('=?utf-8?Q?We_test_whether_the_copyright_character_=C2=A9_is_encoded_correctly?=', \TYPO3\CMS\Core\Utility\GeneralUtility
::encodeHeader('We test whether the copyright character © is encoded correctly', 'quoted-printable', 'utf-8'));
1707 public function encodeHeaderEncodesQuestionmarksInQuotedPrintableMailHeader() {
1708 $this->assertEquals('=?utf-8?Q?Is_the_copyright_character_=C2=A9_really_encoded_correctly=3F_Really=3F?=', \TYPO3\CMS\Core\Utility\GeneralUtility
::encodeHeader('Is the copyright character © really encoded correctly? Really?', 'quoted-printable', 'utf-8'));
1711 //////////////////////////////////
1712 // Tests concerning isValidUrl
1713 //////////////////////////////////
1715 * Data provider for valid isValidUrl's
1717 * @return array Valid ressource
1719 public function validUrlValidRessourceDataProvider() {
1721 'http' => array('http://www.example.org/'),
1722 'http without trailing slash' => array('http://qwe'),
1723 'http directory with trailing slash' => array('http://www.example/img/dir/'),
1724 'http directory without trailing slash' => array('http://www.example/img/dir'),
1725 'http index.html' => array('http://example.com/index.html'),
1726 'http index.php' => array('http://www.example.com/index.php'),
1727 'http test.png' => array('http://www.example/img/test.png'),
1728 'http username password querystring and ancher' => array('https://user:pw@www.example.org:80/path?arg=value#fragment'),
1729 'file' => array('file:///tmp/test.c'),
1730 'file directory' => array('file://foo/bar'),
1731 'ftp directory' => array('ftp://ftp.example.com/tmp/'),
1732 'mailto' => array('mailto:foo@bar.com'),
1733 'news' => array('news:news.php.net'),
1734 'telnet' => array('telnet://192.0.2.16:80/'),
1735 'ldap' => array('ldap://[2001:db8::7]/c=GB?objectClass?one'),
1736 'http punycode domain name' => array('http://www.xn--bb-eka.at'),
1737 'http punicode subdomain' => array('http://xn--h-zfa.oebb.at'),
1738 'http domain-name umlauts' => array('http://www.öbb.at'),
1739 'http subdomain umlauts' => array('http://äh.oebb.at'),
1740 'http directory umlauts' => array('http://www.oebb.at/äöü/')
1746 * @dataProvider validUrlValidRessourceDataProvider
1748 public function validURLReturnsTrueForValidRessource($url) {
1749 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::isValidUrl($url));
1753 * Data provider for invalid isValidUrl's
1755 * @return array Invalid ressource
1757 public function isValidUrlInvalidRessourceDataProvider() {
1759 'http missing colon' => array('http//www.example/wrong/url/'),
1760 'http missing slash' => array('http:/www.example'),
1761 'hostname only' => array('www.example.org/'),
1762 'file missing protocol specification' => array('/tmp/test.c'),
1763 'slash only' => array('/'),
1764 'string http://' => array('http://'),
1765 'string http:/' => array('http:/'),
1766 'string http:' => array('http:'),
1767 'string http' => array('http'),
1768 'empty string' => array(''),
1769 'string -1' => array('-1'),
1770 'string array()' => array('array()'),
1771 'random string' => array('qwe')
1777 * @dataProvider isValidUrlInvalidRessourceDataProvider
1779 public function validURLReturnsFalseForInvalidRessoure($url) {
1780 $this->assertFalse(\TYPO3\CMS\Core\Utility\GeneralUtility
::isValidUrl($url));
1783 //////////////////////////////////
1784 // Tests concerning isOnCurrentHost
1785 //////////////////////////////////
1789 public function isOnCurrentHostReturnsTrueWithCurrentHost() {
1790 $testUrl = \TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_REQUEST_URL');
1791 $this->assertTrue(\TYPO3\CMS\Core\Utility\GeneralUtility
::isOnCurrentHost($testUrl));
1795 * Data provider for invalid isOnCurrentHost's
1797 * @return array Invalid Hosts
1799 public function checkisOnCurrentHostInvalidHosts() {
1801 'empty string' => array(''),
1802 'arbitrary string' => array('arbitrary string'),
1803 'localhost IP' => array('127.0.0.1'),
1804 'relative path' => array('./relpath/file.txt'),
1805 'absolute path' => array('/abspath/file.txt?arg=value'),
1806 'differnt host' => array(\TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_REQUEST_HOST') . '.example.org')
1810 ////////////////////////////////////////
1811 // Tests concerning sanitizeLocalUrl
1812 ////////////////////////////////////////
1814 * Data provider for valid sanitizeLocalUrl's
1816 * @return array Valid url
1818 public function sanitizeLocalUrlValidUrlDataProvider() {
1819 $subDirectory = \TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_SITE_PATH');
1820 $typo3SiteUrl = \TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_SITE_URL');
1821 $typo3RequestHost = \TYPO3\CMS\Core\Utility\GeneralUtility
::getIndpEnv('TYPO3_REQUEST_HOST');
1823 'alt_intro.php' => array('alt_intro.php'),
1824 'alt_intro.php?foo=1&bar=2' => array('alt_intro.php?foo=1&bar=2'),
1825 $subDirectory . 'typo3/alt_intro.php' => array($subDirectory . 'typo3/alt_intro.php'),
1826 $subDirectory . 'index.php' => array($subDirectory . 'index.php'),
1827 '../index.php' => array('../index.php'),
1828 '../typo3/alt_intro.php' => array('../typo3/alt_intro.php'),
1829 '../~userDirectory/index.php' => array('../~userDirectory/index.php'),
1830 '../typo3/mod.php?var1=test-case&var2=~user' => array('../typo3/mod.php?var1=test-case&var2=~user'),
1831 PATH_site
. 'typo3/alt_intro.php' => array(PATH_site
. 'typo3/alt_intro.php'),
1832 $typo3SiteUrl . 'typo3/alt_intro.php' => array($typo3SiteUrl . 'typo3/alt_intro.php'),
1833 ($typo3RequestHost . $subDirectory) . '/index.php' => array(($typo3RequestHost . $subDirectory) . '/index.php')
1839 * @dataProvider sanitizeLocalUrlValidUrlDataProvider
1841 public function sanitizeLocalUrlAcceptsNotEncodedValidUrls($url) {
1842 $this->assertEquals($url, \TYPO3\CMS\Core\Utility\GeneralUtility
::sanitizeLocalUrl($url));
1847 * @dataProvider sanitizeLocalUrlValidUrlDataProvider
1849 public function sanitizeLocalUrlAcceptsEncodedValidUrls($url) {
1850 $this->assertEquals(rawurlencode($url), \TYPO3\CMS\Core\Utility\GeneralUtility
::sanitizeLocalUrl(rawurlencode($url)));
1854 * Data provider for invalid sanitizeLocalUrl's
1856 * @return array Valid url
1858 public function sanitizeLocalUrlInvalidDataProvider() {
1860 'empty string' => array(''),
1861 'http domain' => array('http://www.google.de/'),
1862 'https domain' => array('https://www.google.de/'),
1863 'relative path with XSS' => array('../typo3/whatever.php?argument=javascript:alert(0)')
1869 * @dataProvider sanitizeLocalUrlInvalidDataProvider
1871 public function sanitizeLocalUrlDeniesPlainInvalidUrls($url) {
1872 $this->assertEquals('', \TYPO3\CMS\Core\Utility\GeneralUtility
::sanitizeLocalUrl($url));
1877 * @dataProvider sanitizeLocalUrlInvalidDataProvider
1879 public function sanitizeLocalUrlDeniesEncodedInvalidUrls($url) {
1880 $this->assertEquals('', \TYPO3\CMS\Core\Utility\GeneralUtility
::sanitizeLocalUrl(rawurlencode($url)));
1883 //////////////////////////////////////
1884 // Tests concerning addSlashesOnArray
1885 //////////////////////////////////////
1889 public function addSlashesOnArrayAddsSlashesRecursive() {
1890 $inputArray = array(
1892 'key11' => 'val\'ue1',
1893 'key12' => 'val"ue2'
1895 'key2' => 'val\\ue3'
1897 $expectedResult = array(
1899 'key11' => 'val\\\'ue1',
1900 'key12' => 'val\\"ue2'
1902 'key2' => 'val\\\\ue3'
1904 \TYPO3\CMS\Core\Utility\GeneralUtility
::addSlashesOnArray($inputArray);
1905 $this->assertEquals($expectedResult, $inputArray);
1908 //////////////////////////////////////
1909 // Tests concerning addSlashesOnArray
1910 //////////////////////////////////////
1914 public function stripSlashesOnArrayStripsSlashesRecursive() {
1915 $inputArray = array(
1917 'key11' => 'val\\\'ue1',
1918 'key12' => 'val\\"ue2'
1920 'key2' => 'val\\\\ue3'
1922 $expectedResult = array(
1924 'key11' => 'val\'ue1',
1925 'key12' => 'val"ue2'
1927 'key2' => 'val\\ue3'
1929 \TYPO3\CMS\Core\Utility\GeneralUtility
::stripSlashesOnArray($inputArray);
1930 $this->assertEquals($expectedResult, $inputArray);
1933 //////////////////////////////////////
1934 // Tests concerning arrayDiffAssocRecursive
1935 //////////////////////////////////////
1939 public function arrayDiffAssocRecursiveHandlesOneDimensionalArrays() {
1949 $expectedResult = array(
1952 $actualResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::arrayDiffAssocRecursive($array1, $array2);
1953 $this->assertEquals($expectedResult, $actualResult);
1959 public function arrayDiffAssocRecursiveHandlesMultiDimensionalArrays() {
1963 'key21' => 'value21',
1964 'key22' => 'value22',
1966 'key231' => 'value231',
1967 'key232' => 'value232'
1974 'key21' => 'value21',
1976 'key231' => 'value231'
1980 $expectedResult = array(
1982 'key22' => 'value22',
1984 'key232' => 'value232'
1988 $actualResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::arrayDiffAssocRecursive($array1, $array2);
1989 $this->assertEquals($expectedResult, $actualResult);
1995 public function arrayDiffAssocRecursiveHandlesMixedArrays() {
1998 'key11' => 'value11',
1999 'key12' => 'value12'
2007 'key21' => 'value21'
2010 $expectedResult = array(
2013 $actualResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::arrayDiffAssocRecursive($array1, $array2);
2014 $this->assertEquals($expectedResult, $actualResult);
2017 //////////////////////////////////////
2018 // Tests concerning removeDotsFromTS
2019 //////////////////////////////////////
2023 public function removeDotsFromTypoScriptSucceedsWithDottedArray() {
2024 $typoScript = array(
2025 'propertyA.' => array(
2033 $expectedResult = array(
2034 'propertyA' => array(
2042 $this->assertEquals($expectedResult, \TYPO3\CMS\Core\Utility\GeneralUtility
::removeDotsFromTS($typoScript));
2048 public function removeDotsFromTypoScriptOverridesSubArray() {
2049 $typoScript = array(
2050 'propertyA.' => array(
2051 'keyA' => 'getsOverridden',
2059 $expectedResult = array(
2060 'propertyA' => array(
2068 $this->assertEquals($expectedResult, \TYPO3\CMS\Core\Utility\GeneralUtility
::removeDotsFromTS($typoScript));
2074 public function removeDotsFromTypoScriptOverridesWithScalar() {
2075 $typoScript = array(
2076 'propertyA.' => array(
2080 'keyA' => 'willOverride',
2085 $expectedResult = array(
2086 'propertyA' => array(
2087 'keyA' => 'willOverride',
2092 $this->assertEquals($expectedResult, \TYPO3\CMS\Core\Utility\GeneralUtility
::removeDotsFromTS($typoScript));
2095 //////////////////////////////////////
2096 // Tests concerning naturalKeySortRecursive
2097 //////////////////////////////////////
2101 public function naturalKeySortRecursiveReturnsFalseIfInputIsNotAnArray() {
2102 $testValues = array(
2107 foreach ($testValues as $testValue) {
2108 $this->assertFalse(\TYPO3\CMS\Core\Utility\GeneralUtility
::naturalKeySortRecursive($testValue));
2115 public function naturalKeySortRecursiveSortsOneDimensionalArrayByNaturalOrder() {
2129 $expectedResult = array(
2142 \TYPO3\CMS\Core\Utility\GeneralUtility
::naturalKeySortRecursive($testArray);
2143 $this->assertEquals($expectedResult, array_values($testArray));
2149 public function naturalKeySortRecursiveSortsMultiDimensionalArrayByNaturalOrder() {
2187 $expectedResult = array(
2200 \TYPO3\CMS\Core\Utility\GeneralUtility
::naturalKeySortRecursive($testArray);
2201 $this->assertEquals($expectedResult, array_values(array_keys($testArray['aaa']['bad'])));
2202 $this->assertEquals($expectedResult, array_values(array_keys($testArray['aaa'])));
2203 $this->assertEquals($expectedResult, array_values(array_keys($testArray)));
2206 //////////////////////////////////////
2207 // Tests concerning get_dirs
2208 //////////////////////////////////////
2212 public function getDirsReturnsArrayOfDirectoriesFromGivenDirectory() {
2214 $directories = \TYPO3\CMS\Core\Utility\GeneralUtility
::get_dirs($path);
2215 $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType
::TYPE_ARRAY
, $directories);
2221 public function getDirsReturnsStringErrorOnPathFailure() {
2223 $result = \TYPO3\CMS\Core\Utility\GeneralUtility
::get_dirs($path);
2224 $expectedResult = 'error';
2225 $this->assertEquals($expectedResult, $result);
2228 //////////////////////////////////
2229 // Tests concerning hmac
2230 //////////////////////////////////
2234 public function hmacReturnsHashOfProperLength() {
2235 $hmac = \TYPO3\CMS\Core\Utility\GeneralUtility
::hmac('message');
2236 $this->assertTrue(!empty($hmac) && is_string($hmac));
2237 $this->assertTrue(strlen($hmac) == 40);
2243 public function hmacReturnsEqualHashesForEqualInput() {
2246 $this->assertEquals(\TYPO3\CMS\Core\Utility\GeneralUtility
::hmac($msg0), \TYPO3\CMS\Core\Utility\GeneralUtility
::hmac($msg1));
2252 public function hmacReturnsNoEqualHashesForNonEqualInput() {
2255 $this->assertNotEquals(\TYPO3\CMS\Core\Utility\GeneralUtility
::hmac($msg0), \TYPO3\CMS\Core\Utility\GeneralUtility
::hmac($msg1));
2258 //////////////////////////////////
2259 // Tests concerning quoteJSvalue
2260 //////////////////////////////////
2262 * Data provider for quoteJSvalueTest.
2266 public function quoteJsValueDataProvider() {
2268 'Immune characters are returned as is' => array(
2272 'Alphanumerical characters are returned as is' => array(
2273 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
2274 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
2276 'Angel brackets and ampersand are encoded' => array(
2280 'Quotes and slashes are encoded' => array(
2282 '\\x22\\x27\\x5C\\x2F'
2284 'Empty string stays empty' => array(
2288 'Exclamation mark and space are properly encoded' => array(
2290 'Hello\\x20World\\x21'
2292 'Whitespaces are properly encoded' => array(
2293 ((TAB
. LF
) . CR
) . ' ',
2294 '\\x09\\x0A\\x0D\\x20'
2296 'Null byte is properly encoded' => array(
2300 'Umlauts are properly encoded' => array(
2302 '\\xDC\\xFC\\xD6\\xF6\\xC4\\xE4'
2309 * @param string $input
2310 * @param string $expected
2311 * @dataProvider quoteJsValueDataProvider
2313 public function quoteJsValueTest($input, $expected) {
2314 $this->assertSame(('\'' . $expected) . '\'', \TYPO3\CMS\Core\Utility\GeneralUtility
::quoteJSvalue($input));
2317 //////////////////////////////////
2318 // Tests concerning readLLfile
2319 //////////////////////////////////
2323 public function readLLfileHandlesLocallangXMLOverride() {
2324 $unique = uniqid('locallangXMLOverrideTest');
2325 $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
2328 <languageKey index="default" type="array">
2329 <label index="buttons.logout">EXIT</label>
2333 $file = ((PATH_site
. 'typo3temp/') . $unique) . '.xml';
2334 \TYPO3\CMS\Core\Utility\GeneralUtility
::writeFileToTypo3tempDir($file, $xml);
2335 // Make sure there is no cached version of the label
2336 $GLOBALS['typo3CacheManager']->getCache('t3lib_l10n')->flush();
2337 // Get default value
2338 $defaultLL = \TYPO3\CMS\Core\Utility\GeneralUtility
::readLLfile('EXT:lang/locallang_core.xml', 'default');
2339 // Clear language cache again
2340 $GLOBALS['typo3CacheManager']->getCache('t3lib_l10n')->flush();
2341 // Set override file
2342 $GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride']['EXT:lang/locallang_core.xml'][$unique] = $file;
2343 /** @var $store \TYPO3\CMS\Core\Localization\LanguageStore */
2344 $store = \TYPO3\CMS\Core\Utility\GeneralUtility
::makeInstance('TYPO3\\CMS\\Core\\Localization\\LanguageStore');
2345 $store->flushData('EXT:lang/locallang_core.xml');
2346 // Get override value
2347 $overrideLL = \TYPO3\CMS\Core\Utility\GeneralUtility
::readLLfile('EXT:lang/locallang_core.xml', 'default');
2350 $this->assertNotEquals($overrideLL['default']['buttons.logout'][0]['target'], '');
2351 $this->assertNotEquals($defaultLL['default']['buttons.logout'][0]['target'], $overrideLL['default']['buttons.logout'][0]['target']);
2352 $this->assertEquals($overrideLL['default']['buttons.logout'][0]['target'], 'EXIT');
2355 ///////////////////////////////
2356 // Tests concerning _GETset()
2357 ///////////////////////////////
2361 public function getSetWritesArrayToGetSystemVariable() {
2363 $GLOBALS['HTTP_GET_VARS'] = array();
2364 $getParameters = array('foo' => 'bar');
2365 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset($getParameters);
2366 $this->assertSame($getParameters, $_GET);
2372 public function getSetWritesArrayToGlobalsHttpGetVars() {
2374 $GLOBALS['HTTP_GET_VARS'] = array();
2375 $getParameters = array('foo' => 'bar');
2376 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset($getParameters);
2377 $this->assertSame($getParameters, $GLOBALS['HTTP_GET_VARS']);
2383 public function getSetForArrayDropsExistingValues() {
2385 $GLOBALS['HTTP_GET_VARS'] = array();
2386 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset(array('foo' => 'bar'));
2387 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset(array('oneKey' => 'oneValue'));
2388 $this->assertEquals(array('oneKey' => 'oneValue'), $GLOBALS['HTTP_GET_VARS']);
2394 public function getSetAssignsOneValueToOneKey() {
2396 $GLOBALS['HTTP_GET_VARS'] = array();
2397 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset('oneValue', 'oneKey');
2398 $this->assertEquals('oneValue', $GLOBALS['HTTP_GET_VARS']['oneKey']);
2404 public function getSetForOneValueDoesNotDropUnrelatedValues() {
2406 $GLOBALS['HTTP_GET_VARS'] = array();
2407 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset(array('foo' => 'bar'));
2408 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset('oneValue', 'oneKey');
2409 $this->assertEquals(array('foo' => 'bar', 'oneKey' => 'oneValue'), $GLOBALS['HTTP_GET_VARS']);
2415 public function getSetCanAssignsAnArrayToASpecificArrayElement() {
2417 $GLOBALS['HTTP_GET_VARS'] = array();
2418 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset(array('childKey' => 'oneValue'), 'parentKey');
2419 $this->assertEquals(array('parentKey' => array('childKey' => 'oneValue')), $GLOBALS['HTTP_GET_VARS']);
2425 public function getSetCanAssignAStringValueToASpecificArrayChildElement() {
2427 $GLOBALS['HTTP_GET_VARS'] = array();
2428 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset('oneValue', 'parentKey|childKey');
2429 $this->assertEquals(array('parentKey' => array('childKey' => 'oneValue')), $GLOBALS['HTTP_GET_VARS']);
2435 public function getSetCanAssignAnArrayToASpecificArrayChildElement() {
2437 $GLOBALS['HTTP_GET_VARS'] = array();
2438 \TYPO3\CMS\Core\Utility\GeneralUtility
::_GETset(array('key1' => 'value1', 'key2' => 'value2'), 'parentKey|childKey');
2439 $this->assertEquals(array(
2440 'parentKey' => array(
2441 'childKey' => array('key1' => 'value1', 'key2' => 'value2')
2443 ), $GLOBALS['HTTP_GET_VARS']);
2446 ///////////////////////////
2447 // Tests concerning minifyJavaScript
2448 ///////////////////////////
2452 public function minifyJavaScriptReturnsInputStringIfNoHookIsRegistered() {
2453 unset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript']);
2454 $testString = uniqid('string');
2455 $this->assertSame($testString, \TYPO3\CMS\Core\Utility\GeneralUtility
::minifyJavaScript($testString));
2459 * Create an own hook callback class, register as hook, and check
2460 * if given string to compress is given to hook method
2464 public function minifyJavaScriptCallsRegisteredHookWithInputString() {
2465 $hookClassName = uniqid('tx_coretest');
2466 $minifyHookMock = $this->getMock('stdClass', array('minify'), array(), $hookClassName);
2467 $functionName = ('&' . $hookClassName) . '->minify';
2468 $GLOBALS['T3_VAR']['callUserFunction'][$functionName] = array();
2469 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['obj'] = $minifyHookMock;
2470 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['method'] = 'minify';
2471 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'][] = $functionName;
2472 $minifyHookMock->expects($this->once())->method('minify')->will($this->returnCallback(array($this, 'isMinifyJavaScriptHookCalledCallback')));
2473 \TYPO3\CMS\Core\Utility\GeneralUtility
::minifyJavaScript('foo');
2477 * Callback function used in minifyJavaScriptCallsRegisteredHookWithInputString test
2479 * @param array $params
2481 public function isMinifyJavaScriptHookCalledCallback(array $params) {
2482 // We can not throw an exception here, because that would be caught by the
2483 // minifyJavaScript method under test itself. Thus, we just die if the
2484 // input string is not ok.
2485 if ($params['script'] !== 'foo') {
2491 * Create a hook callback, use callback to throw an exception and check
2492 * if the exception is given as error parameter to the calling method.
2496 public function minifyJavaScriptReturnsErrorStringOfHookException() {
2497 $hookClassName = uniqid('tx_coretest');
2498 $minifyHookMock = $this->getMock('stdClass', array('minify'), array(), $hookClassName);
2499 $functionName = ('&' . $hookClassName) . '->minify';
2500 $GLOBALS['T3_VAR']['callUserFunction'][$functionName] = array();
2501 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['obj'] = $minifyHookMock;
2502 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['method'] = 'minify';
2503 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'][] = $functionName;
2504 $minifyHookMock->expects($this->any())->method('minify')->will($this->returnCallback(array($this, 'minifyJavaScriptErroneousCallback')));
2506 \TYPO3\CMS\Core\Utility\GeneralUtility
::minifyJavaScript('string to compress', $error);
2507 $this->assertSame('Error minifying java script: foo', $error);
2511 * Check if the error message that is returned by the hook callback
2512 * is logged to t3lib_div::devLog.
2516 public function minifyJavaScriptWritesExceptionMessageToDevLog() {
2517 $namespace = 'TYPO3\\CMS\\Core\\Utility';
2518 $t3libDivMock = uniqid('GeneralUtility');
2519 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();') . ' }') . '}');
2520 $t3libDivMock = $namespace . '\\' . $t3libDivMock;
2521 $hookClassName = uniqid('tx_coretest');
2522 $minifyHookMock = $this->getMock('stdClass', array('minify'), array(), $hookClassName);
2523 $functionName = ('&' . $hookClassName) . '->minify';
2524 $GLOBALS['T3_VAR']['callUserFunction'][$functionName] = array();
2525 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['obj'] = $minifyHookMock;
2526 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['method'] = 'minify';
2527 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'][] = $functionName;
2528 $minifyHookMock->expects($this->any())->method('minify')->will($this->returnCallback(array($this, 'minifyJavaScriptErroneousCallback')));
2529 $this->setExpectedException('\\RuntimeException');
2530 $t3libDivMock::minifyJavaScript('string to compress');
2534 * Callback function used in
2535 * minifyJavaScriptReturnsErrorStringOfHookException and
2536 * minifyJavaScriptWritesExceptionMessageToDevLog
2538 * @throws \RuntimeException
2540 public function minifyJavaScriptErroneousCallback() {
2541 throw new \
RuntimeException('foo', 1344888548);
2544 ///////////////////////////
2545 // Tests concerning getUrl
2546 ///////////////////////////
2550 public function getUrlWithAdditionalRequestHeadersProvidesHttpHeaderOnError() {
2551 $url = 'http://typo3.org/i-do-not-exist-' . time();
2553 \TYPO3\CMS\Core\Utility\GeneralUtility
::getUrl($url, 0, array(), $report);
2554 $this->assertContains('404', $report['message']);
2560 public function getUrlProvidesWithoutAdditionalRequestHeadersHttpHeaderOnError() {
2561 $url = 'http://typo3.org/i-do-not-exist-' . time();
2563 \TYPO3\CMS\Core\Utility\GeneralUtility
::getUrl($url, 0, FALSE, $report);
2564 $this->assertContains('404', $report['message'], 'Did not provide the HTTP response header when requesting a failing URL.');
2567 ///////////////////////////////
2568 // Tests concerning fixPermissions
2569 ///////////////////////////////
2573 public function fixPermissionsSetsGroup() {
2574 if (TYPO3_OS
== 'WIN') {
2575 $this->markTestSkipped('fixPermissionsSetsGroup() tests not available on Windows');
2577 if (!function_exists('posix_getegid')) {
2578 $this->markTestSkipped('Function posix_getegid() not available, fixPermissionsSetsGroup() tests skipped');
2580 if (posix_getegid() === -1) {
2581 $this->markTestSkipped('The fixPermissionsSetsGroup() is not available on Mac OS because posix_getegid() always returns -1 on Mac OS.');
2583 // Create and prepare test file
2584 $filename = (PATH_site
. 'typo3temp/') . uniqid('test_');
2585 \TYPO3\CMS\Core\Utility\GeneralUtility
::writeFileToTypo3tempDir($filename, '42');
2586 $currentGroupId = posix_getegid();
2587 // Set target group and run method
2588 $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'] = $currentGroupId;
2589 $fixPermissionsResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::fixPermissions($filename);
2591 $resultFileGroup = filegroup($filename);
2593 $this->assertEquals($currentGroupId, $resultFileGroup);
2599 public function fixPermissionsSetsPermissionsToFile() {
2600 if (TYPO3_OS
== 'WIN') {
2601 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2603 // Create and prepare test file
2604 $filename = (PATH_site
. 'typo3temp/') . uniqid('test_');
2605 \TYPO3\CMS\Core\Utility\GeneralUtility
::writeFileToTypo3tempDir($filename, '42');
2606 chmod($filename, 482);
2607 // Set target permissions and run method
2608 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2609 $fixPermissionsResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::fixPermissions($filename);
2610 // Get actual permissions and clean up
2612 $resultFilePermissions = substr(decoct(fileperms($filename)), 2);
2614 // Test if everything was ok
2615 $this->assertTrue($fixPermissionsResult);
2616 $this->assertEquals($resultFilePermissions, '0660');
2622 public function fixPermissionsSetsPermissionsToHiddenFile() {
2623 if (TYPO3_OS
== 'WIN') {
2624 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2626 // Create and prepare test file
2627 $filename = (PATH_site
. 'typo3temp/') . uniqid('.test_');
2628 \TYPO3\CMS\Core\Utility\GeneralUtility
::writeFileToTypo3tempDir($filename, '42');
2629 chmod($filename, 482);
2630 // Set target permissions and run method
2631 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2632 $fixPermissionsResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::fixPermissions($filename);
2633 // Get actual permissions and clean up
2635 $resultFilePermissions = substr(decoct(fileperms($filename)), 2);
2637 // Test if everything was ok
2638 $this->assertTrue($fixPermissionsResult);
2639 $this->assertEquals($resultFilePermissions, '0660');
2645 public function fixPermissionsSetsPermissionsToDirectory() {
2646 if (TYPO3_OS
== 'WIN') {
2647 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2649 // Create and prepare test directory
2650 $directory = (PATH_site
. 'typo3temp/') . uniqid('test_');
2651 \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($directory);
2652 chmod($directory, 1551);
2653 // Set target permissions and run method
2654 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = '0770';
2655 $fixPermissionsResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::fixPermissions($directory);
2656 // Get actual permissions and clean up
2658 $resultDirectoryPermissions = substr(decoct(fileperms($directory)), 1);
2659 \TYPO3\CMS\Core\Utility\GeneralUtility
::rmdir($directory);
2660 // Test if everything was ok
2661 $this->assertTrue($fixPermissionsResult);
2662 $this->assertEquals($resultDirectoryPermissions, '0770');
2668 public function fixPermissionsSetsPermissionsToDirectoryWithTrailingSlash() {
2669 if (TYPO3_OS
== 'WIN') {
2670 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2672 // Create and prepare test directory
2673 $directory = (PATH_site
. 'typo3temp/') . uniqid('test_');
2674 \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($directory);
2675 chmod($directory, 1551);
2676 // Set target permissions and run method
2677 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = '0770';
2678 $fixPermissionsResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::fixPermissions($directory . '/');
2679 // Get actual permissions and clean up
2681 $resultDirectoryPermissions = substr(decoct(fileperms($directory)), 1);
2682 \TYPO3\CMS\Core\Utility\GeneralUtility
::rmdir($directory);
2683 // Test if everything was ok
2684 $this->assertTrue($fixPermissionsResult);
2685 $this->assertEquals($resultDirectoryPermissions, '0770');
2691 public function fixPermissionsSetsPermissionsToHiddenDirectory() {
2692 if (TYPO3_OS
== 'WIN') {
2693 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2695 // Create and prepare test directory
2696 $directory = (PATH_site
. 'typo3temp/') . uniqid('.test_');
2697 \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($directory);
2698 chmod($directory, 1551);
2699 // Set target permissions and run method
2700 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = '0770';
2701 $fixPermissionsResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::fixPermissions($directory);
2702 // Get actual permissions and clean up
2704 $resultDirectoryPermissions = substr(decoct(fileperms($directory)), 1);
2705 \TYPO3\CMS\Core\Utility\GeneralUtility
::rmdir($directory);
2706 // Test if everything was ok
2707 $this->assertTrue($fixPermissionsResult);
2708 $this->assertEquals($resultDirectoryPermissions, '0770');
2714 public function fixPermissionsCorrectlySetsPermissionsRecursive() {
2715 if (TYPO3_OS
== 'WIN') {
2716 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2718 // Create and prepare test directory and file structure
2719 $baseDirectory = (PATH_site
. 'typo3temp/') . uniqid('test_');
2720 \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($baseDirectory);
2721 chmod($baseDirectory, 1751);
2722 \TYPO3\CMS\Core\Utility\GeneralUtility
::writeFileToTypo3tempDir($baseDirectory . '/file', '42');
2723 chmod($baseDirectory . '/file', 482);
2724 \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($baseDirectory . '/foo');
2725 chmod($baseDirectory . '/foo', 1751);
2726 \TYPO3\CMS\Core\Utility\GeneralUtility
::writeFileToTypo3tempDir($baseDirectory . '/foo/file', '42');
2727 chmod($baseDirectory . '/foo/file', 482);
2728 \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($baseDirectory . '/.bar');
2729 chmod($baseDirectory . '/.bar', 1751);
2730 // Use this if writeFileToTypo3tempDir is fixed to create hidden files in subdirectories
2731 // t3lib_div::writeFileToTypo3tempDir($baseDirectory . '/.bar/.file', '42');
2732 // t3lib_div::writeFileToTypo3tempDir($baseDirectory . '/.bar/..file2', '42');
2733 touch($baseDirectory . '/.bar/.file', '42');
2734 chmod($baseDirectory . '/.bar/.file', 482);
2735 touch($baseDirectory . '/.bar/..file2', '42');
2736 chmod($baseDirectory . '/.bar/..file2', 482);
2737 // Set target permissions and run method
2738 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2739 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = '0770';
2740 $fixPermissionsResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::fixPermissions($baseDirectory, TRUE);
2741 // Get actual permissions
2743 $resultBaseDirectoryPermissions = substr(decoct(fileperms($baseDirectory)), 1);
2744 $resultBaseFilePermissions = substr(decoct(fileperms($baseDirectory . '/file')), 2);
2745 $resultFooDirectoryPermissions = substr(decoct(fileperms($baseDirectory . '/foo')), 1);
2746 $resultFooFilePermissions = substr(decoct(fileperms($baseDirectory . '/foo/file')), 2);
2747 $resultBarDirectoryPermissions = substr(decoct(fileperms($baseDirectory . '/.bar')), 1);
2748 $resultBarFilePermissions = substr(decoct(fileperms($baseDirectory . '/.bar/.file')), 2);
2749 $resultBarFile2Permissions = substr(decoct(fileperms($baseDirectory . '/.bar/..file2')), 2);
2751 unlink($baseDirectory . '/file');
2752 unlink($baseDirectory . '/foo/file');
2753 unlink($baseDirectory . '/.bar/.file');
2754 unlink($baseDirectory . '/.bar/..file2');
2755 \TYPO3\CMS\Core\Utility\GeneralUtility
::rmdir($baseDirectory . '/foo');
2756 \TYPO3\CMS\Core\Utility\GeneralUtility
::rmdir($baseDirectory . '/.bar');
2757 \TYPO3\CMS\Core\Utility\GeneralUtility
::rmdir($baseDirectory);
2758 // Test if everything was ok
2759 $this->assertTrue($fixPermissionsResult);
2760 $this->assertEquals($resultBaseDirectoryPermissions, '0770');
2761 $this->assertEquals($resultBaseFilePermissions, '0660');
2762 $this->assertEquals($resultFooDirectoryPermissions, '0770');
2763 $this->assertEquals($resultFooFilePermissions, '0660');
2764 $this->assertEquals($resultBarDirectoryPermissions, '0770');
2765 $this->assertEquals($resultBarFilePermissions, '0660');
2766 $this->assertEquals($resultBarFile2Permissions, '0660');
2772 public function fixPermissionsDoesNotSetPermissionsToNotAllowedPath() {
2773 if (TYPO3_OS
== 'WIN') {
2774 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2776 // Create and prepare test file
2777 $filename = (PATH_site
. 'typo3temp/../typo3temp/') . uniqid('test_');
2779 chmod($filename, 482);
2780 // Set target permissions and run method
2781 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2782 $fixPermissionsResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::fixPermissions($filename);
2783 // Get actual permissions and clean up
2785 $resultFilePermissions = substr(decoct(fileperms($filename)), 2);
2787 // Test if everything was ok
2788 $this->assertFalse($fixPermissionsResult);
2794 public function fixPermissionsSetsPermissionsWithRelativeFileReference() {
2795 if (TYPO3_OS
== 'WIN') {
2796 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2798 $filename = 'typo3temp/' . uniqid('test_');
2799 \TYPO3\CMS\Core\Utility\GeneralUtility
::writeFileToTypo3tempDir(PATH_site
. $filename, '42');
2800 chmod(PATH_site
. $filename, 482);
2801 // Set target permissions and run method
2802 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = '0660';
2803 $fixPermissionsResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::fixPermissions($filename);
2804 // Get actual permissions and clean up
2806 $resultFilePermissions = substr(decoct(fileperms(PATH_site
. $filename)), 2);
2807 unlink(PATH_site
. $filename);
2808 // Test if everything was ok
2809 $this->assertTrue($fixPermissionsResult);
2810 $this->assertEquals($resultFilePermissions, '0660');
2813 ///////////////////////////////
2814 // Tests concerning mkdir
2815 ///////////////////////////////
2819 public function mkdirCreatesDirectory() {
2820 $directory = (PATH_site
. 'typo3temp/') . uniqid('test_');
2821 $mkdirResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($directory);
2823 $directoryCreated = is_dir($directory);
2825 $this->assertTrue($mkdirResult);
2826 $this->assertTrue($directoryCreated);
2832 public function mkdirCreatesHiddenDirectory() {
2833 $directory = (PATH_site
. 'typo3temp/') . uniqid('.test_');
2834 $mkdirResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($directory);
2836 $directoryCreated = is_dir($directory);
2838 $this->assertTrue($mkdirResult);
2839 $this->assertTrue($directoryCreated);
2845 public function mkdirCreatesDirectoryWithTrailingSlash() {
2846 $directory = ((PATH_site
. 'typo3temp/') . uniqid('test_')) . '/';
2847 $mkdirResult = \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($directory);
2849 $directoryCreated = is_dir($directory);
2851 $this->assertTrue($mkdirResult);
2852 $this->assertTrue($directoryCreated);
2858 public function mkdirSetsPermissionsOfCreatedDirectory() {
2859 if (TYPO3_OS
== 'WIN') {
2860 $this->markTestSkipped('mkdirSetsPermissionsOfCreatedDirectory() test not available on Windows');
2862 $directory = (PATH_site
. 'typo3temp/') . uniqid('test_');
2863 $oldUmask = umask(19);
2864 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = '0772';
2865 \TYPO3\CMS\Core\Utility\GeneralUtility
::mkdir($directory);
2867 $resultDirectoryPermissions = substr(decoct(fileperms($directory)), 1);
2870 $this->assertEquals($resultDirectoryPermissions, '0772');
2876 public function mkdirSetsGroupOwnershipOfCreatedDirectory() {
2877 if (!function_exists('posix_getegid')) {
2878 $this->markTestSkipped('Function posix_getegid() not available, mkdirSetsGroupOwnershipOfCreatedDirectory() tests skipped');
2880 if (posix_getegid() === -1) {
2881 $this->markTestSkipped('The mkdirSetsGroupOwnershipOfCreatedDirectory() is not available on Mac OS because posix_getegid() always returns -1 on Mac OS.');