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