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