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