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