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