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