2 namespace TYPO3\CMS\Core\Tests\Unit\Utility
;
5 * This file is part of the TYPO3 CMS project.
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
17 use TYPO3\CMS\Core\Tests\Unit\Utility\Fixtures\GeneralUtilityFixture
;
18 use TYPO3\CMS\Core\Tests\Unit\Utility\Fixtures\GeneralUtilityMinifyJavaScriptFixture
;
19 use TYPO3\CMS\Core\Tests\Unit\Utility\Fixtures\OriginalClassFixture
;
20 use TYPO3\CMS\Core\Tests\Unit\Utility\Fixtures\OtherReplacementClassFixture
;
21 use TYPO3\CMS\Core\Tests\Unit\Utility\Fixtures\ReplacementClassFixture
;
22 use TYPO3\CMS\Core\Tests\Unit\Utility\Fixtures\TwoParametersConstructorFixture
;
23 use TYPO3\CMS\Core\Utility\GeneralUtility
;
24 use org
\bovigo
\vfs
\vfsStream
;
25 use org
\bovigo
\vfs
\vfsStreamDirectory
;
26 use org
\bovigo
\vfs
\vfsStreamWrapper
;
27 use TYPO3\CMS\Core\Tests\FileStreamWrapper
;
30 * Testcase for class \TYPO3\CMS\Core\Utility\GeneralUtility
32 class GeneralUtilityTest
extends \TYPO3\CMS\Core\Tests\UnitTestCase
35 * @var array A backup of registered singleton instances
37 protected $singletonInstances = array();
39 protected function setUp()
41 GeneralUtilityFixture
::flushInternalRuntimeCaches();
42 GeneralUtilityFixture
::$isAllowedHostHeaderValueCallCount = 0;
43 GeneralUtilityFixture
::setAllowHostHeaderValue(false
);
44 $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] = GeneralUtility
::ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL
;
45 $this->singletonInstances
= GeneralUtility
::getSingletonInstances();
48 protected function tearDown()
50 GeneralUtility
::resetSingletonInstances($this->singletonInstances
);
55 * Helper method to test for an existing internet connection.
56 * Some tests are skipped if there is no working uplink.
58 * @return bool $isConnected
60 public function isConnected()
63 $connected = @fsockopen
('typo3.org', 80);
71 ///////////////////////////
72 // Tests concerning _GP
73 ///////////////////////////
76 * @dataProvider gpDataProvider
78 public function canRetrieveValueWithGP($key, $get, $post, $expected)
82 $this->assertSame($expected, GeneralUtility
::_GP($key));
86 * Data provider for canRetrieveValueWithGP.
87 * All test values also check whether slashes are stripped properly.
91 public function gpDataProvider()
94 'No key parameter' => array(null
, array(), array(), null
),
95 'Key not found' => array('cake', array(), array(), null
),
96 'Value only in GET' => array('cake', array('cake' => 'li\\e'), array(), 'li\\e'),
97 'Value only in POST' => array('cake', array(), array('cake' => 'l\\ie'), 'l\\ie'),
98 'Value from POST preferred over GET' => array('cake', array('cake' => 'is a'), array('cake' => '\\lie'), '\\lie'),
99 'Value can be an array' => array(
101 array('cake' => array('is a' => 'l\\ie')),
103 array('is a' => 'l\\ie')
108 ///////////////////////////
109 // Tests concerning _GPmerged
110 ///////////////////////////
113 * @dataProvider gpMergedDataProvider
115 public function gpMergedWillMergeArraysFromGetAndPost($get, $post, $expected)
119 $this->assertEquals($expected, GeneralUtility
::_GPmerged('cake'));
123 * Data provider for gpMergedWillMergeArraysFromGetAndPost
127 public function gpMergedDataProvider()
129 $fullDataArray = array('cake' => array('a' => 'is a', 'b' => 'lie'));
130 $postPartData = array('cake' => array('b' => 'lie'));
131 $getPartData = array('cake' => array('a' => 'is a'));
132 $getPartDataModified = array('cake' => array('a' => 'is not a'));
134 'Key doesn\' exist' => array(array('foo'), array('bar'), array()),
135 'No POST data' => array($fullDataArray, array(), $fullDataArray['cake']),
136 'No GET data' => array(array(), $fullDataArray, $fullDataArray['cake']),
137 'POST and GET are merged' => array($getPartData, $postPartData, $fullDataArray['cake']),
138 'POST is preferred over GET' => array($getPartDataModified, $fullDataArray, $fullDataArray['cake'])
142 ///////////////////////////////
143 // Tests concerning _GET / _POST
144 ///////////////////////////////
146 * Data provider for canRetrieveGlobalInputsThroughGet
147 * and canRetrieveGlobalInputsThroughPost
151 public function getAndPostDataProvider()
154 'Requested input data doesn\'t exist' => array('cake', array(), null
),
155 'No key will return entire input data' => array(null
, array('cake' => 'l\\ie'), array('cake' => 'l\\ie')),
156 'Can retrieve specific input' => array('cake', array('cake' => 'l\\ie', 'foo'), 'l\\ie'),
157 'Can retrieve nested input data' => array('cake', array('cake' => array('is a' => 'l\\ie')), array('is a' => 'l\\ie'))
163 * @dataProvider getAndPostDataProvider
165 public function canRetrieveGlobalInputsThroughGet($key, $get, $expected)
168 $this->assertSame($expected, GeneralUtility
::_GET($key));
173 * @dataProvider getAndPostDataProvider
175 public function canRetrieveGlobalInputsThroughPost($key, $post, $expected)
178 $this->assertSame($expected, GeneralUtility
::_POST($key));
181 ///////////////////////////////
182 // Tests concerning _GETset
183 ///////////////////////////////
186 * @dataProvider getSetDataProvider
188 public function canSetNewGetInputValues($input, $key, $expected, $getPreset = array())
191 GeneralUtility
::_GETset($input, $key);
192 $this->assertSame($expected, $_GET);
196 * Data provider for canSetNewGetInputValues
200 public function getSetDataProvider()
203 'No input data used without target key' => array(null
, null
, array()),
204 'No input data used with target key' => array('', 'cake', array('cake' => '')),
205 'No target key used with string input data' => array('data', null
, array()),
206 'No target key used with array input data' => array(array('cake' => 'lie'), null
, array('cake' => 'lie')),
207 'Target key and string input data' => array('lie', 'cake', array('cake' => 'lie')),
208 'Replace existing GET data' => array('lie', 'cake', array('cake' => 'lie'), array('cake' => 'is a lie')),
209 'Target key pointing to sublevels and string input data' => array('lie', 'cake|is', array('cake' => array('is' => 'lie'))),
210 'Target key pointing to sublevels and array input data' => array(array('a' => 'lie'), 'cake|is', array('cake' => array('is' => array('a' => 'lie'))))
214 ///////////////////////////
215 // Tests concerning cmpIPv4
216 ///////////////////////////
218 * Data provider for cmpIPv4ReturnsTrueForMatchingAddress
220 * @return array Data sets
222 public static function cmpIPv4DataProviderMatching()
225 'host with full IP address' => array('127.0.0.1', '127.0.0.1'),
226 'host with two wildcards at the end' => array('127.0.0.1', '127.0.*.*'),
227 'host with wildcard at third octet' => array('127.0.0.1', '127.0.*.1'),
228 'host with wildcard at second octet' => array('127.0.0.1', '127.*.0.1'),
229 '/8 subnet' => array('127.0.0.1', '127.1.1.1/8'),
230 '/32 subnet (match only name)' => array('127.0.0.1', '127.0.0.1/32'),
231 '/30 subnet' => array('10.10.3.1', '10.10.3.3/30'),
232 'host with wildcard in list with IPv4/IPv6 addresses' => array('192.168.1.1', '127.0.0.1, 1234:5678::/126, 192.168.*'),
233 'host in list with IPv4/IPv6 addresses' => array('192.168.1.1', '::1, 1234:5678::/126, 192.168.1.1'),
239 * @dataProvider cmpIPv4DataProviderMatching
241 public function cmpIPv4ReturnsTrueForMatchingAddress($ip, $list)
243 $this->assertTrue(GeneralUtility
::cmpIPv4($ip, $list));
247 * Data provider for cmpIPv4ReturnsFalseForNotMatchingAddress
249 * @return array Data sets
251 public static function cmpIPv4DataProviderNotMatching()
254 'single host' => array('127.0.0.1', '127.0.0.2'),
255 'single host with wildcard' => array('127.0.0.1', '127.*.1.1'),
256 'single host with /32 subnet mask' => array('127.0.0.1', '127.0.0.2/32'),
257 '/31 subnet' => array('127.0.0.1', '127.0.0.2/31'),
258 'list with IPv4/IPv6 addresses' => array('127.0.0.1', '10.0.2.3, 192.168.1.1, ::1'),
259 'list with only IPv6 addresses' => array('10.20.30.40', '::1, 1234:5678::/127')
265 * @dataProvider cmpIPv4DataProviderNotMatching
267 public function cmpIPv4ReturnsFalseForNotMatchingAddress($ip, $list)
269 $this->assertFalse(GeneralUtility
::cmpIPv4($ip, $list));
272 ///////////////////////////
273 // Tests concerning cmpIPv6
274 ///////////////////////////
276 * Data provider for cmpIPv6ReturnsTrueForMatchingAddress
278 * @return array Data sets
280 public static function cmpIPv6DataProviderMatching()
283 'empty address' => array('::', '::'),
284 'empty with netmask in list' => array('::', '::/0'),
285 'empty with netmask 0 and host-bits set in list' => array('::', '::123/0'),
286 'localhost' => array('::1', '::1'),
287 'localhost with leading zero blocks' => array('::1', '0:0::1'),
288 'host with submask /128' => array('::1', '0:0::1/128'),
289 '/16 subnet' => array('1234::1', '1234:5678::/16'),
290 '/126 subnet' => array('1234:5678::3', '1234:5678::/126'),
291 '/126 subnet with host-bits in list set' => array('1234:5678::3', '1234:5678::2/126'),
292 'list with IPv4/IPv6 addresses' => array('1234:5678::3', '::1, 127.0.0.1, 1234:5678::/126, 192.168.1.1')
298 * @dataProvider cmpIPv6DataProviderMatching
300 public function cmpIPv6ReturnsTrueForMatchingAddress($ip, $list)
302 $this->assertTrue(GeneralUtility
::cmpIPv6($ip, $list));
306 * Data provider for cmpIPv6ReturnsFalseForNotMatchingAddress
308 * @return array Data sets
310 public static function cmpIPv6DataProviderNotMatching()
313 'empty against localhost' => array('::', '::1'),
314 'empty against localhost with /128 netmask' => array('::', '::1/128'),
315 'localhost against different host' => array('::1', '::2'),
316 'localhost against host with prior bits set' => array('::1', '::1:1'),
317 'host against different /17 subnet' => array('1234::1', '1234:f678::/17'),
318 'host against different /127 subnet' => array('1234:5678::3', '1234:5678::/127'),
319 'host against IPv4 address list' => array('1234:5678::3', '127.0.0.1, 192.168.1.1'),
320 'host against mixed list with IPv6 host in different subnet' => array('1234:5678::3', '::1, 1234:5678::/127')
326 * @dataProvider cmpIPv6DataProviderNotMatching
328 public function cmpIPv6ReturnsFalseForNotMatchingAddress($ip, $list)
330 $this->assertFalse(GeneralUtility
::cmpIPv6($ip, $list));
333 ///////////////////////////////
334 // Tests concerning IPv6Hex2Bin
335 ///////////////////////////////
337 * Data provider for IPv6Hex2BinCorrect
339 * @return array Data sets
341 public static function IPv6Hex2BinDataProviderCorrect()
344 'empty 1' => array('::', str_pad('', 16, "\x00")),
345 'empty 2, already normalized' => array('0000:0000:0000:0000:0000:0000:0000:0000', str_pad('', 16, "\x00")),
346 'already normalized' => array('0102:0304:0000:0000:0000:0000:0506:0078', "\x01\x02\x03\x04" . str_pad('', 8, "\x00") . "\x05\x06\x00\x78"),
347 'expansion in middle 1' => array('1::2', "\x00\x01" . str_pad('', 12, "\x00") . "\x00\x02"),
348 'expansion in middle 2' => array('beef::fefa', "\xbe\xef" . str_pad('', 12, "\x00") . "\xfe\xfa"),
354 * @dataProvider IPv6Hex2BinDataProviderCorrect
356 public function IPv6Hex2BinCorrectlyConvertsAddresses($hex, $binary)
358 $this->assertTrue(GeneralUtility
::IPv6Hex2Bin($hex) === $binary);
361 ///////////////////////////////
362 // Tests concerning IPv6Bin2Hex
363 ///////////////////////////////
365 * Data provider for IPv6Bin2HexCorrect
367 * @return array Data sets
369 public static function IPv6Bin2HexDataProviderCorrect()
372 'empty' => array(str_pad('', 16, "\x00"), '::'),
373 'non-empty front' => array("\x01" . str_pad('', 15, "\x00"), '100::'),
374 'non-empty back' => array(str_pad('', 15, "\x00") . "\x01", '::1'),
375 'normalized' => array("\x01\x02\x03\x04" . str_pad('', 8, "\x00") . "\x05\x06\x00\x78", '102:304::506:78'),
376 'expansion in middle 1' => array("\x00\x01" . str_pad('', 12, "\x00") . "\x00\x02", '1::2'),
377 'expansion in middle 2' => array("\xbe\xef" . str_pad('', 12, "\x00") . "\xfe\xfa", 'beef::fefa'),
383 * @dataProvider IPv6Bin2HexDataProviderCorrect
385 public function IPv6Bin2HexCorrectlyConvertsAddresses($binary, $hex)
387 $this->assertEquals(GeneralUtility
::IPv6Bin2Hex($binary), $hex);
390 ////////////////////////////////////////////////
391 // Tests concerning normalizeIPv6 / compressIPv6
392 ////////////////////////////////////////////////
394 * Data provider for normalizeIPv6ReturnsCorrectlyNormalizedFormat
396 * @return array Data sets
398 public static function normalizeCompressIPv6DataProviderCorrect()
401 'empty' => array('::', '0000:0000:0000:0000:0000:0000:0000:0000'),
402 'localhost' => array('::1', '0000:0000:0000:0000:0000:0000:0000:0001'),
403 'expansion in middle 1' => array('1::2', '0001:0000:0000:0000:0000:0000:0000:0002'),
404 'expansion in middle 2' => array('1:2::3', '0001:0002:0000:0000:0000:0000:0000:0003'),
405 'expansion in middle 3' => array('1::2:3', '0001:0000:0000:0000:0000:0000:0002:0003'),
406 'expansion in middle 4' => array('1:2::3:4:5', '0001:0002:0000:0000:0000:0003:0004:0005')
412 * @dataProvider normalizeCompressIPv6DataProviderCorrect
414 public function normalizeIPv6CorrectlyNormalizesAddresses($compressed, $normalized)
416 $this->assertEquals($normalized, GeneralUtility
::normalizeIPv6($compressed));
421 * @dataProvider normalizeCompressIPv6DataProviderCorrect
423 public function compressIPv6CorrectlyCompressesAdresses($compressed, $normalized)
425 $this->assertEquals($compressed, GeneralUtility
::compressIPv6($normalized));
431 public function compressIPv6CorrectlyCompressesAdressWithSomeAddressOnRightSide()
433 if (strtolower(PHP_OS
) === 'darwin') {
434 $this->markTestSkipped('This test does not work on OSX / Darwin OS.');
436 $this->assertEquals('::f0f', GeneralUtility
::compressIPv6('0000:0000:0000:0000:0000:0000:0000:0f0f'));
439 ///////////////////////////////
440 // Tests concerning validIP
441 ///////////////////////////////
443 * Data provider for checkValidIpReturnsTrueForValidIp
445 * @return array Data sets
447 public static function validIpDataProvider()
450 '0.0.0.0' => array('0.0.0.0'),
451 'private IPv4 class C' => array('192.168.0.1'),
452 'private IPv4 class A' => array('10.0.13.1'),
453 'private IPv6' => array('fe80::daa2:5eff:fe8b:7dfb')
459 * @dataProvider validIpDataProvider
461 public function validIpReturnsTrueForValidIp($ip)
463 $this->assertTrue(GeneralUtility
::validIP($ip));
467 * Data provider for checkValidIpReturnsFalseForInvalidIp
469 * @return array Data sets
471 public static function invalidIpDataProvider()
474 'null' => array(null
),
476 'string' => array('test'),
477 'string empty' => array(''),
478 'string NULL' => array('NULL'),
479 'out of bounds IPv4' => array('300.300.300.300'),
480 'dotted decimal notation with only two dots' => array('127.0.1')
486 * @dataProvider invalidIpDataProvider
488 public function validIpReturnsFalseForInvalidIp($ip)
490 $this->assertFalse(GeneralUtility
::validIP($ip));
493 ///////////////////////////////
494 // Tests concerning cmpFQDN
495 ///////////////////////////////
497 * Data provider for cmpFqdnReturnsTrue
499 * @return array Data sets
501 public static function cmpFqdnValidDataProvider()
504 'localhost should usually resolve, IPv4' => array('127.0.0.1', '*'),
505 'localhost should usually resolve, IPv6' => array('::1', '*'),
506 // other testcases with resolving not possible since it would
507 // require a working IPv4/IPv6-connectivity
508 'aaa.bbb.ccc.ddd.eee, full' => array('aaa.bbb.ccc.ddd.eee', 'aaa.bbb.ccc.ddd.eee'),
509 'aaa.bbb.ccc.ddd.eee, wildcard first' => array('aaa.bbb.ccc.ddd.eee', '*.ccc.ddd.eee'),
510 'aaa.bbb.ccc.ddd.eee, wildcard last' => array('aaa.bbb.ccc.ddd.eee', 'aaa.bbb.ccc.*'),
511 'aaa.bbb.ccc.ddd.eee, wildcard middle' => array('aaa.bbb.ccc.ddd.eee', 'aaa.*.eee'),
512 'list-matches, 1' => array('aaa.bbb.ccc.ddd.eee', 'xxx, yyy, zzz, aaa.*.eee'),
513 'list-matches, 2' => array('aaa.bbb.ccc.ddd.eee', '127:0:0:1,,aaa.*.eee,::1')
519 * @dataProvider cmpFqdnValidDataProvider
521 public function cmpFqdnReturnsTrue($baseHost, $list)
523 $this->assertTrue(GeneralUtility
::cmpFQDN($baseHost, $list));
527 * Data provider for cmpFqdnReturnsFalse
529 * @return array Data sets
531 public static function cmpFqdnInvalidDataProvider()
534 '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'),
535 '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')
541 * @dataProvider cmpFqdnInvalidDataProvider
543 public function cmpFqdnReturnsFalse($baseHost, $list)
545 $this->assertFalse(GeneralUtility
::cmpFQDN($baseHost, $list));
548 ///////////////////////////////
549 // Tests concerning inList
550 ///////////////////////////////
553 * @param string $haystack
554 * @dataProvider inListForItemContainedReturnsTrueDataProvider
556 public function inListForItemContainedReturnsTrue($haystack)
558 $this->assertTrue(GeneralUtility
::inList($haystack, 'findme'));
562 * Data provider for inListForItemContainedReturnsTrue.
566 public function inListForItemContainedReturnsTrueDataProvider()
569 'Element as second element of four items' => array('one,findme,three,four'),
570 'Element at beginning of list' => array('findme,one,two'),
571 'Element at end of list' => array('one,two,findme'),
572 'One item list' => array('findme')
578 * @param string $haystack
579 * @dataProvider inListForItemNotContainedReturnsFalseDataProvider
581 public function inListForItemNotContainedReturnsFalse($haystack)
583 $this->assertFalse(GeneralUtility
::inList($haystack, 'findme'));
587 * Data provider for inListForItemNotContainedReturnsFalse.
591 public function inListForItemNotContainedReturnsFalseDataProvider()
594 'Four item list' => array('one,two,three,four'),
595 'One item list' => array('one'),
596 'Empty list' => array('')
600 ///////////////////////////////
601 // Tests concerning rmFromList
602 ///////////////////////////////
605 * @param string $initialList
606 * @param string $listWithElementRemoved
607 * @dataProvider rmFromListRemovesElementsFromCommaSeparatedListDataProvider
609 public function rmFromListRemovesElementsFromCommaSeparatedList($initialList, $listWithElementRemoved)
611 $this->assertSame($listWithElementRemoved, GeneralUtility
::rmFromList('removeme', $initialList));
615 * Data provider for rmFromListRemovesElementsFromCommaSeparatedList
619 public function rmFromListRemovesElementsFromCommaSeparatedListDataProvider()
622 'Element as second element of three' => array('one,removeme,two', 'one,two'),
623 'Element at beginning of list' => array('removeme,one,two', 'one,two'),
624 'Element at end of list' => array('one,two,removeme', 'one,two'),
625 'One item list' => array('removeme', ''),
626 'Element not contained in list' => array('one,two,three', 'one,two,three'),
627 'Empty element survives' => array('one,,three,,removeme', 'one,,three,'),
628 'Empty element survives at start' => array(',removeme,three,removeme', ',three'),
629 'Empty element survives at end' => array('removeme,three,removeme,', 'three,'),
630 'Empty list' => array('', ''),
631 'List contains removeme multiple times' => array('removeme,notme,removeme,removeme', 'notme'),
632 'List contains removeme multiple times nothing else' => array('removeme,removeme,removeme', ''),
633 'List contains removeme multiple times nothing else 2x' => array('removeme,removeme', ''),
634 'List contains removeme multiple times nothing else 3x' => array('removeme,removeme,removeme', ''),
635 'List contains removeme multiple times nothing else 4x' => array('removeme,removeme,removeme,removeme', ''),
636 'List contains removeme multiple times nothing else 5x' => array('removeme,removeme,removeme,removeme,removeme', ''),
640 ///////////////////////////////
641 // Tests concerning expandList
642 ///////////////////////////////
645 * @param string $list
646 * @param string $expectation
647 * @dataProvider expandListExpandsIntegerRangesDataProvider
649 public function expandListExpandsIntegerRanges($list, $expectation)
651 $this->assertSame($expectation, GeneralUtility
::expandList($list));
655 * Data provider for expandListExpandsIntegerRangesDataProvider
659 public function expandListExpandsIntegerRangesDataProvider()
662 'Expand for the same number' => array('1,2-2,7', '1,2,7'),
663 'Small range expand with parameters reversed ignores reversed items' => array('1,5-3,7', '1,7'),
664 'Small range expand' => array('1,3-5,7', '1,3,4,5,7'),
665 'Expand at beginning' => array('3-5,1,7', '3,4,5,1,7'),
666 'Expand at end' => array('1,7,3-5', '1,7,3,4,5'),
667 'Multiple small range expands' => array('1,3-5,7-10,12', '1,3,4,5,7,8,9,10,12'),
668 'One item list' => array('1-5', '1,2,3,4,5'),
669 'Nothing to expand' => array('1,2,3,4', '1,2,3,4'),
670 'Empty list' => array('', '')
677 public function expandListExpandsForTwoThousandElementsExpandsOnlyToThousandElementsMaximum()
679 $list = GeneralUtility
::expandList('1-2000');
680 $this->assertSame(1000, count(explode(',', $list)));
683 ///////////////////////////////
684 // Tests concerning uniqueList
685 ///////////////////////////////
688 * @param string $initialList
689 * @param string $unifiedList
690 * @dataProvider uniqueListUnifiesCommaSeparatedListDataProvider
692 public function uniqueListUnifiesCommaSeparatedList($initialList, $unifiedList)
694 $this->assertSame($unifiedList, GeneralUtility
::uniqueList($initialList));
698 * Data provider for uniqueListUnifiesCommaSeparatedList
702 public function uniqueListUnifiesCommaSeparatedListDataProvider()
705 'List without duplicates' => array('one,two,three', 'one,two,three'),
706 'List with two consecutive duplicates' => array('one,two,two,three,three', 'one,two,three'),
707 'List with non-consecutive duplicates' => array('one,two,three,two,three', 'one,two,three'),
708 'One item list' => array('one', 'one'),
709 'Empty list' => array('', '')
713 ///////////////////////////////
714 // Tests concerning isFirstPartOfStr
715 ///////////////////////////////
717 * Data provider for isFirstPartOfStrReturnsTrueForMatchingFirstParts
721 public function isFirstPartOfStrReturnsTrueForMatchingFirstPartDataProvider()
724 'match first part of string' => array('hello world', 'hello'),
725 'match whole string' => array('hello', 'hello'),
726 'integer is part of string with same number' => array('24', 24),
727 'string is part of integer with same number' => array(24, '24'),
728 'integer is part of string starting with same number' => array('24 beer please', 24)
734 * @dataProvider isFirstPartOfStrReturnsTrueForMatchingFirstPartDataProvider
736 public function isFirstPartOfStrReturnsTrueForMatchingFirstPart($string, $part)
738 $this->assertTrue(GeneralUtility
::isFirstPartOfStr($string, $part));
742 * Data provider for checkIsFirstPartOfStrReturnsFalseForNotMatchingFirstParts
746 public function isFirstPartOfStrReturnsFalseForNotMatchingFirstPartDataProvider()
749 'no string match' => array('hello', 'bye'),
750 'no case sensitive string match' => array('hello world', 'Hello'),
751 'array is not part of string' => array('string', array()),
752 'string is not part of array' => array(array(), 'string'),
753 'NULL is not part of string' => array('string', null
),
754 'string is not part of NULL' => array(null
, 'string'),
755 'NULL is not part of array' => array(array(), null
),
756 'array is not part of NULL' => array(null
, array()),
757 'empty string is not part of empty string' => array('', ''),
758 'NULL is not part of empty string' => array('', null
),
759 'false is not part of empty string' => array('', false
),
760 'empty string is not part of NULL' => array(null
, ''),
761 'empty string is not part of false' => array(false
, ''),
762 'empty string is not part of zero integer' => array(0, ''),
763 'zero integer is not part of NULL' => array(null
, 0),
764 'zero integer is not part of empty string' => array('', 0)
770 * @dataProvider isFirstPartOfStrReturnsFalseForNotMatchingFirstPartDataProvider
772 public function isFirstPartOfStrReturnsFalseForNotMatchingFirstPart($string, $part)
774 $this->assertFalse(GeneralUtility
::isFirstPartOfStr($string, $part));
777 ///////////////////////////////
778 // Tests concerning formatSize
779 ///////////////////////////////
782 * @dataProvider formatSizeDataProvider
784 public function formatSizeTranslatesBytesToHigherOrderRepresentation($size, $labels, $base, $expected)
786 $this->assertEquals($expected, GeneralUtility
::formatSize($size, $labels, $base));
790 * Data provider for formatSizeTranslatesBytesToHigherOrderRepresentation
794 public function formatSizeDataProvider()
797 'IEC Bytes stay bytes (min)' => array(1, '', 0, '1 '),
798 'IEC Bytes stay bytes (max)' => array(921, '', 0, '921 '),
799 'IEC Kilobytes are used (min)' => array(922, '', 0, '0.90 Ki'),
800 'IEC Kilobytes are used (max)' => array(943718, '', 0, '922 Ki'),
801 'IEC Megabytes are used (min)' => array(943719, '', 0, '0.90 Mi'),
802 'IEC Megabytes are used (max)' => array(966367641, '', 0, '922 Mi'),
803 'IEC Gigabytes are used (min)' => array(966367642, '', 0, '0.90 Gi'),
804 'IEC Gigabytes are used (max)' => array(989560464998, '', 0, '922 Gi'),
805 'IEC Decimal is omitted for large kilobytes' => array(31080, '', 0, '30 Ki'),
806 'IEC Decimal is omitted for large megabytes' => array(31458000, '', 0, '30 Mi'),
807 'IEC Decimal is omitted for large gigabytes' => array(32212254720, '', 0, '30 Gi'),
808 'SI Bytes stay bytes (min)' => array(1, 'si', 0, '1 '),
809 'SI Bytes stay bytes (max)' => array(899, 'si', 0, '899 '),
810 'SI Kilobytes are used (min)' => array(901, 'si', 0, '0.90 k'),
811 'SI Kilobytes are used (max)' => array(900000, 'si', 0, '900 k'),
812 'SI Megabytes are used (min)' => array(900001, 'si', 0, '0.90 M'),
813 'SI Megabytes are used (max)' => array(900000000, 'si', 0, '900 M'),
814 'SI Gigabytes are used (min)' => array(900000001, 'si', 0, '0.90 G'),
815 'SI Gigabytes are used (max)' => array(900000000000, 'si', 0, '900 G'),
816 'SI Decimal is omitted for large kilobytes' => array(30000, 'si', 0, '30 k'),
817 'SI Decimal is omitted for large megabytes' => array(30000000, 'si', 0, '30 M'),
818 'SI Decimal is omitted for large gigabytes' => array(30000000000, 'si', 0, '30 G'),
819 'Label for bytes can be exchanged (binary unit)' => array(1, ' Foo|||', 0, '1 Foo'),
820 'Label for kilobytes can be exchanged (binary unit)' => array(1024, '| Foo||', 0, '1.00 Foo'),
821 'Label for megabyes can be exchanged (binary unit)' => array(1048576, '|| Foo|', 0, '1.00 Foo'),
822 'Label for gigabytes can be exchanged (binary unit)' => array(1073741824, '||| Foo', 0, '1.00 Foo'),
823 'Label for bytes can be exchanged (decimal unit)' => array(1, ' Foo|||', 1000, '1 Foo'),
824 'Label for kilobytes can be exchanged (decimal unit)' => array(1000, '| Foo||', 1000, '1.00 Foo'),
825 'Label for megabyes can be exchanged (decimal unit)' => array(1000000, '|| Foo|', 1000, '1.00 Foo'),
826 'Label for gigabytes can be exchanged (decimal unit)' => array(1000000000, '||| Foo', 1000, '1.00 Foo'),
827 'IEC Base is ignored' => array(1024, 'iec', 1000, '1.00 Ki'),
828 'SI Base is ignored' => array(1000, 'si', 1024, '1.00 k'),
829 'Use binary base for unexpected base' => array(2048, '| Bar||', 512, '2.00 Bar')
833 ///////////////////////////////
834 // Tests concerning splitCalc
835 ///////////////////////////////
837 * Data provider for splitCalc
839 * @return array expected values, arithmetic expression
841 public function splitCalcDataProvider()
844 'empty string returns empty array' => array(
848 'number without operator returns array with plus and number' => array(
849 array(array('+', 42)),
852 'two numbers with asterisk return first number with plus and second number with asterisk' => array(
853 array(array('+', 42), array('*', 31)),
861 * @dataProvider splitCalcDataProvider
863 public function splitCalcCorrectlySplitsExpression($expected, $expression)
865 $this->assertEquals($expected, GeneralUtility
::splitCalc($expression, '+-*/'));
868 ///////////////////////////////
869 // Tests concerning htmlspecialchars_decode
870 ///////////////////////////////
874 public function htmlspecialcharsDecodeReturnsDecodedString()
876 $string = '<typo3 version="6.0"> </typo3>';
877 $encoded = htmlspecialchars($string);
878 $decoded = htmlspecialchars_decode($encoded);
879 $this->assertEquals($string, $decoded);
882 ///////////////////////////////
883 // Tests concerning deHSCentities
884 ///////////////////////////////
887 * @dataProvider deHSCentitiesReturnsDecodedStringDataProvider
889 public function deHSCentitiesReturnsDecodedString($input, $expected)
891 $this->assertEquals($expected, GeneralUtility
::deHSCentities($input));
895 * Data provider for deHSCentitiesReturnsDecodedString
899 public function deHSCentitiesReturnsDecodedStringDataProvider()
902 'Empty string' => array('', ''),
903 'Double encoded &' => array('&amp;', '&'),
904 'Double encoded numeric entity' => array('&#1234;', 'Ӓ'),
905 'Double encoded hexadecimal entity' => array('&#x1b;', ''),
906 'Single encoded entities are not touched' => array('& Ӓ ', '& Ӓ ')
910 //////////////////////////////////
911 // Tests concerning slashJS
912 //////////////////////////////////
915 * @dataProvider slashJsDataProvider
917 public function slashJsEscapesSingleQuotesAndSlashes($input, $extended, $expected)
919 $this->assertEquals($expected, GeneralUtility
::slashJS($input, $extended));
923 * Data provider for slashJsEscapesSingleQuotesAndSlashes
927 public function slashJsDataProvider()
930 'Empty string is not changed' => array('', false
, ''),
931 'Normal string is not changed' => array('The cake is a lie √', false
, 'The cake is a lie √'),
932 'String with single quotes' => array('The \'cake\' is a lie', false
, 'The \\\'cake\\\' is a lie'),
933 'String with single quotes and backslashes - just escape single quotes' => array('The \\\'cake\\\' is a lie', false
, 'The \\\\\'cake\\\\\' is a lie'),
934 'String with single quotes and backslashes - escape both' => array('The \\\'cake\\\' is a lie', true
, 'The \\\\\\\'cake\\\\\\\' is a lie')
938 //////////////////////////////////
939 // Tests concerning rawUrlEncodeJS
940 //////////////////////////////////
944 public function rawUrlEncodeJsPreservesWhitespaces()
946 $input = 'Encode \'me\', but leave my spaces √';
947 $expected = 'Encode %27me%27%2C but leave my spaces %E2%88%9A';
948 $this->assertEquals($expected, GeneralUtility
::rawUrlEncodeJS($input));
951 //////////////////////////////////
952 // Tests concerning rawUrlEncodeJS
953 //////////////////////////////////
957 public function rawUrlEncodeFpPreservesSlashes()
959 $input = 'Encode \'me\', but leave my / √';
960 $expected = 'Encode%20%27me%27%2C%20but%20leave%20my%20/%20%E2%88%9A';
961 $this->assertEquals($expected, GeneralUtility
::rawUrlEncodeFP($input));
964 //////////////////////////////////
965 // Tests concerning strtoupper / strtolower
966 //////////////////////////////////
968 * Data provider for strtoupper and strtolower
972 public function strtouppperDataProvider()
975 'Empty string' => array('', ''),
976 'String containing only latin characters' => array('the cake is a lie.', 'THE CAKE IS A LIE.'),
977 'String with umlauts and accent characters' => array('the cà kê is ä lie.', 'THE Cà Kê IS ä LIE.')
983 * @dataProvider strtouppperDataProvider
985 public function strtoupperConvertsOnlyLatinCharacters($input, $expected)
987 $this->assertEquals($expected, GeneralUtility
::strtoupper($input));
992 * @dataProvider strtouppperDataProvider
994 public function strtolowerConvertsOnlyLatinCharacters($expected, $input)
996 $this->assertEquals($expected, GeneralUtility
::strtolower($input));
999 //////////////////////////////////
1000 // Tests concerning validEmail
1001 //////////////////////////////////
1003 * Data provider for valid validEmail's
1005 * @return array Valid email addresses
1007 public function validEmailValidDataProvider()
1010 'short mail address' => array('a@b.c'),
1011 'simple mail address' => array('test@example.com'),
1012 'uppercase characters' => array('QWERTYUIOPASDFGHJKLZXCVBNM@QWERTYUIOPASDFGHJKLZXCVBNM.NET'),
1013 'equal sign in local part' => array('test=mail@example.com'),
1014 'dash in local part' => array('test-mail@example.com'),
1015 'plus in local part' => array('test+mail@example.com'),
1016 'question mark in local part' => array('test?mail@example.com'),
1017 'slash in local part' => array('foo/bar@example.com'),
1018 'hash in local part' => array('foo#bar@example.com'),
1019 'dot in local part' => array('firstname.lastname@employee.2something.com'),
1020 'dash as local part' => array('-@foo.com'),
1021 'umlauts in domain part' => array('foo@äöüfoo.com')
1027 * @dataProvider validEmailValidDataProvider
1029 public function validEmailReturnsTrueForValidMailAddress($address)
1031 $this->assertTrue(GeneralUtility
::validEmail($address));
1035 * Data provider for invalid validEmail's
1037 * @return array Invalid email addresses
1039 public function validEmailInvalidDataProvider()
1042 'empty string' => array(''),
1043 'empty array' => array(array()),
1044 'integer' => array(42),
1045 'float' => array(42.23),
1046 'array' => array(array('foo')),
1047 'object' => array(new \
stdClass()),
1048 '@ sign only' => array('@'),
1049 'string longer than 320 characters' => array(str_repeat('0123456789', 33)),
1050 'duplicate @' => array('test@@example.com'),
1051 'duplicate @ combined with further special characters in local part' => array('test!.!@#$%^&*@example.com'),
1052 'opening parenthesis in local part' => array('foo(bar@example.com'),
1053 'closing parenthesis in local part' => array('foo)bar@example.com'),
1054 'opening square bracket in local part' => array('foo[bar@example.com'),
1055 'closing square bracket as local part' => array(']@example.com'),
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 'dot at beginning of domain part' => array('test@.com'),
1062 'local part ends with dot' => array('e.x.a.m.p.l.e.@example.com'),
1063 'umlauts in local part' => array('äöüfoo@bar.com'),
1064 'trailing whitespace' => array('test@example.com '),
1065 'trailing carriage return' => array('test@example.com' . CR
),
1066 'trailing linefeed' => array('test@example.com' . LF
),
1067 'trailing carriage return linefeed' => array('test@example.com' . CRLF
),
1068 'trailing tab' => array('test@example.com' . TAB
)
1074 * @dataProvider validEmailInvalidDataProvider
1076 public function validEmailReturnsFalseForInvalidMailAddress($address)
1078 $this->assertFalse(GeneralUtility
::validEmail($address));
1081 //////////////////////////////////
1082 // Tests concerning intExplode
1083 //////////////////////////////////
1087 public function intExplodeConvertsStringsToInteger()
1089 $testString = '1,foo,2';
1090 $expectedArray = array(1, 0, 2);
1091 $actualArray = GeneralUtility
::intExplode(',', $testString);
1092 $this->assertEquals($expectedArray, $actualArray);
1095 //////////////////////////////////
1096 // Tests concerning implodeArrayForUrl / explodeUrl2Array
1097 //////////////////////////////////
1099 * Data provider for implodeArrayForUrlBuildsValidParameterString and
1100 * explodeUrl2ArrayTransformsParameterStringToArray
1104 public function implodeArrayForUrlDataProvider()
1106 $valueArray = array('one' => '√', 'two' => 2);
1108 'Empty input' => array('foo', array(), ''),
1109 'String parameters' => array('foo', $valueArray, '&foo[one]=%E2%88%9A&foo[two]=2'),
1110 'Nested array parameters' => array('foo', array($valueArray), '&foo[0][one]=%E2%88%9A&foo[0][two]=2'),
1111 'Keep blank parameters' => array('foo', array('one' => '√', ''), '&foo[one]=%E2%88%9A&foo[0]=')
1117 * @dataProvider implodeArrayForUrlDataProvider
1119 public function implodeArrayForUrlBuildsValidParameterString($name, $input, $expected)
1121 $this->assertSame($expected, GeneralUtility
::implodeArrayForUrl($name, $input));
1127 public function implodeArrayForUrlCanSkipEmptyParameters()
1129 $input = array('one' => '√', '');
1130 $expected = '&foo[one]=%E2%88%9A';
1131 $this->assertSame($expected, GeneralUtility
::implodeArrayForUrl('foo', $input, '', true
));
1137 public function implodeArrayForUrlCanUrlEncodeKeyNames()
1139 $input = array('one' => '√', '');
1140 $expected = '&foo%5Bone%5D=%E2%88%9A&foo%5B0%5D=';
1141 $this->assertSame($expected, GeneralUtility
::implodeArrayForUrl('foo', $input, '', false
, true
));
1146 * @dataProvider implodeArrayForUrlDataProvider
1148 public function explodeUrl2ArrayTransformsParameterStringToNestedArray($name, $array, $input)
1150 $expected = $array ?
array($name => $array) : array();
1151 $this->assertEquals($expected, GeneralUtility
::explodeUrl2Array($input, true
));
1156 * @dataProvider explodeUrl2ArrayDataProvider
1158 public function explodeUrl2ArrayTransformsParameterStringToFlatArray($input, $expected)
1160 $this->assertEquals($expected, GeneralUtility
::explodeUrl2Array($input, false
));
1164 * Data provider for explodeUrl2ArrayTransformsParameterStringToFlatArray
1168 public function explodeUrl2ArrayDataProvider()
1171 'Empty string' => array('', array()),
1172 'Simple parameter string' => array('&one=%E2%88%9A&two=2', array('one' => '√', 'two' => 2)),
1173 'Nested parameter string' => array('&foo[one]=%E2%88%9A&two=2', array('foo[one]' => '√', 'two' => 2))
1177 //////////////////////////////////
1178 // Tests concerning compileSelectedGetVarsFromArray
1179 //////////////////////////////////
1183 public function compileSelectedGetVarsFromArrayFiltersIncomingData()
1185 $filter = 'foo,bar';
1186 $getArray = array('foo' => 1, 'cake' => 'lie');
1187 $expected = array('foo' => 1);
1188 $result = GeneralUtility
::compileSelectedGetVarsFromArray($filter, $getArray, false
);
1189 $this->assertSame($expected, $result);
1195 public function compileSelectedGetVarsFromArrayUsesGetPostDataFallback()
1198 $filter = 'foo,bar';
1199 $getArray = array('foo' => 1, 'cake' => 'lie');
1200 $expected = array('foo' => 1, 'bar' => '2');
1201 $result = GeneralUtility
::compileSelectedGetVarsFromArray($filter, $getArray, true
);
1202 $this->assertSame($expected, $result);
1205 //////////////////////////////////
1206 // Tests concerning array_merge
1207 //////////////////////////////////
1209 * Test demonstrating array_merge. This is actually
1210 * a native PHP operator, therefore this test is mainly used to
1211 * show how this function can be used.
1215 public function arrayMergeKeepsIndexesAfterMerge()
1217 $array1 = array(10 => 'FOO', '20' => 'BAR');
1218 $array2 = array('5' => 'PLONK');
1219 $expected = array('5' => 'PLONK', 10 => 'FOO', '20' => 'BAR');
1220 $this->assertEquals($expected, GeneralUtility
::array_merge($array1, $array2));
1223 //////////////////////////////////
1224 // Tests concerning revExplode
1225 //////////////////////////////////
1230 public function revExplodeDataProvider()
1233 'limit 0 should return unexploded string' => array(
1237 array('my:words:here')
1239 'limit 1 should return unexploded string' => array(
1243 array('my:words:here')
1245 'limit 2 should return two pieces' => array(
1249 array('my:words', 'here')
1251 'limit 3 should return unexploded string' => array(
1255 array('my', 'words', 'here')
1257 'limit 0 should return unexploded string if no delimiter is contained' => array(
1261 array('mywordshere')
1263 'limit 1 should return unexploded string if no delimiter is contained' => array(
1267 array('mywordshere')
1269 'limit 2 should return unexploded string if no delimiter is contained' => array(
1273 array('mywordshere')
1275 'limit 3 should return unexploded string if no delimiter is contained' => array(
1279 array('mywordshere')
1281 'multi character delimiter is handled properly with limit 2' => array(
1285 array('a[b][c', 'd]')
1287 'multi character delimiter is handled properly with limit 3' => array(
1291 array('a[b', 'c', 'd]')
1298 * @dataProvider revExplodeDataProvider
1300 public function revExplodeCorrectlyExplodesStringForGivenPartsCount($delimiter, $testString, $count, $expectedArray)
1302 $actualArray = GeneralUtility
::revExplode($delimiter, $testString, $count);
1303 $this->assertEquals($expectedArray, $actualArray);
1309 public function revExplodeRespectsLimitThreeWhenExploding()
1311 $testString = 'even:more:of:my:words:here';
1312 $expectedArray = array('even:more:of:my', 'words', 'here');
1313 $actualArray = GeneralUtility
::revExplode(':', $testString, 3);
1314 $this->assertEquals($expectedArray, $actualArray);
1317 //////////////////////////////////
1318 // Tests concerning trimExplode
1319 //////////////////////////////////
1322 * @dataProvider trimExplodeReturnsCorrectResultDataProvider
1324 * @param string $delimiter
1325 * @param string $testString
1326 * @param bool $removeEmpty
1328 * @param array $expectedResult
1330 public function trimExplodeReturnsCorrectResult($delimiter, $testString, $removeEmpty, $limit, $expectedResult)
1332 $this->assertSame($expectedResult, GeneralUtility
::trimExplode($delimiter, $testString, $removeEmpty, $limit));
1338 public function trimExplodeReturnsCorrectResultDataProvider()
1341 'spaces at element start and end' => [
1343 ' a , b , c ,d ,, e,f,',
1346 ['a', 'b', 'c', 'd', '', 'e', 'f', '']
1348 'removes newline' => [
1350 ' a , b , ' . LF
. ' ,d ,, e,f,',
1353 ['a', 'b', 'd', 'e', 'f']
1355 'removes empty elements' => [
1357 'a , b , c , ,d ,, ,e,f,',
1360 ['a', 'b', 'c', 'd', 'e', 'f']
1362 'keeps remaining results with empty items after reaching limit with positive parameter' => [
1364 ' a , b , c , , d,, ,e ',
1367 ['a', 'b', 'c , , d,, ,e']
1369 'keeps remaining results without empty items after reaching limit with positive parameter' => [
1371 ' a , b , c , , d,, ,e ',
1374 ['a', 'b', 'c , d,e']
1376 'keeps remaining results with empty items after reaching limit with negative parameter' => [
1378 ' a , b , c , d, ,e, f , , ',
1381 ['a', 'b', 'c', 'd', '', 'e']
1383 'keeps remaining results without empty items after reaching limit with negative parameter' => [
1385 ' a , b , c , d, ,e, f , , ',
1390 'returns exact results without reaching limit with positive parameter' => [
1392 ' a , b , , c , , , ',
1397 'keeps zero as string' => [
1399 'a , b , c , ,d ,, ,e,f, 0 ,',
1402 ['a', 'b', 'c', 'd', 'e', 'f', '0']
1404 'keeps whitespace inside elements' => [
1406 'a , b , c , ,d ,, ,e,f, g h ,',
1409 ['a', 'b', 'c', 'd', 'e', 'f', 'g h']
1411 'can use internal regex delimiter as explode delimiter' => [
1413 'a / b / c / /d // /e/f/ g h /',
1416 ['a', 'b', 'c', 'd', 'e', 'f', 'g h']
1418 'can use whitespaces as delimiter' => [
1423 ['*', '*', '*', '*', '*']
1425 'can use words as delimiter' => [
1430 ['Hello', 'Together']
1432 'can use word with appended and prepended spaces as delimiter' => [
1434 'Hello all together',
1437 ['Hello', 'together']
1439 'can use word with appended and prepended spaces as delimiter and do not remove empty' => [
1441 'Hello all together all there all all are all none',
1444 ['Hello', 'together', 'there', '', 'are', 'none']
1446 'can use word with appended and prepended spaces as delimiter, do not remove empty and limit' => [
1448 'Hello all together all there all all are all none',
1451 ['Hello', 'together', 'there', '', 'are all none']
1453 'can use word with appended and prepended spaces as delimiter, do not remove empty, limit and multiple delimiter in last' => [
1455 'Hello all together all there all all are all none',
1458 ['Hello', 'together', 'there', 'all are all none']
1460 'can use word with appended and prepended spaces as delimiter, remove empty and limit' => [
1462 'Hello all together all there all all are all none',
1465 ['Hello', 'together', 'there', 'are all none']
1467 'can use word with appended and prepended spaces as delimiter, remove empty and limit and multiple delimiter in last' => [
1469 'Hello all together all there all all are all none',
1472 ['Hello', 'together', 'there', 'are' ,'none']
1474 'can use words as delimiter and do not remove empty' => [
1476 'Helloall theretogether all there all there are all there none',
1479 ['Hello', 'together', '', 'are', 'none']
1481 'can use words as delimiter, do not remove empty and limit' => [
1483 'Helloall theretogether all there all there are all there none',
1486 ['Hello', 'together', '', 'are all there none']
1488 'can use words as delimiter, do not remove empty, limit and multiple delimiter in last' => [
1490 'Helloall theretogether all there all there are all there none',
1493 ['Hello', 'together', 'all there are all there none']
1495 'can use words as delimiter, remove empty' => [
1497 'Helloall theretogether all there all there are all there none',
1500 ['Hello', 'together', 'are', 'none']
1502 'can use words as delimiter, remove empty and limit' => [
1504 'Helloall theretogether all there all there are all there none',
1507 ['Hello', 'together', 'are all there none']
1509 'can use words as delimiter, remove empty and limit and multiple delimiter in last' => [
1511 'Helloall theretogether all there all there are all there none',
1514 ['Hello', 'together', 'are' , 'none']
1516 'can use new line as delimiter' => [
1518 "Hello\nall\ntogether",
1521 ['Hello', 'all', 'together']
1523 'works with whitespace separator' => [
1525 " a b \t c \t \t d \t e \t u j \t s",
1528 ['a b', 'c', '', 'd', 'e', 'u j', 's']
1530 'works with whitespace separator and limit' => [
1532 " a b \t c \t \t d \t e \t u j \t s",
1535 ['a b', 'c', '', "d \t e \t u j \t s"]
1537 'works with whitespace separator and remove empty' => [
1539 " a b \t c \t \t d \t e \t u j \t s",
1542 ['a b', 'c', 'd', 'e', 'u j', 's']
1544 'works with whitespace separator remove empty and limit' => [
1546 " a b \t c \t \t d \t e \t u j \t s",
1549 ['a b', 'c', "d \t e \t u j \t s"]
1554 //////////////////////////////////
1555 // Tests concerning getBytesFromSizeMeasurement
1556 //////////////////////////////////
1558 * Data provider for getBytesFromSizeMeasurement
1560 * @return array expected value, input string
1562 public function getBytesFromSizeMeasurementDataProvider()
1565 '100 kilo Bytes' => array('102400', '100k'),
1566 '100 mega Bytes' => array('104857600', '100m'),
1567 '100 giga Bytes' => array('107374182400', '100g')
1573 * @dataProvider getBytesFromSizeMeasurementDataProvider
1575 public function getBytesFromSizeMeasurementCalculatesCorrectByteValue($expected, $byteString)
1577 $this->assertEquals($expected, GeneralUtility
::getBytesFromSizeMeasurement($byteString));
1580 //////////////////////////////////
1581 // Tests concerning getIndpEnv
1582 //////////////////////////////////
1586 public function getIndpEnvTypo3SitePathReturnNonEmptyString()
1588 $this->assertTrue(strlen(GeneralUtility
::getIndpEnv('TYPO3_SITE_PATH')) >= 1);
1594 public function getIndpEnvTypo3SitePathReturnsStringStartingWithSlash()
1596 if (TYPO3_OS
=== 'WIN') {
1597 $this->markTestSkipped('Test not available on Windows OS.');
1599 $result = GeneralUtility
::getIndpEnv('TYPO3_SITE_PATH');
1600 $this->assertEquals('/', $result[0]);
1606 public function getIndpEnvTypo3SitePathReturnsStringStartingWithDrive()
1608 if (TYPO3_OS
!== 'WIN') {
1609 $this->markTestSkipped('Test available only on Windows OS.');
1611 $result = GeneralUtility
::getIndpEnv('TYPO3_SITE_PATH');
1612 $this->assertRegExp('/^[a-z]:\//i', $result);
1618 public function getIndpEnvTypo3SitePathReturnsStringEndingWithSlash()
1620 $result = GeneralUtility
::getIndpEnv('TYPO3_SITE_PATH');
1621 $this->assertEquals('/', $result[strlen($result) - 1]);
1627 public static function hostnameAndPortDataProvider()
1630 'localhost ipv4 without port' => array('127.0.0.1', '127.0.0.1', ''),
1631 'localhost ipv4 with port' => array('127.0.0.1:81', '127.0.0.1', '81'),
1632 'localhost ipv6 without port' => array('[::1]', '[::1]', ''),
1633 'localhost ipv6 with port' => array('[::1]:81', '[::1]', '81'),
1634 'ipv6 without port' => array('[2001:DB8::1]', '[2001:DB8::1]', ''),
1635 'ipv6 with port' => array('[2001:DB8::1]:81', '[2001:DB8::1]', '81'),
1636 'hostname without port' => array('lolli.did.this', 'lolli.did.this', ''),
1637 'hostname with port' => array('lolli.did.this:42', 'lolli.did.this', '42')
1643 * @dataProvider hostnameAndPortDataProvider
1645 public function getIndpEnvTypo3HostOnlyParsesHostnamesAndIpAdresses($httpHost, $expectedIp)
1647 GeneralUtility
::flushInternalRuntimeCaches();
1648 $_SERVER['HTTP_HOST'] = $httpHost;
1649 $this->assertEquals($expectedIp, GeneralUtility
::getIndpEnv('TYPO3_HOST_ONLY'));
1655 public function isAllowedHostHeaderValueReturnsFalseIfTrusedHostsIsNotConfigured()
1657 unset($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern']);
1658 $this->assertFalse(GeneralUtilityFixture
::isAllowedHostHeaderValue('evil.foo.bar'));
1664 public static function hostnamesMatchingTrustedHostsConfigurationDataProvider()
1667 'hostname without port matching' => array('lolli.did.this', '.*\.did\.this'),
1668 'other hostname without port matching' => array('helmut.did.this', '.*\.did\.this'),
1669 'two different hostnames without port matching 1st host' => array('helmut.is.secure', '(helmut\.is\.secure|lolli\.is\.secure)'),
1670 'two different hostnames without port matching 2nd host' => array('lolli.is.secure', '(helmut\.is\.secure|lolli\.is\.secure)'),
1671 'hostname with port matching' => array('lolli.did.this:42', '.*\.did\.this:42'),
1672 'hostnames are case insensitive 1' => array('lolli.DID.this:42', '.*\.did.this:42'),
1673 'hostnames are case insensitive 2' => array('lolli.did.this:42', '.*\.DID.this:42'),
1680 public static function hostnamesNotMatchingTrustedHostsConfigurationDataProvider()
1683 'hostname without port' => array('lolli.did.this', 'helmut\.did\.this'),
1684 'hostname with port, but port not allowed' => array('lolli.did.this:42', 'helmut\.did\.this'),
1685 'two different hostnames in pattern but host header starts with differnet value #1' => array('sub.helmut.is.secure', '(helmut\.is\.secure|lolli\.is\.secure)'),
1686 'two different hostnames in pattern but host header starts with differnet value #2' => array('sub.lolli.is.secure', '(helmut\.is\.secure|lolli\.is\.secure)'),
1687 'two different hostnames in pattern but host header ends with differnet value #1' => array('helmut.is.secure.tld', '(helmut\.is\.secure|lolli\.is\.secure)'),
1688 'two different hostnames in pattern but host header ends with differnet value #2' => array('lolli.is.secure.tld', '(helmut\.is\.secure|lolli\.is\.secure)'),
1693 * @param string $httpHost HTTP_HOST string
1694 * @param string $hostNamePattern trusted hosts pattern
1696 * @dataProvider hostnamesMatchingTrustedHostsConfigurationDataProvider
1698 public function isAllowedHostHeaderValueReturnsTrueIfHostValueMatches($httpHost, $hostNamePattern)
1700 $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] = $hostNamePattern;
1701 $this->assertTrue(GeneralUtilityFixture
::isAllowedHostHeaderValue($httpHost));
1705 * @param string $httpHost HTTP_HOST string
1706 * @param string $hostNamePattern trusted hosts pattern
1708 * @dataProvider hostnamesNotMatchingTrustedHostsConfigurationDataProvider
1710 public function isAllowedHostHeaderValueReturnsFalseIfHostValueMatches($httpHost, $hostNamePattern)
1712 $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] = $hostNamePattern;
1713 $this->assertFalse(GeneralUtilityFixture
::isAllowedHostHeaderValue($httpHost));
1716 public function serverNamePatternDataProvider()
1719 'host value matches server name and server port is default http' => array(
1720 'httpHost' => 'secure.web.server',
1721 'serverName' => 'secure.web.server',
1722 'isAllowed' => true
,
1723 'serverPort' => '80',
1726 'host value matches server name if compared case insensitive 1' => array(
1727 'httpHost' => 'secure.web.server',
1728 'serverName' => 'secure.WEB.server',
1729 'isAllowed' => true
,
1731 'host value matches server name if compared case insensitive 2' => array(
1732 'httpHost' => 'secure.WEB.server',
1733 'serverName' => 'secure.web.server',
1734 'isAllowed' => true
,
1736 'host value matches server name and server port is default https' => array(
1737 'httpHost' => 'secure.web.server',
1738 'serverName' => 'secure.web.server',
1739 'isAllowed' => true
,
1740 'serverPort' => '443',
1743 'host value matches server name and server port' => array(
1744 'httpHost' => 'secure.web.server:88',
1745 'serverName' => 'secure.web.server',
1746 'isAllowed' => true
,
1747 'serverPort' => '88',
1749 'host value matches server name case insensitive 1 and server port' => array(
1750 'httpHost' => 'secure.WEB.server:88',
1751 'serverName' => 'secure.web.server',
1752 'isAllowed' => true
,
1753 'serverPort' => '88',
1755 'host value matches server name case insensitive 2 and server port' => array(
1756 'httpHost' => 'secure.web.server:88',
1757 'serverName' => 'secure.WEB.server',
1758 'isAllowed' => true
,
1759 'serverPort' => '88',
1761 'host value is ipv6 but matches server name and server port' => array(
1762 'httpHost' => '[::1]:81',
1763 'serverName' => '[::1]',
1764 'isAllowed' => true
,
1765 'serverPort' => '81',
1767 'host value does not match server name' => array(
1768 'httpHost' => 'insecure.web.server',
1769 'serverName' => 'secure.web.server',
1770 'isAllowed' => false
,
1772 'host value does not match server port' => array(
1773 'httpHost' => 'secure.web.server:88',
1774 'serverName' => 'secure.web.server',
1775 'isAllowed' => false
,
1776 'serverPort' => '89',
1778 'host value has default port that does not match server port' => array(
1779 'httpHost' => 'secure.web.server',
1780 'serverName' => 'secure.web.server',
1781 'isAllowed' => false
,
1782 'serverPort' => '81',
1785 'host value has default port that does not match server ssl port' => array(
1786 'httpHost' => 'secure.web.server',
1787 'serverName' => 'secure.web.server',
1788 'isAllowed' => false
,
1789 'serverPort' => '444',
1796 * @param string $httpHost
1797 * @param string $serverName
1798 * @param bool $isAllowed
1799 * @param string $serverPort
1800 * @param string $ssl
1803 * @dataProvider serverNamePatternDataProvider
1805 public function isAllowedHostHeaderValueWorksCorrectlyWithWithServerNamePattern($httpHost, $serverName, $isAllowed, $serverPort = '80', $ssl = 'Off')
1807 $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] = GeneralUtility
::ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME
;
1808 $_SERVER['SERVER_NAME'] = $serverName;
1809 $_SERVER['SERVER_PORT'] = $serverPort;
1810 $_SERVER['HTTPS'] = $ssl;
1811 $this->assertSame($isAllowed, GeneralUtilityFixture
::isAllowedHostHeaderValue($httpHost));
1817 public function allGetIndpEnvCallsRelatedToHostNamesCallIsAllowedHostHeaderValue()
1819 GeneralUtilityFixture
::getIndpEnv('HTTP_HOST');
1820 GeneralUtility
::flushInternalRuntimeCaches();
1821 GeneralUtilityFixture
::getIndpEnv('TYPO3_HOST_ONLY');
1822 GeneralUtility
::flushInternalRuntimeCaches();
1823 GeneralUtilityFixture
::getIndpEnv('TYPO3_REQUEST_HOST');
1824 GeneralUtility
::flushInternalRuntimeCaches();
1825 GeneralUtilityFixture
::getIndpEnv('TYPO3_REQUEST_URL');
1826 $this->assertSame(4, GeneralUtilityFixture
::$isAllowedHostHeaderValueCallCount);
1830 * @param string $httpHost HTTP_HOST string
1831 * @param string $hostNamePattern trusted hosts pattern
1833 * @dataProvider hostnamesNotMatchingTrustedHostsConfigurationDataProvider
1834 * @expectedException \UnexpectedValueException
1835 * @expectedExceptionCode 1396795884
1837 public function getIndpEnvForHostThrowsExceptionForNotAllowedHostnameValues($httpHost, $hostNamePattern)
1839 $_SERVER['HTTP_HOST'] = $httpHost;
1840 $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] = $hostNamePattern;
1841 GeneralUtilityFixture
::getIndpEnv('HTTP_HOST');
1845 * @param string $httpHost HTTP_HOST string
1846 * @param string $hostNamePattern trusted hosts pattern (not used in this test currently)
1848 * @dataProvider hostnamesNotMatchingTrustedHostsConfigurationDataProvider
1850 public function getIndpEnvForHostAllowsAllHostnameValuesIfHostPatternIsSetToAllowAll($httpHost, $hostNamePattern)
1852 $_SERVER['HTTP_HOST'] = $httpHost;
1853 $GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] = GeneralUtility
::ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL
;
1854 $this->assertSame($httpHost, GeneralUtility
::getIndpEnv('HTTP_HOST'));
1859 * @dataProvider hostnameAndPortDataProvider
1861 public function getIndpEnvTypo3PortParsesHostnamesAndIpAdresses($httpHost, $dummy, $expectedPort)
1863 $_SERVER['HTTP_HOST'] = $httpHost;
1864 $this->assertEquals($expectedPort, GeneralUtility
::getIndpEnv('TYPO3_PORT'));
1867 //////////////////////////////////
1868 // Tests concerning underscoredToUpperCamelCase
1869 //////////////////////////////////
1871 * Data provider for underscoredToUpperCamelCase
1873 * @return array expected, input string
1875 public function underscoredToUpperCamelCaseDataProvider()
1878 'single word' => array('Blogexample', 'blogexample'),
1879 'multiple words' => array('BlogExample', 'blog_example')
1885 * @dataProvider underscoredToUpperCamelCaseDataProvider
1887 public function underscoredToUpperCamelCase($expected, $inputString)
1889 $this->assertEquals($expected, GeneralUtility
::underscoredToUpperCamelCase($inputString));
1892 //////////////////////////////////
1893 // Tests concerning underscoredToLowerCamelCase
1894 //////////////////////////////////
1896 * Data provider for underscoredToLowerCamelCase
1898 * @return array expected, input string
1900 public function underscoredToLowerCamelCaseDataProvider()
1903 'single word' => array('minimalvalue', 'minimalvalue'),
1904 'multiple words' => array('minimalValue', 'minimal_value')
1910 * @dataProvider underscoredToLowerCamelCaseDataProvider
1912 public function underscoredToLowerCamelCase($expected, $inputString)
1914 $this->assertEquals($expected, GeneralUtility
::underscoredToLowerCamelCase($inputString));
1917 //////////////////////////////////
1918 // Tests concerning camelCaseToLowerCaseUnderscored
1919 //////////////////////////////////
1921 * Data provider for camelCaseToLowerCaseUnderscored
1923 * @return array expected, input string
1925 public function camelCaseToLowerCaseUnderscoredDataProvider()
1928 'single word' => array('blogexample', 'blogexample'),
1929 'single word starting upper case' => array('blogexample', 'Blogexample'),
1930 'two words starting lower case' => array('minimal_value', 'minimalValue'),
1931 'two words starting upper case' => array('blog_example', 'BlogExample')
1937 * @dataProvider camelCaseToLowerCaseUnderscoredDataProvider
1939 public function camelCaseToLowerCaseUnderscored($expected, $inputString)
1941 $this->assertEquals($expected, GeneralUtility
::camelCaseToLowerCaseUnderscored($inputString));
1944 //////////////////////////////////
1945 // Tests concerning lcFirst
1946 //////////////////////////////////
1948 * Data provider for lcFirst
1950 * @return array expected, input string
1952 public function lcfirstDataProvider()
1955 'single word' => array('blogexample', 'blogexample'),
1956 'single Word starting upper case' => array('blogexample', 'Blogexample'),
1957 'two words' => array('blogExample', 'BlogExample')
1963 * @dataProvider lcfirstDataProvider
1965 public function lcFirst($expected, $inputString)
1967 $this->assertEquals($expected, GeneralUtility
::lcfirst($inputString));
1970 //////////////////////////////////
1971 // Tests concerning encodeHeader
1972 //////////////////////////////////
1976 public function encodeHeaderEncodesWhitespacesInQuotedPrintableMailHeader()
1978 $this->assertEquals('=?utf-8?Q?We_test_whether_the_copyright_character_=C2=A9_is_encoded_correctly?=', GeneralUtility
::encodeHeader('We test whether the copyright character © is encoded correctly', 'quoted-printable', 'utf-8'));
1984 public function encodeHeaderEncodesQuestionmarksInQuotedPrintableMailHeader()
1986 $this->assertEquals('=?utf-8?Q?Is_the_copyright_character_=C2=A9_really_encoded_correctly=3F_Really=3F?=', GeneralUtility
::encodeHeader('Is the copyright character © really encoded correctly? Really?', 'quoted-printable', 'utf-8'));
1989 //////////////////////////////////
1990 // Tests concerning isValidUrl
1991 //////////////////////////////////
1993 * Data provider for valid isValidUrl's
1995 * @return array Valid resource
1997 public function validUrlValidResourceDataProvider()
2000 'http' => array('http://www.example.org/'),
2001 'http without trailing slash' => array('http://qwe'),
2002 'http directory with trailing slash' => array('http://www.example/img/dir/'),
2003 'http directory without trailing slash' => array('http://www.example/img/dir'),
2004 'http index.html' => array('http://example.com/index.html'),
2005 'http index.php' => array('http://www.example.com/index.php'),
2006 'http test.png' => array('http://www.example/img/test.png'),
2007 'http username password querystring and ancher' => array('https://user:pw@www.example.org:80/path?arg=value#fragment'),
2008 'file' => array('file:///tmp/test.c'),
2009 'file directory' => array('file://foo/bar'),
2010 'ftp directory' => array('ftp://ftp.example.com/tmp/'),
2011 'mailto' => array('mailto:foo@bar.com'),
2012 'news' => array('news:news.php.net'),
2013 'telnet' => array('telnet://192.0.2.16:80/'),
2014 'ldap' => array('ldap://[2001:db8::7]/c=GB?objectClass?one'),
2015 'http punycode domain name' => array('http://www.xn--bb-eka.at'),
2016 'http punicode subdomain' => array('http://xn--h-zfa.oebb.at'),
2017 'http domain-name umlauts' => array('http://www.öbb.at'),
2018 'http subdomain umlauts' => array('http://äh.oebb.at'),
2024 * @dataProvider validUrlValidResourceDataProvider
2026 public function validURLReturnsTrueForValidResource($url)
2028 $this->assertTrue(GeneralUtility
::isValidUrl($url));
2032 * Data provider for invalid isValidUrl's
2034 * @return array Invalid ressource
2036 public function isValidUrlInvalidRessourceDataProvider()
2039 'http missing colon' => array('http//www.example/wrong/url/'),
2040 'http missing slash' => array('http:/www.example'),
2041 'hostname only' => array('www.example.org/'),
2042 'file missing protocol specification' => array('/tmp/test.c'),
2043 'slash only' => array('/'),
2044 'string http://' => array('http://'),
2045 'string http:/' => array('http:/'),
2046 'string http:' => array('http:'),
2047 'string http' => array('http'),
2048 'empty string' => array(''),
2049 'string -1' => array('-1'),
2050 'string array()' => array('array()'),
2051 'random string' => array('qwe'),
2052 'http directory umlauts' => array('http://www.oebb.at/äöü/'),
2058 * @dataProvider isValidUrlInvalidRessourceDataProvider
2060 public function validURLReturnsFalseForInvalidRessoure($url)
2062 $this->assertFalse(GeneralUtility
::isValidUrl($url));
2065 //////////////////////////////////
2066 // Tests concerning isOnCurrentHost
2067 //////////////////////////////////
2071 public function isOnCurrentHostReturnsTrueWithCurrentHost()
2073 $testUrl = GeneralUtility
::getIndpEnv('TYPO3_REQUEST_URL');
2074 $this->assertTrue(GeneralUtility
::isOnCurrentHost($testUrl));
2078 * Data provider for invalid isOnCurrentHost's
2080 * @return array Invalid Hosts
2082 public function checkisOnCurrentHostInvalidHosts()
2085 'empty string' => array(''),
2086 'arbitrary string' => array('arbitrary string'),
2087 'localhost IP' => array('127.0.0.1'),
2088 'relative path' => array('./relpath/file.txt'),
2089 'absolute path' => array('/abspath/file.txt?arg=value'),
2090 'differnt host' => array(GeneralUtility
::getIndpEnv('TYPO3_REQUEST_HOST') . '.example.org')
2094 ////////////////////////////////////////
2095 // Tests concerning sanitizeLocalUrl
2096 ////////////////////////////////////////
2098 * Data provider for valid sanitizeLocalUrl paths
2100 * @return array Valid url
2102 public function sanitizeLocalUrlValidPathsDataProvider()
2105 'alt_intro.php' => array('alt_intro.php'),
2106 'alt_intro.php?foo=1&bar=2' => array('alt_intro.php?foo=1&bar=2'),
2107 '../index.php' => array('../index.php'),
2108 '../typo3/alt_intro.php' => array('../typo3/alt_intro.php'),
2109 '../~userDirectory/index.php' => array('../~userDirectory/index.php'),
2110 '../typo3/index.php?var1=test-case&var2=~user' => array('../typo3/index.php?var1=test-case&var2=~user'),
2111 PATH_site
. 'typo3/alt_intro.php' => array(PATH_site
. 'typo3/alt_intro.php'),
2117 * @param string $path
2118 * @dataProvider sanitizeLocalUrlValidPathsDataProvider
2120 public function sanitizeLocalUrlAcceptsNotEncodedValidPaths($path)
2122 $this->assertEquals($path, GeneralUtility
::sanitizeLocalUrl($path));
2127 * @param string $path
2128 * @dataProvider sanitizeLocalUrlValidPathsDataProvider
2130 public function sanitizeLocalUrlAcceptsEncodedValidPaths($path)
2132 $this->assertEquals(rawurlencode($path), GeneralUtility
::sanitizeLocalUrl(rawurlencode($path)));
2136 * Data provider for valid sanitizeLocalUrl's
2138 * @return array Valid url
2140 public function sanitizeLocalUrlValidUrlsDataProvider()
2142 $host = 'localhost';
2143 $subDirectory = '/cms/';
2146 $subDirectory . 'typo3/alt_intro.php' => array(
2147 $subDirectory . 'typo3/alt_intro.php',
2151 $subDirectory . 'index.php' => array(
2152 $subDirectory . 'index.php',
2156 'http://' . $host . '/typo3/alt_intro.php' => array(
2157 'http://' . $host . '/typo3/alt_intro.php',
2161 'http://' . $host . $subDirectory . 'typo3/alt_intro.php' => array(
2162 'http://' . $host . $subDirectory . 'typo3/alt_intro.php',
2171 * @param string $url
2172 * @param string $host
2173 * @param string $subDirectory
2174 * @dataProvider sanitizeLocalUrlValidUrlsDataProvider
2176 public function sanitizeLocalUrlAcceptsNotEncodedValidUrls($url, $host, $subDirectory)
2178 $_SERVER['HTTP_HOST'] = $host;
2179 $_SERVER['SCRIPT_NAME'] = $subDirectory . 'typo3/index.php';
2180 GeneralUtility
::flushInternalRuntimeCaches();
2181 $this->assertEquals($url, GeneralUtility
::sanitizeLocalUrl($url));
2186 * @param string $url
2187 * @param string $host
2188 * @param string $subDirectory
2189 * @dataProvider sanitizeLocalUrlValidUrlsDataProvider
2191 public function sanitizeLocalUrlAcceptsEncodedValidUrls($url, $host, $subDirectory)
2193 $_SERVER['HTTP_HOST'] = $host;
2194 $_SERVER['SCRIPT_NAME'] = $subDirectory . 'typo3/index.php';
2195 GeneralUtility
::flushInternalRuntimeCaches();
2196 $this->assertEquals(rawurlencode($url), GeneralUtility
::sanitizeLocalUrl(rawurlencode($url)));
2200 * Data provider for invalid sanitizeLocalUrl's
2202 * @return array Valid url
2204 public function sanitizeLocalUrlInvalidDataProvider()
2207 'empty string' => array(''),
2208 'http domain' => array('http://www.google.de/'),
2209 'https domain' => array('https://www.google.de/'),
2210 'relative path with XSS' => array('../typo3/whatever.php?argument=javascript:alert(0)'),
2211 'base64 encoded string' => array('data:%20text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4='),
2217 * @dataProvider sanitizeLocalUrlInvalidDataProvider
2219 public function sanitizeLocalUrlDeniesPlainInvalidUrls($url)
2221 $this->assertEquals('', GeneralUtility
::sanitizeLocalUrl($url));
2226 * @dataProvider sanitizeLocalUrlInvalidDataProvider
2228 public function sanitizeLocalUrlDeniesEncodedInvalidUrls($url)
2230 $this->assertEquals('', GeneralUtility
::sanitizeLocalUrl(rawurlencode($url)));
2233 ////////////////////////////////////////
2234 // Tests concerning unlink_tempfile
2235 ////////////////////////////////////////
2240 public function unlink_tempfileRemovesValidFileInTypo3temp()
2242 $fixtureFile = __DIR__
. '/Fixtures/clear.gif';
2243 $testFilename = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_') . '.gif';
2244 @copy
($fixtureFile, $testFilename);
2245 GeneralUtility
::unlink_tempfile($testFilename);
2246 $fileExists = file_exists($testFilename);
2247 $this->assertFalse($fileExists);
2253 public function unlink_tempfileRemovesHiddenFile()
2255 $fixtureFile = __DIR__
. '/Fixtures/clear.gif';
2256 $testFilename = PATH_site
. 'typo3temp/' . $this->getUniqueId('.test_') . '.gif';
2257 @copy
($fixtureFile, $testFilename);
2258 GeneralUtility
::unlink_tempfile($testFilename);
2259 $fileExists = file_exists($testFilename);
2260 $this->assertFalse($fileExists);
2266 public function unlink_tempfileReturnsTrueIfFileWasRemoved()
2268 $fixtureFile = __DIR__
. '/Fixtures/clear.gif';
2269 $testFilename = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_') . '.gif';
2270 @copy
($fixtureFile, $testFilename);
2271 $returnValue = GeneralUtility
::unlink_tempfile($testFilename);
2272 $this->assertTrue($returnValue);
2278 public function unlink_tempfileReturnsNullIfFileDoesNotExist()
2280 $returnValue = GeneralUtility
::unlink_tempfile(PATH_site
. 'typo3temp/' . $this->getUniqueId('i_do_not_exist'));
2281 $this->assertNull($returnValue);
2287 public function unlink_tempfileReturnsNullIfFileIsNowWithinTypo3temp()
2289 $returnValue = GeneralUtility
::unlink_tempfile('/tmp/typo3-unit-test-unlink_tempfile');
2290 $this->assertNull($returnValue);
2293 //////////////////////////////////////
2294 // Tests concerning tempnam
2295 //////////////////////////////////////
2300 public function tempnamReturnsPathStartingWithGivenPrefix()
2302 $filePath = GeneralUtility
::tempnam('foo');
2303 $fileName = basename($filePath);
2304 $this->assertStringStartsWith('foo', $fileName);
2310 public function tempnamReturnsPathWithoutBackslashes()
2312 $filePath = GeneralUtility
::tempnam('foo');
2313 $this->assertNotContains('\\', $filePath);
2319 public function tempnamReturnsAbsolutePathInsideDocumentRoot()
2321 $filePath = GeneralUtility
::tempnam('foo');
2322 $this->assertStringStartsWith(PATH_site
, $filePath);
2325 //////////////////////////////////////
2326 // Tests concerning addSlashesOnArray
2327 //////////////////////////////////////
2331 public function addSlashesOnArrayAddsSlashesRecursive()
2333 $inputArray = array(
2335 'key11' => 'val\'ue1',
2336 'key12' => 'val"ue2'
2338 'key2' => 'val\\ue3'
2340 $expectedResult = array(
2342 'key11' => 'val\\\'ue1',
2343 'key12' => 'val\\"ue2'
2345 'key2' => 'val\\\\ue3'
2347 GeneralUtility
::addSlashesOnArray($inputArray);
2348 $this->assertEquals($expectedResult, $inputArray);
2351 //////////////////////////////////////
2352 // Tests concerning addSlashesOnArray
2353 //////////////////////////////////////
2357 public function stripSlashesOnArrayStripsSlashesRecursive()
2359 $inputArray = array(
2361 'key11' => 'val\\\'ue1',
2362 'key12' => 'val\\"ue2'
2364 'key2' => 'val\\\\ue3'
2366 $expectedResult = array(
2368 'key11' => 'val\'ue1',
2369 'key12' => 'val"ue2'
2371 'key2' => 'val\\ue3'
2373 GeneralUtility
::stripSlashesOnArray($inputArray);
2374 $this->assertEquals($expectedResult, $inputArray);
2377 //////////////////////////////////////
2378 // Tests concerning removeDotsFromTS
2379 //////////////////////////////////////
2383 public function removeDotsFromTypoScriptSucceedsWithDottedArray()
2385 $typoScript = array(
2386 'propertyA.' => array(
2394 $expectedResult = array(
2395 'propertyA' => array(
2403 $this->assertEquals($expectedResult, GeneralUtility
::removeDotsFromTS($typoScript));
2409 public function removeDotsFromTypoScriptOverridesSubArray()
2411 $typoScript = array(
2412 'propertyA.' => array(
2413 'keyA' => 'getsOverridden',
2421 $expectedResult = array(
2422 'propertyA' => array(
2430 $this->assertEquals($expectedResult, GeneralUtility
::removeDotsFromTS($typoScript));
2436 public function removeDotsFromTypoScriptOverridesWithScalar()
2438 $typoScript = array(
2439 'propertyA.' => array(
2443 'keyA' => 'willOverride',
2448 $expectedResult = array(
2449 'propertyA' => array(
2450 'keyA' => 'willOverride',
2455 $this->assertEquals($expectedResult, GeneralUtility
::removeDotsFromTS($typoScript));
2458 //////////////////////////////////////
2459 // Tests concerning get_dirs
2460 //////////////////////////////////////
2464 public function getDirsReturnsArrayOfDirectoriesFromGivenDirectory()
2466 $path = PATH_typo3conf
;
2467 $directories = GeneralUtility
::get_dirs($path);
2468 $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType
::TYPE_ARRAY
, $directories);
2474 public function getDirsReturnsStringErrorOnPathFailure()
2477 $result = GeneralUtility
::get_dirs($path);
2478 $expectedResult = 'error';
2479 $this->assertEquals($expectedResult, $result);
2482 //////////////////////////////////
2483 // Tests concerning hmac
2484 //////////////////////////////////
2488 public function hmacReturnsHashOfProperLength()
2490 $hmac = GeneralUtility
::hmac('message');
2491 $this->assertTrue(!empty($hmac) && is_string($hmac));
2492 $this->assertTrue(strlen($hmac) == 40);
2498 public function hmacReturnsEqualHashesForEqualInput()
2502 $this->assertEquals(GeneralUtility
::hmac($msg0), GeneralUtility
::hmac($msg1));
2508 public function hmacReturnsNoEqualHashesForNonEqualInput()
2512 $this->assertNotEquals(GeneralUtility
::hmac($msg0), GeneralUtility
::hmac($msg1));
2515 //////////////////////////////////
2516 // Tests concerning quoteJSvalue
2517 //////////////////////////////////
2519 * Data provider for quoteJSvalueTest.
2523 public function quoteJsValueDataProvider()
2526 'Immune characters are returned as is' => array(
2530 'Alphanumerical characters are returned as is' => array(
2531 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
2532 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
2534 'Angle brackets and ampersand are encoded' => array(
2536 '\\u003C\\u003E\\u0026'
2538 'Quotes and backslashes are encoded' => array(
2540 '\\u0022\\u0027\\u005C'
2542 'Forward slashes are escaped' => array(
2544 '\\u003C\\/script\\u003E'
2546 'Empty string stays empty' => array(
2550 'Exclamation mark and space are properly encoded' => array(
2552 'Hello\\u0020World\\u0021'
2554 'Whitespaces are properly encoded' => array(
2555 TAB
. LF
. CR
. ' ',
2556 '\\u0009\\u000A\\u000D\\u0020'
2558 'Null byte is properly encoded' => array(
2562 'Umlauts are properly encoded' => array(
2564 '\\u00dc\\u00fc\\u00d6\\u00f6\\u00c4\\u00e4'
2571 * @param string $input
2572 * @param string $expected
2573 * @dataProvider quoteJsValueDataProvider
2575 public function quoteJsValueTest($input, $expected)
2577 $this->assertSame('\'' . $expected . '\'', GeneralUtility
::quoteJSvalue($input));
2580 ///////////////////////////////
2581 // Tests concerning _GETset()
2582 ///////////////////////////////
2586 public function getSetWritesArrayToGetSystemVariable()
2589 $GLOBALS['HTTP_GET_VARS'] = array();
2590 $getParameters = array('foo' => 'bar');
2591 GeneralUtility
::_GETset($getParameters);
2592 $this->assertSame($getParameters, $_GET);
2598 public function getSetWritesArrayToGlobalsHttpGetVars()
2601 $GLOBALS['HTTP_GET_VARS'] = array();
2602 $getParameters = array('foo' => 'bar');
2603 GeneralUtility
::_GETset($getParameters);
2604 $this->assertSame($getParameters, $GLOBALS['HTTP_GET_VARS']);
2610 public function getSetForArrayDropsExistingValues()
2613 $GLOBALS['HTTP_GET_VARS'] = array();
2614 GeneralUtility
::_GETset(array('foo' => 'bar'));
2615 GeneralUtility
::_GETset(array('oneKey' => 'oneValue'));
2616 $this->assertEquals(array('oneKey' => 'oneValue'), $GLOBALS['HTTP_GET_VARS']);
2622 public function getSetAssignsOneValueToOneKey()
2625 $GLOBALS['HTTP_GET_VARS'] = array();
2626 GeneralUtility
::_GETset('oneValue', 'oneKey');
2627 $this->assertEquals('oneValue', $GLOBALS['HTTP_GET_VARS']['oneKey']);
2633 public function getSetForOneValueDoesNotDropUnrelatedValues()
2636 $GLOBALS['HTTP_GET_VARS'] = array();
2637 GeneralUtility
::_GETset(array('foo' => 'bar'));
2638 GeneralUtility
::_GETset('oneValue', 'oneKey');
2639 $this->assertEquals(array('foo' => 'bar', 'oneKey' => 'oneValue'), $GLOBALS['HTTP_GET_VARS']);
2645 public function getSetCanAssignsAnArrayToASpecificArrayElement()
2648 $GLOBALS['HTTP_GET_VARS'] = array();
2649 GeneralUtility
::_GETset(array('childKey' => 'oneValue'), 'parentKey');
2650 $this->assertEquals(array('parentKey' => array('childKey' => 'oneValue')), $GLOBALS['HTTP_GET_VARS']);
2656 public function getSetCanAssignAStringValueToASpecificArrayChildElement()
2659 $GLOBALS['HTTP_GET_VARS'] = array();
2660 GeneralUtility
::_GETset('oneValue', 'parentKey|childKey');
2661 $this->assertEquals(array('parentKey' => array('childKey' => 'oneValue')), $GLOBALS['HTTP_GET_VARS']);
2667 public function getSetCanAssignAnArrayToASpecificArrayChildElement()
2670 $GLOBALS['HTTP_GET_VARS'] = array();
2671 GeneralUtility
::_GETset(array('key1' => 'value1', 'key2' => 'value2'), 'parentKey|childKey');
2672 $this->assertEquals(array(
2673 'parentKey' => array(
2674 'childKey' => array('key1' => 'value1', 'key2' => 'value2')
2676 ), $GLOBALS['HTTP_GET_VARS']);
2679 ///////////////////////////
2680 // Tests concerning minifyJavaScript
2681 ///////////////////////////
2685 public function minifyJavaScriptReturnsInputStringIfNoHookIsRegistered()
2687 unset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript']);
2688 $testString = $this->getUniqueId('string');
2689 $this->assertSame($testString, GeneralUtility
::minifyJavaScript($testString));
2693 * Create an own hook callback class, register as hook, and check
2694 * if given string to compress is given to hook method
2698 public function minifyJavaScriptCallsRegisteredHookWithInputString()
2700 $hookClassName = $this->getUniqueId('tx_coretest');
2701 $minifyHookMock = $this->getMock('stdClass', array('minify'), array(), $hookClassName);
2702 $functionName = $hookClassName . '->minify';
2703 $GLOBALS['T3_VAR']['callUserFunction'][$functionName] = array();
2704 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['obj'] = $minifyHookMock;
2705 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['method'] = 'minify';
2706 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'][] = $functionName;
2707 $minifyHookMock->expects($this->once())->method('minify')->will($this->returnCallback(array($this, 'isMinifyJavaScriptHookCalledCallback')));
2708 GeneralUtility
::minifyJavaScript('foo');
2712 * Callback function used in minifyJavaScriptCallsRegisteredHookWithInputString test
2714 * @param array $params
2716 public function isMinifyJavaScriptHookCalledCallback(array $params)
2718 // We can not throw an exception here, because that would be caught by the
2719 // minifyJavaScript method under test itself. Thus, we just die if the
2720 // input string is not ok.
2721 if ($params['script'] !== 'foo') {
2727 * Create a hook callback, use callback to throw an exception and check
2728 * if the exception is given as error parameter to the calling method.
2732 public function minifyJavaScriptReturnsErrorStringOfHookException()
2734 $hookClassName = $this->getUniqueId('tx_coretest');
2735 $minifyHookMock = $this->getMock('stdClass', array('minify'), array(), $hookClassName);
2736 $functionName = '&' . $hookClassName . '->minify';
2737 $GLOBALS['T3_VAR']['callUserFunction'][$functionName] = array();
2738 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['obj'] = $minifyHookMock;
2739 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['method'] = 'minify';
2740 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'][] = $functionName;
2741 $minifyHookMock->expects($this->any())->method('minify')->will($this->returnCallback(array($this, 'minifyJavaScriptErroneousCallback')));
2743 GeneralUtility
::minifyJavaScript('string to compress', $error);
2744 $this->assertSame('Error minifying java script: foo', $error);
2748 * Check if the error message that is returned by the hook callback
2749 * is logged to \TYPO3\CMS\Core\GeneralUtility::devLog.
2753 public function minifyJavaScriptWritesExceptionMessageToDevLog()
2755 $hookClassName = $this->getUniqueId('tx_coretest');
2756 $minifyHookMock = $this->getMock('stdClass', array('minify'), array(), $hookClassName);
2757 $functionName = '&' . $hookClassName . '->minify';
2758 $GLOBALS['T3_VAR']['callUserFunction'][$functionName] = array();
2759 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['obj'] = $minifyHookMock;
2760 $GLOBALS['T3_VAR']['callUserFunction'][$functionName]['method'] = 'minify';
2761 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'][] = $functionName;
2762 $minifyHookMock->expects($this->any())->method('minify')->will($this->returnCallback(array($this, 'minifyJavaScriptErroneousCallback')));
2763 $this->setExpectedException('\\RuntimeException');
2764 GeneralUtilityMinifyJavaScriptFixture
::minifyJavaScript('string to compress');
2768 * Callback function used in
2769 * minifyJavaScriptReturnsErrorStringOfHookException and
2770 * minifyJavaScriptWritesExceptionMessageToDevLog
2772 * @throws \RuntimeException
2774 public function minifyJavaScriptErroneousCallback()
2776 throw new \
RuntimeException('foo', 1344888548);
2779 ///////////////////////////////
2780 // Tests concerning fixPermissions
2781 ///////////////////////////////
2785 public function fixPermissionsSetsGroup()
2787 if (TYPO3_OS
=== 'WIN') {
2788 $this->markTestSkipped('fixPermissionsSetsGroup() tests not available on Windows');
2790 if (!function_exists('posix_getegid')) {
2791 $this->markTestSkipped('Function posix_getegid() not available, fixPermissionsSetsGroup() tests skipped');
2793 if (posix_getegid() === -1) {
2794 $this->markTestSkipped('The fixPermissionsSetsGroup() is not available on Mac OS because posix_getegid() always returns -1 on Mac OS.');
2796 // Create and prepare test file
2797 $filename = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_');
2798 GeneralUtility
::writeFileToTypo3tempDir($filename, '42');
2799 $this->testFilesToDelete
[] = $filename;
2800 $currentGroupId = posix_getegid();
2801 // Set target group and run method
2802 $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'] = $currentGroupId;
2803 GeneralUtility
::fixPermissions($filename);
2805 $this->assertEquals($currentGroupId, filegroup($filename));
2811 public function fixPermissionsSetsPermissionsToFile()
2813 if (TYPO3_OS
== 'WIN') {
2814 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2816 // Create and prepare test file
2817 $filename = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_');
2818 GeneralUtility
::writeFileToTypo3tempDir($filename, '42');
2819 $this->testFilesToDelete
[] = $filename;
2820 chmod($filename, 482);
2821 // Set target permissions and run method
2822 $GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'] = '0660';
2823 $fixPermissionsResult = GeneralUtility
::fixPermissions($filename);
2825 $this->assertTrue($fixPermissionsResult);
2826 $this->assertEquals('0660', substr(decoct(fileperms($filename)), 2));
2832 public function fixPermissionsSetsPermissionsToHiddenFile()
2834 if (TYPO3_OS
== 'WIN') {
2835 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2837 // Create and prepare test file
2838 $filename = PATH_site
. 'typo3temp/' . $this->getUniqueId('.test_');
2839 GeneralUtility
::writeFileToTypo3tempDir($filename, '42');
2840 $this->testFilesToDelete
[] = $filename;
2841 chmod($filename, 482);
2842 // Set target permissions and run method
2843 $GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'] = '0660';
2844 $fixPermissionsResult = GeneralUtility
::fixPermissions($filename);
2846 $this->assertTrue($fixPermissionsResult);
2847 $this->assertEquals('0660', substr(decoct(fileperms($filename)), 2));
2853 public function fixPermissionsSetsPermissionsToDirectory()
2855 if (TYPO3_OS
== 'WIN') {
2856 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2858 // Create and prepare test directory
2859 $directory = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_');
2860 GeneralUtility
::mkdir($directory);
2861 $this->testFilesToDelete
[] = $directory;
2862 chmod($directory, 1551);
2863 // Set target permissions and run method
2864 $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] = '0770';
2865 $fixPermissionsResult = GeneralUtility
::fixPermissions($directory);
2867 $this->assertTrue($fixPermissionsResult);
2868 $this->assertEquals('0770', substr(decoct(fileperms($directory)), 1));
2874 public function fixPermissionsSetsPermissionsToDirectoryWithTrailingSlash()
2876 if (TYPO3_OS
== 'WIN') {
2877 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2879 // Create and prepare test directory
2880 $directory = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_');
2881 GeneralUtility
::mkdir($directory);
2882 $this->testFilesToDelete
[] = $directory;
2883 chmod($directory, 1551);
2884 // Set target permissions and run method
2885 $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] = '0770';
2886 $fixPermissionsResult = GeneralUtility
::fixPermissions($directory . '/');
2887 // Get actual permissions and clean up
2889 $this->assertTrue($fixPermissionsResult);
2890 $this->assertEquals('0770', substr(decoct(fileperms($directory)), 1));
2896 public function fixPermissionsSetsPermissionsToHiddenDirectory()
2898 if (TYPO3_OS
== 'WIN') {
2899 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2901 // Create and prepare test directory
2902 $directory = PATH_site
. 'typo3temp/' . $this->getUniqueId('.test_');
2903 GeneralUtility
::mkdir($directory);
2904 $this->testFilesToDelete
[] = $directory;
2905 chmod($directory, 1551);
2906 // Set target permissions and run method
2907 $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] = '0770';
2908 $fixPermissionsResult = GeneralUtility
::fixPermissions($directory);
2909 // Get actual permissions and clean up
2911 $this->assertTrue($fixPermissionsResult);
2912 $this->assertEquals('0770', substr(decoct(fileperms($directory)), 1));
2918 public function fixPermissionsCorrectlySetsPermissionsRecursive()
2920 if (TYPO3_OS
== 'WIN') {
2921 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2923 // Create and prepare test directory and file structure
2924 $baseDirectory = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_');
2925 GeneralUtility
::mkdir($baseDirectory);
2926 $this->testFilesToDelete
[] = $baseDirectory;
2927 chmod($baseDirectory, 1751);
2928 GeneralUtility
::writeFileToTypo3tempDir($baseDirectory . '/file', '42');
2929 chmod($baseDirectory . '/file', 482);
2930 GeneralUtility
::mkdir($baseDirectory . '/foo');
2931 chmod($baseDirectory . '/foo', 1751);
2932 GeneralUtility
::writeFileToTypo3tempDir($baseDirectory . '/foo/file', '42');
2933 chmod($baseDirectory . '/foo/file', 482);
2934 GeneralUtility
::mkdir($baseDirectory . '/.bar');
2935 chmod($baseDirectory . '/.bar', 1751);
2936 // Use this if writeFileToTypo3tempDir is fixed to create hidden files in subdirectories
2937 // \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($baseDirectory . '/.bar/.file', '42');
2938 // \TYPO3\CMS\Core\Utility\GeneralUtility::writeFileToTypo3tempDir($baseDirectory . '/.bar/..file2', '42');
2939 touch($baseDirectory . '/.bar/.file', '42');
2940 chmod($baseDirectory . '/.bar/.file', 482);
2941 touch($baseDirectory . '/.bar/..file2', '42');
2942 chmod($baseDirectory . '/.bar/..file2', 482);
2943 // Set target permissions and run method
2944 $GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'] = '0660';
2945 $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] = '0770';
2946 $fixPermissionsResult = GeneralUtility
::fixPermissions($baseDirectory, true
);
2947 // Get actual permissions
2949 $resultBaseDirectoryPermissions = substr(decoct(fileperms($baseDirectory)), 1);
2950 $resultBaseFilePermissions = substr(decoct(fileperms($baseDirectory . '/file')), 2);
2951 $resultFooDirectoryPermissions = substr(decoct(fileperms($baseDirectory . '/foo')), 1);
2952 $resultFooFilePermissions = substr(decoct(fileperms($baseDirectory . '/foo/file')), 2);
2953 $resultBarDirectoryPermissions = substr(decoct(fileperms($baseDirectory . '/.bar')), 1);
2954 $resultBarFilePermissions = substr(decoct(fileperms($baseDirectory . '/.bar/.file')), 2);
2955 $resultBarFile2Permissions = substr(decoct(fileperms($baseDirectory . '/.bar/..file2')), 2);
2956 // Test if everything was ok
2957 $this->assertTrue($fixPermissionsResult);
2958 $this->assertEquals('0770', $resultBaseDirectoryPermissions);
2959 $this->assertEquals('0660', $resultBaseFilePermissions);
2960 $this->assertEquals('0770', $resultFooDirectoryPermissions);
2961 $this->assertEquals('0660', $resultFooFilePermissions);
2962 $this->assertEquals('0770', $resultBarDirectoryPermissions);
2963 $this->assertEquals('0660', $resultBarFilePermissions);
2964 $this->assertEquals('0660', $resultBarFile2Permissions);
2970 public function fixPermissionsDoesNotSetPermissionsToNotAllowedPath()
2972 if (TYPO3_OS
== 'WIN') {
2973 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2975 // Create and prepare test file
2976 $filename = PATH_site
. 'typo3temp/../typo3temp/' . $this->getUniqueId('test_');
2978 chmod($filename, 482);
2979 // Set target permissions and run method
2980 $GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'] = '0660';
2981 $fixPermissionsResult = GeneralUtility
::fixPermissions($filename);
2983 $this->testFilesToDelete
[] = $filename;
2984 $this->assertFalse($fixPermissionsResult);
2990 public function fixPermissionsSetsPermissionsWithRelativeFileReference()
2992 if (TYPO3_OS
== 'WIN') {
2993 $this->markTestSkipped('fixPermissions() tests not available on Windows');
2995 $filename = 'typo3temp/' . $this->getUniqueId('test_');
2996 GeneralUtility
::writeFileToTypo3tempDir(PATH_site
. $filename, '42');
2997 $this->testFilesToDelete
[] = PATH_site
. $filename;
2998 chmod(PATH_site
. $filename, 482);
2999 // Set target permissions and run method
3000 $GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'] = '0660';
3001 $fixPermissionsResult = GeneralUtility
::fixPermissions($filename);
3003 $this->assertTrue($fixPermissionsResult);
3004 $this->assertEquals('0660', substr(decoct(fileperms(PATH_site
. $filename)), 2));
3010 public function fixPermissionsSetsDefaultPermissionsToFile()
3012 if (TYPO3_OS
== 'WIN') {
3013 $this->markTestSkipped('fixPermissions() tests not available on Windows');
3015 $filename = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_');
3016 GeneralUtility
::writeFileToTypo3tempDir($filename, '42');
3017 $this->testFilesToDelete
[] = $filename;
3018 chmod($filename, 482);
3019 unset($GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask']);
3020 $fixPermissionsResult = GeneralUtility
::fixPermissions($filename);
3022 $this->assertTrue($fixPermissionsResult);
3023 $this->assertEquals('0644', substr(decoct(fileperms($filename)), 2));
3029 public function fixPermissionsSetsDefaultPermissionsToDirectory()
3031 if (TYPO3_OS
== 'WIN') {
3032 $this->markTestSkipped('fixPermissions() tests not available on Windows');
3034 $directory = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_');
3035 GeneralUtility
::mkdir($directory);
3036 $this->testFilesToDelete
[] = $directory;
3037 chmod($directory, 1551);
3038 unset($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']);
3039 $fixPermissionsResult = GeneralUtility
::fixPermissions($directory);
3041 $this->assertTrue($fixPermissionsResult);
3042 $this->assertEquals('0755', substr(decoct(fileperms($directory)), 1));
3045 ///////////////////////////////
3046 // Tests concerning mkdir
3047 ///////////////////////////////
3051 public function mkdirCreatesDirectory()
3053 $directory = PATH_site
. 'typo3temp/' . $this->getUniqueId('test_');
3054 $mkdirResult = GeneralUtility
::mkdir($directory);
3055 $this->testFilesToDelete
[] = $directory;
3057 $this->assertTrue($mkdirResult);
3058 $this->assertTrue(is_dir($directory));