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