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