[BUGFIX] Streamline calls to sysLog
[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 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
876 */
877 static public function modifyHTMLColor($color, $R, $G, $B) {
878 self::logDeprecatedFunction();
879 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
880 $nR = MathUtility::forceIntegerInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
881 $nG = MathUtility::forceIntegerInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
882 $nB = MathUtility::forceIntegerInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
883 return '#' . substr(('0' . dechex($nR)), -2) . substr(('0' . dechex($nG)), -2) . substr(('0' . dechex($nB)), -2);
884 }
885
886 /**
887 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
888 *
889 * @param string $color A hexadecimal color code, #xxxxxx
890 * @param int $all Offset value 0-255 for all three channels.
891 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
892 * @see modifyHTMLColor()
893 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
894 */
895 static public function modifyHTMLColorAll($color, $all) {
896 self::logDeprecatedFunction();
897 return self::modifyHTMLColor($color, $all, $all, $all);
898 }
899
900 /**
901 * Returns TRUE if the first part of $str matches the string $partStr
902 *
903 * @param string $str Full string to check
904 * @param string $partStr Reference string which must be found as the "first part" of the full string
905 * @return bool TRUE if $partStr was found to be equal to the first part of $str
906 */
907 static public function isFirstPartOfStr($str, $partStr) {
908 return $partStr != '' && strpos((string)$str, (string)$partStr, 0) === 0;
909 }
910
911 /**
912 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
913 *
914 * @param int $sizeInBytes Number of bytes to format.
915 * @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".
916 * @param int $base The unit base if not using a unit name. Defaults to 1024.
917 * @return string Formatted representation of the byte number, for output.
918 */
919 static public function formatSize($sizeInBytes, $labels = '', $base = 0) {
920 $defaultFormats = array(
921 'iec' => array('base' => 1024, 'labels' => array(' ', ' Ki', ' Mi', ' Gi', ' Ti', ' Pi', ' Ei', ' Zi', ' Yi')),
922 'si' => array('base' => 1000, 'labels' => array(' ', ' k', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y')),
923 );
924 // Set labels and base:
925 if (empty($labels)) {
926 $labels = 'iec';
927 }
928 if (isset($defaultFormats[$labels])) {
929 $base = $defaultFormats[$labels]['base'];
930 $labelArr = $defaultFormats[$labels]['labels'];
931 } else {
932 $base = (int)$base;
933 if ($base !== 1000 && $base !== 1024) {
934 $base = 1024;
935 }
936 $labelArr = explode('|', str_replace('"', '', $labels));
937 }
938 // @todo find out which locale is used for current BE user to cover the BE case as well
939 $oldLocale = setlocale(LC_NUMERIC, 0);
940 $newLocale = is_object($GLOBALS['TSFE']) ? $GLOBALS['TSFE']->config['config']['locale_all'] : '';
941 if ($newLocale) {
942 setlocale(LC_NUMERIC, $newLocale);
943 }
944 $localeInfo = localeconv();
945 if ($newLocale) {
946 setlocale(LC_NUMERIC, $oldLocale);
947 }
948 $sizeInBytes = max($sizeInBytes, 0);
949 $multiplier = floor(($sizeInBytes ? log($sizeInBytes) : 0) / log($base));
950 $sizeInUnits = $sizeInBytes / pow($base, $multiplier);
951 if ($sizeInUnits > ($base * .9)) {
952 $multiplier++;
953 }
954 $multiplier = min($multiplier, count($labelArr) - 1);
955 $sizeInUnits = $sizeInBytes / pow($base, $multiplier);
956 return number_format($sizeInUnits, (($multiplier > 0) && ($sizeInUnits < 20)) ? 2 : 0, $localeInfo['decimal_point'], '') . $labelArr[$multiplier];
957 }
958
959 /**
960 * Returns microtime input to milliseconds
961 *
962 * @param string $microtime Microtime
963 * @return int Microtime input string converted to an integer (milliseconds)
964 */
965 static public function convertMicrotime($microtime) {
966 $parts = explode(' ', $microtime);
967 return round(($parts[0] + $parts[1]) * 1000);
968 }
969
970 /**
971 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
972 *
973 * @param string $string Input string, eg "123 + 456 / 789 - 4
974 * @param string $operators Operators to split by, typically "/+-*
975 * @return array Array with operators and operands separated.
976 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc(), \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset()
977 */
978 static public function splitCalc($string, $operators) {
979 $res = array();
980 $sign = '+';
981 while ($string) {
982 $valueLen = strcspn($string, $operators);
983 $value = substr($string, 0, $valueLen);
984 $res[] = array($sign, trim($value));
985 $sign = substr($string, $valueLen, 1);
986 $string = substr($string, $valueLen + 1);
987 }
988 reset($res);
989 return $res;
990 }
991
992 /**
993 * Re-converts HTML entities if they have been converted by htmlspecialchars()
994 * Note: Use htmlspecialchars($str, ENT_COMPAT, 'UTF-8', FALSE) to avoid double encoding.
995 * This makes the call to this method obsolete.
996 *
997 * @param string $str String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;
998 * @return string Converted result.
999 *
1000 */
1001 static public function deHSCentities($str) {
1002 return preg_replace('/&amp;([#[:alnum:]]*;)/', '&\\1', $str);
1003 }
1004
1005 /**
1006 * This function is used to escape any ' -characters when transferring text to JavaScript!
1007 *
1008 * @param string $string String to escape
1009 * @param bool $extended If set, also backslashes are escaped.
1010 * @param string $char The character to escape, default is ' (single-quote)
1011 * @return string Processed input string
1012 */
1013 static public function slashJS($string, $extended = FALSE, $char = '\'') {
1014 if ($extended) {
1015 $string = str_replace('\\', '\\\\', $string);
1016 }
1017 return str_replace($char, '\\' . $char, $string);
1018 }
1019
1020 /**
1021 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1022 * Useful when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1023 *
1024 * @param string $str String to raw-url-encode with spaces preserved
1025 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1026 */
1027 static public function rawUrlEncodeJS($str) {
1028 return str_replace('%20', ' ', rawurlencode($str));
1029 }
1030
1031 /**
1032 * rawurlencode which preserves "/" chars
1033 * Useful when file paths should keep the "/" chars, but have all other special chars encoded.
1034 *
1035 * @param string $str Input string
1036 * @return string Output string
1037 */
1038 static public function rawUrlEncodeFP($str) {
1039 return str_replace('%2F', '/', rawurlencode($str));
1040 }
1041
1042 /**
1043 * Checking syntax of input email address
1044 *
1045 * http://tools.ietf.org/html/rfc3696
1046 * International characters are allowed in email. So the whole address needs
1047 * to be converted to punicode before passing it to filter_var(). We convert
1048 * the user- and domain part separately to increase the chance of hitting an
1049 * entry in self::$idnaStringCache.
1050 *
1051 * Also the @ sign may appear multiple times in an address. If not used as
1052 * a boundary marker between the user- and domain part, it must be escaped
1053 * with a backslash: \@. This mean we can not just explode on the @ sign and
1054 * expect to get just two parts. So we pop off the domain and then glue the
1055 * rest together again.
1056 *
1057 * @param string $email Input string to evaluate
1058 * @return bool Returns TRUE if the $email address (input string) is valid
1059 */
1060 static public function validEmail($email) {
1061 // Early return in case input is not a string
1062 if (!is_string($email)) {
1063 return FALSE;
1064 }
1065 $atPosition = strrpos($email, '@');
1066 if (!$atPosition || $atPosition + 1 === strlen($email)) {
1067 // Return if no @ found or it is placed at the very beginning or end of the email
1068 return FALSE;
1069 }
1070 $domain = substr($email, $atPosition + 1);
1071 $user = substr($email, 0, $atPosition);
1072 if (!preg_match('/^[a-z0-9.\\-]*$/i', $domain)) {
1073 $domain = self::idnaEncode($domain);
1074 }
1075 return filter_var($user . '@' . $domain, FILTER_VALIDATE_EMAIL) !== FALSE;
1076 }
1077
1078 /**
1079 * Checks if current e-mail sending method does not accept recipient/sender name
1080 * in a call to PHP mail() function. Windows version of mail() and mini_sendmail
1081 * program are known not to process such input correctly and they cause SMTP
1082 * errors. This function will return TRUE if current mail sending method has
1083 * problem with recipient name in recipient/sender argument for mail().
1084 *
1085 * @todo 4.3 should have additional configuration variable, which is combined
1086 * by || with the rest in this function.
1087 *
1088 * @return bool TRUE if mail() does not accept recipient name
1089 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1090 */
1091 static public function isBrokenEmailEnvironment() {
1092 self::logDeprecatedFunction();
1093 return TYPO3_OS == 'WIN' || FALSE !== strpos(ini_get('sendmail_path'), 'mini_sendmail');
1094 }
1095
1096 /**
1097 * Changes from/to arguments for mail() function to work in any environment.
1098 *
1099 * @param string $address Address to adjust
1100 * @return string Adjusted address
1101 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1102 */
1103 static public function normalizeMailAddress($address) {
1104 self::logDeprecatedFunction();
1105 if (self::isBrokenEmailEnvironment() && FALSE !== ($pos1 = strrpos($address, '<'))) {
1106 $pos2 = strpos($address, '>', $pos1);
1107 $address = substr($address, $pos1 + 1, ($pos2 ? $pos2 : strlen($address)) - $pos1 - 1);
1108 }
1109 return $address;
1110 }
1111
1112 /**
1113 * Formats a string for output between <textarea>-tags
1114 * All content outputted in a textarea form should be passed through this function
1115 * 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!
1116 *
1117 * @param string $content Input string to be formatted.
1118 * @return string Formatted for <textarea>-tags
1119 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
1120 */
1121 static public function formatForTextarea($content) {
1122 self::logDeprecatedFunction();
1123 return LF . htmlspecialchars($content);
1124 }
1125
1126 /**
1127 * Converts string to uppercase
1128 * The function converts all Latin characters (a-z, but no accents, etc) to
1129 * uppercase. It is safe for all supported character sets (incl. utf-8).
1130 * Unlike strtoupper() it does not honour the locale.
1131 *
1132 * @param string $str Input string
1133 * @return string Uppercase String
1134 */
1135 static public function strtoupper($str) {
1136 return strtr((string)$str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
1137 }
1138
1139 /**
1140 * Converts string to lowercase
1141 * The function converts all Latin characters (A-Z, but no accents, etc) to
1142 * lowercase. It is safe for all supported character sets (incl. utf-8).
1143 * Unlike strtolower() it does not honour the locale.
1144 *
1145 * @param string $str Input string
1146 * @return string Lowercase String
1147 */
1148 static public function strtolower($str) {
1149 return strtr((string)$str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1150 }
1151
1152 /**
1153 * Returns a string of highly randomized bytes (over the full 8-bit range).
1154 *
1155 * Note: Returned values are not guaranteed to be crypto-safe,
1156 * most likely they are not, depending on the used retrieval method.
1157 *
1158 * @param int $bytesToReturn Number of characters (bytes) to return
1159 * @return string Random Bytes
1160 * @see http://bugs.php.net/bug.php?id=52523
1161 * @see http://www.php-security.org/2010/05/09/mops-submission-04-generating-unpredictable-session-ids-and-hashes/index.html
1162 */
1163 static public function generateRandomBytes($bytesToReturn) {
1164 // Cache 4k of the generated bytestream.
1165 static $bytes = '';
1166 $bytesToGenerate = max(4096, $bytesToReturn);
1167 // if we have not enough random bytes cached, we generate new ones
1168 if (!isset($bytes[($bytesToReturn - 1)])) {
1169 if (TYPO3_OS === 'WIN') {
1170 // Openssl seems to be deadly slow on Windows, so try to use mcrypt
1171 $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate);
1172 } else {
1173 // Try to use native PHP functions first, precedence has openssl
1174 $bytes .= self::generateRandomBytesOpenSsl($bytesToGenerate);
1175 if (!isset($bytes[($bytesToReturn - 1)])) {
1176 $bytes .= self::generateRandomBytesMcrypt($bytesToGenerate);
1177 }
1178 // If openssl and mcrypt failed, try /dev/urandom
1179 if (!isset($bytes[($bytesToReturn - 1)])) {
1180 $bytes .= self::generateRandomBytesUrandom($bytesToGenerate);
1181 }
1182 }
1183 // Fall back if other random byte generation failed until now
1184 if (!isset($bytes[($bytesToReturn - 1)])) {
1185 $bytes .= self::generateRandomBytesFallback($bytesToReturn);
1186 }
1187 }
1188 // get first $bytesToReturn and remove it from the byte cache
1189 $output = substr($bytes, 0, $bytesToReturn);
1190 $bytes = substr($bytes, $bytesToReturn);
1191 return $output;
1192 }
1193
1194 /**
1195 * Generate random bytes using openssl if available
1196 *
1197 * @param string $bytesToGenerate
1198 * @return string
1199 */
1200 static protected function generateRandomBytesOpenSsl($bytesToGenerate) {
1201 if (!function_exists('openssl_random_pseudo_bytes')) {
1202 return '';
1203 }
1204 $isStrong = NULL;
1205 return (string)openssl_random_pseudo_bytes($bytesToGenerate, $isStrong);
1206 }
1207
1208 /**
1209 * Generate random bytes using mcrypt if available
1210 *
1211 * @param $bytesToGenerate
1212 * @return string
1213 */
1214 static protected function generateRandomBytesMcrypt($bytesToGenerate) {
1215 if (!function_exists('mcrypt_create_iv')) {
1216 return '';
1217 }
1218 return (string)(@mcrypt_create_iv($bytesToGenerate, MCRYPT_DEV_URANDOM));
1219 }
1220
1221 /**
1222 * Read random bytes from /dev/urandom if it is accessible
1223 *
1224 * @param $bytesToGenerate
1225 * @return string
1226 */
1227 static protected function generateRandomBytesUrandom($bytesToGenerate) {
1228 $bytes = '';
1229 $fh = @fopen('/dev/urandom', 'rb');
1230 if ($fh) {
1231 // PHP only performs buffered reads, so in reality it will always read
1232 // at least 4096 bytes. Thus, it costs nothing extra to read and store
1233 // that much so as to speed any additional invocations.
1234 $bytes = fread($fh, $bytesToGenerate);
1235 fclose($fh);
1236 }
1237 return $bytes;
1238 }
1239
1240 /**
1241 * Generate pseudo random bytes as last resort
1242 *
1243 * @param $bytesToReturn
1244 * @return string
1245 */
1246 static protected function generateRandomBytesFallback($bytesToReturn) {
1247 $bytes = '';
1248 // We initialize with somewhat random.
1249 $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . base_convert(memory_get_usage() % pow(10, 6), 10, 2) . microtime() . uniqid('', TRUE) . getmypid();
1250 while (!isset($bytes[($bytesToReturn - 1)])) {
1251 $randomState = sha1(microtime() . mt_rand() . $randomState);
1252 $bytes .= sha1(mt_rand() . $randomState, TRUE);
1253 }
1254 return $bytes;
1255 }
1256
1257 /**
1258 * Returns an ASCII string (punicode) representation of $value
1259 *
1260 * @param string $value
1261 * @return string An ASCII encoded (punicode) string
1262 */
1263 static public function idnaEncode($value) {
1264 if (isset(self::$idnaStringCache[$value])) {
1265 return self::$idnaStringCache[$value];
1266 } else {
1267 if (!self::$idnaConverter) {
1268 self::$idnaConverter = new \idna_convert(array('idn_version' => 2008));
1269 }
1270 self::$idnaStringCache[$value] = self::$idnaConverter->encode($value);
1271 return self::$idnaStringCache[$value];
1272 }
1273 }
1274
1275 /**
1276 * Returns a hex representation of a random byte string.
1277 *
1278 * @param int $count Number of hex characters to return
1279 * @return string Random Bytes
1280 */
1281 static public function getRandomHexString($count) {
1282 return substr(bin2hex(self::generateRandomBytes((int)(($count + 1) / 2))), 0, $count);
1283 }
1284
1285 /**
1286 * Returns a given string with underscores as UpperCamelCase.
1287 * Example: Converts blog_example to BlogExample
1288 *
1289 * @param string $string String to be converted to camel case
1290 * @return string UpperCamelCasedWord
1291 */
1292 static public function underscoredToUpperCamelCase($string) {
1293 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1294 return $upperCamelCase;
1295 }
1296
1297 /**
1298 * Returns a given string with underscores as lowerCamelCase.
1299 * Example: Converts minimal_value to minimalValue
1300 *
1301 * @param string $string String to be converted to camel case
1302 * @return string lowerCamelCasedWord
1303 */
1304 static public function underscoredToLowerCamelCase($string) {
1305 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1306 $lowerCamelCase = self::lcfirst($upperCamelCase);
1307 return $lowerCamelCase;
1308 }
1309
1310 /**
1311 * Returns a given CamelCasedString as an lowercase string with underscores.
1312 * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
1313 *
1314 * @param string $string String to be converted to lowercase underscore
1315 * @return string lowercase_and_underscored_string
1316 */
1317 static public function camelCaseToLowerCaseUnderscored($string) {
1318 return self::strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string));
1319 }
1320
1321 /**
1322 * Converts the first char of a string to lowercase if it is a latin character (A-Z).
1323 * Example: Converts "Hello World" to "hello World"
1324 *
1325 * @param string $string The string to be used to lowercase the first character
1326 * @return string The string with the first character as lowercase
1327 */
1328 static public function lcfirst($string) {
1329 return self::strtolower($string[0]) . substr($string, 1);
1330 }
1331
1332 /**
1333 * Checks if a given string is a Uniform Resource Locator (URL).
1334 *
1335 * On seriously malformed URLs, parse_url may return FALSE and emit an
1336 * E_WARNING.
1337 *
1338 * filter_var() requires a scheme to be present.
1339 *
1340 * http://www.faqs.org/rfcs/rfc2396.html
1341 * Scheme names consist of a sequence of characters beginning with a
1342 * lower case letter and followed by any combination of lower case letters,
1343 * digits, plus ("+"), period ("."), or hyphen ("-"). For resiliency,
1344 * programs interpreting URI should treat upper case letters as equivalent to
1345 * lower case in scheme names (e.g., allow "HTTP" as well as "http").
1346 * scheme = alpha *( alpha | digit | "+" | "-" | "." )
1347 *
1348 * Convert the domain part to punicode if it does not look like a regular
1349 * domain name. Only the domain part because RFC3986 specifies the the rest of
1350 * the url may not contain special characters:
1351 * http://tools.ietf.org/html/rfc3986#appendix-A
1352 *
1353 * @param string $url The URL to be validated
1354 * @return bool Whether the given URL is valid
1355 */
1356 static public function isValidUrl($url) {
1357 $parsedUrl = parse_url($url);
1358 if (!$parsedUrl || !isset($parsedUrl['scheme'])) {
1359 return FALSE;
1360 }
1361 // HttpUtility::buildUrl() will always build urls with <scheme>://
1362 // our original $url might only contain <scheme>: (e.g. mail:)
1363 // so we convert that to the double-slashed version to ensure
1364 // our check against the $recomposedUrl is proper
1365 if (!self::isFirstPartOfStr($url, $parsedUrl['scheme'] . '://')) {
1366 $url = str_replace($parsedUrl['scheme'] . ':', $parsedUrl['scheme'] . '://', $url);
1367 }
1368 $recomposedUrl = HttpUtility::buildUrl($parsedUrl);
1369 if ($recomposedUrl !== $url) {
1370 // The parse_url() had to modify characters, so the URL is invalid
1371 return FALSE;
1372 }
1373 if (isset($parsedUrl['host']) && !preg_match('/^[a-z0-9.\\-]*$/i', $parsedUrl['host'])) {
1374 $parsedUrl['host'] = self::idnaEncode($parsedUrl['host']);
1375 }
1376 return filter_var(HttpUtility::buildUrl($parsedUrl), FILTER_VALIDATE_URL) !== FALSE;
1377 }
1378
1379 /*************************
1380 *
1381 * ARRAY FUNCTIONS
1382 *
1383 *************************/
1384 /**
1385 * Check if an string item exists in an array.
1386 * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
1387 *
1388 * Comparison to PHP in_array():
1389 * -> $array = array(0, 1, 2, 3);
1390 * -> variant_a := \TYPO3\CMS\Core\Utility\ArrayUtility::inArray($array, $needle)
1391 * -> variant_b := in_array($needle, $array)
1392 * -> variant_c := in_array($needle, $array, TRUE)
1393 * +---------+-----------+-----------+-----------+
1394 * | $needle | variant_a | variant_b | variant_c |
1395 * +---------+-----------+-----------+-----------+
1396 * | '1a' | FALSE | TRUE | FALSE |
1397 * | '' | FALSE | TRUE | FALSE |
1398 * | '0' | TRUE | TRUE | FALSE |
1399 * | 0 | TRUE | TRUE | TRUE |
1400 * +---------+-----------+-----------+-----------+
1401 *
1402 * @param array $in_array One-dimensional array of items
1403 * @param string $item Item to check for
1404 * @return bool TRUE if $item is in the one-dimensional array $in_array
1405 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::inArray() instead
1406 */
1407 static public function inArray(array $in_array, $item) {
1408 static::logDeprecatedFunction();
1409 return ArrayUtility::inArray($in_array, $item);
1410 }
1411
1412 /**
1413 * Explodes a $string delimited by $delim and casts each item in the array to (int).
1414 * Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values.
1415 *
1416 * @param string $delimiter Delimiter string to explode with
1417 * @param string $string The string to explode
1418 * @param bool $removeEmptyValues If set, all empty values (='') will NOT be set in output
1419 * @param int $limit If positive, the result will contain a maximum of limit elements,
1420 * @return array Exploded values, all converted to integers
1421 */
1422 static public function intExplode($delimiter, $string, $removeEmptyValues = FALSE, $limit = 0) {
1423 $result = explode($delimiter, $string);
1424 foreach ($result as $key => &$value) {
1425 if ($removeEmptyValues && ($value === '' || trim($value) === '')) {
1426 unset($result[$key]);
1427 } else {
1428 $value = (int)$value;
1429 }
1430 }
1431 unset($value);
1432 if ($limit !== 0) {
1433 if ($limit < 0) {
1434 $result = array_slice($result, 0, $limit);
1435 } elseif (count($result) > $limit) {
1436 $lastElements = array_slice($result, $limit - 1);
1437 $result = array_slice($result, 0, $limit - 1);
1438 $result[] = implode($delimiter, $lastElements);
1439 }
1440 }
1441 return $result;
1442 }
1443
1444 /**
1445 * Reverse explode which explodes the string counting from behind.
1446 *
1447 * Note: The delimiter has to given in the reverse order as
1448 * it is occurring within the string.
1449 *
1450 * GeneralUtility::revExplode('[]', '[my][words][here]', 2)
1451 * ==> array('[my][words', 'here]')
1452 *
1453 * @param string $delimiter Delimiter string to explode with
1454 * @param string $string The string to explode
1455 * @param int $count Number of array entries
1456 * @return array Exploded values
1457 */
1458 static public function revExplode($delimiter, $string, $count = 0) {
1459 // 2 is the (currently, as of 2014-02) most-used value for $count in the core, therefore we check it first
1460 if ($count === 2) {
1461 $position = strrpos($string, strrev($delimiter));
1462 if ($position !== FALSE) {
1463 return array(substr($string, 0, $position), substr($string, $position + strlen($delimiter)));
1464 } else {
1465 return array($string);
1466 }
1467 } elseif ($count <= 1) {
1468 return array($string);
1469 } else {
1470 $explodedValues = explode($delimiter, strrev($string), $count);
1471 $explodedValues = array_map('strrev', $explodedValues);
1472 return array_reverse($explodedValues);
1473 }
1474 }
1475
1476 /**
1477 * Explodes a string and trims all values for whitespace in the ends.
1478 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1479 *
1480 * @param string $delim Delimiter string to explode with
1481 * @param string $string The string to explode
1482 * @param bool $removeEmptyValues If set, all empty values will be removed in output
1483 * @param int $limit If positive, the result will contain a maximum of
1484 * @return array Exploded values
1485 */
1486 static public function trimExplode($delim, $string, $removeEmptyValues = FALSE, $limit = 0) {
1487 $result = array_map('trim', explode($delim, $string));
1488 if ($removeEmptyValues) {
1489 $temp = array();
1490 foreach ($result as $value) {
1491 if ($value !== '') {
1492 $temp[] = $value;
1493 }
1494 }
1495 $result = $temp;
1496 }
1497 if ($limit > 0 && count($result) > $limit) {
1498 $lastElements = array_splice($result, $limit - 1);
1499 $result[] = implode($delim, $lastElements);
1500 } elseif ($limit < 0) {
1501 $result = array_slice($result, 0, $limit);
1502 }
1503 return $result;
1504 }
1505
1506 /**
1507 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1508 *
1509 * @param array $array Array containing the values
1510 * @param string $cmpValue Value to search for and if found remove array entry where found.
1511 * @return array Output array with entries removed if search string is found
1512 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::removeArrayEntryByValue() instead
1513 */
1514 static public function removeArrayEntryByValue(array $array, $cmpValue) {
1515 static::logDeprecatedFunction();
1516 return ArrayUtility::removeArrayEntryByValue($array, $cmpValue);
1517 }
1518
1519 /**
1520 * Filters an array to reduce its elements to match the condition.
1521 * The values in $keepItems can be optionally evaluated by a custom callback function.
1522 *
1523 * Example (arguments used to call this function):
1524 * $array = array(
1525 * array('aa' => array('first', 'second'),
1526 * array('bb' => array('third', 'fourth'),
1527 * array('cc' => array('fifth', 'sixth'),
1528 * );
1529 * $keepItems = array('third');
1530 * $getValueFunc = function($value) { return $value[0]; }
1531 *
1532 * Returns:
1533 * array(
1534 * array('bb' => array('third', 'fourth'),
1535 * )
1536 *
1537 * @param array $array The initial array to be filtered/reduced
1538 * @param mixed $keepItems The items which are allowed/kept in the array - accepts array or csv string
1539 * @param string $getValueFunc (optional) Callback function used to get the value to keep
1540 * @return array The filtered/reduced array with the kept items
1541 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::keepItemsInArray() instead
1542 */
1543 static public function keepItemsInArray(array $array, $keepItems, $getValueFunc = NULL) {
1544 static::logDeprecatedFunction();
1545 return ArrayUtility::keepItemsInArray($array, $keepItems, $getValueFunc);
1546 }
1547
1548 /**
1549 * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1550 *
1551 * @param string $name Name prefix for entries. Set to blank if you wish none.
1552 * @param array $theArray The (multidimensional) array to implode
1553 * @param string $str (keep blank)
1554 * @param bool $skipBlank If set, parameters which were blank strings would be removed.
1555 * @param bool $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1556 * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1557 * @see explodeUrl2Array()
1558 */
1559 static public function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = FALSE, $rawurlencodeParamName = FALSE) {
1560 foreach ($theArray as $Akey => $AVal) {
1561 $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1562 if (is_array($AVal)) {
1563 $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1564 } else {
1565 if (!$skipBlank || (string)$AVal !== '') {
1566 $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) . '=' . rawurlencode($AVal);
1567 }
1568 }
1569 }
1570 return $str;
1571 }
1572
1573 /**
1574 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1575 *
1576 * @param string $string GETvars string
1577 * @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())
1578 * @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!
1579 * @see implodeArrayForUrl()
1580 */
1581 static public function explodeUrl2Array($string, $multidim = FALSE) {
1582 $output = array();
1583 if ($multidim) {
1584 parse_str($string, $output);
1585 } else {
1586 $p = explode('&', $string);
1587 foreach ($p as $v) {
1588 if ($v !== '') {
1589 list($pK, $pV) = explode('=', $v, 2);
1590 $output[rawurldecode($pK)] = rawurldecode($pV);
1591 }
1592 }
1593 }
1594 return $output;
1595 }
1596
1597 /**
1598 * Returns an array with selected keys from incoming data.
1599 * (Better read source code if you want to find out...)
1600 *
1601 * @param string $varList List of variable/key names
1602 * @param array $getArray Array from where to get values based on the keys in $varList
1603 * @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
1604 * @return array Output array with selected variables.
1605 */
1606 static public function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = TRUE) {
1607 $keys = self::trimExplode(',', $varList, TRUE);
1608 $outArr = array();
1609 foreach ($keys as $v) {
1610 if (isset($getArray[$v])) {
1611 $outArr[$v] = $getArray[$v];
1612 } elseif ($GPvarAlt) {
1613 $outArr[$v] = self::_GP($v);
1614 }
1615 }
1616 return $outArr;
1617 }
1618
1619 /**
1620 * AddSlash array
1621 * This function traverses a multidimensional array and adds slashes to the values.
1622 * NOTE that the input array is and argument by reference.!!
1623 * Twin-function to stripSlashesOnArray
1624 *
1625 * @param array $theArray Multidimensional input array, (REFERENCE!)
1626 * @return array
1627 */
1628 static public function addSlashesOnArray(array &$theArray) {
1629 foreach ($theArray as &$value) {
1630 if (is_array($value)) {
1631 self::addSlashesOnArray($value);
1632 } else {
1633 $value = addslashes($value);
1634 }
1635 }
1636 unset($value);
1637 reset($theArray);
1638 }
1639
1640 /**
1641 * StripSlash array
1642 * This function traverses a multidimensional array and strips slashes to the values.
1643 * NOTE that the input array is and argument by reference.!!
1644 * Twin-function to addSlashesOnArray
1645 *
1646 * @param array $theArray Multidimensional input array, (REFERENCE!)
1647 * @return array
1648 */
1649 static public function stripSlashesOnArray(array &$theArray) {
1650 foreach ($theArray as &$value) {
1651 if (is_array($value)) {
1652 self::stripSlashesOnArray($value);
1653 } else {
1654 $value = stripslashes($value);
1655 }
1656 }
1657 unset($value);
1658 reset($theArray);
1659 }
1660
1661 /**
1662 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1663 *
1664 * @param array $arr Multidimensional input array
1665 * @param string $cmd "add" or "strip", depending on usage you wish.
1666 * @return array
1667 */
1668 static public function slashArray(array $arr, $cmd) {
1669 if ($cmd == 'strip') {
1670 self::stripSlashesOnArray($arr);
1671 }
1672 if ($cmd == 'add') {
1673 self::addSlashesOnArray($arr);
1674 }
1675 return $arr;
1676 }
1677
1678 /**
1679 * Rename Array keys with a given mapping table
1680 *
1681 * @param array $array Array by reference which should be remapped
1682 * @param array $mappingTable Array with remap information, array/$oldKey => $newKey)
1683 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::remapArrayKeys() instead
1684 */
1685 static public function remapArrayKeys(&$array, $mappingTable) {
1686 static::logDeprecatedFunction();
1687 ArrayUtility::remapArrayKeys($array, $mappingTable);
1688 }
1689
1690 /**
1691 * 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.
1692 *
1693 * @param array $arr1 First array
1694 * @param array $arr2 Second array
1695 * @return array Merged result.
1696 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - native php '+' operator instead
1697 */
1698 static public function array_merge(array $arr1, array $arr2) {
1699 static::logDeprecatedFunction();
1700 return $arr2 + $arr1;
1701 }
1702
1703 /**
1704 * Filters keys off from first array that also exist in second array. Comparison is done by keys.
1705 * This method is a recursive version of php array_diff_assoc()
1706 *
1707 * @param array $array1 Source array
1708 * @param array $array2 Reduce source array by this array
1709 * @return array Source array reduced by keys also present in second array
1710 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::arrayDiffAssocRecursive() instead
1711 */
1712 static public function arrayDiffAssocRecursive(array $array1, array $array2) {
1713 static::logDeprecatedFunction();
1714 return ArrayUtility::arrayDiffAssocRecursive($array1, $array2);
1715 }
1716
1717 /**
1718 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1719 *
1720 * @param array $row Input array of values
1721 * @param string $delim Delimited, default is comma
1722 * @param string $quote Quote-character to wrap around the values.
1723 * @return string A single line of CSV
1724 */
1725 static public function csvValues(array $row, $delim = ',', $quote = '"') {
1726 $out = array();
1727 foreach ($row as $value) {
1728 $out[] = str_replace($quote, $quote . $quote, $value);
1729 }
1730 $str = $quote . implode(($quote . $delim . $quote), $out) . $quote;
1731 return $str;
1732 }
1733
1734 /**
1735 * Removes dots "." from end of a key identifier of TypoScript styled array.
1736 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1737 *
1738 * @param array $ts TypoScript configuration array
1739 * @return array TypoScript configuration array without dots at the end of all keys
1740 */
1741 static public function removeDotsFromTS(array $ts) {
1742 $out = array();
1743 foreach ($ts as $key => $value) {
1744 if (is_array($value)) {
1745 $key = rtrim($key, '.');
1746 $out[$key] = self::removeDotsFromTS($value);
1747 } else {
1748 $out[$key] = $value;
1749 }
1750 }
1751 return $out;
1752 }
1753
1754 /**
1755 * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
1756 *
1757 * @param array $array array to be sorted recursively, passed by reference
1758 * @return bool TRUE if param is an array
1759 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8 - use ArrayUtility::naturalKeySortRecursive() instead
1760 */
1761 static public function naturalKeySortRecursive(&$array) {
1762 static::logDeprecatedFunction();
1763 return ArrayUtility::naturalKeySortRecursive($array);
1764 }
1765
1766 /*************************
1767 *
1768 * HTML/XML PROCESSING
1769 *
1770 *************************/
1771 /**
1772 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1773 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1774 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1775 *
1776 * @param string $tag HTML-tag string (or attributes only)
1777 * @return array Array with the attribute values.
1778 */
1779 static public function get_tag_attributes($tag) {
1780 $components = self::split_tag_attributes($tag);
1781 // Attribute name is stored here
1782 $name = '';
1783 $valuemode = FALSE;
1784 $attributes = array();
1785 foreach ($components as $key => $val) {
1786 // 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
1787 if ($val != '=') {
1788 if ($valuemode) {
1789 if ($name) {
1790 $attributes[$name] = $val;
1791 $name = '';
1792 }
1793 } else {
1794 if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val))) {
1795 $attributes[$key] = '';
1796 $name = $key;
1797 }
1798 }
1799 $valuemode = FALSE;
1800 } else {
1801 $valuemode = TRUE;
1802 }
1803 }
1804 return $attributes;
1805 }
1806
1807 /**
1808 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1809 * Removes tag-name if found
1810 *
1811 * @param string $tag HTML-tag string (or attributes only)
1812 * @return array Array with the attribute values.
1813 */
1814 static public function split_tag_attributes($tag) {
1815 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
1816 // Removes any > in the end of the string
1817 $tag_tmp = trim(rtrim($tag_tmp, '>'));
1818 $value = array();
1819 // Compared with empty string instead , 030102
1820 while ($tag_tmp !== '') {
1821 $firstChar = $tag_tmp[0];
1822 if ($firstChar === '"' || $firstChar === '\'') {
1823 $reg = explode($firstChar, $tag_tmp, 3);
1824 $value[] = $reg[1];
1825 $tag_tmp = trim($reg[2]);
1826 } elseif ($firstChar === '=') {
1827 $value[] = '=';
1828 // Removes = chars.
1829 $tag_tmp = trim(substr($tag_tmp, 1));
1830 } else {
1831 // There are '' around the value. We look for the next ' ' or '>'
1832 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
1833 $value[] = trim($reg[0]);
1834 $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
1835 }
1836 }
1837 reset($value);
1838 return $value;
1839 }
1840
1841 /**
1842 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1843 *
1844 * @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1845 * @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!
1846 * @param bool $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
1847 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1848 */
1849 static public function implodeAttributes(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
1850 if ($xhtmlSafe) {
1851 $newArr = array();
1852 foreach ($arr as $p => $v) {
1853 if (!isset($newArr[strtolower($p)])) {
1854 $newArr[strtolower($p)] = htmlspecialchars($v);
1855 }
1856 }
1857 $arr = $newArr;
1858 }
1859 $list = array();
1860 foreach ($arr as $p => $v) {
1861 if ((string)$v !== '' || $dontOmitBlankAttribs) {
1862 $list[] = $p . '="' . $v . '"';
1863 }
1864 }
1865 return implode(' ', $list);
1866 }
1867
1868 /**
1869 * Wraps JavaScript code XHTML ready with <script>-tags
1870 * Automatic re-indenting of the JS code is done by using the first line as indent reference.
1871 * This is nice for indenting JS code with PHP code on the same level.
1872 *
1873 * @param string $string JavaScript code
1874 * @param bool $linebreak Wrap script element in line breaks? Default is TRUE.
1875 * @return string The wrapped JS code, ready to put into a XHTML page
1876 */
1877 static public function wrapJS($string, $linebreak = TRUE) {
1878 if (trim($string)) {
1879 // <script wrapped in nl?
1880 $cr = $linebreak ? LF : '';
1881 // remove nl from the beginning
1882 $string = preg_replace('/^\\n+/', '', $string);
1883 // re-ident to one tab using the first line as reference
1884 $match = array();
1885 if (preg_match('/^(\\t+)/', $string, $match)) {
1886 $string = str_replace($match[1], TAB, $string);
1887 }
1888 $string = $cr . '<script type="text/javascript">
1889 /*<![CDATA[*/
1890 ' . $string . '
1891 /*]]>*/
1892 </script>' . $cr;
1893 }
1894 return trim($string);
1895 }
1896
1897 /**
1898 * Parses XML input into a PHP array with associative keys
1899 *
1900 * @param string $string XML data input
1901 * @param int $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1902 * @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.
1903 * @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
1904 */
1905 static public function xml2tree($string, $depth = 999) {
1906 $parser = xml_parser_create();
1907 $vals = array();
1908 $index = array();
1909 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1910 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1911 xml_parse_into_struct($parser, $string, $vals, $index);
1912 if (xml_get_error_code($parser)) {
1913 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1914 }
1915 xml_parser_free($parser);
1916 $stack = array(array());
1917 $stacktop = 0;
1918 $startPoint = 0;
1919 $tagi = array();
1920 foreach ($vals as $key => $val) {
1921 $type = $val['type'];
1922 // open tag:
1923 if ($type == 'open' || $type == 'complete') {
1924 $stack[$stacktop++] = $tagi;
1925 if ($depth == $stacktop) {
1926 $startPoint = $key;
1927 }
1928 $tagi = array('tag' => $val['tag']);
1929 if (isset($val['attributes'])) {
1930 $tagi['attrs'] = $val['attributes'];
1931 }
1932 if (isset($val['value'])) {
1933 $tagi['values'][] = $val['value'];
1934 }
1935 }
1936 // finish tag:
1937 if ($type == 'complete' || $type == 'close') {
1938 $oldtagi = $tagi;
1939 $tagi = $stack[--$stacktop];
1940 $oldtag = $oldtagi['tag'];
1941 unset($oldtagi['tag']);
1942 if ($depth == $stacktop + 1) {
1943 if ($key - $startPoint > 0) {
1944 $partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1);
1945 $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
1946 } else {
1947 $oldtagi['XMLvalue'] = $oldtagi['values'][0];
1948 }
1949 }
1950 $tagi['ch'][$oldtag][] = $oldtagi;
1951 unset($oldtagi);
1952 }
1953 // cdata
1954 if ($type == 'cdata') {
1955 $tagi['values'][] = $val['value'];
1956 }
1957 }
1958 return $tagi['ch'];
1959 }
1960
1961 /**
1962 * Turns PHP array into XML. See array2xml()
1963 *
1964 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1965 * @param string $docTag Alternative document tag. Default is "phparray".
1966 * @param array $options Options for the compilation. See array2xml() for description.
1967 * @param string $charset Forced charset to prologue
1968 * @return string An XML string made from the input content in the array.
1969 * @see xml2array(),array2xml()
1970 */
1971 static public function array2xml_cs(array $array, $docTag = 'phparray', array $options = array(), $charset = '') {
1972 // Set default charset unless explicitly specified
1973 $charset = $charset ?: 'utf-8';
1974 // Return XML:
1975 return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF . self::array2xml($array, '', 0, $docTag, 0, $options);
1976 }
1977
1978 /**
1979 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
1980 *
1981 * Converts a PHP array into an XML string.
1982 * The XML output is optimized for readability since associative keys are used as tag names.
1983 * 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.
1984 * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
1985 * 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
1986 * 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.
1987 * 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!
1988 * 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...
1989 *
1990 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1991 * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
1992 * @param int $level Current recursion level. Don't change, stay at zero!
1993 * @param string $docTag Alternative document tag. Default is "phparray".
1994 * @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
1995 * @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')
1996 * @param array $stackData Stack data. Don't touch.
1997 * @return string An XML string made from the input content in the array.
1998 * @see xml2array()
1999 */
2000 static public function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = array(), array $stackData = array()) {
2001 // 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
2002 $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);
2003 // Set indenting mode:
2004 $indentChar = $spaceInd ? ' ' : TAB;
2005 $indentN = $spaceInd > 0 ? $spaceInd : 1;
2006 $nl = $spaceInd >= 0 ? LF : '';
2007 // Init output variable:
2008 $output = '';
2009 // Traverse the input array
2010 foreach ($array as $k => $v) {
2011 $attr = '';
2012 $tagName = $k;
2013 // Construct the tag name.
2014 // Use tag based on grand-parent + parent tag name
2015 if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) {
2016 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2017 $tagName = (string)$options['grandParentTagMap'][($stackData['grandParentTagName'] . '/' . $stackData['parentTagName'])];
2018 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && MathUtility::canBeInterpretedAsInteger($tagName)) {
2019 // Use tag based on parent tag name + if current tag is numeric
2020 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2021 $tagName = (string)$options['parentTagMap'][($stackData['parentTagName'] . ':_IS_NUM')];
2022 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) {
2023 // Use tag based on parent tag name + current tag
2024 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2025 $tagName = (string)$options['parentTagMap'][($stackData['parentTagName'] . ':' . $tagName)];
2026 } elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) {
2027 // Use tag based on parent tag name:
2028 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2029 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
2030 } elseif (MathUtility::canBeInterpretedAsInteger($tagName)) {
2031 // If integer...;
2032 if ($options['useNindex']) {
2033 // If numeric key, prefix "n"
2034 $tagName = 'n' . $tagName;
2035 } else {
2036 // Use special tag for num. keys:
2037 $attr .= ' index="' . $tagName . '"';
2038 $tagName = $options['useIndexTagForNum'] ?: 'numIndex';
2039 }
2040 } elseif ($options['useIndexTagForAssoc']) {
2041 // Use tag for all associative keys:
2042 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2043 $tagName = $options['useIndexTagForAssoc'];
2044 }
2045 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2046 $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
2047 // If the value is an array then we will call this function recursively:
2048 if (is_array($v)) {
2049 // Sub elements:
2050 if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
2051 $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
2052 $clearStackPath = $subOptions['clearStackPath'];
2053 } else {
2054 $subOptions = $options;
2055 $clearStackPath = FALSE;
2056 }
2057 $content = $nl . self::array2xml($v, $NSprefix, ($level + 1), '', $spaceInd, $subOptions, array(
2058 'parentTagName' => $tagName,
2059 'grandParentTagName' => $stackData['parentTagName'],
2060 'path' => ($clearStackPath ? '' : $stackData['path'] . '/' . $tagName)
2061 )) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
2062 // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2063 if ((int)$options['disableTypeAttrib'] != 2) {
2064 $attr .= ' type="array"';
2065 }
2066 } else {
2067 // Just a value:
2068 // Look for binary chars:
2069 $vLen = strlen($v);
2070 // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
2071 if ($vLen && strcspn($v, $binaryChars) != $vLen) {
2072 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2073 $content = $nl . chunk_split(base64_encode($v));
2074 $attr .= ' base64="1"';
2075 } else {
2076 // Otherwise, just htmlspecialchar the stuff:
2077 $content = htmlspecialchars($v);
2078 $dType = gettype($v);
2079 if ($dType == 'string') {
2080 if ($options['useCDATA'] && $content != $v) {
2081 $content = '<![CDATA[' . $v . ']]>';
2082 }
2083 } elseif (!$options['disableTypeAttrib']) {
2084 $attr .= ' type="' . $dType . '"';
2085 }
2086 }
2087 }
2088 if ((string)$tagName !== '') {
2089 // Add the element to the output string:
2090 $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '')
2091 . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
2092 }
2093 }
2094 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2095 if (!$level) {
2096 $output = '<' . $docTag . '>' . $nl . $output . '</' . $docTag . '>';
2097 }
2098 return $output;
2099 }
2100
2101 /**
2102 * Converts an XML string to a PHP array.
2103 * This is the reverse function of array2xml()
2104 * This is a wrapper for xml2arrayProcess that adds a two-level cache
2105 *
2106 * @param string $string XML content to convert into an array
2107 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2108 * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2109 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2110 * @see array2xml(),xml2arrayProcess()
2111 */
2112 static public function xml2array($string, $NSprefix = '', $reportDocTag = FALSE) {
2113 static $firstLevelCache = array();
2114 $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
2115 // Look up in first level cache
2116 if (!empty($firstLevelCache[$identifier])) {
2117 $array = $firstLevelCache[$identifier];
2118 } else {
2119 // Look up in second level cache
2120 $array = PageRepository::getHash($identifier, 0);
2121 if (!is_array($array)) {
2122 $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
2123 PageRepository::storeHash($identifier, $array, 'ident_xml2array');
2124 }
2125 // Store content in first level cache
2126 $firstLevelCache[$identifier] = $array;
2127 }
2128 return $array;
2129 }
2130
2131 /**
2132 * Converts an XML string to a PHP array.
2133 * This is the reverse function of array2xml()
2134 *
2135 * @param string $string XML content to convert into an array
2136 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2137 * @param bool $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2138 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2139 * @see array2xml()
2140 */
2141 static protected function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = FALSE) {
2142 // Create parser:
2143 $parser = xml_parser_create();
2144 $vals = array();
2145 $index = array();
2146 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2147 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
2148 // Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2149 $match = array();
2150 preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
2151 $theCharset = $match[1] ?: 'utf-8';
2152 // us-ascii / utf-8 / iso-8859-1
2153 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);
2154 // Parse content:
2155 xml_parse_into_struct($parser, $string, $vals, $index);
2156 // If error, return error message:
2157 if (xml_get_error_code($parser)) {
2158 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2159 }
2160 xml_parser_free($parser);
2161 // Init vars:
2162 $stack = array(array());
2163 $stacktop = 0;
2164 $current = array();
2165 $tagName = '';
2166 $documentTag = '';
2167 // Traverse the parsed XML structure:
2168 foreach ($vals as $key => $val) {
2169 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2170 $tagName = $val['tag'];
2171 if (!$documentTag) {
2172 $documentTag = $tagName;
2173 }
2174 // Test for name space:
2175 $tagName = $NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix ? substr($tagName, strlen($NSprefix)) : $tagName;
2176 // Test for numeric tag, encoded on the form "nXXX":
2177 $testNtag = substr($tagName, 1);
2178 // Closing tag.
2179 $tagName = $tagName[0] === 'n' && MathUtility::canBeInterpretedAsInteger($testNtag) ? (int)$testNtag : $tagName;
2180 // Test for alternative index value:
2181 if ((string)$val['attributes']['index'] !== '') {
2182 $tagName = $val['attributes']['index'];
2183 }
2184 // Setting tag-values, manage stack:
2185 switch ($val['type']) {
2186 case 'open':
2187 // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2188 // Setting blank place holder
2189 $current[$tagName] = array();
2190 $stack[$stacktop++] = $current;
2191 $current = array();
2192 break;
2193 case 'close':
2194 // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2195 $oldCurrent = $current;
2196 $current = $stack[--$stacktop];
2197 // Going to the end of array to get placeholder key, key($current), and fill in array next:
2198 end($current);
2199 $current[key($current)] = $oldCurrent;
2200 unset($oldCurrent);
2201 break;
2202 case 'complete':
2203 // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2204 if ($val['attributes']['base64']) {
2205 $current[$tagName] = base64_decode($val['value']);
2206 } else {
2207 // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
2208 $current[$tagName] = (string)$val['value'];
2209 // Cast type:
2210 switch ((string)$val['attributes']['type']) {
2211 case 'integer':
2212 $current[$tagName] = (int)$current[$tagName];
2213 break;
2214 case 'double':
2215 $current[$tagName] = (double) $current[$tagName];
2216 break;
2217 case 'boolean':
2218 $current[$tagName] = (bool)$current[$tagName];
2219 break;
2220 case 'NULL':
2221 $current[$tagName] = NULL;
2222 break;
2223 case 'array':
2224 // 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...
2225 $current[$tagName] = array();
2226 break;
2227 }
2228 }
2229 break;
2230 }
2231 }
2232 if ($reportDocTag) {
2233 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2234 }
2235 // Finally return the content of the document tag.
2236 return $current[$tagName];
2237 }
2238
2239 /**
2240 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2241 *
2242 * @param array $vals An array of XML parts, see xml2tree
2243 * @return string Re-compiled XML data.
2244 */
2245 static public function xmlRecompileFromStructValArray(array $vals) {
2246 $XMLcontent = '';
2247 foreach ($vals as $val) {
2248 $type = $val['type'];
2249 // Open tag:
2250 if ($type == 'open' || $type == 'complete') {
2251 $XMLcontent .= '<' . $val['tag'];
2252 if (isset($val['attributes'])) {
2253 foreach ($val['attributes'] as $k => $v) {
2254 $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
2255 }
2256 }
2257 if ($type == 'complete') {
2258 if (isset($val['value'])) {
2259 $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
2260 } else {
2261 $XMLcontent .= '/>';
2262 }
2263 } else {
2264 $XMLcontent .= '>';
2265 }
2266 if ($type == 'open' && isset($val['value'])) {
2267 $XMLcontent .= htmlspecialchars($val['value']);
2268 }
2269 }
2270 // Finish tag:
2271 if ($type == 'close') {
2272 $XMLcontent .= '</' . $val['tag'] . '>';
2273 }
2274 // Cdata
2275 if ($type == 'cdata') {
2276 $XMLcontent .= htmlspecialchars($val['value']);
2277 }
2278 }
2279 return $XMLcontent;
2280 }
2281
2282 /**
2283 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2284 *
2285 * @param string $xmlData XML data
2286 * @return array Attributes of the xml prologue (header)
2287 */
2288 static public function xmlGetHeaderAttribs($xmlData) {
2289 $match = array();
2290 if (preg_match('/^\\s*<\\?xml([^>]*)\\?\\>/', $xmlData, $match)) {
2291 return self::get_tag_attributes($match[1]);
2292 }
2293 }
2294
2295 /**
2296 * Minifies JavaScript
2297 *
2298 * @param string $script Script to minify
2299 * @param string $error Error message (if any)
2300 * @return string Minified script or source string if error happened
2301 */
2302 static public function minifyJavaScript($script, &$error = '') {
2303 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'])) {
2304 $fakeThis = FALSE;
2305 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'] as $hookMethod) {
2306 try {
2307 $parameters = array('script' => $script);
2308 $script = static::callUserFunction($hookMethod, $parameters, $fakeThis);
2309 } catch (\Exception $e) {
2310 $errorMessage = 'Error minifying java script: ' . $e->getMessage();
2311 $error .= $errorMessage;
2312 static::devLog($errorMessage, \TYPO3\CMS\Core\Utility\GeneralUtility::class, 2, array(
2313 'JavaScript' => $script,
2314 'Stack trace' => $e->getTrace(),
2315 'hook' => $hookMethod
2316 ));
2317 }
2318 }
2319 }
2320 return $script;
2321 }
2322
2323 /*************************
2324 *
2325 * FILES FUNCTIONS
2326 *
2327 *************************/
2328 /**
2329 * Reads the file or url $url and returns the content
2330 * 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.
2331 *
2332 * @param string $url File/URL to read
2333 * @param int $includeHeader Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2334 * @param array $requestHeaders HTTP headers to be used in the request
2335 * @param array $report Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2336 * @return mixed The content from the resource given as input. FALSE if an error has occurred.
2337 */
2338 static public function getUrl($url, $includeHeader = 0, $requestHeaders = FALSE, &$report = NULL) {
2339 $content = FALSE;
2340 if (isset($report)) {
2341 $report['error'] = 0;
2342 $report['message'] = '';
2343 }
2344 // Use cURL for: http, https, ftp, ftps, sftp and scp
2345 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2346 if (isset($report)) {
2347 $report['lib'] = 'cURL';
2348 }
2349 // External URL without error checking.
2350 if (!function_exists('curl_init') || !($ch = curl_init())) {
2351 if (isset($report)) {
2352 $report['error'] = -1;
2353 $report['message'] = 'Couldn\'t initialize cURL.';
2354 }
2355 return FALSE;
2356 }
2357
2358 $followLocationSucceeded = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
2359
2360 curl_setopt($ch, CURLOPT_URL, $url);
2361 curl_setopt($ch, CURLOPT_HEADER, !$followLocationSucceeded || $includeHeader ? 1 : 0);
2362 curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
2363 curl_setopt($ch, CURLOPT_HTTPGET, $includeHeader == 2 ? 'HEAD' : 'GET');
2364 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2365 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
2366 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, max(0, (int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout']));
2367
2368 if (is_array($requestHeaders)) {
2369 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
2370 }
2371 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2372 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2373 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2374 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyNTLM']) {
2375 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
2376 }
2377 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2378 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2379 }
2380 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2381 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2382 }
2383 }
2384 $content = curl_exec($ch);
2385 $curlInfo = curl_getinfo($ch);
2386
2387 if (!$followLocationSucceeded) {
2388 // Check if we need to do redirects
2389 if ($curlInfo['http_code'] >= 300 && $curlInfo['http_code'] < 400) {
2390 $locationUrl = $curlInfo['redirect_url'];
2391 if (!$locationUrl) {
2392 // Some curllib versions do not return redirect_url. Examine headers.
2393 $locationUrl = self::getRedirectUrlFromHttpHeaders($content);
2394 }
2395 if ($locationUrl) {
2396 $content = self::getUrl($locationUrl, $includeHeader, $requestHeaders, $report);
2397 $followLocationSucceeded = TRUE;
2398 } else {
2399 // Failure: we got a redirection status code but not the URL to redirect to.
2400 $content = FALSE;
2401 }
2402 }
2403 if ($content && !$includeHeader) {
2404 $content = self::stripHttpHeaders($content);
2405 }
2406 }
2407
2408 if (isset($report)) {
2409 if (!$followLocationSucceeded && $curlInfo['http_code'] >= 300 && $curlInfo['http_code'] < 400) {
2410 $report['http_code'] = $curlInfo['http_code'];
2411 $report['content_type'] = $curlInfo['content_type'];
2412 $report['error'] = CURLE_GOT_NOTHING;
2413 $report['message'] = 'Expected "Location" header but got nothing.';
2414 } elseif ($content === FALSE) {
2415 $report['error'] = curl_errno($ch);
2416 $report['message'] = curl_error($ch);
2417 } elseif ($includeHeader) {
2418 // Set only for $includeHeader to work exactly like PHP variant
2419 $report['http_code'] = $curlInfo['http_code'];
2420 $report['content_type'] = $curlInfo['content_type'];
2421 }
2422 }
2423 curl_close($ch);
2424 } elseif ($includeHeader) {
2425 if (isset($report)) {
2426 $report['lib'] = 'socket';
2427 }
2428 $parsedURL = parse_url($url);
2429 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2430 if (isset($report)) {
2431 $report['error'] = -1;
2432 $report['message'] = 'Reading headers is not allowed for this protocol.';
2433 }
2434 return FALSE;
2435 }
2436 $port = (int)$parsedURL['port'];
2437 if ($port < 1) {
2438 if ($parsedURL['scheme'] == 'http') {
2439 $port = $port > 0 ? $port : 80;
2440 $scheme = '';
2441 } else {
2442 $port = $port > 0 ? $port : 443;
2443 $scheme = 'ssl://';
2444 }
2445 }
2446 $errno = 0;
2447 $fp = @fsockopen(($scheme . $parsedURL['host']), $port, $errno, $errstr, 2.0);
2448 if (!$fp || $errno > 0) {
2449 if (isset($report)) {
2450 $report['error'] = $errno ?: -1;
2451 $report['message'] = $errno ? ($errstr ?: 'Socket error.') : 'Socket initialization error.';
2452 }
2453 return FALSE;
2454 }
2455 $method = $includeHeader == 2 ? 'HEAD' : 'GET';
2456 $msg = $method . ' ' . (isset($parsedURL['path']) ? $parsedURL['path'] : '/') . ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') . ' HTTP/1.0' . CRLF . 'Host: ' . $parsedURL['host'] . '
2457
2458 Connection: close
2459
2460 ';
2461 if (is_array($requestHeaders)) {
2462 $msg .= implode(CRLF, $requestHeaders) . CRLF;
2463 }
2464 $msg .= CRLF;
2465 fputs($fp, $msg);
2466 while (!feof($fp)) {
2467 $line = fgets($fp, 2048);
2468 if (isset($report)) {
2469 if (preg_match('|^HTTP/\\d\\.\\d +(\\d+)|', $line, $status)) {
2470 $report['http_code'] = $status[1];
2471 } elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2472 $report['content_type'] = $type[1];
2473 }
2474 }
2475 $content .= $line;
2476 if (trim($line) === '') {
2477 // Stop at the first empty line (= end of header)
2478 break;
2479 }
2480 }
2481 if ($includeHeader != 2) {
2482 $content .= stream_get_contents($fp);
2483 }
2484 fclose($fp);
2485 } elseif (is_array($requestHeaders)) {
2486 if (isset($report)) {
2487 $report['lib'] = 'file/context';
2488 }
2489 $parsedURL = parse_url($url);
2490 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2491 if (isset($report)) {
2492 $report['error'] = -1;
2493 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2494 }
2495 return FALSE;
2496 }
2497 $ctx = stream_context_create(array(
2498 'http' => array(
2499 'header' => implode(CRLF, $requestHeaders)
2500 )
2501 ));
2502 $content = @file_get_contents($url, FALSE, $ctx);
2503 if ($content === FALSE && isset($report)) {
2504 $report['error'] = -1;
2505 $report['message'] = 'Couldn\'t get URL: ' . (isset($http_response_header) ? implode(LF, $http_response_header) : $url);
2506 }
2507 } else {
2508 if (isset($report)) {
2509 $report['lib'] = 'file';
2510 }
2511 $content = @file_get_contents($url);
2512 if ($content === FALSE && isset($report)) {
2513 $report['error'] = -1;
2514 $report['message'] = 'Couldn\'t get URL: ' . (isset($http_response_header) ? implode(LF, $http_response_header) : $url);
2515 }
2516 }
2517 return $content;
2518 }
2519
2520 /**
2521 * Parses HTTP headers and returns the content of the "Location" header
2522 * or the empty string if no such header found.
2523 *
2524 * @param string $content
2525 * @return string
2526 */
2527 static protected function getRedirectUrlFromHttpHeaders($content) {
2528 $result = '';
2529 $headers = explode("\r\n", $content);
2530 foreach ($headers as $header) {
2531 if ($header == '') {
2532 break;
2533 }
2534 if (preg_match('/^\s*Location\s*:/i', $header)) {
2535 list(, $result) = self::trimExplode(':', $header, FALSE, 2);
2536 if ($result) {
2537 $result = self::locationHeaderUrl($result);
2538 }
2539 break;
2540 }
2541 }
2542 return $result;
2543 }
2544
2545 /**
2546 * Strips HTTP headers from the content.
2547 *
2548 * @param string $content
2549 * @return string
2550 */
2551 static protected function stripHttpHeaders($content) {
2552 $headersEndPos = strpos($content, "\r\n\r\n");
2553 if ($headersEndPos) {
2554 $content = substr($content, $headersEndPos + 4);
2555 }
2556 return $content;
2557 }
2558
2559 /**
2560 * Writes $content to the file $file
2561 *
2562 * @param string $file Filepath to write to
2563 * @param string $content Content to write
2564 * @param bool $changePermissions If TRUE, permissions are forced to be set
2565 * @return bool TRUE if the file was successfully opened and written to.
2566 */
2567 static public function writeFile($file, $content, $changePermissions = FALSE) {
2568 if (!@is_file($file)) {
2569 $changePermissions = TRUE;
2570 }
2571 if ($fd = fopen($file, 'wb')) {
2572 $res = fwrite($fd, $content);
2573 fclose($fd);
2574 if ($res === FALSE) {
2575 return FALSE;
2576 }
2577 // Change the permissions only if the file has just been created
2578 if ($changePermissions) {
2579 self::fixPermissions($file);
2580 }
2581 return TRUE;
2582 }
2583 return FALSE;
2584 }
2585
2586 /**
2587 * Sets the file system mode and group ownership of a file or a folder.
2588 *
2589 * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
2590 * @param bool $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
2591 * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
2592 */
2593 static public function fixPermissions($path, $recursive = FALSE) {
2594 if (TYPO3_OS != 'WIN') {
2595 $result = FALSE;
2596 // Make path absolute
2597 if (!self::isAbsPath($path)) {
2598 $path = self::getFileAbsFileName($path, FALSE);
2599 }
2600 if (self::isAllowedAbsPath($path)) {
2601 if (@is_file($path)) {
2602 $targetFilePermissions = isset($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])
2603 ? octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])
2604 : octdec('0644');
2605 // "@" is there because file is not necessarily OWNED by the user
2606 $result = @chmod($path, $targetFilePermissions);
2607 } elseif (@is_dir($path)) {
2608 $targetDirectoryPermissions = isset($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])
2609 ? octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])
2610 : octdec('0755');
2611 // "@" is there because file is not necessarily OWNED by the user
2612 $result = @chmod($path, $targetDirectoryPermissions);
2613 }
2614 // Set createGroup if not empty
2615 if (
2616 isset($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])
2617 && $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'] !== ''
2618 ) {
2619 // "@" is there because file is not necessarily OWNED by the user
2620 $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2621 $result = $changeGroupResult ? $result : FALSE;
2622 }
2623 // Call recursive if recursive flag if set and $path is directory
2624 if ($recursive && @is_dir($path)) {
2625 $handle = opendir($path);
2626 while (($file = readdir($handle)) !== FALSE) {
2627 $recursionResult = NULL;
2628 if ($file !== '.' && $file !== '..') {
2629 if (@is_file(($path . '/' . $file))) {
2630 $recursionResult = self::fixPermissions($path . '/' . $file);
2631 } elseif (@is_dir(($path . '/' . $file))) {
2632 $recursionResult = self::fixPermissions($path . '/' . $file, TRUE);
2633 }
2634 if (isset($recursionResult) && !$recursionResult) {
2635 $result = FALSE;
2636 }
2637 }
2638 }
2639 closedir($handle);
2640 }
2641 }
2642 } else {
2643 $result = TRUE;
2644 }
2645 return $result;
2646 }
2647
2648 /**
2649 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2650 * Accepts an additional subdirectory in the file path!
2651 *
2652 * @param string $filepath Absolute file path to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/
2653 * @param string $content Content string to write
2654 * @return string Returns NULL on success, otherwise an error string telling about the problem.
2655 */
2656 static public function writeFileToTypo3tempDir($filepath, $content) {
2657 // Parse filepath into directory and basename:
2658 $fI = pathinfo($filepath);
2659 $fI['dirname'] .= '/';
2660 // Check parts:
2661 if (self::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename']) < 60) {
2662 if (defined('PATH_site')) {
2663 // Setting main temporary directory name (standard)
2664 $dirName = PATH_site . 'typo3temp/';
2665 if (@is_dir($dirName)) {
2666 if (self::isFirstPartOfStr($fI['dirname'], $dirName)) {
2667 // Checking if the "subdir" is found:
2668 $subdir = substr($fI['dirname'], strlen($dirName));
2669 if ($subdir) {
2670 if (preg_match('/^[[:alnum:]_]+\\/$/', $subdir) || preg_match('/^[[:alnum:]_]+\\/[[:alnum:]_]+\\/$/', $subdir)) {
2671 $dirName .= $subdir;
2672 if (!@is_dir($dirName)) {
2673 self::mkdir_deep(PATH_site . 'typo3temp/', $subdir);
2674 }
2675 } else {
2676 return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2677 }
2678 }
2679 // Checking dir-name again (sub-dir might have been created):
2680 if (@is_dir($dirName)) {
2681 if ($filepath == $dirName . $fI['basename']) {
2682 self::writeFile($filepath, $content);
2683 if (!@is_file($filepath)) {
2684 return 'The file was not written to the disk. Please, check that you have write permissions to the typo3temp/ directory.';
2685 }
2686 } else {
2687 return 'Calculated filelocation didn\'t match input $filepath!';
2688 }
2689 } else {
2690 return '"' . $dirName . '" is not a directory!';
2691 }
2692 } else {
2693 return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
2694 }
2695 } else {
2696 return 'PATH_site + "typo3temp/" was not a directory!';
2697 }
2698 } else {
2699 return 'PATH_site constant was NOT defined!';
2700 }
2701 } else {
2702 return 'Input filepath "' . $filepath . '" was generally invalid!';
2703 }
2704 }
2705
2706 /**
2707 * Wrapper function for mkdir.
2708 * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']
2709 * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
2710 *
2711 * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2712 * @return bool TRUE if @mkdir went well!
2713 */
2714 static public function mkdir($newFolder) {
2715 $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2716 if ($result) {
2717 self::fixPermissions($newFolder);
2718 }
2719 return $result;
2720 }
2721
2722 /**
2723 * Creates a directory - including parent directories if necessary and
2724 * sets permissions on newly created directories.
2725 *
2726 * @param string $directory Target directory to create. Must a have trailing slash
2727 * @param string $deepDirectory Directory to create. This second parameter
2728 * @return void
2729 * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
2730 * @throws \RuntimeException If directory could not be created
2731 */
2732 static public function mkdir_deep($directory, $deepDirectory = '') {
2733 if (!is_string($directory)) {
2734 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($directory) . '" but a string is expected.', 1303662955);
2735 }
2736 if (!is_string($deepDirectory)) {
2737 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.', 1303662956);
2738 }
2739 // Ensure there is only one slash
2740 $fullPath = rtrim($directory, '/') . '/' . ltrim($deepDirectory, '/');
2741 if ($fullPath !== '' && !is_dir($fullPath)) {
2742 $firstCreatedPath = self::createDirectoryPath($fullPath);
2743 if ($firstCreatedPath !== '') {
2744 self::fixPermissions($firstCreatedPath, TRUE);
2745 }
2746 }
2747 }
2748
2749 /**
2750 * Creates directories for the specified paths if they do not exist. This
2751 * functions sets proper permission mask but does not set proper user and
2752 * group.
2753 *
2754 * @static
2755 * @param string $fullDirectoryPath
2756 * @return string Path to the the first created directory in the hierarchy
2757 * @see \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep
2758 * @throws \RuntimeException If directory could not be created
2759 */
2760 static protected function createDirectoryPath($fullDirectoryPath) {
2761 $currentPath = $fullDirectoryPath;
2762 $firstCreatedPath = '';
2763 $permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']);
2764 if (!@is_dir($currentPath)) {
2765 do {
2766 $firstCreatedPath = $currentPath;
2767 $separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR);
2768 $currentPath = substr($currentPath, 0, $separatorPosition);
2769 } while (!is_dir($currentPath) && $separatorPosition !== FALSE);
2770 $result = @mkdir($fullDirectoryPath, $permissionMask, TRUE);
2771 // Check existence of directory again to avoid race condition. Directory could have get created by another process between previous is_dir() and mkdir()
2772 if (!$result && !@is_dir($fullDirectoryPath)) {
2773 throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251401);
2774 }
2775 }
2776 return $firstCreatedPath;
2777 }
2778
2779 /**
2780 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2781 *
2782 * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2783 * @param bool $removeNonEmpty Allow deletion of non-empty directories
2784 * @return bool TRUE if @rmdir went well!
2785 */
2786 static public function rmdir($path, $removeNonEmpty = FALSE) {
2787 $OK = FALSE;
2788 // Remove trailing slash
2789 $path = preg_replace('|/$|', '', $path);
2790 if (file_exists($path)) {
2791 $OK = TRUE;
2792 if (!is_link($path) && is_dir($path)) {
2793 if ($removeNonEmpty == TRUE && ($handle = @opendir($path))) {
2794 while ($OK && FALSE !== ($file = readdir($handle))) {
2795 if ($file == '.' || $file == '..') {
2796 continue;
2797 }
2798 $OK = self::rmdir($path . '/' . $file, $removeNonEmpty);
2799 }
2800 closedir($handle);
2801 }
2802 if ($OK) {
2803 $OK = @rmdir($path);
2804 }
2805 } elseif (is_link($path) && is_dir($path) && TYPO3_OS === 'WIN') {
2806 $OK = @rmdir($path);
2807 } else {
2808 // If $path is a file, simply remove it
2809 $OK = @unlink($path);
2810 }
2811 clearstatcache();
2812 } elseif (is_link($path)) {
2813 $OK = @unlink($path);
2814 clearstatcache();
2815 }
2816 return $OK;
2817 }
2818
2819 /**
2820 * Flushes a directory by first moving to a temporary resource, and then
2821 * triggering the remove process. This way directories can be flushed faster
2822 * to prevent race conditions on concurrent processes accessing the same directory.
2823 *
2824 * @param string $directory The directory to be renamed and flushed
2825 * @param bool $keepOriginalDirectory Whether to only empty the directory and not remove it
2826 * @param bool $flushOpcodeCache Also flush the opcode cache right after renaming the directory.
2827 * @return bool Whether the action was successful
2828 */
2829 static public function flushDirectory($directory, $keepOriginalDirectory = FALSE, $flushOpcodeCache = FALSE) {
2830 $result = FALSE;
2831
2832 if (is_dir($directory)) {
2833 $temporaryDirectory = rtrim($directory, '/') . '.' . uniqid('remove', TRUE) . '/';
2834 if (rename($directory, $temporaryDirectory)) {
2835 if ($flushOpcodeCache) {
2836 GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive($directory);
2837 }
2838 if ($keepOriginalDirectory) {
2839 self::mkdir($directory);
2840 }
2841 clearstatcache();
2842 $result = self::rmdir($temporaryDirectory, TRUE);
2843 }
2844 }
2845
2846 return $result;
2847 }
2848
2849 /**
2850 * Returns an array with the names of folders in a specific path
2851 * Will return 'error' (string) if there were an error with reading directory content.
2852 *
2853 * @param string $path Path to list directories from
2854 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2855 */
2856 static public function get_dirs($path) {
2857 if ($path) {
2858 if (is_dir($path)) {
2859 $dir = scandir($path);
2860 $dirs = array();
2861 foreach ($dir as $entry) {
2862 if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
2863 $dirs[] = $entry;
2864 }
2865 }
2866 } else {
2867 $dirs = 'error';
2868 }
2869 }
2870 return $dirs;
2871 }
2872
2873 /**
2874 * Finds all files in a given path and returns them as an array. Each
2875 * array key is a md5 hash of the full path to the file. This is done because
2876 * 'some' extensions like the import/export extension depend on this.
2877 *
2878 * @param string $path The path to retrieve the files from.
2879 * @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.
2880 * @param bool $prependPath If TRUE, the full path to the file is returned. If FALSE only the file name is returned.
2881 * @param string $order The sorting order. The default sorting order is alphabetical. Setting $order to 'mtime' will sort the files by modification time.
2882 * @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 '$/'.
2883 * @return array|string Array of the files found, or an error message in case the path could not be opened.
2884 */
2885 static public function getFilesInDir($path, $extensionList = '', $prependPath = FALSE, $order = '', $excludePattern = '') {
2886 $excludePattern = (string)$excludePattern;
2887 $path = rtrim($path, '/');
2888 if (!@is_dir($path)) {
2889 return array();
2890 }
2891
2892 $rawFileList = scandir($path);
2893 if ($rawFileList === FALSE) {
2894 return 'error opening path: "' . $path . '"';
2895 }
2896
2897 $pathPrefix = $path . '/';
2898 $extensionList = ',' . $extensionList . ',';
2899 $files = array();
2900 foreach ($rawFileList as $entry) {
2901 $completePathToEntry = $pathPrefix . $entry;
2902 if (!@is_file($completePathToEntry)) {
2903 continue;
2904 }
2905
2906 if (
2907 ($extensionList === ',,' || stripos($extensionList, ',' . pathinfo($entry, PATHINFO_EXTENSION) . ',') !== FALSE)
2908 && ($excludePattern === '' || !preg_match(('/^' . $excludePattern . '$/'), $entry))
2909 ) {
2910 if ($order !== 'mtime') {
2911 $files[] = $entry;
2912 } else {
2913 // Store the value in the key so we can do a fast asort later.
2914 $files[$entry] = filemtime($completePathToEntry);
2915 }
2916 }
2917 }
2918
2919 $valueName = 'value';
2920 if ($order === 'mtime') {
2921 asort($files);
2922 $valueName = 'key';
2923 }
2924
2925 $valuePathPrefix = $prependPath ? $pathPrefix : '';
2926 $foundFiles = array();
2927 foreach ($files as $key => $value) {
2928 // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
2929 $foundFiles[md5($pathPrefix . ${$valueName})] = $valuePathPrefix . ${$valueName};
2930 }
2931
2932 return $foundFiles;
2933 }
2934
2935 /**
2936 * Recursively gather all files and folders of a path.
2937 *
2938 * @param array $fileArr Empty input array (will have files added to it)
2939 * @param string $path The path to read recursively from (absolute) (include trailing slash!)
2940 * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2941 * @param bool $regDirs If set, directories are also included in output.
2942 * @param int $recursivityLevels The number of levels to dig down...
2943 * @param string $excludePattern regex pattern of files/directories to exclude
2944 * @return array An array with the found files/directories.
2945 */
2946 static public function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = FALSE, $recursivityLevels = 99, $excludePattern = '') {