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