[TASK] Use arrays in str_replace() calls
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / GeneralUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the textfile GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29 /**
30 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
31 * Most of the functions do not relate specifically to TYPO3
32 * However a section of functions requires certain TYPO3 features available
33 * See comments in the source.
34 * You are encouraged to use this library in your own scripts!
35 *
36 * USE:
37 * The class is intended to be used without creating an instance of it.
38 * So: Don't instantiate - call functions with "\TYPO3\CMS\Core\Utility\GeneralUtility::" prefixed the function name.
39 * So use \TYPO3\CMS\Core\Utility\GeneralUtility::[method-name] to refer to the functions, eg. '\TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds()'
40 *
41 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
42 */
43 class GeneralUtility {
44
45 // Severity constants used by \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog()
46 const SYSLOG_SEVERITY_INFO = 0;
47 const SYSLOG_SEVERITY_NOTICE = 1;
48 const SYSLOG_SEVERITY_WARNING = 2;
49 const SYSLOG_SEVERITY_ERROR = 3;
50 const SYSLOG_SEVERITY_FATAL = 4;
51 /**
52 * Singleton instances returned by makeInstance, using the class names as
53 * array keys
54 *
55 * @var array<\TYPO3\CMS\Core\SingletonInterface>
56 */
57 static protected $singletonInstances = array();
58
59 /**
60 * Instances returned by makeInstance, using the class names as array keys
61 *
62 * @var array<array><object>
63 */
64 static protected $nonSingletonInstances = array();
65
66 /**
67 * The application context
68 *
69 * @var \TYPO3\CMS\Core\Core\ApplicationContext
70 */
71 static protected $applicationContext = NULL;
72
73 /**
74 * IDNA string cache
75 *
76 * @var array<string>
77 */
78 static protected $idnaStringCache = array();
79
80 /**
81 * IDNA converter
82 *
83 * @var \idna_convert
84 */
85 static protected $idnaConverter = NULL;
86
87 /*************************
88 *
89 * GET/POST Variables
90 *
91 * Background:
92 * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
93 * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
94 * But the clean solution is that quotes are never escaped and that is what the functions below offers.
95 * Eventually TYPO3 should provide this in the global space as well.
96 * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
97 *
98 *************************/
99 /**
100 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
101 * Strips slashes from all output, both strings and arrays.
102 * 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
103 * know by which method your data is arriving to the scripts!
104 *
105 * @param string $var GET/POST var to return
106 * @return mixed POST var named $var and if not set, the GET var of the same name.
107 */
108 static public function _GP($var) {
109 if (empty($var)) {
110 return;
111 }
112 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
113 if (isset($value)) {
114 if (is_array($value)) {
115 self::stripSlashesOnArray($value);
116 } else {
117 $value = stripslashes($value);
118 }
119 }
120 return $value;
121 }
122
123 /**
124 * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
125 *
126 * @param string $parameter Key (variable name) from GET or POST vars
127 * @return array Returns the GET vars merged recursively onto the POST vars.
128 */
129 static public function _GPmerged($parameter) {
130 $postParameter = isset($_POST[$parameter]) && is_array($_POST[$parameter]) ? $_POST[$parameter] : array();
131 $getParameter = isset($_GET[$parameter]) && is_array($_GET[$parameter]) ? $_GET[$parameter] : array();
132 $mergedParameters = $getParameter;
133 ArrayUtility::mergeRecursiveWithOverrule($mergedParameters, $postParameter);
134 self::stripSlashesOnArray($mergedParameters);
135 return $mergedParameters;
136 }
137
138 /**
139 * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
140 * ALWAYS use this API function to acquire the GET variables!
141 *
142 * @param string $var Optional pointer to value in GET array (basically name of GET var)
143 * @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!*
144 * @see _POST(), _GP(), _GETset()
145 */
146 static public function _GET($var = NULL) {
147 $value = $var === NULL ? $_GET : (empty($var) ? NULL : $_GET[$var]);
148 // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
149 if (isset($value)) {
150 if (is_array($value)) {
151 self::stripSlashesOnArray($value);
152 } else {
153 $value = stripslashes($value);
154 }
155 }
156 return $value;
157 }
158
159 /**
160 * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
161 * ALWAYS use this API function to acquire the $_POST variables!
162 *
163 * @param string $var Optional pointer to value in POST array (basically name of POST var)
164 * @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!*
165 * @see _GET(), _GP()
166 */
167 static public function _POST($var = NULL) {
168 $value = $var === NULL ? $_POST : (empty($var) ? NULL : $_POST[$var]);
169 // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
170 if (isset($value)) {
171 if (is_array($value)) {
172 self::stripSlashesOnArray($value);
173 } else {
174 $value = stripslashes($value);
175 }
176 }
177 return $value;
178 }
179
180 /**
181 * Writes input value to $_GET.
182 *
183 * @param mixed $inputGet
184 * @param string $key
185 * @return void
186 */
187 static public function _GETset($inputGet, $key = '') {
188 // Adds slashes since TYPO3 standard currently is that slashes
189 // must be applied (regardless of magic_quotes setting)
190 if (is_array($inputGet)) {
191 self::addSlashesOnArray($inputGet);
192 } else {
193 $inputGet = addslashes($inputGet);
194 }
195 if ($key != '') {
196 if (strpos($key, '|') !== FALSE) {
197 $pieces = explode('|', $key);
198 $newGet = array();
199 $pointer = &$newGet;
200 foreach ($pieces as $piece) {
201 $pointer = &$pointer[$piece];
202 }
203 $pointer = $inputGet;
204 $mergedGet = $_GET;
205 ArrayUtility::mergeRecursiveWithOverrule($mergedGet, $newGet);
206 $_GET = $mergedGet;
207 $GLOBALS['HTTP_GET_VARS'] = $mergedGet;
208 } else {
209 $_GET[$key] = $inputGet;
210 $GLOBALS['HTTP_GET_VARS'][$key] = $inputGet;
211 }
212 } elseif (is_array($inputGet)) {
213 $_GET = $inputGet;
214 $GLOBALS['HTTP_GET_VARS'] = $inputGet;
215 }
216 }
217
218 /**
219 * Wrapper for the RemoveXSS function.
220 * Removes potential XSS code from an input string.
221 *
222 * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
223 *
224 * @param string $string Input string
225 * @return string Input string with potential XSS code removed
226 */
227 static public function removeXSS($string) {
228 require_once PATH_typo3 . 'contrib/RemoveXSS/RemoveXSS.php';
229 $string = \RemoveXSS::process($string);
230 return $string;
231 }
232
233 /*************************
234 *
235 * IMAGE FUNCTIONS
236 *
237 *************************/
238 /**
239 * Compressing a GIF file if not already LZW compressed.
240 * 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)
241 *
242 * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
243 * GIF:
244 * 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!)
245 * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
246 * PNG:
247 * No changes.
248 *
249 * $theFile is expected to be a valid GIF-file!
250 * The function returns a code for the operation.
251 *
252 * @param string $theFile Filepath
253 * @param string $type See description of function
254 * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
255 */
256 static public function gif_compress($theFile, $type) {
257 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
258 $returnCode = '';
259 // GIF...
260 if ($gfxConf['gif_compress'] && strtolower(substr($theFile, -4, 4)) == '.gif') {
261 // IM
262 if (($type == 'IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) {
263 // Use temporary file to prevent problems with read and write lock on same file on network file systems
264 $temporaryName = dirname($theFile) . '/' . md5(uniqid()) . '.gif';
265 // Rename could fail, if a simultaneous thread is currently working on the same thing
266 if (@rename($theFile, $temporaryName)) {
267 $cmd = self::imageMagickCommand('convert', '"' . $temporaryName . '" "' . $theFile . '"', $gfxConf['im_path_lzw']);
268 \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd);
269 unlink($temporaryName);
270 }
271 $returnCode = 'IM';
272 if (@is_file($theFile)) {
273 self::fixPermissions($theFile);
274 }
275 } elseif (($type == 'GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) {
276 // GD
277 $tempImage = imageCreateFromGif($theFile);
278 imageGif($tempImage, $theFile);
279 imageDestroy($tempImage);
280 $returnCode = 'GD';
281 if (@is_file($theFile)) {
282 self::fixPermissions($theFile);
283 }
284 }
285 }
286 return $returnCode;
287 }
288
289 /**
290 * Converts a png file to gif.
291 * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set TRUE.
292 *
293 * @param string $theFile The filename with path
294 * @return string New filename
295 */
296 static public function png_to_gif_by_imagemagick($theFile) {
297 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)) {
298 // IM
299 $newFile = substr($theFile, 0, -4) . '.gif';
300 $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
301 \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd);
302 $theFile = $newFile;
303 if (@is_file($newFile)) {
304 self::fixPermissions($newFile);
305 }
306 }
307 return $theFile;
308 }
309
310 /**
311 * Returns filename of the png/gif version of the input file (which can be png or gif).
312 * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
313 *
314 * @param string $theFile Filepath of image file
315 * @param boolean $output_png If set, then input file is converted to PNG, otherwise to GIF
316 * @return string If the new image file exists, its filepath is returned
317 */
318 static public function read_png_gif($theFile, $output_png = FALSE) {
319 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) {
320 $ext = strtolower(substr($theFile, -4, 4));
321 if ((string) $ext == '.png' && $output_png || (string) $ext == '.gif' && !$output_png) {
322 return $theFile;
323 } else {
324 $newFile = PATH_site . 'typo3temp/readPG_' . md5(($theFile . '|' . filemtime($theFile))) . ($output_png ? '.png' : '.gif');
325 $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']);
326 \TYPO3\CMS\Core\Utility\CommandUtility::exec($cmd);
327 if (@is_file($newFile)) {
328 self::fixPermissions($newFile);
329 return $newFile;
330 }
331 }
332 }
333 }
334
335 /*************************
336 *
337 * STRING FUNCTIONS
338 *
339 *************************/
340 /**
341 * Truncates a string with appended/prepended "..." and takes current character set into consideration.
342 *
343 * @param string $string String to truncate
344 * @param integer $chars Must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
345 * @param string $appendString Appendix to the truncated string
346 * @return string Cropped string
347 */
348 static public function fixed_lgd_cs($string, $chars, $appendString = '...') {
349 if (is_object($GLOBALS['LANG'])) {
350 return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet, $string, $chars, $appendString);
351 } elseif (is_object($GLOBALS['TSFE'])) {
352 $charSet = $GLOBALS['TSFE']->renderCharset != '' ? $GLOBALS['TSFE']->renderCharset : $GLOBALS['TSFE']->defaultCharSet;
353 return $GLOBALS['TSFE']->csConvObj->crop($charSet, $string, $chars, $appendString);
354 } else {
355 // This case should not happen
356 $csConvObj = self::makeInstance('TYPO3\\CMS\\Core\\Charset\\CharsetConverter');
357 return $csConvObj->crop('utf-8', $string, $chars, $appendString);
358 }
359 }
360
361 /**
362 * Match IP number with list of numbers with wildcard
363 * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
364 *
365 * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
366 * @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.
367 * @return boolean TRUE if an IP-mask from $list matches $baseIP
368 */
369 static public function cmpIP($baseIP, $list) {
370 $list = trim($list);
371 if ($list === '') {
372 return FALSE;
373 } elseif ($list === '*') {
374 return TRUE;
375 }
376 if (strpos($baseIP, ':') !== FALSE && self::validIPv6($baseIP)) {
377 return self::cmpIPv6($baseIP, $list);
378 } else {
379 return self::cmpIPv4($baseIP, $list);
380 }
381 }
382
383 /**
384 * Match IPv4 number with list of numbers with wildcard
385 *
386 * @param string $baseIP Is the current remote IP address for instance, typ. REMOTE_ADDR
387 * @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
388 * @return boolean TRUE if an IP-mask from $list matches $baseIP
389 */
390 static public function cmpIPv4($baseIP, $list) {
391 $IPpartsReq = explode('.', $baseIP);
392 if (count($IPpartsReq) == 4) {
393 $values = self::trimExplode(',', $list, TRUE);
394 foreach ($values as $test) {
395 $testList = explode('/', $test);
396 if (count($testList) == 2) {
397 list($test, $mask) = $testList;
398 } else {
399 $mask = FALSE;
400 }
401 if (intval($mask)) {
402 // "192.168.3.0/24"
403 $lnet = ip2long($test);
404 $lip = ip2long($baseIP);
405 $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT);
406 $firstpart = substr($binnet, 0, $mask);
407 $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT);
408 $firstip = substr($binip, 0, $mask);
409 $yes = strcmp($firstpart, $firstip) == 0;
410 } else {
411 // "192.168.*.*"
412 $IPparts = explode('.', $test);
413 $yes = 1;
414 foreach ($IPparts as $index => $val) {
415 $val = trim($val);
416 if ($val !== '*' && $IPpartsReq[$index] !== $val) {
417 $yes = 0;
418 }
419 }
420 }
421 if ($yes) {
422 return TRUE;
423 }
424 }
425 }
426 return FALSE;
427 }
428
429 /**
430 * Match IPv6 address with a list of IPv6 prefixes
431 *
432 * @param string $baseIP Is the current remote IP address for instance
433 * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
434 * @return boolean TRUE If an baseIP matches any prefix
435 */
436 static public function cmpIPv6($baseIP, $list) {
437 // Policy default: Deny connection
438 $success = FALSE;
439 $baseIP = self::normalizeIPv6($baseIP);
440 $values = self::trimExplode(',', $list, TRUE);
441 foreach ($values as $test) {
442 $testList = explode('/', $test);
443 if (count($testList) == 2) {
444 list($test, $mask) = $testList;
445 } else {
446 $mask = FALSE;
447 }
448 if (self::validIPv6($test)) {
449 $test = self::normalizeIPv6($test);
450 $maskInt = intval($mask) ? intval($mask) : 128;
451 // Special case; /0 is an allowed mask - equals a wildcard
452 if ($mask === '0') {
453 $success = TRUE;
454 } elseif ($maskInt == 128) {
455 $success = $test === $baseIP;
456 } else {
457 $testBin = self::IPv6Hex2Bin($test);
458 $baseIPBin = self::IPv6Hex2Bin($baseIP);
459 $success = TRUE;
460 // Modulo is 0 if this is a 8-bit-boundary
461 $maskIntModulo = $maskInt % 8;
462 $numFullCharactersUntilBoundary = intval($maskInt / 8);
463 if (substr($testBin, 0, $numFullCharactersUntilBoundary) !== substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) {
464 $success = FALSE;
465 } elseif ($maskIntModulo > 0) {
466 // If not an 8-bit-boundary, check bits of last character
467 $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
468 $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT);
469 if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
470 $success = FALSE;
471 }
472 }
473 }
474 }
475 if ($success) {
476 return TRUE;
477 }
478 }
479 return FALSE;
480 }
481
482 /**
483 * Transform a regular IPv6 address from hex-representation into binary
484 *
485 * @param string $hex IPv6 address in hex-presentation
486 * @return string Binary representation (16 characters, 128 characters)
487 * @see IPv6Bin2Hex()
488 */
489 static public function IPv6Hex2Bin($hex) {
490 return inet_pton($hex);
491 }
492
493 /**
494 * Transform an IPv6 address from binary to hex-representation
495 *
496 * @param string $bin IPv6 address in hex-presentation
497 * @return string Binary representation (16 characters, 128 characters)
498 * @see IPv6Hex2Bin()
499 */
500 static public function IPv6Bin2Hex($bin) {
501 return inet_ntop($bin);
502 }
503
504 /**
505 * Normalize an IPv6 address to full length
506 *
507 * @param string $address Given IPv6 address
508 * @return string Normalized address
509 * @see compressIPv6()
510 */
511 static public function normalizeIPv6($address) {
512 $normalizedAddress = '';
513 $stageOneAddress = '';
514 // According to RFC lowercase-representation is recommended
515 $address = strtolower($address);
516 // Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
517 if (strlen($address) == 39) {
518 // Already in full expanded form
519 return $address;
520 }
521 // Count 2 if if address has hidden zero blocks
522 $chunks = explode('::', $address);
523 if (count($chunks) == 2) {
524 $chunksLeft = explode(':', $chunks[0]);
525 $chunksRight = explode(':', $chunks[1]);
526 $left = count($chunksLeft);
527 $right = count($chunksRight);
528 // Special case: leading zero-only blocks count to 1, should be 0
529 if ($left == 1 && strlen($chunksLeft[0]) == 0) {
530 $left = 0;
531 }
532 $hiddenBlocks = 8 - ($left + $right);
533 $hiddenPart = '';
534 $h = 0;
535 while ($h < $hiddenBlocks) {
536 $hiddenPart .= '0000:';
537 $h++;
538 }
539 if ($left == 0) {
540 $stageOneAddress = $hiddenPart . $chunks[1];
541 } else {
542 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
543 }
544 } else {
545 $stageOneAddress = $address;
546 }
547 // Normalize the blocks:
548 $blocks = explode(':', $stageOneAddress);
549 $divCounter = 0;
550 foreach ($blocks as $block) {
551 $tmpBlock = '';
552 $i = 0;
553 $hiddenZeros = 4 - strlen($block);
554 while ($i < $hiddenZeros) {
555 $tmpBlock .= '0';
556 $i++;
557 }
558 $normalizedAddress .= $tmpBlock . $block;
559 if ($divCounter < 7) {
560 $normalizedAddress .= ':';
561 $divCounter++;
562 }
563 }
564 return $normalizedAddress;
565 }
566
567 /**
568 * Compress an IPv6 address to the shortest notation
569 *
570 * @param string $address Given IPv6 address
571 * @return string Compressed address
572 * @see normalizeIPv6()
573 */
574 static public function compressIPv6($address) {
575 return inet_ntop(inet_pton($address));
576 }
577
578 /**
579 * Validate a given IP address.
580 *
581 * Possible format are IPv4 and IPv6.
582 *
583 * @param string $ip IP address to be tested
584 * @return boolean TRUE if $ip is either of IPv4 or IPv6 format.
585 */
586 static public function validIP($ip) {
587 return filter_var($ip, FILTER_VALIDATE_IP) !== FALSE;
588 }
589
590 /**
591 * Validate a given IP address to the IPv4 address format.
592 *
593 * Example for possible format: 10.0.45.99
594 *
595 * @param string $ip IP address to be tested
596 * @return boolean TRUE if $ip is of IPv4 format.
597 */
598 static public function validIPv4($ip) {
599 return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE;
600 }
601
602 /**
603 * Validate a given IP address to the IPv6 address format.
604 *
605 * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
606 *
607 * @param string $ip IP address to be tested
608 * @return boolean TRUE if $ip is of IPv6 format.
609 */
610 static public function validIPv6($ip) {
611 return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE;
612 }
613
614 /**
615 * Match fully qualified domain name with list of strings with wildcard
616 *
617 * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
618 * @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)
619 * @return boolean TRUE if a domain name mask from $list matches $baseIP
620 */
621 static public function cmpFQDN($baseHost, $list) {
622 $baseHost = trim($baseHost);
623 if (empty($baseHost)) {
624 return FALSE;
625 }
626 if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) {
627 // Resolve hostname
628 // Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
629 // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
630 $baseHostName = gethostbyaddr($baseHost);
631 if ($baseHostName === $baseHost) {
632 // Unable to resolve hostname
633 return FALSE;
634 }
635 } else {
636 $baseHostName = $baseHost;
637 }
638 $baseHostNameParts = explode('.', $baseHostName);
639 $values = self::trimExplode(',', $list, TRUE);
640 foreach ($values as $test) {
641 $hostNameParts = explode('.', $test);
642 // To match hostNameParts can only be shorter (in case of wildcards) or equal
643 if (count($hostNameParts) > count($baseHostNameParts)) {
644 continue;
645 }
646 $yes = TRUE;
647 foreach ($hostNameParts as $index => $val) {
648 $val = trim($val);
649 if ($val === '*') {
650 // Wildcard valid for one or more hostname-parts
651 $wildcardStart = $index + 1;
652 // Wildcard as last/only part always matches, otherwise perform recursive checks
653 if ($wildcardStart < count($hostNameParts)) {
654 $wildcardMatched = FALSE;
655 $tempHostName = implode('.', array_slice($hostNameParts, $index + 1));
656 while ($wildcardStart < count($baseHostNameParts) && !$wildcardMatched) {
657 $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
658 $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName);
659 $wildcardStart++;
660 }
661 if ($wildcardMatched) {
662 // Match found by recursive compare
663 return TRUE;
664 } else {
665 $yes = FALSE;
666 }
667 }
668 } elseif ($baseHostNameParts[$index] !== $val) {
669 // In case of no match
670 $yes = FALSE;
671 }
672 }
673 if ($yes) {
674 return TRUE;
675 }
676 }
677 return FALSE;
678 }
679
680 /**
681 * Checks if a given URL matches the host that currently handles this HTTP request.
682 * Scheme, hostname and (optional) port of the given URL are compared.
683 *
684 * @param string $url URL to compare with the TYPO3 request host
685 * @return boolean Whether the URL matches the TYPO3 request host
686 */
687 static public function isOnCurrentHost($url) {
688 return stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0;
689 }
690
691 /**
692 * Check for item in list
693 * Check if an item exists in a comma-separated list of items.
694 *
695 * @param string $list Comma-separated list of items (string)
696 * @param string $item Item to check for
697 * @return boolean TRUE if $item is in $list
698 */
699 static public function inList($list, $item) {
700 return strpos(',' . $list . ',', ',' . $item . ',') !== FALSE;
701 }
702
703 /**
704 * Removes an item from a comma-separated list of items.
705 *
706 * @param string $element Element to remove
707 * @param string $list Comma-separated list of items (string)
708 * @return string New comma-separated list of items
709 */
710 static public function rmFromList($element, $list) {
711 $items = explode(',', $list);
712 foreach ($items as $k => $v) {
713 if ($v == $element) {
714 unset($items[$k]);
715 }
716 }
717 return implode(',', $items);
718 }
719
720 /**
721 * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
722 * Ranges are limited to 1000 values per range.
723 *
724 * @param string $list Comma-separated list of integers with ranges (string)
725 * @return string New comma-separated list of items
726 */
727 static public function expandList($list) {
728 $items = explode(',', $list);
729 $list = array();
730 foreach ($items as $item) {
731 $range = explode('-', $item);
732 if (isset($range[1])) {
733 $runAwayBrake = 1000;
734 for ($n = $range[0]; $n <= $range[1]; $n++) {
735 $list[] = $n;
736 $runAwayBrake--;
737 if ($runAwayBrake <= 0) {
738 break;
739 }
740 }
741 } else {
742 $list[] = $item;
743 }
744 }
745 return implode(',', $list);
746 }
747
748 /**
749 * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
750 *
751 * @param string $verNumberStr Version number on format x.x.x
752 * @return integer Integer version of version number (where each part can count to 999)
753 * @deprecated Use VersionNumberUtility::convertVersionNumberToInteger instead, will be removed after 6.2
754 */
755 static public function int_from_ver($verNumberStr) {
756 self::logDeprecatedFunction();
757 return VersionNumberUtility::convertVersionNumberToInteger($verNumberStr);
758 }
759
760 /**
761 * Returns TRUE if the current TYPO3 version (or compatibility version) is compatible to the input version
762 * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
763 *
764 * @param string $verNumberStr Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
765 * @return boolean Returns TRUE if this setup is compatible with the provided version number
766 * @todo Still needs a function to convert versions to branches
767 */
768 static public function compat_version($verNumberStr) {
769 $currVersionStr = $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] : TYPO3_branch;
770 if (\TYPO3\CMS\Core\Utility\VersionNumberUtility::convertVersionNumberToInteger($currVersionStr) < \TYPO3\CMS\Core\Utility\VersionNumberUtility::convertVersionNumberToInteger($verNumberStr)) {
771 return FALSE;
772 } else {
773 return TRUE;
774 }
775 }
776
777 /**
778 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
779 *
780 * @param string $str String to md5-hash
781 * @return integer Returns 28bit integer-hash
782 */
783 static public function md5int($str) {
784 return hexdec(substr(md5($str), 0, 7));
785 }
786
787 /**
788 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
789 *
790 * @param string $input Input string to be md5-hashed
791 * @param integer $len The string-length of the output
792 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
793 */
794 static public function shortMD5($input, $len = 10) {
795 return substr(md5($input), 0, $len);
796 }
797
798 /**
799 * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
800 *
801 * @param string $input Input string to create HMAC from
802 * @param string $additionalSecret additionalSecret to prevent hmac beeing used in a different context
803 * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
804 */
805 static public function hmac($input, $additionalSecret = '') {
806 $hashAlgorithm = 'sha1';
807 $hashBlocksize = 64;
808 $hmac = '';
809 $secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
810 if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
811 $hmac = hash_hmac($hashAlgorithm, $input, $secret);
812 } else {
813 // Outer padding
814 $opad = str_repeat(chr(92), $hashBlocksize);
815 // Inner padding
816 $ipad = str_repeat(chr(54), $hashBlocksize);
817 if (strlen($secret) > $hashBlocksize) {
818 // Keys longer than block size are shorten
819 $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, chr(0));
820 } else {
821 // Keys shorter than block size are zero-padded
822 $key = str_pad($secret, $hashBlocksize, chr(0));
823 }
824 $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, (($key ^ $ipad) . $input))));
825 }
826 return $hmac;
827 }
828
829 /**
830 * Takes comma-separated lists and arrays and removes all duplicates
831 * If a value in the list is trim(empty), the value is ignored.
832 *
833 * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
834 * @param mixed $secondParameter Dummy field, which if set will show a warning!
835 * @return string Returns the list without any duplicates of values, space around values are trimmed
836 */
837 static public function uniqueList($in_list, $secondParameter = NULL) {
838 if (is_array($in_list)) {
839 throw new \InvalidArgumentException('TYPO3 Fatal Error: TYPO3\\CMS\\Core\\Utility\\GeneralUtility::uniqueList() does NOT support array arguments anymore! Only string comma lists!', 1270853885);
840 }
841 if (isset($secondParameter)) {
842 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);
843 }
844 return implode(',', array_unique(self::trimExplode(',', $in_list, TRUE)));
845 }
846
847 /**
848 * Splits a reference to a file in 5 parts
849 *
850 * @param string $fileref Filename/filepath to be analysed
851 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
852 */
853 static public function split_fileref($fileref) {
854 $reg = array();
855 if (preg_match('/(.*\\/)(.*)$/', $fileref, $reg)) {
856 $info['path'] = $reg[1];
857 $info['file'] = $reg[2];
858 } else {
859 $info['path'] = '';
860 $info['file'] = $fileref;
861 }
862 $reg = '';
863 if (!is_dir($fileref) && preg_match('/(.*)\\.([^\\.]*$)/', $info['file'], $reg)) {
864 $info['filebody'] = $reg[1];
865 $info['fileext'] = strtolower($reg[2]);
866 $info['realFileext'] = $reg[2];
867 } else {
868 $info['filebody'] = $info['file'];
869 $info['fileext'] = '';
870 }
871 reset($info);
872 return $info;
873 }
874
875 /**
876 * Returns the directory part of a path without trailing slash
877 * If there is no dir-part, then an empty string is returned.
878 * Behaviour:
879 *
880 * '/dir1/dir2/script.php' => '/dir1/dir2'
881 * '/dir1/' => '/dir1'
882 * 'dir1/script.php' => 'dir1'
883 * 'd/script.php' => 'd'
884 * '/script.php' => ''
885 * '' => ''
886 *
887 * @param string $path Directory name / path
888 * @return string Processed input value. See function description.
889 */
890 static public function dirname($path) {
891 $p = self::revExplode('/', $path, 2);
892 return count($p) == 2 ? $p[0] : '';
893 }
894
895 /**
896 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
897 *
898 * @param string $color A hexadecimal color code, #xxxxxx
899 * @param integer $R Offset value 0-255
900 * @param integer $G Offset value 0-255
901 * @param integer $B Offset value 0-255
902 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
903 * @see modifyHTMLColorAll()
904 */
905 static public function modifyHTMLColor($color, $R, $G, $B) {
906 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
907 $nR = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
908 $nG = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
909 $nB = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
910 return '#' . substr(('0' . dechex($nR)), -2) . substr(('0' . dechex($nG)), -2) . substr(('0' . dechex($nB)), -2);
911 }
912
913 /**
914 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
915 *
916 * @param string $color A hexadecimal color code, #xxxxxx
917 * @param integer $all Offset value 0-255 for all three channels.
918 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
919 * @see modifyHTMLColor()
920 */
921 static public function modifyHTMLColorAll($color, $all) {
922 return self::modifyHTMLColor($color, $all, $all, $all);
923 }
924
925 /**
926 * Returns TRUE if the first part of $str matches the string $partStr
927 *
928 * @param string $str Full string to check
929 * @param string $partStr Reference string which must be found as the "first part" of the full string
930 * @return boolean TRUE if $partStr was found to be equal to the first part of $str
931 */
932 static public function isFirstPartOfStr($str, $partStr) {
933 return $partStr != '' && strpos((string) $str, (string) $partStr, 0) === 0;
934 }
935
936 /**
937 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
938 *
939 * @param integer $sizeInBytes Number of bytes to format.
940 * @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)
941 * @return string Formatted representation of the byte number, for output.
942 */
943 static public function formatSize($sizeInBytes, $labels = '') {
944 // Set labels:
945 if (strlen($labels) == 0) {
946 $labels = ' | K| M| G';
947 } else {
948 $labels = str_replace('"', '', $labels);
949 }
950 $labelArr = explode('|', $labels);
951 // Find size:
952 if ($sizeInBytes > 900) {
953 // GB
954 if ($sizeInBytes > 900000000) {
955 $val = $sizeInBytes / (1024 * 1024 * 1024);
956 return number_format($val, ($val < 20 ? 1 : 0), '.', '') . $labelArr[3];
957 } elseif ($sizeInBytes > 900000) {
958 // MB
959 $val = $sizeInBytes / (1024 * 1024);
960 return number_format($val, ($val < 20 ? 1 : 0), '.', '') . $labelArr[2];
961 } else {
962 // KB
963 $val = $sizeInBytes / 1024;
964 return number_format($val, ($val < 20 ? 1 : 0), '.', '') . $labelArr[1];
965 }
966 } else {
967 // Bytes
968 return $sizeInBytes . $labelArr[0];
969 }
970 }
971
972 /**
973 * Returns microtime input to milliseconds
974 *
975 * @param string $microtime Microtime
976 * @return integer Microtime input string converted to an integer (milliseconds)
977 */
978 static public function convertMicrotime($microtime) {
979 $parts = explode(' ', $microtime);
980 return round(($parts[0] + $parts[1]) * 1000);
981 }
982
983 /**
984 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
985 *
986 * @param string $string Input string, eg "123 + 456 / 789 - 4
987 * @param string $operators Operators to split by, typically "/+-*
988 * @return array Array with operators and operands separated.
989 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::calc(), \TYPO3\CMS\Frontend\Imaging\GifBuilder::calcOffset()
990 */
991 static public function splitCalc($string, $operators) {
992 $res = array();
993 $sign = '+';
994 while ($string) {
995 $valueLen = strcspn($string, $operators);
996 $value = substr($string, 0, $valueLen);
997 $res[] = array($sign, trim($value));
998 $sign = substr($string, $valueLen, 1);
999 $string = substr($string, $valueLen + 1);
1000 }
1001 reset($res);
1002 return $res;
1003 }
1004
1005 /**
1006 * Inverse version of htmlspecialchars()
1007 *
1008 * @param string $value Value where &gt;, &lt;, &quot; and &amp; should be converted to regular chars.
1009 * @return string Converted result.
1010 */
1011 static public function htmlspecialchars_decode($value) {
1012 return str_replace(
1013 array('&gt;', '&lt;', '&quot;', '&amp;'),
1014 array('>', '<', '"', '&'),
1015 $value
1016 );
1017
1018 }
1019
1020 /**
1021 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1022 *
1023 * @param string $str String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;
1024 * @return string Converted result.
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 boolean $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 boolean 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 boolean 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 integer $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('') . 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 integer $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(intval(($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(substr($string, 0, 1)) . 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 boolean 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 boolean 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) && !strcmp($val, $item)) {
1431 return TRUE;
1432 }
1433 }
1434 return FALSE;
1435 }
1436
1437 /**
1438 * Explodes a $string delimited by $delim and passes each item in the array through intval().
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 boolean $onlyNonEmptyValues If set, all empty values (='') will NOT be set in output
1444 * @param integer $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, $onlyNonEmptyValues = FALSE, $limit = 0) {
1448 $explodedValues = self::trimExplode($delimiter, $string, $onlyNonEmptyValues, $limit);
1449 return array_map('intval', $explodedValues);
1450 }
1451
1452 /**
1453 * Reverse explode which explodes the string counting from behind.
1454 * Thus \TYPO3\CMS\Core\Utility\GeneralUtility::revExplode(':','my:words:here',2) will return array('my:words','here')
1455 *
1456 * @param string $delimiter Delimiter string to explode with
1457 * @param string $string The string to explode
1458 * @param integer $count Number of array entries
1459 * @return array Exploded values
1460 */
1461 static public function revExplode($delimiter, $string, $count = 0) {
1462 $explodedValues = explode($delimiter, strrev($string), $count);
1463 $explodedValues = array_map('strrev', $explodedValues);
1464 return array_reverse($explodedValues);
1465 }
1466
1467 /**
1468 * Explodes a string and trims all values for whitespace in the ends.
1469 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1470 *
1471 * @param string $delim Delimiter string to explode with
1472 * @param string $string The string to explode
1473 * @param boolean $removeEmptyValues If set, all empty values will be removed in output
1474 * @param integer $limit If positive, the result will contain a maximum of
1475 * @return array Exploded values
1476 */
1477 static public function trimExplode($delim, $string, $removeEmptyValues = FALSE, $limit = 0) {
1478 $explodedValues = explode($delim, $string);
1479 $result = array_map('trim', $explodedValues);
1480 if ($removeEmptyValues) {
1481 $temp = array();
1482 foreach ($result as $value) {
1483 if ($value !== '') {
1484 $temp[] = $value;
1485 }
1486 }
1487 $result = $temp;
1488 }
1489 if ($limit != 0) {
1490 if ($limit < 0) {
1491 $result = array_slice($result, 0, $limit);
1492 } elseif (count($result) > $limit) {
1493 $lastElements = array_slice($result, $limit - 1);
1494 $result = array_slice($result, 0, $limit - 1);
1495 $result[] = implode($delim, $lastElements);
1496 }
1497 }
1498 return $result;
1499 }
1500
1501 /**
1502 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1503 *
1504 * @param array $array Array containing the values
1505 * @param string $cmpValue Value to search for and if found remove array entry where found.
1506 * @return array Output array with entries removed if search string is found
1507 */
1508 static public function removeArrayEntryByValue(array $array, $cmpValue) {
1509 foreach ($array as $k => $v) {
1510 if (is_array($v)) {
1511 $array[$k] = self::removeArrayEntryByValue($v, $cmpValue);
1512 } elseif (!strcmp($v, $cmpValue)) {
1513 unset($array[$k]);
1514 }
1515 }
1516 return $array;
1517 }
1518
1519 /**
1520 * Filters an array to reduce its elements to match the condition.
1521 * The values in $keepItems can be optionally evaluated by a custom callback function.
1522 *
1523 * Example (arguments used to call this function):
1524 * $array = array(
1525 * array('aa' => array('first', 'second'),
1526 * array('bb' => array('third', 'fourth'),
1527 * array('cc' => array('fifth', 'sixth'),
1528 * );
1529 * $keepItems = array('third');
1530 * $getValueFunc = create_function('$value', 'return $value[0];');
1531 *
1532 * Returns:
1533 * array(
1534 * array('bb' => array('third', 'fourth'),
1535 * )
1536 *
1537 * @param array $array The initial array to be filtered/reduced
1538 * @param mixed $keepItems The items which are allowed/kept in the array - accepts array or csv string
1539 * @param string $getValueFunc (optional) Callback function used to get the value to keep
1540 * @return array The filtered/reduced array with the kept items
1541 */
1542 static public function keepItemsInArray(array $array, $keepItems, $getValueFunc = NULL) {
1543 if ($array) {
1544 // Convert strings to arrays:
1545 if (is_string($keepItems)) {
1546 $keepItems = self::trimExplode(',', $keepItems);
1547 }
1548 // Check if valueFunc can be executed:
1549 if (!is_callable($getValueFunc)) {
1550 $getValueFunc = NULL;
1551 }
1552 // Do the filtering:
1553 if (is_array($keepItems) && count($keepItems)) {
1554 foreach ($array as $key => $value) {
1555 // Get the value to compare by using the callback function:
1556 $keepValue = isset($getValueFunc) ? call_user_func($getValueFunc, $value) : $value;
1557 if (!in_array($keepValue, $keepItems)) {
1558 unset($array[$key]);
1559 }
1560 }
1561 }
1562 }
1563 return $array;
1564 }
1565
1566 /**
1567 * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1568 *
1569 * @param string $name Name prefix for entries. Set to blank if you wish none.
1570 * @param array $theArray The (multidimensional) array to implode
1571 * @param string $str (keep blank)
1572 * @param boolean $skipBlank If set, parameters which were blank strings would be removed.
1573 * @param boolean $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1574 * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1575 * @see explodeUrl2Array()
1576 */
1577 static public function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = FALSE, $rawurlencodeParamName = FALSE) {
1578 foreach ($theArray as $Akey => $AVal) {
1579 $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1580 if (is_array($AVal)) {
1581 $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1582 } else {
1583 if (!$skipBlank || strcmp($AVal, '')) {
1584 $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) . '=' . rawurlencode($AVal);
1585 }
1586 }
1587 }
1588 return $str;
1589 }
1590
1591 /**
1592 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1593 *
1594 * @param string $string GETvars string
1595 * @param boolean $multidim If set, the string will be parsed into a multidimensional array if square brackets are used in variable names (using PHP function parse_str())
1596 * @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!
1597 * @see implodeArrayForUrl()
1598 */
1599 static public function explodeUrl2Array($string, $multidim = FALSE) {
1600 $output = array();
1601 if ($multidim) {
1602 parse_str($string, $output);
1603 } else {
1604 $p = explode('&', $string);
1605 foreach ($p as $v) {
1606 if (strlen($v)) {
1607 list($pK, $pV) = explode('=', $v, 2);
1608 $output[rawurldecode($pK)] = rawurldecode($pV);
1609 }
1610 }
1611 }
1612 return $output;
1613 }
1614
1615 /**
1616 * Returns an array with selected keys from incoming data.
1617 * (Better read source code if you want to find out...)
1618 *
1619 * @param string $varList List of variable/key names
1620 * @param array $getArray Array from where to get values based on the keys in $varList
1621 * @param boolean $GPvarAlt If set, then \TYPO3\CMS\Core\Utility\GeneralUtility::_GP() is used to fetch the value if not found (isset) in the $getArray
1622 * @return array Output array with selected variables.
1623 */
1624 static public function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = TRUE) {
1625 $keys = self::trimExplode(',', $varList, TRUE);
1626 $outArr = array();
1627 foreach ($keys as $v) {
1628 if (isset($getArray[$v])) {
1629 $outArr[$v] = $getArray[$v];
1630 } elseif ($GPvarAlt) {
1631 $outArr[$v] = self::_GP($v);
1632 }
1633 }
1634 return $outArr;
1635 }
1636
1637 /**
1638 * AddSlash array
1639 * This function traverses a multidimensional array and adds slashes to the values.
1640 * NOTE that the input array is and argument by reference.!!
1641 * Twin-function to stripSlashesOnArray
1642 *
1643 * @param array $theArray Multidimensional input array, (REFERENCE!)
1644 * @return array
1645 */
1646 static public function addSlashesOnArray(array &$theArray) {
1647 foreach ($theArray as &$value) {
1648 if (is_array($value)) {
1649 self::addSlashesOnArray($value);
1650 } else {
1651 $value = addslashes($value);
1652 }
1653 }
1654 unset($value);
1655 reset($theArray);
1656 }
1657
1658 /**
1659 * StripSlash array
1660 * This function traverses a multidimensional array and strips slashes to the values.
1661 * NOTE that the input array is and argument by reference.!!
1662 * Twin-function to addSlashesOnArray
1663 *
1664 * @param array $theArray Multidimensional input array, (REFERENCE!)
1665 * @return array
1666 */
1667 static public function stripSlashesOnArray(array &$theArray) {
1668 foreach ($theArray as &$value) {
1669 if (is_array($value)) {
1670 self::stripSlashesOnArray($value);
1671 } else {
1672 $value = stripslashes($value);
1673 }
1674 }
1675 unset($value);
1676 reset($theArray);
1677 }
1678
1679 /**
1680 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1681 *
1682 * @param array $arr Multidimensional input array
1683 * @param string $cmd "add" or "strip", depending on usage you wish.
1684 * @return array
1685 */
1686 static public function slashArray(array $arr, $cmd) {
1687 if ($cmd == 'strip') {
1688 self::stripSlashesOnArray($arr);
1689 }
1690 if ($cmd == 'add') {
1691 self::addSlashesOnArray($arr);
1692 }
1693 return $arr;
1694 }
1695
1696 /**
1697 * Rename Array keys with a given mapping table
1698 *
1699 * @param array $array Array by reference which should be remapped
1700 * @param array $mappingTable Array with remap information, array/$oldKey => $newKey)
1701 */
1702 static public function remapArrayKeys(&$array, $mappingTable) {
1703 if (is_array($mappingTable)) {
1704 foreach ($mappingTable as $old => $new) {
1705 if ($new && isset($array[$old])) {
1706 $array[$new] = $array[$old];
1707 unset($array[$old]);
1708 }
1709 }
1710 }
1711 }
1712
1713 /**
1714 * Merges two arrays recursively and "binary safe" (integer keys are
1715 * overridden as well), overruling similar values in the first array
1716 * ($arr0) with the values of the second array ($arr1)
1717 * In case of identical keys, ie. keeping the values of the second.
1718 *
1719 * @param array $arr0 First array
1720 * @param array $arr1 Second array, overruling the first array
1721 * @param boolean $notAddKeys If set, keys that are NOT found in $arr0 (first array) will not be set. Thus only existing value can/will be overruled from second array.
1722 * @param boolean $includeEmptyValues If set, values from $arr1 will overrule if they are empty or zero. Default: TRUE
1723 * @param boolean $enableUnsetFeature If set, special values "__UNSET" can be used in the second array in order to unset array keys in the resulting array.
1724 * @return array Resulting array where $arr1 values has overruled $arr0 values
1725 * @deprecated since 6.2 - will be removed two versions later: use ArrayUtility::mergeRecursiveWithOverrule instead. Consider that the first array is directly modified there. (better performance)
1726 */
1727 static public function array_merge_recursive_overrule(array $arr0, array $arr1, $notAddKeys = FALSE, $includeEmptyValues = TRUE, $enableUnsetFeature = TRUE) {
1728 self::logDeprecatedFunction();
1729 ArrayUtility::mergeRecursiveWithOverrule($arr0, $arr1, !$notAddKeys, $includeEmptyValues, $enableUnsetFeature);
1730 // Our local $arr0 has been modified now, so return it as result
1731 return $arr0;
1732 }
1733
1734 /**
1735 * 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.
1736 *
1737 * @param array $arr1 First array
1738 * @param array $arr2 Second array
1739 * @return array Merged result.
1740 */
1741 static public function array_merge(array $arr1, array $arr2) {
1742 return $arr2 + $arr1;
1743 }
1744
1745 /**
1746 * Filters keys off from first array that also exist in second array. Comparison is done by keys.
1747 * This method is a recursive version of php array_diff_assoc()
1748 *
1749 * @param array $array1 Source array
1750 * @param array $array2 Reduce source array by this array
1751 * @return array Source array reduced by keys also present in second array
1752 */
1753 static public function arrayDiffAssocRecursive(array $array1, array $array2) {
1754 $differenceArray = array();
1755 foreach ($array1 as $key => $value) {
1756 if (!array_key_exists($key, $array2)) {
1757 $differenceArray[$key] = $value;
1758 } elseif (is_array($value)) {
1759 if (is_array($array2[$key])) {
1760 $differenceArray[$key] = self::arrayDiffAssocRecursive($value, $array2[$key]);
1761 }
1762 }
1763 }
1764 return $differenceArray;
1765 }
1766
1767 /**
1768 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1769 *
1770 * @param array $row Input array of values
1771 * @param string $delim Delimited, default is comma
1772 * @param string $quote Quote-character to wrap around the values.
1773 * @return string A single line of CSV
1774 */
1775 static public function csvValues(array $row, $delim = ',', $quote = '"') {
1776 $out = array();
1777 foreach ($row as $value) {
1778 $out[] = str_replace($quote, $quote . $quote, $value);
1779 }
1780 $str = $quote . implode(($quote . $delim . $quote), $out) . $quote;
1781 return $str;
1782 }
1783
1784 /**
1785 * Removes dots "." from end of a key identifier of TypoScript styled array.
1786 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1787 *
1788 * @param array $ts TypoScript configuration array
1789 * @return array TypoScript configuration array without dots at the end of all keys
1790 */
1791 static public function removeDotsFromTS(array $ts) {
1792 $out = array();
1793 foreach ($ts as $key => $value) {
1794 if (is_array($value)) {
1795 $key = rtrim($key, '.');
1796 $out[$key] = self::removeDotsFromTS($value);
1797 } else {
1798 $out[$key] = $value;
1799 }
1800 }
1801 return $out;
1802 }
1803
1804 /**
1805 * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
1806 *
1807 * @param array $array array to be sorted recursively, passed by reference
1808 * @return boolean TRUE if param is an array
1809 */
1810 static public function naturalKeySortRecursive(&$array) {
1811 if (!is_array($array)) {
1812 return FALSE;
1813 }
1814 uksort($array, 'strnatcasecmp');
1815 foreach ($array as $key => $value) {
1816 self::naturalKeySortRecursive($array[$key]);
1817 }
1818 return TRUE;
1819 }
1820
1821 /*************************
1822 *
1823 * HTML/XML PROCESSING
1824 *
1825 *************************/
1826 /**
1827 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1828 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1829 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1830 *
1831 * @param string $tag HTML-tag string (or attributes only)
1832 * @return array Array with the attribute values.
1833 */
1834 static public function get_tag_attributes($tag) {
1835 $components = self::split_tag_attributes($tag);
1836 // Attribute name is stored here
1837 $name = '';
1838 $valuemode = FALSE;
1839 $attributes = array();
1840 foreach ($components as $key => $val) {
1841 // 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
1842 if ($val != '=') {
1843 if ($valuemode) {
1844 if ($name) {
1845 $attributes[$name] = $val;
1846 $name = '';
1847 }
1848 } else {
1849 if ($key = strtolower(preg_replace('/[^[:alnum:]_\\:\\-]/', '', $val))) {
1850 $attributes[$key] = '';
1851 $name = $key;
1852 }
1853 }
1854 $valuemode = FALSE;
1855 } else {
1856 $valuemode = TRUE;
1857 }
1858 }
1859 return $attributes;
1860 }
1861
1862 /**
1863 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1864 * Removes tag-name if found
1865 *
1866 * @param string $tag HTML-tag string (or attributes only)
1867 * @return array Array with the attribute values.
1868 */
1869 static public function split_tag_attributes($tag) {
1870 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
1871 // Removes any > in the end of the string
1872 $tag_tmp = trim(rtrim($tag_tmp, '>'));
1873 $value = array();
1874 // Compared with empty string instead , 030102
1875 while (strcmp($tag_tmp, '')) {
1876 $firstChar = substr($tag_tmp, 0, 1);
1877 if (!strcmp($firstChar, '"') || !strcmp($firstChar, '\'')) {
1878 $reg = explode($firstChar, $tag_tmp, 3);
1879 $value[] = $reg[1];
1880 $tag_tmp = trim($reg[2]);
1881 } elseif (!strcmp($firstChar, '=')) {
1882 $value[] = '=';
1883 // Removes = chars.
1884 $tag_tmp = trim(substr($tag_tmp, 1));
1885 } else {
1886 // There are '' around the value. We look for the next ' ' or '>'
1887 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
1888 $value[] = trim($reg[0]);
1889 $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
1890 }
1891 }
1892 reset($value);
1893 return $value;
1894 }
1895
1896 /**
1897 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1898 *
1899 * @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1900 * @param boolean $xhtmlSafe If set the resulting attribute list will have a) all attributes in lowercase (and duplicates weeded out, first entry taking precedence) and b) all values htmlspecialchar()'ed. It is recommended to use this switch!
1901 * @param boolean $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
1902 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1903 */
1904 static public function implodeAttributes(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
1905 if ($xhtmlSafe) {
1906 $newArr = array();
1907 foreach ($arr as $p => $v) {
1908 if (!isset($newArr[strtolower($p)])) {
1909 $newArr[strtolower($p)] = htmlspecialchars($v);
1910 }
1911 }
1912 $arr = $newArr;
1913 }
1914 $list = array();
1915 foreach ($arr as $p => $v) {
1916 if (strcmp($v, '') || $dontOmitBlankAttribs) {
1917 $list[] = $p . '="' . $v . '"';
1918 }
1919 }
1920 return implode(' ', $list);
1921 }
1922
1923 /**
1924 * Wraps JavaScript code XHTML ready with <script>-tags
1925 * Automatic re-indenting of the JS code is done by using the first line as indent reference.
1926 * This is nice for indenting JS code with PHP code on the same level.
1927 *
1928 * @param string $string JavaScript code
1929 * @param boolean $linebreak Wrap script element in line breaks? Default is TRUE.
1930 * @return string The wrapped JS code, ready to put into a XHTML page
1931 */
1932 static public function wrapJS($string, $linebreak = TRUE) {
1933 if (trim($string)) {
1934 // <script wrapped in nl?
1935 $cr = $linebreak ? LF : '';
1936 // remove nl from the beginning
1937 $string = preg_replace('/^\\n+/', '', $string);
1938 // re-ident to one tab using the first line as reference
1939 $match = array();
1940 if (preg_match('/^(\\t+)/', $string, $match)) {
1941 $string = str_replace($match[1], TAB, $string);
1942 }
1943 $string = $cr . '<script type="text/javascript">
1944 /*<![CDATA[*/
1945 ' . $string . '
1946 /*]]>*/
1947 </script>' . $cr;
1948 }
1949 return trim($string);
1950 }
1951
1952 /**
1953 * Parses XML input into a PHP array with associative keys
1954 *
1955 * @param string $string XML data input
1956 * @param integer $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1957 * @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.
1958 * @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
1959 */
1960 static public function xml2tree($string, $depth = 999) {
1961 $parser = xml_parser_create();
1962 $vals = array();
1963 $index = array();
1964 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
1965 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
1966 xml_parse_into_struct($parser, $string, $vals, $index);
1967 if (xml_get_error_code($parser)) {
1968 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
1969 }
1970 xml_parser_free($parser);
1971 $stack = array(array());
1972 $stacktop = 0;
1973 $startPoint = 0;
1974 $tagi = array();
1975 foreach ($vals as $key => $val) {
1976 $type = $val['type'];
1977 // open tag:
1978 if ($type == 'open' || $type == 'complete') {
1979 $stack[$stacktop++] = $tagi;
1980 if ($depth == $stacktop) {
1981 $startPoint = $key;
1982 }
1983 $tagi = array('tag' => $val['tag']);
1984 if (isset($val['attributes'])) {
1985 $tagi['attrs'] = $val['attributes'];
1986 }
1987 if (isset($val['value'])) {
1988 $tagi['values'][] = $val['value'];
1989 }
1990 }
1991 // finish tag:
1992 if ($type == 'complete' || $type == 'close') {
1993 $oldtagi = $tagi;
1994 $tagi = $stack[--$stacktop];
1995 $oldtag = $oldtagi['tag'];
1996 unset($oldtagi['tag']);
1997 if ($depth == $stacktop + 1) {
1998 if ($key - $startPoint > 0) {
1999 $partArray = array_slice($vals, $startPoint + 1, $key - $startPoint - 1);
2000 $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
2001 } else {
2002 $oldtagi['XMLvalue'] = $oldtagi['values'][0];
2003 }
2004 }
2005 $tagi['ch'][$oldtag][] = $oldtagi;
2006 unset($oldtagi);
2007 }
2008 // cdata
2009 if ($type == 'cdata') {
2010 $tagi['values'][] = $val['value'];
2011 }
2012 }
2013 return $tagi['ch'];
2014 }
2015
2016 /**
2017 * Turns PHP array into XML. See array2xml()
2018 *
2019 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2020 * @param string $docTag Alternative document tag. Default is "phparray".
2021 * @param array $options Options for the compilation. See array2xml() for description.
2022 * @param string $charset Forced charset to prologue
2023 * @return string An XML string made from the input content in the array.
2024 * @see xml2array(),array2xml()
2025 */
2026 static public function array2xml_cs(array $array, $docTag = 'phparray', array $options = array(), $charset = '') {
2027 // Set default charset unless explicitly specified
2028 $charset = $charset ? $charset : 'utf-8';
2029 // Return XML:
2030 return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF . self::array2xml($array, '', 0, $docTag, 0, $options);
2031 }
2032
2033 /**
2034 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
2035 *
2036 * Converts a PHP array into an XML string.
2037 * The XML output is optimized for readability since associative keys are used as tag names.
2038 * 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.
2039 * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
2040 * 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
2041 * 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.
2042 * 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!
2043 * 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...
2044 *
2045 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2046 * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:
2047 * @param integer $level Current recursion level. Don't change, stay at zero!
2048 * @param string $docTag Alternative document tag. Default is "phparray".
2049 * @param integer $spaceInd If greater than zero, then the number of spaces corresponding to this number is used for indenting, if less than zero - no indentation, if zero - a single TAB is used
2050 * @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')
2051 * @param array $stackData Stack data. Don't touch.
2052 * @return string An XML string made from the input content in the array.
2053 * @see xml2array()
2054 */
2055 static public function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = array(), array $stackData = array()) {
2056 // 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
2057 $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);
2058 // Set indenting mode:
2059 $indentChar = $spaceInd ? ' ' : TAB;
2060 $indentN = $spaceInd > 0 ? $spaceInd : 1;
2061 $nl = $spaceInd >= 0 ? LF : '';
2062 // Init output variable:
2063 $output = '';
2064 // Traverse the input array
2065 foreach ($array as $k => $v) {
2066 $attr = '';
2067 $tagName = $k;
2068 // Construct the tag name.
2069 // Use tag based on grand-parent + parent tag name
2070 if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) {
2071 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2072 $tagName = (string) $options['grandParentTagMap'][($stackData['grandParentTagName'] . '/' . $stackData['parentTagName'])];
2073 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($tagName)) {
2074 // Use tag based on parent tag name + if current tag is numeric
2075 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2076 $tagName = (string) $options['parentTagMap'][($stackData['parentTagName'] . ':_IS_NUM')];
2077 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) {
2078 // Use tag based on parent tag name + current tag
2079 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2080 $tagName = (string) $options['parentTagMap'][($stackData['parentTagName'] . ':' . $tagName)];
2081 } elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) {
2082 // Use tag based on parent tag name:
2083 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2084 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName']];
2085 } elseif (!strcmp(intval($tagName), $tagName)) {
2086 // If integer...;
2087 if ($options['useNindex']) {
2088 // If numeric key, prefix "n"
2089 $tagName = 'n' . $tagName;
2090 } else {
2091 // Use special tag for num. keys:
2092 $attr .= ' index="' . $tagName . '"';
2093 $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
2094 }
2095 } elseif ($options['useIndexTagForAssoc']) {
2096 // Use tag for all associative keys:
2097 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2098 $tagName = $options['useIndexTagForAssoc'];
2099 }
2100 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2101 $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
2102 // If the value is an array then we will call this function recursively:
2103 if (is_array($v)) {
2104 // Sub elements:
2105 if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
2106 $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
2107 $clearStackPath = $subOptions['clearStackPath'];
2108 } else {
2109 $subOptions = $options;
2110 $clearStackPath = FALSE;
2111 }
2112 $content = $nl . self::array2xml($v, $NSprefix, ($level + 1), '', $spaceInd, $subOptions, array(
2113 'parentTagName' => $tagName,
2114 'grandParentTagName' => $stackData['parentTagName'],
2115 'path' => ($clearStackPath ? '' : $stackData['path'] . '/' . $tagName)
2116 )) . ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
2117 // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2118 if ((int) $options['disableTypeAttrib'] != 2) {
2119 $attr .= ' type="array"';
2120 }
2121 } else {
2122 // Just a value:
2123 // Look for binary chars:
2124 // Check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
2125 $vLen = strlen($v);
2126 // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
2127 if ($vLen && strcspn($v, $binaryChars) != $vLen) {
2128 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2129 $content = $nl . chunk_split(base64_encode($v));
2130 $attr .= ' base64="1"';
2131 } else {
2132 // Otherwise, just htmlspecialchar the stuff:
2133 $content = htmlspecialchars($v);
2134 $dType = gettype($v);
2135 if ($dType == 'string') {
2136 if ($options['useCDATA'] && $content != $v) {
2137 $content = '<![CDATA[' . $v . ']]>';
2138 }
2139 } elseif (!$options['disableTypeAttrib']) {
2140 $attr .= ' type="' . $dType . '"';
2141 }
2142 }
2143 }
2144 if ((string)$tagName !== '') {
2145 // Add the element to the output string:
2146 $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '')
2147 . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
2148 }
2149 }
2150 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2151 if (!$level) {
2152 $output = '<' . $docTag . '>' . $nl . $output . '</' . $docTag . '>';
2153 }
2154 return $output;
2155 }
2156
2157 /**
2158 * Converts an XML string to a PHP array.
2159 * This is the reverse function of array2xml()
2160 * This is a wrapper for xml2arrayProcess that adds a two-level cache
2161 *
2162 * @param string $string XML content to convert into an array
2163 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:
2164 * @param boolean $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2165 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2166 * @see array2xml(),xml2arrayProcess()
2167 */
2168 static public function xml2array($string, $NSprefix = '', $reportDocTag = FALSE) {
2169 static $firstLevelCache = array();
2170 $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
2171 // Look up in first level cache
2172 if (!empty($firstLevelCache[$identifier])) {
2173 $array = $firstLevelCache[$identifier];
2174 } else {
2175 // Look up in second level cache
2176 $array = \TYPO3\CMS\Frontend\Page\PageRepository::getHash($identifier, 0);
2177 if (!is_array($array)) {
2178 $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
2179 \TYPO3\CMS\Frontend\Page\PageRepository::storeHash($identifier, $array, 'ident_xml2array');
2180 }
2181 // Store content in first level cache
2182 $firstLevelCache[$identifier] = $array;
2183 }
2184 return $array;
2185 }
2186
2187 /**
2188 * Converts an XML string to a PHP array.
2189 * This is the reverse function of array2xml()
2190 *
2191 * @param string $string XML content to convert into an array
2192 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:
2193 * @param boolean $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2194 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2195 * @see array2xml()
2196 */
2197 static protected function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = FALSE) {
2198 // Create parser:
2199 $parser = xml_parser_create();
2200 $vals = array();
2201 $index = array();
2202 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2203 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
2204 // Default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2205 $match = array();
2206 preg_match('/^[[:space:]]*<\\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
2207 $theCharset = $match[1] ? $match[1] : 'utf-8';
2208 // us-ascii / utf-8 / iso-8859-1
2209 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);
2210 // Parse content:
2211 xml_parse_into_struct($parser, $string, $vals, $index);
2212 // If error, return error message:
2213 if (xml_get_error_code($parser)) {
2214 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2215 }
2216 xml_parser_free($parser);
2217 // Init vars:
2218 $stack = array(array());
2219 $stacktop = 0;
2220 $current = array();
2221 $tagName = '';
2222 $documentTag = '';
2223 // Traverse the parsed XML structure:
2224 foreach ($vals as $key => $val) {
2225 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2226 $tagName = $val['tag'];
2227 if (!$documentTag) {
2228 $documentTag = $tagName;
2229 }
2230 // Test for name space:
2231 $tagName = $NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix ? substr($tagName, strlen($NSprefix)) : $tagName;
2232 // Test for numeric tag, encoded on the form "nXXX":
2233 $testNtag = substr($tagName, 1);
2234 // Closing tag.
2235 $tagName = substr($tagName, 0, 1) == 'n' && !strcmp(intval($testNtag), $testNtag) ? intval($testNtag) : $tagName;
2236 // Test for alternative index value:
2237 if (strlen($val['attributes']['index'])) {
2238 $tagName = $val['attributes']['index'];
2239 }
2240 // Setting tag-values, manage stack:
2241 switch ($val['type']) {
2242 case 'open':
2243 // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2244 // Setting blank place holder
2245 $current[$tagName] = array();
2246 $stack[$stacktop++] = $current;
2247 $current = array();
2248 break;
2249 case 'close':
2250 // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2251 $oldCurrent = $current;
2252 $current = $stack[--$stacktop];
2253 // Going to the end of array to get placeholder key, key($current), and fill in array next:
2254 end($current);
2255 $current[key($current)] = $oldCurrent;
2256 unset($oldCurrent);
2257 break;
2258 case 'complete':
2259 // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2260 if ($val['attributes']['base64']) {
2261 $current[$tagName] = base64_decode($val['value']);
2262 } else {
2263 // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
2264 $current[$tagName] = (string) $val['value'];
2265 // Cast type:
2266 switch ((string) $val['attributes']['type']) {
2267 case 'integer':
2268 $current[$tagName] = (int) $current[$tagName];
2269 break;
2270 case 'double':
2271 $current[$tagName] = (double) $current[$tagName];
2272 break;
2273 case 'boolean':
2274 $current[$tagName] = (bool) $current[$tagName];
2275 break;
2276 case 'array':
2277 // 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...
2278 $current[$tagName] = array();
2279 break;
2280 }
2281 }
2282 break;
2283 }
2284 }
2285 if ($reportDocTag) {
2286 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2287 }
2288 // Finally return the content of the document tag.
2289 return $current[$tagName];
2290 }
2291
2292 /**
2293 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2294 *
2295 * @param array $vals An array of XML parts, see xml2tree
2296 * @return string Re-compiled XML data.
2297 */
2298 static public function xmlRecompileFromStructValArray(array $vals) {
2299 $XMLcontent = '';
2300 foreach ($vals as $val) {
2301 $type = $val['type'];
2302 // Open tag:
2303 if ($type == 'open' || $type == 'complete') {
2304 $XMLcontent .= '<' . $val['tag'];
2305 if (isset($val['attributes'])) {
2306 foreach ($val['attributes'] as $k => $v) {
2307 $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
2308 }
2309 }
2310 if ($type == 'complete') {
2311 if (isset($val['value'])) {
2312 $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
2313 } else {
2314 $XMLcontent .= '/>';
2315 }
2316 } else {
2317 $XMLcontent .= '>';
2318 }
2319 if ($type == 'open' && isset($val['value'])) {
2320 $XMLcontent .= htmlspecialchars($val['value']);
2321 }
2322 }
2323 // Finish tag:
2324 if ($type == 'close') {
2325 $XMLcontent .= '</' . $val['tag'] . '>';
2326 }
2327 // Cdata
2328 if ($type == 'cdata') {
2329 $XMLcontent .= htmlspecialchars($val['value']);
2330 }
2331 }
2332 return $XMLcontent;
2333 }
2334
2335 /**
2336 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2337 *
2338 * @param string $xmlData XML data
2339 * @return array Attributes of the xml prologue (header)
2340 */
2341 static public function xmlGetHeaderAttribs($xmlData) {
2342 $match = array();
2343 if (preg_match('/^\\s*<\\?xml([^>]*)\\?\\>/', $xmlData, $match)) {
2344 return self::get_tag_attributes($match[1]);
2345 }
2346 }
2347
2348 /**
2349 * Minifies JavaScript
2350 *
2351 * @param string $script Script to minify
2352 * @param string $error Error message (if any)
2353 * @return string Minified script or source string if error happened
2354 */
2355 static public function minifyJavaScript($script, &$error = '') {
2356 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'])) {
2357 $fakeThis = FALSE;
2358 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['minifyJavaScript'] as $hookMethod) {
2359 try {
2360 $parameters = array('script' => $script);
2361 $script = static::callUserFunction($hookMethod, $parameters, $fakeThis);
2362 } catch (\Exception $e) {
2363 $errorMessage = 'Error minifying java script: ' . $e->getMessage();
2364 $error .= $errorMessage;
2365 static::devLog($errorMessage, 'TYPO3\\CMS\\Core\\Utility\\GeneralUtility', 2, array(
2366 'JavaScript' => $script,
2367 'Stack trace' => $e->getTrace(),
2368 'hook' => $hookMethod
2369 ));
2370 }
2371 }
2372 }
2373 return $script;
2374 }
2375
2376 /*************************
2377 *
2378 * FILES FUNCTIONS
2379 *
2380 *************************/
2381 /**
2382 * Reads the file or url $url and returns the content
2383 * 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.
2384 *
2385 * @param string $url File/URL to read
2386 * @param integer $includeHeader Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2387 * @param array $requestHeaders HTTP headers to be used in the request
2388 * @param array $report Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2389 * @return mixed The content from the resource given as input. FALSE if an error has occured.
2390 */
2391 static public function getUrl($url, $includeHeader = 0, $requestHeaders = FALSE, &$report = NULL) {
2392 $content = FALSE;
2393 if (isset($report)) {
2394 $report['error'] = 0;
2395 $report['message'] = '';
2396 }
2397 // Use cURL for: http, https, ftp, ftps, sftp and scp
2398 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2399 if (isset($report)) {
2400 $report['lib'] = 'cURL';
2401 }
2402 // External URL without error checking.
2403 if (!function_exists('curl_init') || !($ch = curl_init())) {
2404 if (isset($report)) {
2405 $report['error'] = -1;
2406 $report['message'] = 'Couldn\'t initialize cURL.';
2407 }
2408 return FALSE;
2409 }
2410 curl_setopt($ch, CURLOPT_URL, $url);
2411 curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
2412 curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
2413 curl_setopt($ch, CURLOPT_HTTPGET, $includeHeader == 2 ? 'HEAD' : 'GET');
2414 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2415 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
2416 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, max(0, intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout'])));
2417 $followLocation = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
2418 if (is_array($requestHeaders)) {
2419 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
2420 }
2421 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2422 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2423 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2424 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyNTLM']) {
2425 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_NTLM);
2426 }
2427 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2428 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2429 }
2430 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2431 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2432 }
2433 }
2434 $content = curl_exec($ch);
2435 if (isset($report)) {
2436 if ($content === FALSE) {
2437 $report['error'] = curl_errno($ch);
2438 $report['message'] = curl_error($ch);
2439 } else {
2440 $curlInfo = curl_getinfo($ch);
2441 // We hit a redirection but we couldn't follow it
2442 if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
2443 $report['error'] = -1;
2444 $report['message'] = 'Couldn\'t follow location redirect (PHP configuration option open_basedir is in effect).';
2445 } elseif ($includeHeader) {
2446 // Set only for $includeHeader to work exactly like PHP variant
2447 $report['http_code'] = $curlInfo['http_code'];
2448 $report['content_type'] = $curlInfo['content_type'];
2449 }
2450 }
2451 }
2452 curl_close($ch);
2453 } elseif ($includeHeader) {
2454 if (isset($report)) {
2455 $report['lib'] = 'socket';
2456 }
2457 $parsedURL = parse_url($url);
2458 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2459 if (isset($report)) {
2460 $report['error'] = -1;
2461 $report['message'] = 'Reading headers is not allowed for this protocol.';
2462 }
2463 return FALSE;
2464 }
2465 $port = intval($parsedURL['port']);
2466 if ($port < 1) {
2467 if ($parsedURL['scheme'] == 'http') {
2468 $port = $port > 0 ? $port : 80;
2469 $scheme = '';
2470 } else {
2471 $port = $port > 0 ? $port : 443;
2472 $scheme = 'ssl://';
2473 }
2474 }
2475 $errno = 0;
2476 $fp = @fsockopen(($scheme . $parsedURL['host']), $port, $errno, $errstr, 2.0);
2477 if (!$fp || $errno > 0) {
2478 if (isset($report)) {
2479 $report['error'] = $errno ? $errno : -1;
2480 $report['message'] = $errno ? ($errstr ? $errstr : 'Socket error.') : 'Socket initialization error.';
2481 }
2482 return FALSE;
2483 }
2484 $method = $includeHeader == 2 ? 'HEAD' : 'GET';
2485 $msg = $method . ' ' . (isset($parsedURL['path']) ? $parsedURL['path'] : '/') . ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') . ' HTTP/1.0' . CRLF . 'Host: ' . $parsedURL['host'] . '
2486
2487 Connection: close
2488
2489 ';
2490 if (is_array($requestHeaders)) {
2491 $msg .= implode(CRLF, $requestHeaders) . CRLF;
2492 }
2493 $msg .= CRLF;
2494 fputs($fp, $msg);
2495 while (!feof($fp)) {
2496 $line = fgets($fp, 2048);
2497 if (isset($report)) {
2498 if (preg_match('|^HTTP/\\d\\.\\d +(\\d+)|', $line, $status)) {
2499 $report['http_code'] = $status[1];
2500 } elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2501 $report['content_type'] = $type[1];
2502 }
2503 }
2504 $content .= $line;
2505 if (!strlen(trim($line))) {
2506 // Stop at the first empty line (= end of header)
2507 break;
2508 }
2509 }
2510 if ($includeHeader != 2) {
2511 $content .= stream_get_contents($fp);
2512 }
2513 fclose($fp);
2514 } elseif (is_array($requestHeaders)) {
2515 if (isset($report)) {
2516 $report['lib'] = 'file/context';
2517 }
2518 $parsedURL = parse_url($url);
2519 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2520 if (isset($report)) {
2521 $report['error'] = -1;
2522 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2523 }
2524 return FALSE;
2525 }
2526 $ctx = stream_context_create(array(
2527 'http' => array(
2528 'header' => implode(CRLF, $requestHeaders)
2529 )
2530 ));
2531 $content = @file_get_contents($url, FALSE, $ctx);
2532 if ($content === FALSE && isset($report)) {
2533 $report['error'] = -1;
2534 $report['message'] = 'Couldn\'t get URL: ' . implode(LF, $http_response_header);
2535 }
2536 } else {
2537 if (isset($report)) {
2538 $report['lib'] = 'file';
2539 }
2540 $content = @file_get_contents($url);
2541 if ($content === FALSE && isset($report)) {
2542 $report['error'] = -1;
2543 $report['message'] = 'Couldn\'t get URL: ' . implode(LF, $http_response_header);
2544 }
2545 }
2546 return $content;
2547 }
2548
2549 /**
2550 * Writes $content to the file $file
2551 *
2552 * @param string $file Filepath to write to
2553 * @param string $content Content to write
2554 * @param boolean $changePermissions If TRUE, permissions are forced to be set
2555 * @return boolean TRUE if the file was successfully opened and written to.
2556 */
2557 static public function writeFile($file, $content, $changePermissions = FALSE) {
2558 if (!@is_file($file)) {
2559 $changePermissions = TRUE;
2560 }
2561 if ($fd = fopen($file, 'wb')) {
2562 $res = fwrite($fd, $content);
2563 fclose($fd);
2564 if ($res === FALSE) {
2565 return FALSE;
2566 }
2567 // Change the permissions only if the file has just been created
2568 if ($changePermissions) {
2569 self::fixPermissions($file);
2570 }
2571 return TRUE;
2572 }
2573 return FALSE;
2574 }
2575
2576 /**
2577 * Sets the file system mode and group ownership of a file or a folder.
2578 *
2579 * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
2580 * @param boolean $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
2581 * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
2582 */
2583 static public function fixPermissions($path, $recursive = FALSE) {
2584 if (TYPO3_OS != 'WIN') {
2585 $result = FALSE;
2586 // Make path absolute
2587 if (!self::isAbsPath($path)) {
2588 $path = self::getFileAbsFileName($path, FALSE);
2589 }
2590 if (self::isAllowedAbsPath($path)) {
2591 if (@is_file($path)) {
2592 $targetFilePermissions = isset($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])
2593 ? octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])
2594 : octdec('0644');
2595 // "@" is there because file is not necessarily OWNED by the user
2596 $result = @chmod($path, $targetFilePermissions);
2597 } elseif (@is_dir($path)) {
2598 $targetDirectoryPermissions = isset($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])
2599 ? octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])
2600 : octdec('0755');
2601 // "@" is there because file is not necessarily OWNED by the user
2602 $result = @chmod($path, $targetDirectoryPermissions);
2603 }
2604 // Set createGroup if not empty
2605 if (
2606 isset($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])
2607 && strlen($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) > 0
2608 ) {
2609 // "@" is there because file is not necessarily OWNED by the user
2610 $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2611 $result = $changeGroupResult ? $result : FALSE;
2612 }
2613 // Call recursive if recursive flag if set and $path is directory
2614 if ($recursive && @is_dir($path)) {
2615 $handle = opendir($path);
2616 while (($file = readdir($handle)) !== FALSE) {
2617 $recursionResult = NULL;
2618 if ($file !== '.' && $file !== '..') {
2619 if (@is_file(($path . '/' . $file))) {
2620 $recursionResult = self::fixPermissions($path . '/' . $file);
2621 } elseif (@is_dir(($path . '/' . $file))) {
2622 $recursionResult = self::fixPermissions($path . '/' . $file, TRUE);
2623 }
2624 if (isset($recursionResult) && !$recursionResult) {
2625 $result = FALSE;
2626 }
2627 }
2628 }
2629 closedir($handle);
2630 }
2631 }
2632 } else {
2633 $result = TRUE;
2634 }
2635 return $result;
2636 }
2637
2638 /**
2639 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2640 * Accepts an additional subdirectory in the file path!
2641 *
2642 * @param string $filepath Absolute file path to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/
2643 * @param string $content Content string to write
2644 * @return string Returns NULL on success, otherwise an error string telling about the problem.
2645 */
2646 static public function writeFileToTypo3tempDir($filepath, $content) {
2647 // Parse filepath into directory and basename:
2648 $fI = pathinfo($filepath);
2649 $fI['dirname'] .= '/';
2650 // Check parts:
2651 if (self::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename']) < 60) {
2652 if (defined('PATH_site')) {
2653 // Setting main temporary directory name (standard)
2654 $dirName = PATH_site . 'typo3temp/';
2655 if (@is_dir($dirName)) {
2656 if (self::isFirstPartOfStr($fI['dirname'], $dirName)) {
2657 // Checking if the "subdir" is found:
2658 $subdir = substr($fI['dirname'], strlen($dirName));
2659 if ($subdir) {
2660 if (preg_match('/^[[:alnum:]_]+\\/$/', $subdir) || preg_match('/^[[:alnum:]_]+\\/[[:alnum:]_]+\\/$/', $subdir)) {
2661 $dirName .= $subdir;
2662 if (!@is_dir($dirName)) {
2663 self::mkdir_deep(PATH_site . 'typo3temp/', $subdir);
2664 }
2665 } else {
2666 return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2667 }
2668 }
2669 // Checking dir-name again (sub-dir might have been created):
2670 if (@is_dir($dirName)) {
2671 if ($filepath == $dirName . $fI['basename']) {
2672 self::writeFile($filepath, $content);
2673 if (!@is_file($filepath)) {
2674 return 'The file was not written to the disk. Please, check that you have write permissions to the typo3temp/ directory.';
2675 }
2676 } else {
2677 return 'Calculated filelocation didn\'t match input $filepath!';
2678 }
2679 } else {
2680 return '"' . $dirName . '" is not a directory!';
2681 }
2682 } else {
2683 return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
2684 }
2685 } else {
2686 return 'PATH_site + "typo3temp/" was not a directory!';
2687 }
2688 } else {
2689 return 'PATH_site constant was NOT defined!';
2690 }
2691 } else {
2692 return 'Input filepath "' . $filepath . '" was generally invalid!';
2693 }
2694 }
2695
2696 /**
2697 * Wrapper function for mkdir.
2698 * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']
2699 * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
2700 *
2701 * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2702 * @return boolean TRUE if @mkdir went well!
2703 */
2704 static public function mkdir($newFolder) {
2705 $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2706 if ($result) {
2707 self::fixPermissions($newFolder);
2708 }
2709 return $result;
2710 }
2711
2712 /**
2713 * Creates a directory - including parent directories if necessary and
2714 * sets permissions on newly created directories.
2715 *
2716 * @param string $directory Target directory to create. Must a have trailing slash
2717 * @param string $deepDirectory Directory to create. This second parameter
2718 * @return void
2719 * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
2720 * @throws \RuntimeException If directory could not be created
2721 */
2722 static public function mkdir_deep($directory, $deepDirectory = '') {
2723 if (!is_string($directory)) {
2724 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($directory) . '" but a string is expected.', 1303662955);
2725 }
2726 if (!is_string($deepDirectory)) {
2727 throw new \InvalidArgumentException('The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.', 1303662956);
2728 }
2729 $fullPath = $directory . $deepDirectory;
2730 if (!is_dir($fullPath) && strlen($fullPath) > 0) {
2731 $firstCreatedPath = self::createDirectoryPath($fullPath);
2732 if ($firstCreatedPath !== '') {
2733 self::fixPermissions($firstCreatedPath, TRUE);
2734 }
2735 }
2736 }
2737
2738 /**
2739 * Creates directories for the specified paths if they do not exist. This
2740 * functions sets proper permission mask but does not set proper user and
2741 * group.
2742 *
2743 * @static
2744 * @param string $fullDirectoryPath
2745 * @return string Path to the the first created directory in the hierarchy
2746 * @see \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir_deep
2747 * @throws \RuntimeException If directory could not be created
2748 */
2749 static protected function createDirectoryPath($fullDirectoryPath) {
2750 $currentPath = $fullDirectoryPath;
2751 $firstCreatedPath = '';
2752 $permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']);
2753 if (!@is_dir($currentPath)) {
2754 do {
2755 $firstCreatedPath = $currentPath;
2756 $separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR);
2757 $currentPath = substr($currentPath, 0, $separatorPosition);
2758 } while (!is_dir($currentPath) && $separatorPosition !== FALSE);
2759 $result = @mkdir($fullDirectoryPath, $permissionMask, TRUE);
2760 if (!$result) {
2761 throw new \RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251400);
2762 }
2763 }
2764 return $firstCreatedPath;
2765 }
2766
2767 /**
2768 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2769 *
2770 * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2771 * @param boolean $removeNonEmpty Allow deletion of non-empty directories
2772 * @return boolean TRUE if @rmdir went well!
2773 */
2774 static public function rmdir($path, $removeNonEmpty = FALSE) {
2775 $OK = FALSE;
2776 // Remove trailing slash
2777 $path = preg_replace('|/$|', '', $path);
2778 if (file_exists($path)) {
2779 $OK = TRUE;
2780 if (!is_link($path) && is_dir($path)) {
2781 if ($removeNonEmpty == TRUE && ($handle = opendir($path))) {
2782 while ($OK && FALSE !== ($file = readdir($handle))) {
2783 if ($file == '.' || $file == '..') {
2784 continue;
2785 }
2786 $OK = self::rmdir($path . '/' . $file, $removeNonEmpty);
2787 }
2788 closedir($handle);
2789 }
2790 if ($OK) {
2791 $OK = @rmdir($path);
2792 }
2793 } else {
2794 // If $path is a file, simply remove it
2795 $OK = unlink($path);
2796 }
2797 clearstatcache();
2798 } elseif (is_link($path)) {
2799 $OK = unlink($path);
2800 clearstatcache();
2801 }
2802 return $OK;
2803 }
2804
2805 /**
2806 * Flushes a directory by first moving to a temporary resource, and then
2807 * triggering the remove process. This way directories can be flushed faster
2808 * to prevent race conditions on concurrent processes accessing the same directory.
2809 *
2810 * @param string $directory The directory to be renamed and flushed
2811 * @return boolean Whether the action was successful
2812 */
2813 static public function flushDirectory($directory) {
2814 $result = FALSE;
2815
2816 if (is_dir($directory)) {
2817 $temporaryDirectory = rtrim($directory, '/') . '.' . uniqid('remove') . '/';
2818 if (rename($directory, $temporaryDirectory)) {
2819 clearstatcache();
2820 $result = self::rmdir($temporaryDirectory, TRUE);
2821 }
2822 }
2823
2824 return $result;
2825 }
2826
2827 /**
2828 * Returns an array with the names of folders in a specific path
2829 * Will return 'error' (string) if there were an error with reading directory content.
2830 *
2831 * @param string $path Path to list directories from
2832 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2833 */
2834 static public function get_dirs($path) {
2835 if ($path) {
2836 if (is_dir($path)) {
2837 $dir = scandir($path);
2838 $dirs = array();
2839 foreach ($dir as $entry) {
2840 if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
2841 $dirs[] = $entry;
2842 }
2843 }
2844 } else {
2845 $dirs = 'error';
2846 }
2847 }
2848 return $dirs;
2849 }
2850
2851 /**
2852 * Returns an array with the names of files in a specific path
2853 *
2854 * @param string $path Is the path to the file
2855 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2856 * @param boolean $prependPath If set, then the path is prepended the file names. Otherwise only the file names are returned in the array
2857 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2858 * @param string $excludePattern A comma separated list of file names to exclude, no wildcards
2859 * @return array Array of the files found
2860 */
2861 static public function getFilesInDir($path, $extensionList = '', $prependPath = FALSE, $order = '', $excludePattern = '') {
2862 // Initialize variables:
2863 $filearray = array();
2864 $sortarray = array();
2865 $path = rtrim($path, '/');
2866 // Find files+directories:
2867 if (@is_dir($path)) {
2868 $extensionList = strtolower($extensionList);
2869 $d = dir($path);
2870 if (is_object($d)) {
2871 while ($entry = $d->read()) {
2872 if (@is_file(($path . '/' . $entry))) {
2873 $fI = pathinfo($entry);
2874 // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
2875 $key = md5($path . '/' . $entry);
2876 if ((!strlen($extensionList) || self::inList($extensionList, strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match(('/^' . $excludePattern . '$/'), $entry))) {
2877 $filearray[$key] = ($prependPath ? $path . '/' : '') . $entry;
2878 if ($order == 'mtime') {
2879 $sortarray[$key] = filemtime($path . '/' . $entry);
2880 } elseif ($order) {
2881 $sortarray[$key] = strtolower($entry);
2882 }
2883 }
2884 }
2885 }
2886 $d->close();
2887 } else {
2888 return 'error opening path: "' . $path . '"';
2889 }
2890 }
2891 // Sort them:
2892 if ($order) {
2893 asort($sortarray);
2894 $newArr = array();
2895 foreach ($sortarray as $k => $v) {
2896 $newArr[$k] = $filearray[$k];
2897 }
2898 $filearray = $newArr;
2899 }
2900 // Return result
2901 reset($filearray);
2902 return $filearray;
2903 }
2904
2905 /**
2906 * Recursively gather all files and folders of a path.
2907 *
2908 * @param array $fileArr Empty input array (will have files added to it)
2909 * @param string $path The path to read recursively from (absolute) (include trailing slash!)
2910 * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2911 * @param boolean $regDirs If set, directories are also included in output.
2912 * @param integer $recursivityLevels The number of levels to dig down...
2913 * @param string $excludePattern regex pattern of files/directories to exclude
2914 * @return array An array with the found files/directories.
2915 */
2916 static public function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = FALSE, $recursivityLevels = 99, $excludePattern = '') {
2917 if ($regDirs) {
2918 $fileArr[] = $path;
2919 }
2920 $fileArr = array_merge($fileArr, self::getFilesInDir($path, $extList, 1, 1, $excludePattern));
2921 $dirs = self::get_dirs($path);
2922 if (is_array($dirs) && $recursivityLevels > 0) {
2923 foreach ($dirs as $subdirs) {
2924 if ((string) $subdirs != '' && (!strlen($excludePattern) || !preg_match(('/^' . $excludePattern . '$/'), $subdirs))) {
2925 $fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
2926 }
2927 }
2928 }
2929 return $fileArr;
2930 }
2931
2932 /**
2933 * Removes the absolute part of all files/folders in fileArr
2934 *
2935 * @param array $fileArr The file array to remove the prefix from
2936 * @param string $prefixToRemove The prefix path to remove (if found as first part of string!)
2937 * @return array The input $fileArr processed.
2938 */
2939 static public function removePrefixPathFromList(array $fileArr, $prefixToRemove) {
2940 foreach ($fileArr as $k => &$absFileRef) {
2941 if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
2942 $absFileRef = substr($absFileRef, strlen($prefixToRemove));
2943 } else {
2944 return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2945 }
2946 }
2947 unset($absFileRef);
2948 return $fileArr;
2949 }
2950
2951 /**
2952 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2953 *
2954 * @param string $theFile File path to process
2955 * @return string
2956 */
2957 static public function fixWindowsFilePath($theFile) {
2958 return str_replace('//', '/', str_replace('\\', '/', $theFile));
2959 }
2960
2961 /**
2962 * Resolves "../" sections in the input path string.
2963 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2964 *
2965 * @param string $pathStr File path in which "/../" is resolved
2966 * @return string
2967 */
2968 static public function resolveBackPath($pathStr) {
2969 $parts = explode('/', $pathStr);
2970 $output = array();
2971 $c = 0;
2972 foreach ($parts as $pV) {
2973 if ($pV == '..') {
2974 if ($c) {
2975 array_pop($output);
2976 $c--;
2977 } else {
2978 $output[] = $pV;
2979 }
2980 } else {
2981 $c++;
2982 $output[] = $pV;
2983 }
2984 }
2985 return implode('/', $output);
2986 }
2987
2988 /**
2989 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2990 * - If already having a scheme, nothing is prepended
2991 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2992 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2993 *
2994 * @param string $path URL / path to prepend full URL addressing to.
2995 * @return string
2996 */
2997 static public function locationHeaderUrl($path) {
2998 $uI = parse_url($path);
2999 // relative to HOST
3000 if (substr($path, 0, 1) == '/') {
3001 $path = self::getIndpEnv('TYPO3_REQUEST_HOST') . $path;
3002 } elseif (!$uI['scheme']) {
3003 // No scheme either
3004 $path = self::getIndpEnv('TYPO3_REQUEST_DIR') . $path;
3005 }
3006 return $path;
3007 }
3008
3009 /**
3010 * Returns the maximum upload size for a file that is allowed. Measured in KB.
3011 * This might be handy to find out the real upload limit that is possible for this
3012 * TYPO3 installation. The first parameter can be used to set something that overrides
3013 * the maxFileSize, usually for the TCA values.
3014 *
3015 * @param integer $localLimit the number of Kilobytes (!) that should be used as
3016 * @return integer The maximum size of uploads that are allowed (measured in kilobytes)
3017 */
3018 static public function getMaxUploadFileSize($localLimit = 0) {
3019 // Don't allow more than the global max file size at all
3020 $t3Limit = intval($localLimit > 0 ? $localLimit : $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize']);
3021 // As TYPO3 is handling the file size in KB, multiply by 1024 to get bytes
3022 $t3Limit = $t3Limit * 1024;
3023 // Check for PHP restrictions of the maximum size of one of the $_FILES
3024 $phpUploadLimit = self::getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
3025 // Check for PHP restrictions of the maximum $_POST size
3026 $phpPostLimit = self::getBytesFromSizeMeasurement(ini_get('post_max_size'));
3027 // If the total amount of post data is smaller (!) than the upload_max_filesize directive,
3028 // then this is the real limit in PHP
3029 $phpUploadLimit = $phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit;
3030 // Is the allowed PHP limit (upload_max_filesize) lower than the TYPO3 limit?, also: revert back to KB
3031 return floor(($phpUploadLimit < $t3Limit ? $phpUploadLimit : $t3Limit)) / 1024;
3032 }
3033
3034 /**
3035 * Gets the bytes value from a measurement string like "100k".
3036 *
3037 * @param string $measurement The measurement (e.g. "100k")
3038 * @return integer The bytes value (e.g. 102400)
3039 */
3040 static public function getBytesFromSizeMeasurement($measurement) {
3041 $bytes = doubleval($measurement);
3042 if (stripos($measurement, 'G')) {
3043 $bytes *= 1024 * 1024 * 1024;
3044 } elseif (stripos($measurement, 'M')) {
3045 $bytes *= 1024 * 1024;
3046 } elseif (stripos($measurement, 'K')) {
3047 $bytes *= 1024;
3048 }
3049 return $bytes;
3050 }
3051
3052 /**
3053 * Retrieves the maximum path length that is valid in the current environment.
3054 *
3055 * @return integer The maximum available path length
3056 */
3057 static public function getMaximumPathLength() {
3058 return PHP_MAXPATHLEN;
3059 }
3060
3061 /**
3062 * Function for static version numbers on files, based on the filemtime
3063 *
3064 * This will make the filename automatically change when a file is
3065 * changed, and by that re-cached by the browser. If the file does not
3066 * exist physically the original file passed to the function is
3067 * returned without the timestamp.
3068 *
3069 * Behaviour is influenced by the setting
3070 * TYPO3_CONF_VARS[TYPO3_MODE][versionNumberInFilename]
3071 * = TRUE (BE) / "embed" (FE) : modify filename
3072 * = FALSE (BE) / "querystring" (FE) : add timestamp as parameter
3073 *
3074 * @param string $file Relative path to file including all potential query parameters (not htmlspecialchared yet)
3075 * @param boolean $forceQueryString If settings would suggest to embed in filename, this parameter allows us to force the versioning to occur in the query string. This is needed for scriptaculous.js which cannot have a different filename in order to load its modules (?load=...)
3076 * @return Relative path with version filename including the timestamp
3077 */
3078 static public function createVersionNumberedFilename($file, $forceQueryString = FALSE) {
3079 $lookupFile = explode('?', $file);