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