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