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