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