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