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