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