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