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