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