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