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