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