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