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