[BUGFIX] Treat empty responses as error in GeneralUtility::getUrl
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / GeneralUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
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.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use GuzzleHttp\Exception\RequestException;
18 use TYPO3\CMS\Core\Core\ApplicationContext;
19 use TYPO3\CMS\Core\Core\ClassLoadingInformation;
20 use TYPO3\CMS\Core\Crypto\Random;
21 use TYPO3\CMS\Core\Database\ConnectionPool;
22 use TYPO3\CMS\Core\Http\RequestFactory;
23 use TYPO3\CMS\Core\Service\OpcodeCacheService;
24 use TYPO3\CMS\Core\SingletonInterface;
25 use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
26
27 /**
28 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
29 * Most of the functions do not relate specifically to TYPO3
30 * However a section of functions requires certain TYPO3 features available
31 * See comments in the source.
32 * You are encouraged to use this library in your own scripts!
33 *
34 * USE:
35 * The class is intended to be used without creating an instance of it.
36 * So: Don't instantiate - call functions with "\TYPO3\CMS\Core\Utility\GeneralUtility::" prefixed the function name.
37 * So use \TYPO3\CMS\Core\Utility\GeneralUtility::[method-name] to refer to the functions, eg. '\TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds()'
38 */
39 class GeneralUtility
40 {
41 // Severity constants used by \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog()
42 const SYSLOG_SEVERITY_INFO = 0;
43 const SYSLOG_SEVERITY_NOTICE = 1;
44 const SYSLOG_SEVERITY_WARNING = 2;
45 const SYSLOG_SEVERITY_ERROR = 3;
46 const SYSLOG_SEVERITY_FATAL = 4;
47
48 const ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL = '.*';
49 const ENV_TRUSTED_HOSTS_PATTERN_SERVER_NAME = 'SERVER_NAME';
50
51 /**
52 * State of host header value security check
53 * in order to avoid unnecessary multiple checks during one request
54 *
55 * @var bool
56 */
57 protected static $allowHostHeaderValue = false;
58
59 /**
60 * Singleton instances returned by makeInstance, using the class names as
61 * array keys
62 *
63 * @var array<\TYPO3\CMS\Core\SingletonInterface>
64 */
65 protected static $singletonInstances = [];
66
67 /**
68 * Instances returned by makeInstance, using the class names as array keys
69 *
70 * @var array<array><object>
71 */
72 protected static $nonSingletonInstances = [];
73
74 /**
75 * Cache for makeInstance with given class name and final class names to reduce number of self::getClassName() calls
76 *
77 * @var array Given class name => final class name
78 */
79 protected static $finalClassNameCache = [];
80
81 /**
82 * The application context
83 *
84 * @var \TYPO3\CMS\Core\Core\ApplicationContext
85 */
86 protected static $applicationContext = null;
87
88 /**
89 * IDNA string cache
90 *
91 * @var array<string>
92 */
93 protected static $idnaStringCache = [];
94
95 /**
96 * IDNA converter
97 *
98 * @var \Mso\IdnaConvert\IdnaConvert
99 */
100 protected static $idnaConverter = null;
101
102 /**
103 * A list of supported CGI server APIs
104 * NOTICE: This is a duplicate of the SAME array in SystemEnvironmentBuilder
105 * @var array
106 */
107 protected static $supportedCgiServerApis = [
108 'fpm-fcgi',
109 'cgi',
110 'isapi',
111 'cgi-fcgi',
112 'srv', // HHVM with fastcgi
113 ];
114
115 /**
116 * @var array
117 */
118 protected static $indpEnvCache = [];
119
120 /*************************
121 *
122 * GET/POST Variables
123 *
124 * Background:
125 * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
126 * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
127 * But the clean solution is that quotes are never escaped and that is what the functions below offers.
128 * Eventually TYPO3 should provide this in the global space as well.
129 * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
130 * This functionality was previously needed to normalize between magic quotes logic, which was removed from PHP 5.4,
131 * so these methods are still in use, but not tackle the slash problem anymore.
132 *
133 *************************/
134 /**
135 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
136 * To enhance security in your scripts, please consider using GeneralUtility::_GET or GeneralUtility::_POST if you already
137 * know by which method your data is arriving to the scripts!
138 *
139 * @param string $var GET/POST var to return
140 * @return mixed POST var named $var and if not set, the GET var of the same name.
141 */
142 public static function _GP($var)
143 {
144 if (empty($var)) {
145 return;
146 }
147 if (isset($_POST[$var])) {
148 $value = $_POST[$var];
149 } elseif (isset($_GET[$var])) {
150 $value = $_GET[$var];
151 } else {
152 $value = null;
153 }
154 // This is there for backwards-compatibility, in order to avoid NULL
155 if (isset($value) && !is_array($value)) {
156 $value = (string)$value;
157 }
158 return $value;
159 }
160
161 /**
162 * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
163 *
164 * @param string $parameter Key (variable name) from GET or POST vars
165 * @return array Returns the GET vars merged recursively onto the POST vars.
166 */
167 public static function _GPmerged($parameter)
168 {
169 $postParameter = isset($_POST[$parameter]) && is_array($_POST[$parameter]) ? $_POST[$parameter] : [];
170 $getParameter = isset($_GET[$parameter]) && is_array($_GET[$parameter]) ? $_GET[$parameter] : [];
171 $mergedParameters = $getParameter;
172 ArrayUtility::mergeRecursiveWithOverrule($mergedParameters, $postParameter);
173 return $mergedParameters;
174 }
175
176 /**
177 * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
178 * ALWAYS use this API function to acquire the GET variables!
179 * This function was previously used to normalize between magic quotes logic, which was removed from PHP 5.5
180 *
181 * @param string $var Optional pointer to value in GET array (basically name of GET var)
182 * @return mixed If $var is set it returns the value of $_GET[$var]. If $var is NULL (default), returns $_GET itself. In any case *slashes are stipped from the output!*
183 * @see _POST(), _GP(), _GETset()
184 */
185 public static function _GET($var = null)
186 {
187 $value = $var === null ? $_GET : (empty($var) ? null : $_GET[$var]);
188 // This is there for backwards-compatibility, in order to avoid NULL
189 if (isset($value) && !is_array($value)) {
190 $value = (string)$value;
191 }
192 return $value;
193 }
194
195 /**
196 * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
197 * ALWAYS use this API function to acquire the $_POST variables!
198 *
199 * @param string $var Optional pointer to value in POST array (basically name of POST var)
200 * @return mixed If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself. In any case *slashes are stipped from the output!*
201 * @see _GET(), _GP()
202 */
203 public static function _POST($var = null)
204 {
205 $value = $var === null ? $_POST : (empty($var) ? null : $_POST[$var]);
206 // This is there for backwards-compatibility, in order to avoid NULL
207 if (isset($value) && !is_array($value)) {
208 $value = (string)$value;
209 }
210 return $value;
211 }
212
213 /**
214 * Writes input value to $_GET.
215 *
216 * @param mixed $inputGet
217 * @param string $key
218 */
219 public static function _GETset($inputGet, $key = '')
220 {
221 if ($key != '') {
222 if (strpos($key, '|') !== false) {
223 $pieces = explode('|', $key);
224 $newGet = [];
225 $pointer = &$newGet;
226 foreach ($pieces as $piece) {
227 $pointer = &$pointer[$piece];
228 }
229 $pointer = $inputGet;
230 $mergedGet = $_GET;
231 ArrayUtility::mergeRecursiveWithOverrule($mergedGet, $newGet);
232 $_GET = $mergedGet;
233 $GLOBALS['HTTP_GET_VARS'] = $mergedGet;
234 } else {
235 $_GET[$key] = $inputGet;
236 $GLOBALS['HTTP_GET_VARS'][$key] = $inputGet;
237 }
238 } elseif (is_array($inputGet)) {
239 $_GET = $inputGet;
240 $GLOBALS['HTTP_GET_VARS'] = $inputGet;
241 }
242 }
243
244 /**
245 * Wrapper for the RemoveXSS function.
246 * Removes potential XSS code from an input string.
247 *
248 * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
249 *
250 * @param string $string Input string
251 * @return string Input string with potential XSS code removed
252 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
253 */
254 public static function removeXSS($string)
255 {
256 static::logDeprecatedFunction();
257 return \RemoveXSS::process($string);
258 }
259
260 /*************************
261 *
262 * IMAGE FUNCTIONS
263 *
264 *************************/
265
266 /*************************
267 *
268 * STRING FUNCTIONS
269 *
270 *************************/
271 /**
272 * Truncates a string with appended/prepended "..." and takes current character set into consideration.
273 *
274 * @param string $string String to truncate
275 * @param int $chars Must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
276 * @param string $appendString Appendix to the truncated string
277 * @return string Cropped string
278 */
279 public static function fixed_lgd_cs($string, $chars, $appendString = '...')
280 {
281 if ((int)$chars === 0 || mb_strlen($string, 'utf-8') <= abs($chars)) {
282 return $string;
283 }
284 if ($chars > 0) {
285 $string = mb_substr($string, 0, $chars, 'utf-8') . $appendString;
286 } else {
287 $string = $appendString . mb_substr($string, $chars, mb_strlen($string, 'utf-8'), 'utf-8');
288 }
289 return $string;
290 }
291
292 /**
293 * Match IP number with list of numbers with wildcard
294 * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
295 *
296 * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
297 * @param string $list Is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168). If list is "*" no check is done and the function returns TRUE immediately. An empty list always returns FALSE.
298 * @return bool TRUE if an IP-mask from $list matches $baseIP
299 */
300 public static function cmpIP($baseIP, $list)
301 {
302 $list = trim($list);
303 if ($list === '') {
304 return false;
305 }
306 if ($list === '*') {
307 return true;
308 }
309 if (strpos($baseIP, ':') !== false && self::validIPv6($baseIP)) {
310 return self::cmpIPv6($baseIP, $list);
311 }
312 return self::cmpIPv4($baseIP, $list);
313 }
314
315 /**
316 * Match IPv4 number with list of numbers with wildcard
317 *
318 * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
319 * @param string $list Is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168), could also contain IPv6 addresses
320 * @return bool TRUE if an IP-mask from $list matches $baseIP
321 */
322 public static function cmpIPv4($baseIP, $list)
323 {
324 $IPpartsReq = explode('.', $baseIP);
325 if (count($IPpartsReq) === 4) {
326 $values = self::trimExplode(',', $list, true);
327 foreach ($values as $test) {
328 $testList = explode('/', $test);
329 if (count($testList) === 2) {
330 list($test, $mask) = $testList;
331 } else {
332 $mask = false;
333 }
334 if ((int)$mask) {
335 // "192.168.3.0/24"
336 $lnet = ip2long($test);
337 $lip = ip2long($baseIP);
338 $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
339 $firstpart = substr($binnet, 0, $mask);
340 $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
341 $firstip = substr($binip, 0, $mask);
342 $yes = $firstpart === $firstip;
343 } else {
344 // "192.168.*.*"
345 $IPparts = explode('.', $test);
346 $yes = 1;
347 foreach ($IPparts as $index => $val) {
348 $val = trim($val);
349 if ($val !== '*' && $IPpartsReq[$index] !== $val) {
350 $yes = 0;
351 }
352 }
353 }
354 if ($yes) {
355 return true;
356 }
357 }
358 }
359 return false;
360 }
361
362 /**
363 * Match IPv6 address with a list of IPv6 prefixes
364 *
365 * @param string $baseIP Is the current remote IP address for instance
366 * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
367 * @return bool TRUE If an baseIP matches any prefix
368 */
369 public static function cmpIPv6($baseIP, $list)
370 {
371 // Policy default: Deny connection
372 $success = false;
373 $baseIP = self::normalizeIPv6($baseIP);
374 $values = self::trimExplode(',', $list, true);
375 foreach ($values as $test) {
376 $testList = explode('/', $test);
377 if (count($testList) === 2) {
378 list($test, $mask) = $testList;
379 } else {
380 $mask = false;
381 }
382 if (self::validIPv6($test)) {
383 $test = self::normalizeIPv6($test);
384 $maskInt = (int)$mask ?: 128;
385 // Special case; /0 is an allowed mask - equals a wildcard
386 if ($mask === '0') {
387 $success = true;
388 } elseif ($maskInt == 128) {
389 $success = $test === $baseIP;
390 } else {
391 $testBin = self::IPv6Hex2Bin($test);
392 $baseIPBin = self::IPv6Hex2Bin($baseIP);
393 $success = true;
394 // Modulo is 0 if this is a 8-bit-boundary
395 $maskIntModulo = $maskInt % 8;
396 $numFullCharactersUntilBoundary = (int)($maskInt / 8);
397 if (substr($testBin, 0, $numFullCharactersUntilBoundary) !== substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) {
398 $success = false;
399 } elseif ($maskIntModulo > 0) {
400 // If not an 8-bit-boundary, check bits of last character
401 $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
402 $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
403 if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
404 $success = false;
405 }
406 }
407 }
408 }
409 if ($success) {
410 return true;
411 }
412 }
413 return false;
414 }
415
416 /**
417 * Transform a regular IPv6 address from hex-representation into binary
418 *
419 * @param string $hex IPv6 address in hex-presentation
420 * @return string Binary representation (16 characters, 128 characters)
421 * @see IPv6Bin2Hex()
422 */
423 public static function IPv6Hex2Bin($hex)
424 {
425 return inet_pton($hex);
426 }
427
428 /**
429 * Transform an IPv6 address from binary to hex-representation
430 *
431 * @param string $bin IPv6 address in hex-presentation
432 * @return string Binary representation (16 characters, 128 characters)
433 * @see IPv6Hex2Bin()
434 */
435 public static function IPv6Bin2Hex($bin)
436 {
437 return inet_ntop($bin);
438 }
439
440 /**
441 * Normalize an IPv6 address to full length
442 *
443 * @param string $address Given IPv6 address
444 * @return string Normalized address
445 * @see compressIPv6()
446 */
447 public static function normalizeIPv6($address)
448 {
449 $normalizedAddress = '';
450 $stageOneAddress = '';
451 // According to RFC lowercase-representation is recommended
452 $address = strtolower($address);
453 // Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
454 if (strlen($address) === 39) {
455 // Already in full expanded form
456 return $address;
457 }
458 // Count 2 if if address has hidden zero blocks
459 $chunks = explode('::', $address);
460 if (count($chunks) === 2) {
461 $chunksLeft = explode(':', $chunks[0]);
462 $chunksRight = explode(':', $chunks[1]);
463 $left = count($chunksLeft);
464 $right = count($chunksRight);
465 // Special case: leading zero-only blocks count to 1, should be 0
466 if ($left === 1 && strlen($chunksLeft[0]) === 0) {
467 $left = 0;
468 }
469 $hiddenBlocks = 8 - ($left + $right);
470 $hiddenPart = '';
471 $h = 0;
472 while ($h < $hiddenBlocks) {
473 $hiddenPart .= '0000:';
474 $h++;
475 }
476 if ($left === 0) {
477 $stageOneAddress = $hiddenPart . $chunks[1];
478 } else {
479 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
480 }
481 } else {
482 $stageOneAddress = $address;
483 }
484 // Normalize the blocks:
485 $blocks = explode(':', $stageOneAddress);
486 $divCounter = 0;
487 foreach ($blocks as $block) {
488 $tmpBlock = '';
489 $i = 0;
490 $hiddenZeros = 4 - strlen($block);
491 while ($i < $hiddenZeros) {
492 $tmpBlock .= '0';
493 $i++;
494 }
495 $normalizedAddress .= $tmpBlock . $block;
496 if ($divCounter < 7) {
497 $normalizedAddress .= ':';
498 $divCounter++;
499 }
500 }
501 return $normalizedAddress;
502 }
503
504 /**
505 * Compress an IPv6 address to the shortest notation
506 *
507 * @param string $address Given IPv6 address
508 * @return string Compressed address
509 * @see normalizeIPv6()
510 */
511 public static function compressIPv6($address)
512 {
513 return inet_ntop(inet_pton($address));
514 }
515
516 /**
517 * Validate a given IP address.
518 *
519 * Possible format are IPv4 and IPv6.
520 *
521 * @param string $ip IP address to be tested
522 * @return bool TRUE if $ip is either of IPv4 or IPv6 format.
523 */
524 public static function validIP($ip)
525 {
526 return filter_var($ip, FILTER_VALIDATE_IP) !== false;
527 }
528
529 /**
530 * Validate a given IP address to the IPv4 address format.
531 *
532 * Example for possible format: 10.0.45.99
533 *
534 * @param string $ip IP address to be tested
535 * @return bool TRUE if $ip is of IPv4 format.
536 */
537 public static function validIPv4($ip)
538 {
539 return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
540 }
541
542 /**
543 * Validate a given IP address to the IPv6 address format.
544 *
545 * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
546 *
547 * @param string $ip IP address to be tested
548 * @return bool TRUE if $ip is of IPv6 format.
549 */
550 public static function validIPv6($ip)
551 {
552 return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
553 }
554
555 /**
556 * Match fully qualified domain name with list of strings with wildcard
557 *
558 * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
559 * @param string $list A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong)
560 * @return bool TRUE if a domain name mask from $list matches $baseIP
561 */
562 public static function cmpFQDN($baseHost, $list)
563 {
564 $baseHost = trim($baseHost);
565 if (empty($baseHost)) {
566 return false;
567 }
568 if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
569 // Resolve hostname
570 // Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
571 // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
572 $baseHostName = gethostbyaddr($baseHost);
573 if ($baseHostName === $baseHost) {
574 // Unable to resolve hostname
575 return false;
576 }
577 } else {
578 $baseHostName = $baseHost;
579 }
580 $baseHostNameParts = explode('.', $baseHostName);
581 $values = self::trimExplode(',', $list, true);
582 foreach ($values as $test) {
583 $hostNameParts = explode('.', $test);
584 // To match hostNameParts can only be shorter (in case of wildcards) or equal
585 $hostNamePartsCount = count($hostNameParts);
586 $baseHostNamePartsCount = count($baseHostNameParts);
587 if ($hostNamePartsCount > $baseHostNamePartsCount) {
588 continue;
589 }
590 $yes = true;
591 foreach ($hostNameParts as $index => $val) {
592 $val = trim($val);
593 if ($val === '*') {
594 // Wildcard valid for one or more hostname-parts
595 $wildcardStart = $index + 1;
596 // Wildcard as last/only part always matches, otherwise perform recursive checks
597 if ($wildcardStart < $hostNamePartsCount) {
598 $wildcardMatched = false;
599 $tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
600 while ($wildcardStart < $baseHostNamePartsCount && !$wildcardMatched) {
601 $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
602 $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
603 $wildcardStart++;
604 }
605 if ($wildcardMatched) {
606 // Match found by recursive compare
607 return true;
608 }
609 $yes = false;
610 }
611 } elseif ($baseHostNameParts[$index] !== $val) {
612 // In case of no match
613 $yes = false;
614 }
615 }
616 if ($yes) {
617 return true;
618 }
619 }
620 return false;
621 }
622
623 /**
624 * Checks if a given URL matches the host that currently handles this HTTP request.
625 * Scheme, hostname and (optional) port of the given URL are compared.
626 *
627 * @param string $url URL to compare with the TYPO3 request host
628 * @return bool Whether the URL matches the TYPO3 request host
629 */
630 public static function isOnCurrentHost($url)
631 {
632 return stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0;
633 }
634
635 /**
636 * Check for item in list
637 * Check if an item exists in a comma-separated list of items.
638 *
639 * @param string $list Comma-separated list of items (string)
640 * @param string $item Item to check for
641 * @return bool TRUE if $item is in $list
642 */
643 public static function inList($list, $item)
644 {
645 return strpos(',' . $list . ',', ',' . $item . ',') !== false;
646 }
647
648 /**
649 * Removes an item from a comma-separated list of items.
650 *
651 * If $element contains a comma, the behaviour of this method is undefined.
652 * Empty elements in the list are preserved.
653 *
654 * @param string $element Element to remove
655 * @param string $list Comma-separated list of items (string)
656 * @return string New comma-separated list of items
657 */
658 public static function rmFromList($element, $list)
659 {
660 $items = explode(',', $list);
661 foreach ($items as $k => $v) {
662 if ($v == $element) {
663 unset($items[$k]);
664 }
665 }
666 return implode(',', $items);
667 }
668
669 /**
670 * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
671 * Ranges are limited to 1000 values per range.
672 *
673 * @param string $list Comma-separated list of integers with ranges (string)
674 * @return string New comma-separated list of items
675 */
676 public static function expandList($list)
677 {
678 $items = explode(',', $list);
679 $list = [];
680 foreach ($items as $item) {
681 $range = explode('-', $item);
682 if (isset($range[1])) {
683 $runAwayBrake = 1000;
684 for ($n = $range[0]; $n <= $range[1]; $n++) {
685 $list[] = $n;
686 $runAwayBrake--;
687 if ($runAwayBrake <= 0) {
688 break;
689 }
690 }
691 } else {
692 $list[] = $item;
693 }
694 }
695 return implode(',', $list);
696 }
697
698 /**
699 * Returns TRUE if the current TYPO3 version (or compatibility version) is compatible to the input version
700 * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
701 *
702 * @param string $verNumberStr Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
703 * @return bool Returns TRUE if this setup is compatible with the provided version number
704 * @todo Still needs a function to convert versions to branches
705 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
706 */
707 public static function compat_version($verNumberStr)
708 {
709 static::logDeprecatedFunction();
710 return VersionNumberUtility::convertVersionNumberToInteger(TYPO3_branch) >= VersionNumberUtility::convertVersionNumberToInteger($verNumberStr);
711 }
712
713 /**
714 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
715 *
716 * @param string $str String to md5-hash
717 * @return int Returns 28bit integer-hash
718 */
719 public static function md5int($str)
720 {
721 return hexdec(substr(md5($str), 0, 7));
722 }
723
724 /**
725 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
726 *
727 * @param string $input Input string to be md5-hashed
728 * @param int $len The string-length of the output
729 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
730 */
731 public static function shortMD5($input, $len = 10)
732 {
733 return substr(md5($input), 0, $len);
734 }
735
736 /**
737 * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
738 *
739 * @param string $input Input string to create HMAC from
740 * @param string $additionalSecret additionalSecret to prevent hmac being used in a different context
741 * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
742 */
743 public static function hmac($input, $additionalSecret = '')
744 {
745 $hashAlgorithm = 'sha1';
746 $hashBlocksize = 64;
747 $hmac = '';
748 $secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
749 if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
750 $hmac = hash_hmac($hashAlgorithm, $input, $secret);
751 } else {
752 // Outer padding
753 $opad = str_repeat(chr(92), $hashBlocksize);
754 // Inner padding
755 $ipad = str_repeat(chr(54), $hashBlocksize);
756 if (strlen($secret) > $hashBlocksize) {
757 // Keys longer than block size are shorten
758 $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, chr(0));
759 } else {
760 // Keys shorter than block size are zero-padded
761 $key = str_pad($secret, $hashBlocksize, chr(0));
762 }
763 $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, (($key ^ $ipad) . $input))));
764 }
765 return $hmac;
766 }
767
768 /**
769 * Takes comma-separated lists and arrays and removes all duplicates
770 * If a value in the list is trim(empty), the value is ignored.
771 *
772 * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
773 * @param mixed $secondParameter Dummy field, which if set will show a warning!
774 * @return string Returns the list without any duplicates of values, space around values are trimmed
775 */
776 public static function uniqueList($in_list, $secondParameter = null)
777 {
778 if (is_array($in_list)) {
779 throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support array arguments anymore! Only string comma lists!', 1270853885);
780 }
781 if (isset($secondParameter)) {
782 throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!', 1270853886);
783 }
784 return implode(',', array_unique(self::trimExplode(',', $in_list, true)));
785 }
786
787 /**
788 * Splits a reference to a file in 5 parts
789 *
790 * @param string $fileNameWithPath File name with path to be analysed (must exist if open_basedir is set)
791 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
792 */
793 public static function split_fileref($fileNameWithPath)
794 {
795 $reg = [];
796 if (preg_match('/(.*\\/)(.*)$/', $fileNameWithPath, $reg)) {
797 $info['path'] = $reg[1];
798 $info['file'] = $reg[2];
799 } else {
800 $info['path'] = '';
801 $info['file'] = $fileNameWithPath;
802 }
803 $reg = '';
804 // If open_basedir is set and the fileName was supplied without a path the is_dir check fails
805 if (!is_dir($fileNameWithPath) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], $reg)) {
806 $info['filebody'] = $reg[1];
807 $info['fileext'] = strtolower($reg[2]);
808 $info['realFileext'] = $reg[2];
809 } else {
810 $info['filebody'] = $info['file'];
811 $info['fileext'] = '';
812 }
813 reset($info);
814 return $info;
815 }
816
817 /**
818 * Returns the directory part of a path without trailing slash
819 * If there is no dir-part, then an empty string is returned.
820 * Behaviour:
821 *
822 * '/dir1/dir2/script.php' => '/dir1/dir2'
823 * '/dir1/' => '/dir1'
824 * 'dir1/script.php' => 'dir1'
825 * 'd/script.php' => 'd'
826 * '/script.php' => ''
827 * '' => ''
828 *
829 * @param string $path Directory name / path
830 * @return string Processed input value. See function description.
831 */
832 public static function dirname($path)
833 {
834 $p = self::revExplode('/', $path, 2);
835 return count($p) === 2 ? $p[0] : '';
836 }
837
838 /**
839 * Returns TRUE if the first part of $str matches the string $partStr
840 *
841 * @param string $str Full string to check
842 * @param string $partStr Reference string which must be found as the "first part" of the full string
843 * @return bool TRUE if $partStr was found to be equal to the first part of $str
844 */
845 public static function isFirstPartOfStr($str, $partStr)
846 {
847 return $partStr != '' && strpos((string)$str, (string)$partStr, 0) === 0;
848 }
849
850 /**
851 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
852 *
853 * @param int $sizeInBytes Number of bytes to format.
854 * @param string $labels Binary unit name "iec", decimal unit name "si" or labels for bytes, kilo, mega, giga, and so on separated by vertical bar (|) and possibly encapsulated in "". Eg: " | K| M| G". Defaults to "iec".
855 * @param int $base The unit base if not using a unit name. Defaults to 1024.
856 * @return string Formatted representation of the byte number, for output.
857 */
858 public static function formatSize($sizeInBytes, $labels = '', $base = 0)
859 {
860 $defaultFormats = [
861 'iec' => ['base' => 1024, 'labels' => [' ', ' Ki', ' Mi', ' Gi', ' Ti', ' Pi', ' Ei', ' Zi', ' Yi']],
862 'si' => ['base' => 1000, 'labels' => [' ', ' k', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']],
863 ];
864 // Set labels and base:
865 if (empty($labels)) {
866 $labels = 'iec';
867 }
868 if (isset($defaultFormats[$labels])) {
869 $base = $defaultFormats[$labels]['base'];
870 $labelArr = $defaultFormats[$labels]['labels'];
871 } else {
872 $base = (int)$base;
873 if ($base !== 1000 && $base !== 1024) {
874 $base = 1024;
875 }
876 $labelArr = explode('|', str_replace('"', '', $labels));
877 }
878 // @todo find out which locale is used for current BE user to cover the BE case as well
879 $oldLocale = setlocale(LC_NUMERIC, 0);
880 $newLocale = isset($GLOBALS['TSFE']) ? $GLOBALS['TSFE']->config['config']['locale_all'] : '';
881 if ($newLocale) {
882 setlocale(LC_NUMERIC, $newLocale);
883 }
884 $localeInfo = localeconv();
885 if ($newLocale) {
886 setlocale(LC_NUMERIC, $oldLocale);
887 }
888 $sizeInBytes = max($sizeInBytes, 0);
889 $multiplier = floor(($sizeInBytes ? log($sizeInBytes) : 0) / log($base));
890 $sizeInUnits = $sizeInBytes / pow($base, $multiplier);
891 if ($sizeInUnits > ($base * .9)) {
892 $multiplier++;
893 }
894 $multiplier = min($multiplier, count($labelArr) - 1);
895 $sizeInUnits = $sizeInBytes / pow($base, $multiplier);
896 return number_format($sizeInUnits, (($multiplier > 0) && ($sizeInUnits < 20)) ? 2 : 0, $localeInfo['decimal_point'], '') . $labelArr[$multiplier];
897 }
898
899 /**
900 * Returns microtime input to milliseconds
901 *
902 * @param string $microtime Microtime
903 * @return int Microtime input string converted to an integer (milliseconds)
904 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
905 */
906 public static function convertMicrotime($microtime)
907 {
908 static::logDeprecatedFunction();
909 $parts = explode(' ', $microtime);
910 return round(($parts[0] + $parts[1]) * 1000);
911 }
912
913 /**
914 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
915 *
916 * @param string $string Input string, eg "123 + 456 / 789 - 4
917 * @param string $operators Operators to split by, typically "/+-*
918 * @return array Array with operators and operands separated.
919 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc(), \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset()
920 */
921 public static function splitCalc($string, $operators)
922 {
923 $res = [];
924 $sign = '+';
925 while ($string) {
926 $valueLen = strcspn($string, $operators);
927 $value = substr($string, 0, $valueLen);
928 $res[] = [$sign, trim($value)];
929 $sign = substr($string, $valueLen, 1);
930 $string = substr($string, $valueLen + 1);
931 }
932 reset($res);
933 return $res;
934 }
935
936 /**
937 * Re-converts HTML entities if they have been converted by htmlspecialchars()
938 * Note: Use htmlspecialchars($str, ENT_COMPAT, 'UTF-8', FALSE) to avoid double encoding.
939 * This makes the call to this method obsolete.
940 *
941 * @param string $str String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;
942 * @return string Converted result.
943 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
944 */
945 public static function deHSCentities($str)
946 {
947 static::logDeprecatedFunction();
948 return preg_replace('/&amp;([#[:alnum:]]*;)/', '&\\1', $str);
949 }
950
951 /**
952 * This function is used to escape any ' -characters when transferring text to JavaScript!
953 *
954 * @param string $string String to escape
955 * @param bool $extended If set, also backslashes are escaped.
956 * @param string $char The character to escape, default is ' (single-quote)
957 * @return string Processed input string
958 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
959 */
960 public static function slashJS($string, $extended = false, $char = '\'')
961 {
962 static::logDeprecatedFunction();
963 if ($extended) {
964 $string = str_replace('\\', '\\\\', $string);
965 }
966 return str_replace($char, '\\' . $char, $string);
967 }
968
969 /**
970 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
971 * Useful when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
972 *
973 * @param string $str String to raw-url-encode with spaces preserved
974 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
975 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9, implement directly via PHP instead
976 */
977 public static function rawUrlEncodeJS($str)
978 {
979 static::logDeprecatedFunction();
980 return str_replace('%20', ' ', rawurlencode($str));
981 }
982
983 /**
984 * rawurlencode which preserves "/" chars
985 * Useful when file paths should keep the "/" chars, but have all other special chars encoded.
986 *
987 * @param string $str Input string
988 * @return string Output string
989 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9, use the PHP methods directly instead
990 */
991 public static function rawUrlEncodeFP($str)
992 {
993 static::logDeprecatedFunction();
994 return str_replace('%2F', '/', rawurlencode($str));
995 }
996
997 /**
998 * Checking syntax of input email address
999 *
1000 * http://tools.ietf.org/html/rfc3696
1001 * International characters are allowed in email. So the whole address needs
1002 * to be converted to punicode before passing it to filter_var(). We convert
1003 * the user- and domain part separately to increase the chance of hitting an
1004 * entry in self::$idnaStringCache.
1005 *
1006 * Also the @ sign may appear multiple times in an address. If not used as
1007 * a boundary marker between the user- and domain part, it must be escaped
1008 * with a backslash: \@. This mean we can not just explode on the @ sign and
1009 * expect to get just two parts. So we pop off the domain and then glue the
1010 * rest together again.
1011 *
1012 * @param string $email Input string to evaluate
1013 * @return bool Returns TRUE if the $email address (input string) is valid
1014 */
1015 public static function validEmail($email)
1016 {
1017 // Early return in case input is not a string
1018 if (!is_string($email)) {
1019 return false;
1020 }
1021 $atPosition = strrpos($email, '@');
1022 if (!$atPosition || $atPosition + 1 === strlen($email)) {
1023 // Return if no @ found or it is placed at the very beginning or end of the email
1024 return false;
1025 }
1026 $domain = substr($email, $atPosition + 1);
1027 $user = substr($email, 0, $atPosition);
1028 if (!preg_match('/^[a-z0-9.\\-]*$/i', $domain)) {
1029 try {
1030 $domain = self::idnaEncode($domain);
1031 } catch (\InvalidArgumentException $exception) {
1032 return false;
1033 }
1034 }
1035 return filter_var($user . '@' . $domain, FILTER_VALIDATE_EMAIL) !== false;
1036 }
1037
1038 /**
1039 * Converts string to uppercase
1040 * The function converts all Latin characters (a-z, but no accents, etc) to
1041 * uppercase. It is safe for all supported character sets (incl. utf-8).
1042 * Unlike strtoupper() it does not honour the locale.
1043 *
1044 * @param string $str Input string
1045 * @return string Uppercase String
1046 * @deprecated since TYPO3 CMS v8, this method will be removed in TYPO3 CMS v9, use mb_strtoupper() instead
1047 */
1048 public static function strtoupper($str)
1049 {
1050 self::logDeprecatedFunction();
1051 return strtr((string)$str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
1052 }
1053
1054 /**
1055 * Converts string to lowercase
1056 * The function converts all Latin characters (A-Z, but no accents, etc) to
1057 * lowercase. It is safe for all supported character sets (incl. utf-8).
1058 * Unlike strtolower() it does not honour the locale.
1059 *
1060 * @param string $str Input string
1061 * @return string Lowercase String
1062 * @deprecated since TYPO3 CMS v8, this method will be removed in TYPO3 CMS v9, use mb_strtolower() instead
1063 */
1064 public static function strtolower($str)
1065 {
1066 self::logDeprecatedFunction();
1067 return strtr((string)$str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1068 }
1069
1070 /**
1071 * Returns a string of highly randomized bytes (over the full 8-bit range).
1072 *
1073 * @param int $bytesToReturn Number of bytes to return
1074 * @return string Random Bytes
1075 * @deprecated since TYPO3 CMS 8, this method will be removed in TYPO3 CMS 9. Use \TYPO3\CMS\Core\Crypto\Random->generateRandomBytes() instead
1076 */
1077 public static function generateRandomBytes($bytesToReturn)
1078 {
1079 self::logDeprecatedFunction();
1080 return self::makeInstance(Random::class)->generateRandomBytes($bytesToReturn);
1081 }
1082
1083 /**
1084 * Returns an ASCII string (punicode) representation of $value
1085 *
1086 * @param string $value
1087 * @return string An ASCII encoded (punicode) string
1088 */
1089 public static function idnaEncode($value)
1090 {
1091 if (isset(self::$idnaStringCache[$value])) {
1092 return self::$idnaStringCache[$value];
1093 }
1094 if (!self::$idnaConverter) {
1095 self::$idnaConverter = new \Mso\IdnaConvert\IdnaConvert(['idn_version' => 2008]);
1096 }
1097 self::$idnaStringCache[$value] = self::$idnaConverter->encode($value);
1098 return self::$idnaStringCache[$value];
1099 }
1100
1101 /**
1102 * Returns a hex representation of a random byte string.
1103 *
1104 * @param int $count Number of hex characters to return
1105 * @return string Random Bytes
1106 * @deprecated since TYPO3 CMS 8, this method will be removed in TYPO3 CMS 9. Use \TYPO3\CMS\Core\Crypto\Random::generateRandomHexString() instead
1107 */
1108 public static function getRandomHexString($count)
1109 {
1110 self::logDeprecatedFunction();
1111 return self::makeInstance(Random::class)->generateRandomHexString($count);
1112 }
1113
1114 /**
1115 * Returns a given string with underscores as UpperCamelCase.
1116 * Example: Converts blog_example to BlogExample
1117 *
1118 * @param string $string String to be converted to camel case
1119 * @return string UpperCamelCasedWord
1120 */
1121 public static function underscoredToUpperCamelCase($string)
1122 {
1123 return str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string))));
1124 }
1125
1126 /**
1127 * Returns a given string with underscores as lowerCamelCase.
1128 * Example: Converts minimal_value to minimalValue
1129 *
1130 * @param string $string String to be converted to camel case
1131 * @return string lowerCamelCasedWord
1132 */
1133 public static function underscoredToLowerCamelCase($string)
1134 {
1135 return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($string)))));
1136 }
1137
1138 /**
1139 * Returns a given CamelCasedString as an lowercase string with underscores.
1140 * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
1141 *
1142 * @param string $string String to be converted to lowercase underscore
1143 * @return string lowercase_and_underscored_string
1144 */
1145 public static function camelCaseToLowerCaseUnderscored($string)
1146 {
1147 $value = preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string);
1148 return mb_strtolower($value, 'utf-8');
1149 }
1150
1151 /**
1152 * Converts the first char of a string to lowercase if it is a latin character (A-Z).
1153 * Example: Converts "Hello World" to "hello World"
1154 *
1155 * @param string $string The string to be used to lowercase the first character
1156 * @return string The string with the first character as lowercase
1157 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
1158 */
1159 public static function lcfirst($string)
1160 {
1161 static::logDeprecatedFunction();
1162 return lcfirst($string);
1163 }
1164
1165 /**
1166 * Checks if a given string is a Uniform Resource Locator (URL).
1167 *
1168 * On seriously malformed URLs, parse_url may return FALSE and emit an
1169 * E_WARNING.
1170 *
1171 * filter_var() requires a scheme to be present.
1172 *
1173 * http://www.faqs.org/rfcs/rfc2396.html
1174 * Scheme names consist of a sequence of characters beginning with a
1175 * lower case letter and followed by any combination of lower case letters,
1176 * digits, plus ("+"), period ("."), or hyphen ("-"). For resiliency,
1177 * programs interpreting URI should treat upper case letters as equivalent to
1178 * lower case in scheme names (e.g., allow "HTTP" as well as "http").
1179 * scheme = alpha *( alpha | digit | "+" | "-" | "." )
1180 *
1181 * Convert the domain part to punicode if it does not look like a regular
1182 * domain name. Only the domain part because RFC3986 specifies the the rest of
1183 * the url may not contain special characters:
1184 * http://tools.ietf.org/html/rfc3986#appendix-A
1185 *
1186 * @param string $url The URL to be validated
1187 * @return bool Whether the given URL is valid
1188 */
1189 public static function isValidUrl($url)
1190 {
1191 $parsedUrl = parse_url($url);
1192 if (!$parsedUrl || !isset($parsedUrl['scheme'])) {
1193 return false;
1194 }
1195 // HttpUtility::buildUrl() will always build urls with <scheme>://
1196 // our original $url might only contain <scheme>: (e.g. mail:)
1197 // so we convert that to the double-slashed version to ensure
1198 // our check against the $recomposedUrl is proper
1199 if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) {
1200 $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url);
1201 }
1202 $recomposedUrl = HttpUtility::buildUrl($parsedUrl);
1203 if ($recomposedUrl !== $url) {
1204 // The parse_url() had to modify characters, so the URL is invalid
1205 return false;
1206 }
1207 if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) {
1208 try {
1209 $parsedUrl['host'] = self::idnaEncode($parsedUrl['host']);
1210 } catch (\InvalidArgumentException $exception) {
1211 return false;
1212 }
1213 }
1214 return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== false;
1215 }
1216
1217 /*************************
1218 *
1219 * ARRAY FUNCTIONS
1220 *
1221 *************************/
1222
1223 /**
1224 * Explodes a $string delimited by $delimiter and casts each item in the array to (int).
1225 * Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values.
1226 *
1227 * @param string $delimiter Delimiter string to explode with
1228 * @param string $string The string to explode
1229 * @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output
1230 * @param int $limit If positive, the result will contain a maximum of limit elements,
1231 * @return array Exploded values, all converted to integers
1232 */
1233 public static function intExplode($delimiter, $string, $removeEmptyValues = false, $limit = 0)
1234 {
1235 $result = explode($delimiter, $string);
1236 foreach ($result as $key => &$value) {
1237 if ($removeEmptyValues && ($value === '' || trim($value) === '')) {
1238 unset($result[$key]);
1239 } else {
1240 $value = (int)$value;
1241 }
1242 }
1243 unset($value);
1244 if ($limit !== 0) {
1245 if ($limit < 0) {
1246 $result = array_slice($result, 0, $limit);
1247 } elseif (count($result) > $limit) {
1248 $lastElements = array_slice($result, $limit - 1);
1249 $result = array_slice($result, 0, $limit - 1);
1250 $result[] = implode($delimiter, $lastElements);
1251 }
1252 }
1253 return $result;
1254 }
1255
1256 /**
1257 * Reverse explode which explodes the string counting from behind.
1258 *
1259 * Note: The delimiter has to given in the reverse order as
1260 * it is occurring within the string.
1261 *
1262 * GeneralUtility::revExplode('[]', '[my][words][here]', 2)
1263 * ==> array('[my][words', 'here]')
1264 *
1265 * @param string $delimiter Delimiter string to explode with
1266 * @param string $string The string to explode
1267 * @param int $count Number of array entries
1268 * @return array Exploded values
1269 */
1270 public static function revExplode($delimiter, $string, $count = 0)
1271 {
1272 // 2 is the (currently, as of 2014-02) most-used value for $count in the core, therefore we check it first
1273 if ($count === 2) {
1274 $position = strrpos($string, strrev($delimiter));
1275 if ($position !== false) {
1276 return [substr($string, 0, $position), substr($string, $position + strlen($delimiter))];
1277 }
1278 return [$string];
1279 }
1280 if ($count <= 1) {
1281 return [$string];
1282 }
1283 $explodedValues = explode($delimiter, strrev($string), $count);
1284 $explodedValues = array_map('strrev', $explodedValues);
1285 return array_reverse($explodedValues);
1286 }
1287
1288 /**
1289 * Explodes a string and trims all values for whitespace in the end.
1290 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1291 *
1292 * @param string $delim Delimiter string to explode with
1293 * @param string $string The string to explode
1294 * @param bool $removeEmptyValues If set, all empty values will be removed in output
1295 * @param int $limit If limit is set and positive, the returned array will contain a maximum of limit elements with
1296 * the last element containing the rest of string. If the limit parameter is negative, all components
1297 * except the last -limit are returned.
1298 * @return array Exploded values
1299 */
1300 public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0)
1301 {
1302 $result = explode($delim, $string);
1303 if ($removeEmptyValues) {
1304 $temp = [];
1305 foreach ($result as $value) {
1306 if (trim($value) !== '') {
1307 $temp[] = $value;
1308 }
1309 }
1310 $result = $temp;
1311 }
1312 if ($limit > 0 && count($result) > $limit) {
1313 $lastElements = array_splice($result, $limit - 1);
1314 $result[] = implode($delim, $lastElements);
1315 } elseif ($limit < 0) {
1316 $result = array_slice($result, 0, $limit);
1317 }
1318 $result = array_map('trim', $result);
1319 return $result;
1320 }
1321
1322 /**
1323 * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1324 *
1325 * @param string $name Name prefix for entries. Set to blank if you wish none.
1326 * @param array $theArray The (multidimensional) array to implode
1327 * @param string $str (keep blank)
1328 * @param bool $skipBlank If set, parameters which were blank strings would be removed.
1329 * @param bool $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1330 * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1331 * @see explodeUrl2Array()
1332 */
1333 public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false)
1334 {
1335 foreach ($theArray as $Akey => $AVal) {
1336 $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1337 if (is_array($AVal)) {
1338 $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1339 } else {
1340 if (!$skipBlank || (string)$AVal !== '') {
1341 $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) . '=' . rawurlencode($AVal);
1342 }
1343 }
1344 }
1345 return $str;
1346 }
1347
1348 /**
1349 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1350 *
1351 * @param string $string GETvars string
1352 * @param bool $multidim If set, the string will be parsed into a multidimensional array if square brackets are used in variable names (using PHP function parse_str())
1353 * @return array Array of values. All values AND keys are rawurldecoded() as they properly should be. But this means that any implosion of the array again must rawurlencode it!
1354 * @see implodeArrayForUrl()
1355 */
1356 public static function explodeUrl2Array($string, $multidim = false)
1357 {
1358 $output = [];
1359 if ($multidim) {
1360 parse_str($string, $output);
1361 } else {
1362 $p = explode('&', $string);
1363 foreach ($p as $v) {
1364 if ($v !== '') {
1365 list($pK, $pV) = explode('=', $v, 2);
1366 $output[rawurldecode($pK)] = rawurldecode($pV);
1367 }
1368 }
1369 }
1370 return $output;
1371 }
1372
1373 /**
1374 * Returns an array with selected keys from incoming data.
1375 * (Better read source code if you want to find out...)
1376 *
1377 * @param string $varList List of variable/key names
1378 * @param array $getArray Array from where to get values based on the keys in $varList
1379 * @param bool $GPvarAlt If set, then \TYPO3\CMS\Core\Utility\GeneralUtility::_GP() is used to fetch the value if not found (isset) in the $getArray
1380 * @return array Output array with selected variables.
1381 */
1382 public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = true)
1383 {
1384 $keys = self::trimExplode(',', $varList, true);
1385 $outArr = [];
1386 foreach ($keys as $v) {
1387 if (isset($getArray[$v])) {
1388 $outArr[$v] = $getArray[$v];
1389 } elseif ($GPvarAlt) {
1390 $outArr[$v] = self::_GP($v);
1391 }
1392 }
1393 return $outArr;
1394 }
1395
1396 /**
1397 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1398 *
1399 * @param array $row Input array of values
1400 * @param string $delim Delimited, default is comma
1401 * @param string $quote Quote-character to wrap around the values.
1402 * @return string A single line of CSV
1403 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9.
1404 */
1405 public static function csvValues(array $row, $delim = ',', $quote = '"')
1406 {
1407 self::logDeprecatedFunction();
1408 return CsvUtility::csvValues($row, $delim, $quote);
1409 }
1410
1411 /**
1412 * Removes dots "." from end of a key identifier of TypoScript styled array.
1413 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1414 *
1415 * @param array $ts TypoScript configuration array
1416 * @return array TypoScript configuration array without dots at the end of all keys
1417 */
1418 public static function removeDotsFromTS(array $ts)
1419 {
1420 $out = [];
1421 foreach ($ts as $key => $value) {
1422 if (is_array($value)) {
1423 $key = rtrim($key, '.');
1424 $out[$key] = self::removeDotsFromTS($value);
1425 } else {
1426 $out[$key] = $value;
1427 }
1428 }
1429 return $out;
1430 }
1431
1432 /*************************
1433 *
1434 * HTML/XML PROCESSING
1435 *
1436 *************************/
1437 /**
1438 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1439 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1440 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1441 *
1442 * @param string $tag HTML-tag string (or attributes only)
1443 * @return array Array with the attribute values.
1444 */
1445 public static function get_tag_attributes($tag)
1446 {
1447 $components = self::split_tag_attributes($tag);
1448 // Attribute name is stored here
1449 $name = '';
1450 $valuemode = false;
1451 $attributes = [];
1452 foreach ($components as $key => $val) {
1453 // Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value
1454 if ($val !== '=') {
1455 if ($valuemode) {
1456 if ($name) {
1457 $attributes[$name] = $val;
1458 $name = '';
1459 }
1460 } else {
1461 if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val))) {
1462 $attributes[$key] = '';
1463 $name = $key;
1464 }
1465 }
1466 $valuemode = false;
1467 } else {
1468 $valuemode = true;
1469 }
1470 }
1471 return $attributes;
1472 }
1473
1474 /**
1475 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1476 * Removes tag-name if found
1477 *
1478 * @param string $tag HTML-tag string (or attributes only)
1479 * @return array Array with the attribute values.
1480 */
1481 public static function split_tag_attributes($tag)
1482 {
1483 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
1484 // Removes any > in the end of the string
1485 $tag_tmp = trim(rtrim($tag_tmp, '>'));
1486 $value = [];
1487 // Compared with empty string instead , 030102
1488 while ($tag_tmp !== '') {
1489 $firstChar = $tag_tmp[0];
1490 if ($firstChar === '"' || $firstChar === '\'') {
1491 $reg = explode($firstChar, $tag_tmp, 3);
1492 $value[] = $reg[1];
1493 $tag_tmp = trim($reg[2]);
1494 } elseif ($firstChar === '=') {
1495 $value[] = '=';
1496 // Removes = chars.
1497 $tag_tmp = trim(substr($tag_tmp, 1));
1498 } else {
1499 // There are '' around the value. We look for the next ' ' or '>'
1500 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
1501 $value[] = trim($reg[0]);
1502 $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
1503 }
1504 }
1505 reset($value);
1506 return $value;
1507 }
1508
1509 /**
1510 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1511 *
1512 * @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1513 * @param bool $xhtmlSafe If set the resulting attribute list will have a) all attributes in lowercase (and duplicates weeded out, first entry taking precedence) and b) all values htmlspecialchar()'ed. It is recommended to use this switch!
1514 * @param bool $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
1515 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1516 */
1517 public static function implodeAttributes(array $arr, $xhtmlSafe = false, $dontOmitBlankAttribs = false)
1518 {
1519 if ($xhtmlSafe) {
1520 $newArr = [];
1521 foreach ($arr as $p => $v) {
1522 if (!isset($newArr[strtolower($p)])) {
1523 $newArr[strtolower($p)] = htmlspecialchars($v);
1524 }
1525 }
1526 $arr = $newArr;
1527 }
1528 $list = [];
1529 foreach ($arr as $p => $v) {
1530 if ((string)$v !== '' || $dontOmitBlankAttribs) {
1531 $list[] = $p . '="' . $v . '"';
1532 }
1533 }
1534 return implode(' ', $list);
1535 }
1536
1537 /**
1538 * Wraps JavaScript code XHTML ready with <script>-tags
1539 * Automatic re-indenting of the JS code is done by using the first line as indent reference.
1540 * This is nice for indenting JS code with PHP code on the same level.
1541 *
1542 * @param string $string JavaScript code
1543 * @param null $_ unused, will be removed in TYPO3 CMS 9
1544 * @return string The wrapped JS code, ready to put into a XHTML page
1545 */
1546 public static function wrapJS($string, $_ = null)
1547 {
1548 if ($_ !== null) {
1549 self::deprecationLog('Parameter 2 of GeneralUtility::wrapJS is obsolete and can be omitted.');
1550 }
1551
1552 if (trim($string)) {
1553 // remove nl from the beginning
1554 $string = ltrim($string, LF);
1555 // re-ident to one tab using the first line as reference
1556 $match = [];
1557 if (preg_match('/^(\\t+)/', $string, $match)) {
1558 $string = str_replace($match[1], TAB, $string);
1559 }
1560 return '<script type="text/javascript">
1561 /*<![CDATA[*/
1562 ' . $string . '
1563 /*]]>*/
1564 </script>';
1565 }
1566 return '';
1567 }
1568
1569 /**
1570 * Parses XML input into a PHP array with associative keys
1571 *
1572 * @param string $string XML data input
1573 * @param int $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1574 * @param array $parserOptions Options that will be passed to PHP's xml_parser_set_option()
1575 * @return mixed The array with the parsed structure unless the XML parser returns with an error in which case the error message string is returned.
1576 */
1577 public static function xml2tree($string, $depth = 999, $parserOptions = [])
1578 {
1579 // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
1580 $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
1581 $parser = xml_parser_create();
1582 $vals = [];
1583 $index = [];
1584 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1585 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1586 foreach ($parserOptions as $option => $value) {
1587 xml_parser_set_option($parser, $option, $value);
1588 }
1589 xml_parse_into_struct($parser, $string, $vals, $index);
1590 libxml_disable_entity_loader($previousValueOfEntityLoader);
1591 if (xml_get_error_code($parser)) {
1592 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1593 }
1594 xml_parser_free($parser);
1595 $stack = [[]];
1596 $stacktop = 0;
1597 $startPoint = 0;
1598 $tagi = [];
1599 foreach ($vals as $key => $val) {
1600 $type = $val['type'];
1601 // open tag:
1602 if ($type === 'open' || $type === 'complete') {
1603 $stack[$stacktop++] = $tagi;
1604 if ($depth == $stacktop) {
1605 $startPoint = $key;
1606 }
1607 $tagi = ['tag' => $val['tag']];
1608 if (isset($val['attributes'])) {
1609 $tagi['attrs'] = $val['attributes'];
1610 }
1611 if (isset($val['value'])) {
1612 $tagi['values'][] = $val['value'];
1613 }
1614 }
1615 // finish tag:
1616 if ($type === 'complete' || $type === 'close') {
1617 $oldtagi = $tagi;
1618 $tagi = $stack[--$stacktop];
1619 $oldtag = $oldtagi['tag'];
1620 unset($oldtagi['tag']);
1621 if ($depth == $stacktop + 1) {
1622 if ($key - $startPoint > 0) {
1623 $partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1);
1624 $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
1625 } else {
1626 $oldtagi['XMLvalue'] = $oldtagi['values'][0];
1627 }
1628 }
1629 $tagi['ch'][$oldtag][] = $oldtagi;
1630 unset($oldtagi);
1631 }
1632 // cdata
1633 if ($type === 'cdata') {
1634 $tagi['values'][] = $val['value'];
1635 }
1636 }
1637 return $tagi['ch'];
1638 }
1639
1640 /**
1641 * Turns PHP array into XML. See array2xml()
1642 *
1643 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1644 * @param string $docTag Alternative document tag. Default is "phparray".
1645 * @param array $options Options for the compilation. See array2xml() for description.
1646 * @param string $charset Forced charset to prologue
1647 * @return string An XML string made from the input content in the array.
1648 * @see xml2array(),array2xml()
1649 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9.
1650 */
1651 public static function array2xml_cs(array $array, $docTag = 'phparray', array $options = [], $charset = '')
1652 {
1653 static::logDeprecatedFunction();
1654 // Set default charset unless explicitly specified
1655 $charset = $charset ?: 'utf-8';
1656 // Return XML:
1657 return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF . self::array2xml($array, '', 0, $docTag, 0, $options);
1658 }
1659
1660 /**
1661 * Converts a PHP array into an XML string.
1662 * The XML output is optimized for readability since associative keys are used as tag names.
1663 * This also means that only alphanumeric characters are allowed in the tag names AND only keys NOT starting with numbers (so watch your usage of keys!). However there are options you can set to avoid this problem.
1664 * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
1665 * The function handles input values from the PHP array in a binary-safe way; All characters below 32 (except 9,10,13) will trigger the content to be converted to a base64-string
1666 * The PHP variable type of the data IS preserved as long as the types are strings, arrays, integers and booleans. Strings are the default type unless the "type" attribute is set.
1667 * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances with 4.x versions. However, with PHP5 there seems to be the need to add an XML prologue a la <?xml version="1.0" encoding="[charset]" standalone="yes" ?> - otherwise UTF-8 is assumed! Unfortunately, many times the output from this function is used without adding that prologue meaning that non-ASCII characters will break the parsing!! This suchs of course! Effectively it means that the prologue should always be prepended setting the right characterset, alternatively the system should always run as utf-8!
1668 * However using MSIE to read the XML output didn't always go well: One reason could be that the character encoding is not observed in the PHP data. The other reason may be if the tag-names are invalid in the eyes of MSIE. Also using the namespace feature will make MSIE break parsing. There might be more reasons...
1669 *
1670 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1671 * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
1672 * @param int $level Current recursion level. Don't change, stay at zero!
1673 * @param string $docTag Alternative document tag. Default is "phparray".
1674 * @param int $spaceInd If greater than zero, then the number of spaces corresponding to this number is used for indenting, if less than zero - no indentation, if zero - a single TAB is used
1675 * @param array $options Options for the compilation. Key "useNindex" => 0/1 (boolean: whether to use "n0, n1, n2" for num. indexes); Key "useIndexTagForNum" => "[tag for numerical indexes]"; Key "useIndexTagForAssoc" => "[tag for associative indexes"; Key "parentTagMap" => array('parentTag' => 'thisLevelTag')
1676 * @param array $stackData Stack data. Don't touch.
1677 * @return string An XML string made from the input content in the array.
1678 * @see xml2array()
1679 */
1680 public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = [], array $stackData = [])
1681 {
1682 // The list of byte values which will trigger binary-safe storage. If any value has one of these char values in it, it will be encoded in base64
1683 $binaryChars = chr(0) . chr(1) . chr(2) . chr(3) . chr(4) . chr(5) . chr(6) . chr(7) . chr(8) . chr(11) . chr(12) . chr(14) . chr(15) . chr(16) . chr(17) . chr(18) . chr(19) . chr(20) . chr(21) . chr(22) . chr(23) . chr(24) . chr(25) . chr(26) . chr(27) . chr(28) . chr(29) . chr(30) . chr(31);
1684 // Set indenting mode:
1685 $indentChar = $spaceInd ? ' ' : TAB;
1686 $indentN = $spaceInd > 0 ? $spaceInd : 1;
1687 $nl = $spaceInd >= 0 ? LF : '';
1688 // Init output variable:
1689 $output = '';
1690 // Traverse the input array
1691 foreach ($array as $k => $v) {
1692 $attr = '';
1693 $tagName = $k;
1694 // Construct the tag name.
1695 // Use tag based on grand-parent + parent tag name
1696 if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) {
1697 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1698 $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']];
1699 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && MathUtility::canBeInterpretedAsInteger($tagName)) {
1700 // Use tag based on parent tag name + if current tag is numeric
1701 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1702 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM'];
1703 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) {
1704 // Use tag based on parent tag name + current tag
1705 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1706 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName];
1707 } elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) {
1708 // Use tag based on parent tag name:
1709 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1710 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
1711 } elseif (MathUtility::canBeInterpretedAsInteger($tagName)) {
1712 // If integer...;
1713 if ($options['useNindex']) {
1714 // If numeric key, prefix "n"
1715 $tagName = 'n' . $tagName;
1716 } else {
1717 // Use special tag for num. keys:
1718 $attr .= ' index="' . $tagName . '"';
1719 $tagName = $options['useIndexTagForNum'] ?: 'numIndex';
1720 }
1721 } elseif ($options['useIndexTagForAssoc']) {
1722 // Use tag for all associative keys:
1723 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
1724 $tagName = $options['useIndexTagForAssoc'];
1725 }
1726 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
1727 $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
1728 // If the value is an array then we will call this function recursively:
1729 if (is_array($v)) {
1730 // Sub elements:
1731 if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
1732 $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
1733 $clearStackPath = $subOptions['clearStackPath'];
1734 } else {
1735 $subOptions = $options;
1736 $clearStackPath = false;
1737 }
1738 if (empty($v)) {
1739 $content = '';
1740 } else {
1741 $content = $nl . self::array2xml($v, $NSprefix, ($level + 1), '', $spaceInd, $subOptions, [
1742 'parentTagName' => $tagName,
1743 'grandParentTagName' => $stackData['parentTagName'],
1744 'path' => ($clearStackPath ? '' : $stackData['path'] . '/' . $tagName)
1745 ]) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
1746 }
1747 // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
1748 if ((int)$options['disableTypeAttrib'] != 2) {
1749 $attr .= ' type="array"';
1750 }
1751 } else {
1752 // Just a value:
1753 // Look for binary chars:
1754 $vLen = strlen($v);
1755 // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
1756 if ($vLen && strcspn($v, $binaryChars) != $vLen) {
1757 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
1758 $content = $nl . chunk_split(base64_encode($v));
1759 $attr .= ' base64="1"';
1760 } else {
1761 // Otherwise, just htmlspecialchar the stuff:
1762 $content = htmlspecialchars($v);
1763 $dType = gettype($v);
1764 if ($dType === 'string') {
1765 if ($options['useCDATA'] && $content != $v) {
1766 $content = '<![CDATA[' . $v . ']]>';
1767 }
1768 } elseif (!$options['disableTypeAttrib']) {
1769 $attr .= ' type="' . $dType . '"';
1770 }
1771 }
1772 }
1773 if ((string)$tagName !== '') {
1774 // Add the element to the output string:
1775 $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '')
1776 . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
1777 }
1778 }
1779 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
1780 if (!$level) {
1781 $output = '<' . $docTag . '>' . $nl . $output . '</' . $docTag . '>';
1782 }
1783 return $output;
1784 }
1785
1786 /**
1787 * Converts an XML string to a PHP array.
1788 * This is the reverse function of array2xml()
1789 * This is a wrapper for xml2arrayProcess that adds a two-level cache
1790 *
1791 * @param string $string XML content to convert into an array
1792 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
1793 * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1794 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1795 * @see array2xml(),xml2arrayProcess()
1796 */
1797 public static function xml2array($string, $NSprefix = '', $reportDocTag = false)
1798 {
1799 static $firstLevelCache = [];
1800 $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
1801 // Look up in first level cache
1802 if (!empty($firstLevelCache[$identifier])) {
1803 $array = $firstLevelCache[$identifier];
1804 } else {
1805 $array = self::xml2arrayProcess(trim($string), $NSprefix, $reportDocTag);
1806 // Store content in first level cache
1807 $firstLevelCache[$identifier] = $array;
1808 }
1809 return $array;
1810 }
1811
1812 /**
1813 * Converts an XML string to a PHP array.
1814 * This is the reverse function of array2xml()
1815 *
1816 * @param string $string XML content to convert into an array
1817 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
1818 * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1819 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1820 * @see array2xml()
1821 */
1822 protected static function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = false)
1823 {
1824 // Disables the functionality to allow external entities to be loaded when parsing the XML, must be kept
1825 $previousValueOfEntityLoader = libxml_disable_entity_loader(true);
1826 // Create parser:
1827 $parser = xml_parser_create();
1828 $vals = [];
1829 $index = [];
1830 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1831 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1832 // Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
1833 $match = [];
1834 preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
1835 $theCharset = $match[1] ?: 'utf-8';
1836 // us-ascii / utf-8 / iso-8859-1
1837 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);
1838 // Parse content:
1839 xml_parse_into_struct($parser, $string, $vals, $index);
1840 libxml_disable_entity_loader($previousValueOfEntityLoader);
1841 // If error, return error message:
1842 if (xml_get_error_code($parser)) {
1843 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1844 }
1845 xml_parser_free($parser);
1846 // Init vars:
1847 $stack = [[]];
1848 $stacktop = 0;
1849 $current = [];
1850 $tagName = '';
1851 $documentTag = '';
1852 // Traverse the parsed XML structure:
1853 foreach ($vals as $key => $val) {
1854 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
1855 $tagName = $val['tag'];
1856 if (!$documentTag) {
1857 $documentTag = $tagName;
1858 }
1859 // Test for name space:
1860 $tagName = $NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix ? substr($tagName, strlen($NSprefix)) : $tagName;
1861 // Test for numeric tag, encoded on the form "nXXX":
1862 $testNtag = substr($tagName, 1);
1863 // Closing tag.
1864 $tagName = $tagName[0] === 'n' && MathUtility::canBeInterpretedAsInteger($testNtag) ? (int)$testNtag : $tagName;
1865 // Test for alternative index value:
1866 if ((string)($val['attributes']['index'] ?? '') !== '') {
1867 $tagName = $val['attributes']['index'];
1868 }
1869 // Setting tag-values, manage stack:
1870 switch ($val['type']) {
1871 case 'open':
1872 // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
1873 // Setting blank place holder
1874 $current[$tagName] = [];
1875 $stack[$stacktop++] = $current;
1876 $current = [];
1877 break;
1878 case 'close':
1879 // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
1880 $oldCurrent = $current;
1881 $current = $stack[--$stacktop];
1882 // Going to the end of array to get placeholder key, key($current), and fill in array next:
1883 end($current);
1884 $current[key($current)] = $oldCurrent;
1885 unset($oldCurrent);
1886 break;
1887 case 'complete':
1888 // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
1889 if ($val['attributes']['base64']) {
1890 $current[$tagName] = base64_decode($val['value']);
1891 } else {
1892 // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
1893 $current[$tagName] = (string)$val['value'];
1894 // Cast type:
1895 switch ((string)$val['attributes']['type']) {
1896 case 'integer':
1897 $current[$tagName] = (int)$current[$tagName];
1898 break;
1899 case 'double':
1900 $current[$tagName] = (double) $current[$tagName];
1901 break;
1902 case 'boolean':
1903 $current[$tagName] = (bool)$current[$tagName];
1904 break;
1905 case 'NULL':
1906 $current[$tagName] = null;
1907 break;
1908 case 'array':
1909 // MUST be an empty array since it is processed as a value; Empty arrays would end up here because they would have no tags inside...
1910 $current[$tagName] = [];
1911 break;
1912 }
1913 }
1914 break;
1915 }
1916 }
1917 if ($reportDocTag) {
1918 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
1919 }
1920 // Finally return the content of the document tag.
1921 return $current[$tagName];
1922 }
1923
1924 /**
1925 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
1926 *
1927 * @param array $vals An array of XML parts, see xml2tree
1928 * @return string Re-compiled XML data.
1929 */
1930 public static function xmlRecompileFromStructValArray(array $vals)
1931 {
1932 $XMLcontent = '';
1933 foreach ($vals as $val) {
1934 $type = $val['type'];
1935 // Open tag:
1936 if ($type === 'open' || $type === 'complete') {
1937 $XMLcontent .= '<' . $val['tag'];
1938 if (isset($val['attributes'])) {
1939 foreach ($val['attributes'] as $k => $v) {
1940 $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
1941 }
1942 }
1943 if ($type === 'complete') {
1944 if (isset($val['value'])) {
1945 $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
1946 } else {
1947 $XMLcontent .= '/>';
1948 }
1949 } else {
1950 $XMLcontent .= '>';
1951 }
1952 if ($type === 'open' && isset($val['value'])) {
1953 $XMLcontent .= htmlspecialchars($val['value']);
1954 }
1955 }
1956 // Finish tag:
1957 if ($type === 'close') {
1958 $XMLcontent .= '</' . $val['tag'] . '>';
1959 }
1960 // Cdata
1961 if ($type === 'cdata') {
1962 $XMLcontent .= htmlspecialchars($val['value']);
1963 }
1964 }
1965 return $XMLcontent;
1966 }
1967
1968 /**
1969 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
1970 *
1971 * @param string $xmlData XML data
1972 * @return array Attributes of the xml prologue (header)
1973 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9.
1974 */
1975 public static function xmlGetHeaderAttribs($xmlData)
1976 {
1977 self::logDeprecatedFunction();
1978 $match = [];
1979 if (preg_match('/^\\s*<\\?xml([^>]*)\\?\\>/', $xmlData, $match)) {
1980 return self::get_tag_attributes($match[1]);
1981 }
1982 }
1983
1984 /**
1985 * Minifies JavaScript
1986 *
1987 * @param string $script Script to minify
1988 * @param string $error Error message (if any)
1989 * @return string Minified script or source string if error happened
1990 */
1991 public static function minifyJavaScript($script, &$error = '')
1992 {
1993 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'])) {
1994 $fakeThis = false;
1995 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'] as $hookMethod) {
1996 try {
1997 $parameters = ['script' => $script];
1998 $script = static::callUserFunction($hookMethod, $parameters, $fakeThis);
1999 } catch (\Exception $e) {
2000 $errorMessage = 'Error minifying java script: ' . $e->getMessage();
2001 $error .= $errorMessage;
2002 static::devLog($errorMessage, \TYPO3\CMS\Core\Utility\GeneralUtility::class, 2, [
2003 'JavaScript' => $script,
2004 'Stack trace' => $e->getTrace(),
2005 'hook' => $hookMethod
2006 ]);
2007 }
2008 }
2009 }
2010 return $script;
2011 }
2012
2013 /*************************
2014 *
2015 * FILES FUNCTIONS
2016 *
2017 *************************/
2018 /**
2019 * Reads the file or url $url and returns the content
2020 * If you are having trouble with proxies when reading URLs you can configure your way out of that with settings within $GLOBALS['TYPO3_CONF_VARS']['HTTP'].
2021 *
2022 * @param string $url File/URL to read
2023 * @param int $includeHeader Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2024 * @param array $requestHeaders HTTP headers to be used in the request
2025 * @param array $report Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2026 * @return mixed The content from the resource given as input. FALSE if an error has occurred.
2027 */
2028 public static function getUrl($url, $includeHeader = 0, $requestHeaders = null, &$report = null)
2029 {
2030 if (isset($report)) {
2031 $report['error'] = 0;
2032 $report['message'] = '';
2033 }
2034 // Looks like it's an external file, use Guzzle by default
2035 if (preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2036 /** @var RequestFactory $requestFactory */
2037 $requestFactory = static::makeInstance(RequestFactory::class);
2038 if (is_array($requestHeaders)) {
2039 $configuration = ['headers' => $requestHeaders];
2040 } else {
2041 $configuration = [];
2042 }
2043
2044 try {
2045 if (isset($report)) {
2046 $report['lib'] = 'GuzzleHttp';
2047 }
2048 $response = $requestFactory->request($url, 'GET', $configuration);
2049 } catch (RequestException $exception) {
2050 if (isset($report)) {
2051 $report['error'] = $exception->getCode();
2052 $report['message'] = $exception->getMessage();
2053 $report['exception'] = $exception;
2054 }
2055 return false;
2056 }
2057
2058 $content = '';
2059
2060 // Add the headers to the output
2061 $includeHeader = (int)$includeHeader;
2062 if ($includeHeader) {
2063 $parsedURL = parse_url($url);
2064 $method = $includeHeader === 2 ? 'HEAD' : 'GET';
2065 $content = $method . ' ' . (isset($parsedURL['path']) ? $parsedURL['path'] : '/')
2066 . ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') . ' HTTP/1.0' . CRLF
2067 . 'Host: ' . $parsedURL['host'] . CRLF
2068 . 'Connection: close' . CRLF;
2069 if (is_array($requestHeaders)) {
2070 $content .= implode(CRLF, $requestHeaders) . CRLF;
2071 }
2072 foreach ($response->getHeaders() as $headerName => $headerValues) {
2073 $content .= $headerName . ': ' . implode(', ', $headerValues) . CRLF;
2074 }
2075 // Headers are separated from the body with two CRLFs
2076 $content .= CRLF;
2077 }
2078 // If not just headers are requested, add the body
2079 if ($includeHeader !== 2) {
2080 $content .= $response->getBody()->getContents();
2081 }
2082 if (isset($report)) {
2083 $report['lib'] = 'http';
2084 if ($response->getStatusCode() >= 300 && $response->getStatusCode() < 400) {
2085 $report['http_code'] = $response->getStatusCode();
2086 $report['content_type'] = $response->getHeader('Content-Type');
2087 $report['error'] = $response->getStatusCode();
2088 $report['message'] = $response->getReasonPhrase();
2089 } elseif (empty($content)) {
2090 $report['error'] = $response->getStatusCode();
2091 $report['message'] = $response->getReasonPhrase();
2092 } elseif ($includeHeader) {
2093 // Set only for $includeHeader to work exactly like PHP variant
2094 $report['http_code'] = $response->getStatusCode();
2095 $report['content_type'] = $response->getHeader('Content-Type');
2096 }
2097 }
2098 } else {
2099 if (isset($report)) {
2100 $report['lib'] = 'file';
2101 }
2102 $content = @file_get_contents($url);
2103 if ($content === false && isset($report)) {
2104 $report['error'] = -1;
2105 $report['message'] = 'Couldn\'t get URL: ' . $url;
2106 }
2107 }
2108 return $content;
2109 }
2110
2111 /**
2112 * Writes $content to the file $file
2113 *
2114 * @param string $file Filepath to write to
2115 * @param string $content Content to write
2116 * @param bool $changePermissions If TRUE, permissions are forced to be set
2117 * @return bool TRUE if the file was successfully opened and written to.
2118 */
2119 public static function writeFile($file, $content, $changePermissions = false)
2120 {
2121 if (!@is_file($file)) {
2122 $changePermissions = true;
2123 }
2124 if ($fd = fopen($file, 'wb')) {
2125 $res = fwrite($fd, $content);
2126 fclose($fd);
2127 if ($res === false) {
2128 return false;
2129 }
2130 // Change the permissions only if the file has just been created
2131 if ($changePermissions) {
2132 static::fixPermissions($file);
2133 }
2134 return true;
2135 }
2136 return false;
2137 }
2138
2139 /**
2140 * Sets the file system mode and group ownership of a file or a folder.
2141 *
2142 * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
2143 * @param bool $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
2144 * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
2145 */
2146 public static function fixPermissions($path, $recursive = false)
2147 {
2148 if (TYPO3_OS === 'WIN') {
2149 return true;
2150 }
2151 $result = false;
2152 // Make path absolute
2153 if (!static::isAbsPath($path)) {
2154 $path = static::getFileAbsFileName($path);
2155 }
2156 if (static::isAllowedAbsPath($path)) {
2157 if (@is_file($path)) {
2158 $targetPermissions = isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask'])
2159 ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['fileCreateMask']
2160 : '0644';
2161 } elseif (@is_dir($path)) {
2162 $targetPermissions = isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'])
2163 ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']
2164 : '0755';
2165 }
2166 if (!empty($targetPermissions)) {
2167 // make sure it's always 4 digits
2168 $targetPermissions = str_pad($targetPermissions, 4, 0, STR_PAD_LEFT);
2169 $targetPermissions = octdec($targetPermissions);
2170 // "@" is there because file is not necessarily OWNED by the user
2171 $result = @chmod($path, $targetPermissions);
2172 }
2173 // Set createGroup if not empty
2174 if (
2175 isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'])
2176 && $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup'] !== ''
2177 ) {
2178 // "@" is there because file is not necessarily OWNED by the user
2179 $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']);
2180 $result = $changeGroupResult ? $result : false;
2181 }
2182 // Call recursive if recursive flag if set and $path is directory
2183 if ($recursive && @is_dir($path)) {
2184 $handle = opendir($path);
2185 if (is_resource($handle)) {
2186 while (($file = readdir($handle)) !== false) {
2187 $recursionResult = null;
2188 if ($file !== '.' && $file !== '..') {
2189 if (@is_file(($path . '/' . $file))) {
2190 $recursionResult = static::fixPermissions($path . '/' . $file);
2191 } elseif (@is_dir(($path . '/' . $file))) {
2192 $recursionResult = static::fixPermissions($path . '/' . $file, true);
2193 }
2194 if (isset($recursionResult) && !$recursionResult) {
2195 $result = false;
2196 }
2197 }
2198 }
2199 closedir($handle);
2200 }
2201 }
2202 }
2203 return $result;
2204 }
2205
2206 /**
2207 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2208 * Accepts an additional subdirectory in the file path!
2209 *
2210 * @param string $filepath Absolute file path to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2211 * @param string $content Content string to write
2212 * @return string Returns NULL on success, otherwise an error string telling about the problem.
2213 */
2214 public static function writeFileToTypo3tempDir($filepath, $content)
2215 {
2216 // Parse filepath into directory and basename:
2217 $fI = pathinfo($filepath);
2218 $fI['dirname'] .= '/';
2219 // Check parts:
2220 if (!static::validPathStr($filepath) || !$fI['basename'] || strlen($fI['basename']) >= 60) {
2221 return 'Input filepath "' . $filepath . '" was generally invalid!';
2222 }
2223 // Setting main temporary directory name (standard)
2224 $dirName = PATH_site . 'typo3temp/';
2225 if (!@is_dir($dirName)) {
2226 return 'PATH_site + "typo3temp/" was not a directory!';
2227 }
2228 if (!static::isFirstPartOfStr($fI['dirname'], $dirName)) {
2229 return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
2230 }
2231 // Checking if the "subdir" is found:
2232 $subdir = substr($fI['dirname'], strlen($dirName));
2233 if ($subdir) {
2234 if (preg_match('#^(?:[[:alnum:]_]+/)+$#', $subdir)) {
2235 $dirName .= $subdir;
2236 if (!@is_dir($dirName)) {
2237 static::mkdir_deep(PATH_site . 'typo3temp/', $subdir);
2238 }
2239 } else {
2240 return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/+"';
2241 }
2242 }
2243 // Checking dir-name again (sub-dir might have been created):
2244 if (@is_dir($dirName)) {
2245 if ($filepath === $dirName . $fI['basename']) {
2246 static::writeFile($filepath, $content);
2247 if (!@is_file($filepath)) {
2248 return 'The file was not written to the disk. Please, check that you have write permissions to the typo3temp/ directory.';
2249 }
2250 } else {
2251 return 'Calculated file location didn\'t match input "' . $filepath . '".';
2252 }
2253 } else {
2254 return '"' . $dirName . '" is not a directory!';
2255 }
2256 return null;
2257 }
2258
2259 /**
2260 * Wrapper function for mkdir.
2261 * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']
2262 * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']
2263 *
2264 * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2265 * @return bool TRUE if @mkdir went well!
2266 */
2267 public static function mkdir($newFolder)
2268 {
2269 $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']));
2270 if ($result) {
2271 static::fixPermissions($newFolder);
2272 }
2273 return $result;
2274 }
2275
2276 /**
2277 * Creates a directory - including parent directories if necessary and
2278 * sets permissions on newly created directories.
2279 *
2280 * @param string $directory Target directory to create. Must a have trailing slash
2281 * @param string $deepDirectory Directory to create. This second parameter
2282 * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
2283 * @throws \RuntimeException If directory could not be created
2284 */
2285 public static function mkdir_deep($directory, $deepDirectory = '')
2286 {
2287 if (!is_string($directory)) {
2288 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($directory) . '" but a string is expected.', 1303662955);
2289 }
2290 if (!is_string($deepDirectory)) {
2291 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.', 1303662956);
2292 }
2293 // Ensure there is only one slash
2294 $fullPath = rtrim($directory, '/') . '/' . ltrim($deepDirectory, '/');
2295 if ($fullPath !== '/' && !is_dir($fullPath)) {
2296 $firstCreatedPath = static::createDirectoryPath($fullPath);
2297 if ($firstCreatedPath !== '') {
2298 static::fixPermissions($firstCreatedPath, true);
2299 }
2300 }
2301 }
2302
2303 /**
2304 * Creates directories for the specified paths if they do not exist. This
2305 * functions sets proper permission mask but does not set proper user and
2306 * group.
2307 *
2308 * @static
2309 * @param string $fullDirectoryPath
2310 * @return string Path to the the first created directory in the hierarchy
2311 * @see \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep
2312 * @throws \RuntimeException If directory could not be created
2313 */
2314 protected static function createDirectoryPath($fullDirectoryPath)
2315 {
2316 $currentPath = $fullDirectoryPath;
2317 $firstCreatedPath = '';
2318 $permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask']);
2319 if (!@is_dir($currentPath)) {
2320 do {
2321 $firstCreatedPath = $currentPath;
2322 $separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR);
2323 $currentPath = substr($currentPath, 0, $separatorPosition);
2324 } while (!is_dir($currentPath) && $separatorPosition !== false);
2325 $result = @mkdir($fullDirectoryPath, $permissionMask, true);
2326 // Check existence of directory again to avoid race condition. Directory could have get created by another process between previous is_dir() and mkdir()
2327 if (!$result && !@is_dir($fullDirectoryPath)) {
2328 throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251401);
2329 }
2330 }
2331 return $firstCreatedPath;
2332 }
2333
2334 /**
2335 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2336 *
2337 * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2338 * @param bool $removeNonEmpty Allow deletion of non-empty directories
2339 * @return bool TRUE if @rmdir went well!
2340 */
2341 public static function rmdir($path, $removeNonEmpty = false)
2342 {
2343 $OK = false;
2344 // Remove trailing slash
2345 $path = preg_replace('|/$|', '', $path);
2346 if (file_exists($path)) {
2347 $OK = true;
2348 if (!is_link($path) && is_dir($path)) {
2349 if ($removeNonEmpty == true && ($handle = @opendir($path))) {
2350 while ($OK && false !== ($file = readdir($handle))) {
2351 if ($file === '.' || $file === '..') {
2352 continue;
2353 }
2354 $OK = static::rmdir($path . '/' . $file, $removeNonEmpty);
2355 }
2356 closedir($handle);
2357 }
2358 if ($OK) {
2359 $OK = @rmdir($path);
2360 }
2361 } elseif (is_link($path) && is_dir($path) && TYPO3_OS === 'WIN') {
2362 $OK = @rmdir($path);
2363 } else {
2364 // If $path is a file, simply remove it
2365 $OK = @unlink($path);
2366 }
2367 clearstatcache();
2368 } elseif (is_link($path)) {
2369 $OK = @unlink($path);
2370 if (!$OK && TYPO3_OS === 'WIN') {
2371 // Try to delete dead folder links on Windows systems
2372 $OK = @rmdir($path);
2373 }
2374 clearstatcache();
2375 }
2376 return $OK;
2377 }
2378
2379 /**
2380 * Flushes a directory by first moving to a temporary resource, and then
2381 * triggering the remove process. This way directories can be flushed faster
2382 * to prevent race conditions on concurrent processes accessing the same directory.
2383 *
2384 * @param string $directory The directory to be renamed and flushed
2385 * @param bool $keepOriginalDirectory Whether to only empty the directory and not remove it
2386 * @param bool $flushOpcodeCache Also flush the opcode cache right after renaming the directory.
2387 * @return bool Whether the action was successful
2388 */
2389 public static function flushDirectory($directory, $keepOriginalDirectory = false, $flushOpcodeCache = false)
2390 {
2391 $result = false;
2392
2393 if (is_dir($directory)) {
2394 $temporaryDirectory = rtrim($directory, '/') . '.' . StringUtility::getUniqueId('remove') . '/';
2395 if (rename($directory, $temporaryDirectory)) {
2396 if ($flushOpcodeCache) {
2397 self::makeInstance(OpcodeCacheService::class)->clearAllActive($directory);
2398 }
2399 if ($keepOriginalDirectory) {
2400 static::mkdir($directory);
2401 }
2402 clearstatcache();
2403 $result = static::rmdir($temporaryDirectory, true);
2404 }
2405 }
2406
2407 return $result;
2408 }
2409
2410 /**
2411 * Returns an array with the names of folders in a specific path
2412 * Will return 'error' (string) if there were an error with reading directory content.
2413 *
2414 * @param string $path Path to list directories from
2415 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2416 */
2417 public static function get_dirs($path)
2418 {
2419 $dirs = null;
2420 if ($path) {
2421 if (is_dir($path)) {
2422 $dir = scandir($path);
2423 $dirs = [];
2424 foreach ($dir as $entry) {
2425 if (is_dir($path . '/' . $entry) && $entry !== '..' && $entry !== '.') {
2426 $dirs[] = $entry;
2427 }
2428 }
2429 } else {
2430 $dirs = 'error';
2431 }
2432 }
2433 return $dirs;
2434 }
2435
2436 /**
2437 * Finds all files in a given path and returns them as an array. Each
2438 * array key is a md5 hash of the full path to the file. This is done because
2439 * 'some' extensions like the import/export extension depend on this.
2440 *
2441 * @param string $path The path to retrieve the files from.
2442 * @param string $extensionList A comma-separated list of file extensions. Only files of the specified types will be retrieved. When left blank, files of any type will be retrieved.
2443 * @param bool $prependPath If TRUE, the full path to the file is returned. If FALSE only the file name is returned.
2444 * @param string $order The sorting order. The default sorting order is alphabetical. Setting $order to 'mtime' will sort the files by modification time.
2445 * @param string $excludePattern A regular expression pattern of file names to exclude. For example: 'clear.gif' or '(clear.gif|.htaccess)'. The pattern will be wrapped with: '/^' and '$/'.
2446 * @return array|string Array of the files found, or an error message in case the path could not be opened.
2447 */
2448 public static function getFilesInDir($path, $extensionList = '', $prependPath = false, $order = '', $excludePattern = '')
2449 {
2450 $excludePattern = (string)$excludePattern;
2451 $path = rtrim($path, '/');
2452 if (!@is_dir($path)) {
2453 return [];
2454 }
2455
2456 $rawFileList = scandir($path);
2457 if ($rawFileList === false) {
2458 return 'error opening path: "' . $path . '"';
2459 }
2460
2461 $pathPrefix = $path . '/';
2462 $allowedFileExtensionArray = self::trimExplode(',', $extensionList);
2463 $extensionList = ',' . str_replace(' ', '', $extensionList) . ',';
2464 $files = [];
2465 foreach ($rawFileList as $entry) {
2466 $completePathToEntry = $pathPrefix . $entry;
2467 if (!@is_file($completePathToEntry)) {
2468 continue;
2469 }
2470
2471 foreach ($allowedFileExtensionArray as $allowedFileExtension) {
2472 if (
2473 ($extensionList === ',,' || stripos($extensionList, ',' . substr($entry, strlen($allowedFileExtension)*-1, strlen($allowedFileExtension)) . ',') !== false)
2474 && ($excludePattern === '' || !preg_match(('/^' . $excludePattern . '$/'), $entry))
2475 ) {
2476 if ($order !== 'mtime') {
2477 $files[] = $entry;
2478 } else {
2479 // Store the value in the key so we can do a fast asort later.
2480 $files[$entry] = filemtime($completePathToEntry);
2481 }
2482 }
2483 }
2484 }
2485
2486 $valueName = 'value';
2487 if ($order === 'mtime') {
2488 asort($files);
2489 $valueName = 'key';
2490 }
2491
2492 $valuePathPrefix = $prependPath ? $pathPrefix : '';
2493 $foundFiles = [];
2494 foreach ($files as $key => $value) {
2495 // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
2496 $foundFiles[md5($pathPrefix . ${$valueName})] = $valuePathPrefix . ${$valueName};
2497 }
2498
2499 return $foundFiles;
2500 }
2501
2502 /**
2503 * Recursively gather all files and folders of a path.
2504 *
2505 * @param array $fileArr Empty input array (will have files added to it)
2506 * @param string $path The path to read recursively from (absolute) (include trailing slash!)
2507 * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2508 * @param bool $regDirs If set, directories are also included in output.
2509 * @param int $recursivityLevels The number of levels to dig down...
2510 * @param string $excludePattern regex pattern of files/directories to exclude
2511 * @return array An array with the found files/directories.
2512 */
2513 public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = false, $recursivityLevels = 99, $excludePattern = '')
2514 {
2515 if ($regDirs) {
2516 $fileArr[md5($path)] = $path;
2517 }
2518 $fileArr = array_merge($fileArr, self::getFilesInDir($path, $extList, 1, 1, $excludePattern));
2519 $dirs = self::get_dirs($path);
2520 if ($recursivityLevels > 0 && is_array($dirs)) {
2521 foreach ($dirs as $subdirs) {
2522 if ((string)$subdirs !== '' && ($excludePattern === '' || !preg_match(('/^' . $excludePattern . '$/'), $subdirs))) {
2523 $fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
2524 }
2525 }
2526 }
2527 return $fileArr;
2528 }
2529
2530 /**
2531 * Removes the absolute part of all files/folders in fileArr
2532 *
2533 * @param array $fileArr The file array to remove the prefix from
2534 * @param string $prefixToRemove The prefix path to remove (if found as first part of string!)
2535 * @return array The input $fileArr processed.
2536 */
2537 public static function removePrefixPathFromList(array $fileArr, $prefixToRemove)
2538 {
2539 foreach ($fileArr as $k => &$absFileRef) {
2540 if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
2541 $absFileRef = substr($absFileRef, strlen($prefixToRemove));
2542 } else {
2543 return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2544 }
2545 }
2546 unset($absFileRef);
2547 return $fileArr;
2548 }
2549
2550 /**
2551 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2552 *
2553 * @param string $theFile File path to process
2554 * @return string
2555 */
2556 public static function fixWindowsFilePath($theFile)
2557 {
2558 return str_replace(['\\', '//'], '/', $theFile);
2559 }
2560
2561 /**
2562 * Resolves "../" sections in the input path string.
2563 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2564 *
2565 * @param string $pathStr File path in which "/../" is resolved
2566 * @return string
2567 */
2568 public static function resolveBackPath($pathStr)
2569 {
2570 if (strpos($pathStr, '..') === false) {
2571 return $pathStr;
2572 }
2573 $parts = explode('/', $pathStr);
2574 $output = [];
2575 $c = 0;
2576 foreach ($parts as $part) {
2577 if ($part === '..') {
2578 if ($c) {
2579 array_pop($output);
2580 --$c;
2581 } else {
2582 $output[] = $part;
2583 }
2584 } else {
2585 ++$c;
2586 $output[] = $part;
2587 }
2588 }
2589 return implode('/', $output);
2590 }
2591
2592 /**
2593 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2594 * - If already having a scheme, nothing is prepended
2595 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2596 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2597 *
2598 * @param string $path URL / path to prepend full URL addressing to.
2599 * @return string
2600 */
2601 public static function locationHeaderUrl($path)
2602 {
2603 $uI = parse_url($path);
2604 // relative to HOST
2605 if ($path[0] === '/') {
2606 $path = self::getIndpEnv('TYPO3_REQUEST_HOST') . $path;
2607 } elseif (!$uI['scheme']) {
2608 // No scheme either
2609 $path = self::getIndpEnv('TYPO3_REQUEST_DIR') . $path;
2610 }
2611 return $path;
2612 }
2613
2614 /**
2615 * Returns the maximum upload size for a file that is allowed. Measured in KB.
2616 * This might be handy to find out the real upload limit that is possible for this
2617 * TYPO3 installation.
2618 *
2619 * @return int The maximum size of uploads that are allowed (measured in kilobytes)
2620 */
2621 public static function getMaxUploadFileSize()
2622 {
2623 // Check for PHP restrictions of the maximum size of one of the $_FILES
2624 $phpUploadLimit = self::getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
2625 // Check for PHP restrictions of the maximum $_POST size
2626 $phpPostLimit = self::getBytesFromSizeMeasurement(ini_get('post_max_size'));
2627 // If the total amount of post data is smaller (!) than the upload_max_filesize directive,
2628 // then this is the real limit in PHP
2629 $phpUploadLimit = $phpPostLimit > 0 && $phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit;
2630 return floor(($phpUploadLimit)) / 1024;
2631 }
2632
2633 /**
2634 * Gets the bytes value from a measurement string like "100k".
2635 *
2636 * @param string $measurement The measurement (e.g. "100k")
2637 * @return int The bytes value (e.g. 102400)
2638 */
2639 public static function getBytesFromSizeMeasurement($measurement)
2640 {
2641 $bytes = (float)$measurement;
2642 if (stripos($measurement, 'G')) {
2643 $bytes *= 1024 * 1024 * 1024;
2644 } elseif (stripos($measurement, 'M')) {
2645 $bytes *= 1024 * 1024;
2646 } elseif (stripos($measurement, 'K')) {
2647 $bytes *= 1024;
2648 }
2649 return $bytes;
2650 }
2651
2652 /**
2653 * Retrieves the maximum path length that is valid in the current environment.
2654 *
2655 * @return int The maximum available path length
2656 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
2657 */
2658 public static function getMaximumPathLength()
2659 {
2660 static::logDeprecatedFunction();
2661 return PHP_MAXPATHLEN;
2662 }
2663
2664 /**
2665 * Function for static version numbers on files, based on the filemtime
2666 *
2667 * This will make the filename automatically change when a file is
2668 * changed, and by that re-cached by the browser. If the file does not
2669 * exist physically the original file passed to the function is
2670 * returned without the timestamp.
2671 *
2672 * Behaviour is influenced by the setting
2673 * TYPO3_CONF_VARS[TYPO3_MODE][versionNumberInFilename]
2674 * = TRUE (BE) / "embed" (FE) : modify filename
2675 * = FALSE (BE) / "querystring" (FE) : add timestamp as parameter
2676 *
2677 * @param string $file Relative path to file including all potential query parameters (not htmlspecialchared yet)
2678 * @return string Relative path with version filename including the timestamp
2679 */
2680 public static function createVersionNumberedFilename($file)
2681 {
2682 $lookupFile = explode('?', $file);
2683 $path = self::resolveBackPath(self::dirname(PATH_thisScript) . '/' . $lookupFile[0]);
2684
2685 $doNothing = false;
2686 if (TYPO3_MODE === 'FE') {
2687 $mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']);
2688 if ($mode === 'embed') {
2689 $mode = true;
2690 } else {
2691 if ($mode === 'querystring') {
2692 $mode = false;
2693 } else {
2694 $doNothing = true;
2695 }
2696 }
2697 } else {
2698 $mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename'];
2699 }
2700 if ($doNothing || !file_exists($path)) {
2701 // File not found, return filename unaltered
2702 $fullName = $file;
2703 } else {
2704 if (!$mode) {
2705 // If use of .htaccess rule is not configured,
2706 // we use the default query-string method
2707 if ($lookupFile[1]) {
2708 $separator = '&';
2709 } else {
2710 $separator = '?';
2711 }
2712 $fullName = $file . $separator . filemtime($path);
2713 } else {
2714 // Change the filename
2715 $name = explode('.', $lookupFile[0]);
2716 $extension = array_pop($name);
2717 array_push($name, filemtime($path), $extension);
2718 $fullName = implode('.', $name);
2719 // Append potential query string
2720 $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
2721 }
2722 }
2723 return $fullName;
2724 }
2725
2726 /*************************
2727 *
2728 * SYSTEM INFORMATION
2729 *
2730 *************************/
2731
2732 /**
2733 * Returns the link-url to the current script.
2734 * In $getParams you can set associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL.
2735 * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
2736 *
2737 * @param array $getParams Array of GET parameters to include
2738 * @return string
2739 */
2740 public static function linkThisScript(array $getParams = [])
2741 {
2742 $parts = self::getIndpEnv('SCRIPT_NAME');
2743 $params = self::_GET();
2744 foreach ($getParams as $key => $value) {
2745 if ($value !== '') {
2746 $params[$key] = $value;
2747 } else {
2748 unset($params[$key]);
2749 }
2750 }
2751 $pString = self::implodeArrayForUrl('', $params);
2752 return $pString ? $parts . '?' . ltrim($pString, '&') : $parts;
2753 }
2754
2755 /**
2756 * Takes a full URL, $url, possibly with a querystring and overlays the $getParams arrays values onto the quirystring, packs it all together and returns the URL again.
2757 * So basically it adds the parameters in $getParams to an existing URL, $url
2758 *
2759 * @param string $url URL string
2760 * @param array $getParams Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
2761 * @return string Output URL with added getParams.
2762 */
2763 public static function linkThisUrl($url, array $getParams = [])
2764 {
2765 $parts = parse_url($url);
2766 $getP = [];
2767 if ($parts['query']) {
2768 parse_str($parts['query'], $getP);
2769 }
2770 ArrayUtility::mergeRecursiveWithOverrule($getP, $getParams);
2771 $uP = explode('?', $url);
2772 $params = self::implodeArrayForUrl('', $getP);
2773 $outurl = $uP[0] . ($params ? '?' . substr($params, 1) : '');
2774 return $outurl;
2775 }
2776
2777 /**
2778 * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
2779 * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
2780 *
2781 * @param string $getEnvName Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY
2782 * @return string Value based on the input key, independent of server/os environment.
2783 * @throws \UnexpectedValueException
2784 */
2785 public static function getIndpEnv($getEnvName)
2786 {
2787 if (isset(self::$indpEnvCache[$getEnvName])) {
2788 return self::$indpEnvCache[$getEnvName];
2789 }
2790
2791 /*
2792 Conventions:
2793 output from parse_url():
2794 URL: http://username:password@192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1
2795 [scheme] => 'http'
2796 [user] => 'username'
2797 [pass] => 'password'
2798 [host] => '192.168.1.4'
2799 [port] => '8080'
2800 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
2801 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
2802 [fragment] => 'link1'Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
2803 [path_dir] = '/typo3/32/temp/phpcheck/'
2804 [path_info] = '/arg1/arg2/arg3/'
2805 [path] = [path_script/path_dir][path_info]Keys supported:URI______:
2806 REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2807 HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
2808 SCRIPT_NAME = [path_script]++ = /typo3/32/temp/phpcheck/index.php // NOTICE THAT SCRIPT_NAME will return the php-script name ALSO. [path_script] may not do that (eg. '/somedir/' may result in SCRIPT_NAME '/somedir/index.php')!
2809 PATH_INFO = [path_info] = /arg1/arg2/arg3/
2810 QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
2811 HTTP_REFERER = [scheme]://[host][:[port]][path] = http://192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2812 (Notice: NO username/password + NO fragment)CLIENT____:
2813 REMOTE_ADDR = (client IP)
2814 REMOTE_HOST = (client host)
2815 HTTP_USER_AGENT = (client user agent)
2816 HTTP_ACCEPT_LANGUAGE = (client accept language)SERVER____:
2817 SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'Special extras:
2818 TYPO3_HOST_ONLY = [host] = 192.168.1.4
2819 TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
2820 TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
2821 TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
2822 TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
2823 TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
2824 TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
2825 TYPO3_SITE_PATH = [path_dir] of the TYPO3 website frontend
2826 TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
2827 TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
2828 TYPO3_SSL = Returns TRUE if this session uses SSL/TLS (https)
2829 TYPO3_PROXY = Returns TRUE if this session runs over a well known proxyNotice: [fragment] is apparently NEVER available to the script!Testing suggestions:
2830 - Output all the values.
2831 - In the script, make a link to the script it self, maybe add some parameters and click the link a few times so HTTP_REFERER is seen
2832 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
2833 */
2834 $retVal = '';
2835 switch ((string)$getEnvName) {
2836 case 'SCRIPT_NAME':
2837 $retVal = self::isRunningOnCgiServerApi()
2838 && ($_SERVER['ORIG_PATH_INFO'] ?: $_SERVER['PATH_INFO'])
2839 ? ($_SERVER['ORIG_PATH_INFO'] ?: $_SERVER['PATH_INFO'])
2840 : ($_SERVER['ORIG_SCRIPT_NAME'] ?: $_SERVER['SCRIPT_NAME']);
2841 // Add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
2842 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
2843 if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
2844 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
2845 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
2846 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
2847 }
2848 }
2849 break;
2850 case 'SCRIPT_FILENAME':
2851 $retVal = PATH_thisScript;
2852 break;
2853 case 'REQUEST_URI':
2854 // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(\TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('REQUEST_URI'))
2855 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']) {
2856 // This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL)
2857 list($v, $n) = explode('|', $GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
2858 $retVal = $GLOBALS[$v][$n];
2859 } elseif (!$_SERVER['REQUEST_URI']) {
2860 // This is for ISS/CGI which does not have the REQUEST_URI available.
2861 $retVal = '/' . ltrim(self::getIndpEnv('SCRIPT_NAME'), '/') . ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '');
2862 } else {
2863 $retVal = '/' . ltrim($_SERVER['REQUEST_URI'], '/');
2864 }
2865 // Add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
2866 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
2867 if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
2868 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
2869 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
2870 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
2871 }
2872 }
2873 break;
2874 case 'PATH_INFO':
2875 // $_SERVER['PATH_INFO'] != $_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI)
2876 // are seen to set PATH_INFO equal to script_name
2877 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
2878 // IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers,
2879 // then 'PHP_SAPI=='cgi'' might be a better check.
2880 // Right now strcmp($_SERVER['PATH_INFO'], GeneralUtility::getIndpEnv('SCRIPT_NAME')) will always
2881 // return FALSE for CGI-versions, but that is only as long as SCRIPT_NAME is set equal to PATH_INFO
2882 // because of PHP_SAPI=='cgi' (see above)
2883 if (!self::isRunningOnCgiServerApi()) {
2884 $retVal = $_SERVER['PATH_INFO'];
2885 }
2886 break;
2887 case 'TYPO3_REV_PROXY':
2888 $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
2889 break;
2890 case 'REMOTE_ADDR':
2891 $retVal = $_SERVER['REMOTE_ADDR'];
2892 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
2893 $ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
2894 // Choose which IP in list to use
2895 if (!empty($ip)) {
2896 switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
2897 case 'last':
2898 $ip = array_pop($ip);
2899 break;
2900 case 'first':
2901 $ip = array_shift($ip);
2902 break;
2903 case 'none':
2904
2905 default:
2906 $ip = '';
2907 }
2908 }
2909 if (self::validIP($ip)) {
2910 $retVal = $ip;
2911 }
2912 }
2913 break;
2914 case 'HTTP_HOST':
2915 // if it is not set we're most likely on the cli
2916 $retVal = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
2917 if (isset($_SERVER['REMOTE_ADDR']) && static::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
2918 $host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
2919 // Choose which host in list to use
2920 if (!empty($host)) {
2921 switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
2922 case 'last':
2923 $host = array_pop($host);
2924 break;
2925 case 'first':
2926 $host = array_shift($host);
2927 break;
2928 case 'none':
2929
2930 default:
2931 $host = '';
2932 }
2933 }
2934 if ($host) {
2935 $retVal = $host;
2936 }
2937 }
2938 if (!static::isAllowedHostHeaderValue($retVal)) {
2939 throw new \UnexpectedValueException(
2940 'The current host header value does not match the configured trusted hosts pattern! Check the pattern defined in $GLOBALS[\'TYPO3_CONF_VARS\'][\'SYS\'][\'trustedHostsPattern\'] and adapt it, if you want to allow the current host header \'' . $retVal . '\' for your installation.',
2941 1396795884
2942 );
2943 }
2944 break;
2945 case 'HTTP_REFERER':
2946
2947 case 'HTTP_USER_AGENT':
2948
2949 case 'HTTP_ACCEPT_ENCODING':
2950
2951 case 'HTTP_ACCEPT_LANGUAGE':
2952
2953 case 'REMOTE_HOST':
2954
2955 case 'QUERY_STRING':
2956 if (isset($_SERVER[$getEnvName])) {
2957 $retVal = $_SERVER[$getEnvName];
2958 }
2959 break;
2960 case 'TYPO3_DOCUMENT_ROOT':
2961 // Get the web root (it is not the root of the TYPO3 installation)
2962 // The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME
2963 // Some CGI-versions (LA13CGI) and mod-rewrite rules on MODULE versions will deliver a 'wrong' DOCUMENT_ROOT (according to our description). Further various aliases/mod_rewrite rules can disturb this as well.
2964 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
2965 $SFN = self::getIndpEnv('SCRIPT_FILENAME');
2966 $SN_A = explode('/', strrev(self::getIndpEnv('SCRIPT_NAME')));
2967 $SFN_A = explode('/', strrev($SFN));
2968 $acc = [];
2969 foreach ($SN_A as $kk => $vv) {
2970 if ((string)$SFN_A[$kk] === (string)$vv) {
2971 $acc[] = $vv;
2972 } else {
2973 break;
2974 }
2975 }
2976 $commonEnd = strrev(implode('/', $acc));
2977 if ((string)$commonEnd !== '') {
2978 $retVal = substr($SFN, 0, -(strlen($commonEnd) + 1));
2979 }
2980 break;
2981 case 'TYPO3_HOST_ONLY':
2982 $httpHost = self::getIndpEnv('HTTP_HOST');
2983 $httpHostBracketPosition = strpos($httpHost, ']');
2984 $httpHostParts = explode(':', $httpHost);
2985 $retVal = $httpHostBracketPosition !== false ? substr($httpHost, 0, $httpHostBracketPosition + 1) : array_shift($httpHostParts);
2986 break;
2987 case 'TYPO3_PORT':
2988 $httpHost = self::getIndpEnv('HTTP_HOST');
2989 $httpHostOnly = self::getIndpEnv('TYPO3_HOST_ONLY');
2990 $retVal = strlen($httpHost) > strlen($httpHostOnly) ? substr($httpHost, strlen($httpHostOnly) + 1) : '';
2991 break;
2992 case 'TYPO3_REQUEST_HOST':
2993 $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://') . self::getIndpEnv('HTTP_HOST');
2994 break;
2995 case 'TYPO3_REQUEST_URL':
2996 $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('REQUEST_URI');
2997 break;
2998 case 'TYPO3_REQUEST_SCRIPT':
2999 $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('SCRIPT_NAME');
3000 break;
3001 case 'TYPO3_REQUEST_DIR':
3002 $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/';
3003 break;
3004 case 'TYPO3_SITE_URL':
3005 $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
3006 // This can only be set by external entry scripts
3007 if (defined('TYPO3_PATH_WEB')) {
3008 $retVal = $url;
3009 } elseif (defined('PATH_thisScript') && defined('PATH_site')) {
3010 $lPath = PathUtility::stripPathSitePrefix(dirname(PATH_thisScript)) . '/';
3011 $siteUrl = substr($url, 0, -strlen($lPath));
3012 if (substr($siteUrl, -1) !== '/') {
3013 $siteUrl .= '/';
3014 }
3015 $retVal = $siteUrl;
3016 }
3017 break;
3018 case 'TYPO3_SITE_PATH':
3019 $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
3020 break;
3021 case 'TYPO3_SITE_SCRIPT':
3022 $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'), strlen(self::getIndpEnv('TYPO3_SITE_URL')));
3023 break;
3024 case 'TYPO3_SSL':
3025 $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']);
3026 if ($proxySSL === '*') {
3027 $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
3028 }
3029 if (self::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL)) {