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