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