[TASK] Remove function index
[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 */
771 public static function intInRange($theInt, $min, $max = 2000000000, $zeroValue = 0) {
772 // Returns $theInt as an integer in the integerspace from $min to $max
773 $theInt = intval($theInt);
774 if ($zeroValue && !$theInt) {
775 $theInt = $zeroValue;
776 } // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
777 if ($theInt < $min) {
778 $theInt = $min;
779 }
780 if ($theInt > $max) {
781 $theInt = $max;
782 }
783 return $theInt;
784 }
785
786 /**
787 * Returns the $integer if greater than zero, otherwise returns zero.
788 * Usage: 1
789 *
790 * @param integer Integer string to process
791 * @return integer
792 */
793 public static function intval_positive($theInt) {
794 $theInt = intval($theInt);
795 if ($theInt < 0) {
796 $theInt = 0;
797 }
798 return $theInt;
799 }
800
801 /**
802 * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
803 * Usage: 2
804 *
805 * @param string Version number on format x.x.x
806 * @return integer Integer version of version number (where each part can count to 999)
807 */
808 public static function int_from_ver($verNumberStr) {
809 $verParts = explode('.', $verNumberStr);
810 return intval((int) $verParts[0] . str_pad((int) $verParts[1], 3, '0', STR_PAD_LEFT) . str_pad((int) $verParts[2], 3, '0', STR_PAD_LEFT));
811 }
812
813 /**
814 * Returns TRUE if the current TYPO3 version (or compatibility version) is compatible to the input version
815 * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
816 *
817 * @param string Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
818 * @return boolean Returns TRUE if this setup is compatible with the provided version number
819 * @todo Still needs a function to convert versions to branches
820 */
821 public static function compat_version($verNumberStr) {
822 $currVersionStr = $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] : TYPO3_branch;
823
824 if (self::int_from_ver($currVersionStr) < self::int_from_ver($verNumberStr)) {
825 return FALSE;
826 } else {
827 return TRUE;
828 }
829 }
830
831 /**
832 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
833 * Usage: 5
834 *
835 * @param string String to md5-hash
836 * @return integer Returns 28bit integer-hash
837 */
838 public static function md5int($str) {
839 return hexdec(substr(md5($str), 0, 7));
840 }
841
842 /**
843 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
844 *
845 * Usage: 37
846 *
847 * @param string Input string to be md5-hashed
848 * @param integer The string-length of the output
849 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
850 */
851 public static function shortMD5($input, $len = 10) {
852 return substr(md5($input), 0, $len);
853 }
854
855 /**
856 * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
857 *
858 * @param string Input string to create HMAC from
859 * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
860 */
861 public static function hmac($input) {
862 $hashAlgorithm = 'sha1';
863 $hashBlocksize = 64;
864 $hmac = '';
865
866 if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
867 $hmac = hash_hmac($hashAlgorithm, $input, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']);
868 } else {
869 // outer padding
870 $opad = str_repeat(chr(0x5C), $hashBlocksize);
871 // innner padding
872 $ipad = str_repeat(chr(0x36), $hashBlocksize);
873 if (strlen($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) > $hashBlocksize) {
874 // keys longer than blocksize are shorten
875 $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])), $hashBlocksize, chr(0x00));
876 } else {
877 // keys shorter than blocksize are zero-padded
878 $key = str_pad($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], $hashBlocksize, chr(0x00));
879 }
880 $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, ($key ^ $ipad) . $input)));
881 }
882 return $hmac;
883 }
884
885 /**
886 * Takes comma-separated lists and arrays and removes all duplicates
887 * If a value in the list is trim(empty), the value is ignored.
888 * Usage: 16
889 *
890 * @param string Accept multiple parameters wich can be comma-separated lists of values and arrays.
891 * @param mixed $secondParameter: Dummy field, which if set will show a warning!
892 * @return string Returns the list without any duplicates of values, space around values are trimmed
893 */
894 public static function uniqueList($in_list, $secondParameter = NULL) {
895 if (is_array($in_list)) {
896 throw new InvalidArgumentException(
897 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!',
898 1270853885
899 );
900 }
901 if (isset($secondParameter)) {
902 throw new InvalidArgumentException(
903 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!',
904 1270853886
905 );
906 }
907
908 return implode(',', array_unique(self::trimExplode(',', $in_list, 1)));
909 }
910
911 /**
912 * Splits a reference to a file in 5 parts
913 * Usage: 43
914 *
915 * @param string Filename/filepath to be analysed
916 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
917 */
918 public static function split_fileref($fileref) {
919 $reg = array();
920 if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
921 $info['path'] = $reg[1];
922 $info['file'] = $reg[2];
923 } else {
924 $info['path'] = '';
925 $info['file'] = $fileref;
926 }
927
928 $reg = '';
929 if (!is_dir($fileref) && preg_match('/(.*)\.([^\.]*$)/', $info['file'], $reg)) {
930 $info['filebody'] = $reg[1];
931 $info['fileext'] = strtolower($reg[2]);
932 $info['realFileext'] = $reg[2];
933 } else {
934 $info['filebody'] = $info['file'];
935 $info['fileext'] = '';
936 }
937 reset($info);
938 return $info;
939 }
940
941 /**
942 * Returns the directory part of a path without trailing slash
943 * If there is no dir-part, then an empty string is returned.
944 * Behaviour:
945 *
946 * '/dir1/dir2/script.php' => '/dir1/dir2'
947 * '/dir1/' => '/dir1'
948 * 'dir1/script.php' => 'dir1'
949 * 'd/script.php' => 'd'
950 * '/script.php' => ''
951 * '' => ''
952 * Usage: 5
953 *
954 * @param string Directory name / path
955 * @return string Processed input value. See function description.
956 */
957 public static function dirname($path) {
958 $p = self::revExplode('/', $path, 2);
959 return count($p) == 2 ? $p[0] : '';
960 }
961
962 /**
963 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
964 * Usage: 11
965 *
966 * @param string A hexadecimal color code, #xxxxxx
967 * @param integer Offset value 0-255
968 * @param integer Offset value 0-255
969 * @param integer Offset value 0-255
970 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
971 * @see modifyHTMLColorAll()
972 */
973 public static function modifyHTMLColor($color, $R, $G, $B) {
974 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
975 $nR = self::intInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
976 $nG = self::intInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
977 $nB = self::intInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
978 return '#' .
979 substr('0' . dechex($nR), -2) .
980 substr('0' . dechex($nG), -2) .
981 substr('0' . dechex($nB), -2);
982 }
983
984 /**
985 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
986 * Usage: 6
987 *
988 * @param string A hexadecimal color code, #xxxxxx
989 * @param integer Offset value 0-255 for all three channels.
990 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
991 * @see modifyHTMLColor()
992 */
993 public static function modifyHTMLColorAll($color, $all) {
994 return self::modifyHTMLColor($color, $all, $all, $all);
995 }
996
997 /**
998 * Removes comma (if present) in the end of string
999 * Usage: 2
1000 *
1001 * @param string String from which the comma in the end (if any) will be removed.
1002 * @return string
1003 * @deprecated since TYPO3 4.5, will be removed in TYPO3 4.7 - Use rtrim() directly
1004 */
1005 public static function rm_endcomma($string) {
1006 self::logDeprecatedFunction();
1007
1008 return rtrim($string, ',');
1009 }
1010
1011 /**
1012 * Tests if the input can be interpreted as integer.
1013 *
1014 * @param mixed Any input variable to test
1015 * @return boolean Returns TRUE if string is an integer
1016 */
1017 public static function testInt($var) {
1018 if ($var === '') {
1019 return FALSE;
1020 }
1021 return (string) intval($var) === (string) $var;
1022 }
1023
1024 /**
1025 * Returns TRUE if the first part of $str matches the string $partStr
1026 * Usage: 59
1027 *
1028 * @param string Full string to check
1029 * @param string Reference string which must be found as the "first part" of the full string
1030 * @return boolean TRUE if $partStr was found to be equal to the first part of $str
1031 */
1032 public static function isFirstPartOfStr($str, $partStr) {
1033 return $partStr != '' && strpos((string) $str, (string) $partStr, 0) === 0;
1034 }
1035
1036 /**
1037 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
1038 * Usage: 53
1039 *
1040 * @param integer Number of bytes to format.
1041 * @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)
1042 * @return string Formatted representation of the byte number, for output.
1043 */
1044 public static function formatSize($sizeInBytes, $labels = '') {
1045
1046 // Set labels:
1047 if (strlen($labels) == 0) {
1048 $labels = ' | K| M| G';
1049 } else {
1050 $labels = str_replace('"', '', $labels);
1051 }
1052 $labelArr = explode('|', $labels);
1053
1054 // Find size:
1055 if ($sizeInBytes > 900) {
1056 if ($sizeInBytes > 900000000) { // GB
1057 $val = $sizeInBytes / (1024 * 1024 * 1024);
1058 return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[3];
1059 }
1060 elseif ($sizeInBytes > 900000) { // MB
1061 $val = $sizeInBytes / (1024 * 1024);
1062 return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[2];
1063 } else { // KB
1064 $val = $sizeInBytes / (1024);
1065 return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[1];
1066 }
1067 } else { // Bytes
1068 return $sizeInBytes . $labelArr[0];
1069 }
1070 }
1071
1072 /**
1073 * Returns microtime input to milliseconds
1074 * Usage: 2
1075 *
1076 * @param string Microtime
1077 * @return integer Microtime input string converted to an integer (milliseconds)
1078 */
1079 public static function convertMicrotime($microtime) {
1080 $parts = explode(' ', $microtime);
1081 return round(($parts[0] + $parts[1]) * 1000);
1082 }
1083
1084 /**
1085 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
1086 * Usage: 2
1087 *
1088 * @param string Input string, eg "123 + 456 / 789 - 4"
1089 * @param string Operators to split by, typically "/+-*"
1090 * @return array Array with operators and operands separated.
1091 * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
1092 */
1093 public static function splitCalc($string, $operators) {
1094 $res = Array();
1095 $sign = '+';
1096 while ($string) {
1097 $valueLen = strcspn($string, $operators);
1098 $value = substr($string, 0, $valueLen);
1099 $res[] = Array($sign, trim($value));
1100 $sign = substr($string, $valueLen, 1);
1101 $string = substr($string, $valueLen + 1);
1102 }
1103 reset($res);
1104 return $res;
1105 }
1106
1107 /**
1108 * Calculates the input by +,-,*,/,%,^ with priority to + and -
1109 * Usage: 1
1110 *
1111 * @param string Input string, eg "123 + 456 / 789 - 4"
1112 * @return integer Calculated value. Or error string.
1113 * @see calcParenthesis()
1114 */
1115 public static function calcPriority($string) {
1116 $string = preg_replace('/[[:space:]]*/', '', $string); // removing all whitespace
1117 $string = '+' . $string; // Ensuring an operator for the first entrance
1118 $qm = '\*\/\+-^%';
1119 $regex = '([' . $qm . '])([' . $qm . ']?[0-9\.]*)';
1120 // split the expression here:
1121 $reg = array();
1122 preg_match_all('/' . $regex . '/', $string, $reg);
1123
1124 reset($reg[2]);
1125 $number = 0;
1126 $Msign = '+';
1127 $err = '';
1128 $buffer = doubleval(current($reg[2]));
1129 next($reg[2]); // Advance pointer
1130
1131 while (list($k, $v) = each($reg[2])) {
1132 $v = doubleval($v);
1133 $sign = $reg[1][$k];
1134 if ($sign == '+' || $sign == '-') {
1135 $number = $Msign == '-' ? $number -= $buffer : $number += $buffer;
1136 $Msign = $sign;
1137 $buffer = $v;
1138 } else {
1139 if ($sign == '/') {
1140 if ($v) {
1141 $buffer /= $v;
1142 } else {
1143 $err = 'dividing by zero';
1144 }
1145 }
1146 if ($sign == '%') {
1147 if ($v) {
1148 $buffer %= $v;
1149 } else {
1150 $err = 'dividing by zero';
1151 }
1152 }
1153 if ($sign == '*') {
1154 $buffer *= $v;
1155 }
1156 if ($sign == '^') {
1157 $buffer = pow($buffer, $v);
1158 }
1159 }
1160 }
1161 $number = $Msign == '-' ? $number -= $buffer : $number += $buffer;
1162 return $err ? 'ERROR: ' . $err : $number;
1163 }
1164
1165 /**
1166 * Calculates the input with parenthesis levels
1167 * Usage: 2
1168 *
1169 * @param string Input string, eg "(123 + 456) / 789 - 4"
1170 * @return integer Calculated value. Or error string.
1171 * @see calcPriority(), tslib_cObj::stdWrap()
1172 */
1173 public static function calcParenthesis($string) {
1174 $securC = 100;
1175 do {
1176 $valueLenO = strcspn($string, '(');
1177 $valueLenC = strcspn($string, ')');
1178 if ($valueLenC == strlen($string) || $valueLenC < $valueLenO) {
1179 $value = self::calcPriority(substr($string, 0, $valueLenC));
1180 $string = $value . substr($string, $valueLenC + 1);
1181 return $string;
1182 } else {
1183 $string = substr($string, 0, $valueLenO) . self::calcParenthesis(substr($string, $valueLenO + 1));
1184 }
1185 // Security:
1186 $securC--;
1187 if ($securC <= 0) {
1188 break;
1189 }
1190 } while ($valueLenO < strlen($string));
1191 return $string;
1192 }
1193
1194 /**
1195 * Inverse version of htmlspecialchars()
1196 * Usage: 4
1197 *
1198 * @param string Value where &gt;, &lt;, &quot; and &amp; should be converted to regular chars.
1199 * @return string Converted result.
1200 */
1201 public static function htmlspecialchars_decode($value) {
1202 $value = str_replace('&gt;', '>', $value);
1203 $value = str_replace('&lt;', '<', $value);
1204 $value = str_replace('&quot;', '"', $value);
1205 $value = str_replace('&amp;', '&', $value);
1206 return $value;
1207 }
1208
1209 /**
1210 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1211 * Usage: 10
1212 *
1213 * @param string String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;"
1214 * @return string Converted result.
1215 */
1216 public static function deHSCentities($str) {
1217 return preg_replace('/&amp;([#[:alnum:]]*;)/', '&\1', $str);
1218 }
1219
1220 /**
1221 * This function is used to escape any ' -characters when transferring text to JavaScript!
1222 * Usage: 3
1223 *
1224 * @param string String to escape
1225 * @param boolean If set, also backslashes are escaped.
1226 * @param string The character to escape, default is ' (single-quote)
1227 * @return string Processed input string
1228 */
1229 public static function slashJS($string, $extended = 0, $char = "'") {
1230 if ($extended) {
1231 $string = str_replace("\\", "\\\\", $string);
1232 }
1233 return str_replace($char, "\\" . $char, $string);
1234 }
1235
1236 /**
1237 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1238 * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1239 * Usage: 4
1240 *
1241 * @param string String to raw-url-encode with spaces preserved
1242 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1243 */
1244 public static function rawUrlEncodeJS($str) {
1245 return str_replace('%20', ' ', rawurlencode($str));
1246 }
1247
1248 /**
1249 * rawurlencode which preserves "/" chars
1250 * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded.
1251 * Usage: 5
1252 *
1253 * @param string Input string
1254 * @return string Output string
1255 */
1256 public static function rawUrlEncodeFP($str) {
1257 return str_replace('%2F', '/', rawurlencode($str));
1258 }
1259
1260 /**
1261 * Checking syntax of input email address
1262 * Usage: 5
1263 *
1264 * @param string Input string to evaluate
1265 * @return boolean Returns TRUE if the $email address (input string) is valid
1266 */
1267 public static function validEmail($email) {
1268 // enforce maximum length to prevent libpcre recursion crash bug #52929 in PHP
1269 // fixed in PHP 5.3.4; length restriction per SMTP RFC 2821
1270 if (strlen($email) > 320) {
1271 return FALSE;
1272 }
1273 return (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE);
1274 }
1275
1276 /**
1277 * Checks if current e-mail sending method does not accept recipient/sender name
1278 * in a call to PHP mail() function. Windows version of mail() and mini_sendmail
1279 * program are known not to process such input correctly and they cause SMTP
1280 * errors. This function will return TRUE if current mail sending method has
1281 * problem with recipient name in recipient/sender argument for mail().
1282 *
1283 * TODO: 4.3 should have additional configuration variable, which is combined
1284 * by || with the rest in this function.
1285 *
1286 * @return boolean TRUE if mail() does not accept recipient name
1287 */
1288 public static function isBrokenEmailEnvironment() {
1289 return TYPO3_OS == 'WIN' || (FALSE !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
1290 }
1291
1292 /**
1293 * Changes from/to arguments for mail() function to work in any environment.
1294 *
1295 * @param string $address Address to adjust
1296 * @return string Adjusted address
1297 * @see t3lib_::isBrokenEmailEnvironment()
1298 */
1299 public static function normalizeMailAddress($address) {
1300 if (self::isBrokenEmailEnvironment() && FALSE !== ($pos1 = strrpos($address, '<'))) {
1301 $pos2 = strpos($address, '>', $pos1);
1302 $address = substr($address, $pos1 + 1, ($pos2 ? $pos2 : strlen($address)) - $pos1 - 1);
1303 }
1304 return $address;
1305 }
1306
1307 /**
1308 * Formats a string for output between <textarea>-tags
1309 * All content outputted in a textarea form should be passed through this function
1310 * 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!
1311 * Usage: 23
1312 *
1313 * @param string Input string to be formatted.
1314 * @return string Formatted for <textarea>-tags
1315 */
1316 public static function formatForTextarea($content) {
1317 return LF . htmlspecialchars($content);
1318 }
1319
1320 /**
1321 * Converts string to uppercase
1322 * The function converts all Latin characters (a-z, but no accents, etc) to
1323 * uppercase. It is safe for all supported character sets (incl. utf-8).
1324 * Unlike strtoupper() it does not honour the locale.
1325 *
1326 * @param string Input string
1327 * @return string Uppercase String
1328 */
1329 public static function strtoupper($str) {
1330 return strtr((string) $str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
1331 }
1332
1333 /**
1334 * Converts string to lowercase
1335 * The function converts all Latin characters (A-Z, but no accents, etc) to
1336 * lowercase. It is safe for all supported character sets (incl. utf-8).
1337 * Unlike strtolower() it does not honour the locale.
1338 *
1339 * @param string Input string
1340 * @return string Lowercase String
1341 */
1342 public static function strtolower($str) {
1343 return strtr((string) $str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1344 }
1345
1346 /**
1347 * Returns a string of highly randomized bytes (over the full 8-bit range).
1348 *
1349 * @copyright Drupal CMS
1350 * @license GNU General Public License version 2
1351 * @param integer Number of characters (bytes) to return
1352 * @return string Random Bytes
1353 */
1354 public static function generateRandomBytes($count) {
1355 $output = '';
1356 // /dev/urandom is available on many *nix systems and is considered
1357 // the best commonly available pseudo-random source.
1358 if (TYPO3_OS != 'WIN' && ($fh = @fopen('/dev/urandom', 'rb'))) {
1359 $output = fread($fh, $count);
1360 fclose($fh);
1361 } elseif (TYPO3_OS == 'WIN') {
1362 if (class_exists('COM')) {
1363 try {
1364 $com = new COM('CAPICOM.Utilities.1');
1365 $output = base64_decode($com->GetRandom($count, 0));
1366 } catch (Exception $e) {
1367 // CAPICOM not installed
1368 }
1369 }
1370 if ($output === '') {
1371 if (function_exists('mcrypt_create_iv')) {
1372 $output = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
1373 } elseif (function_exists('openssl_random_pseudo_bytes')) {
1374 $isStrong = NULL;
1375 $output = openssl_random_pseudo_bytes($count, $isStrong);
1376 // skip ssl since it wasn't using the strong algo
1377 if ($isStrong !== TRUE) {
1378 $output = '';
1379 }
1380 }
1381 }
1382 }
1383
1384 // fallback if other random byte generation failed until now
1385 if (!isset($output{$count - 1})) {
1386 // We initialize with the somewhat random.
1387 $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
1388 . base_convert(memory_get_usage() % pow(10, 6), 10, 2)
1389 . microtime() . uniqid('') . getmypid();
1390 while (!isset($output{$count - 1})) {
1391 $randomState = sha1(microtime() . mt_rand() . $randomState);
1392 $output .= sha1(mt_rand() . $randomState, TRUE);
1393 }
1394 $output = substr($output, strlen($output) - $count, $count);
1395 }
1396 return $output;
1397 }
1398
1399 /**
1400 * Returns a hex representation of a random byte string.
1401 *
1402 * @param integer Number of hex characters to return
1403 * @return string Random Bytes
1404 */
1405 public static function getRandomHexString($count) {
1406 return substr(bin2hex(self::generateRandomBytes(intval(($count + 1) / 2))), 0, $count);
1407 }
1408
1409 /**
1410 * Returns a given string with underscores as UpperCamelCase.
1411 * Example: Converts blog_example to BlogExample
1412 *
1413 * @param string $string: String to be converted to camel case
1414 * @return string UpperCamelCasedWord
1415 */
1416 public static function underscoredToUpperCamelCase($string) {
1417 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1418 return $upperCamelCase;
1419 }
1420
1421 /**
1422 * Returns a given string with underscores as lowerCamelCase.
1423 * Example: Converts minimal_value to minimalValue
1424 *
1425 * @param string $string: String to be converted to camel case
1426 * @return string lowerCamelCasedWord
1427 */
1428 public static function underscoredToLowerCamelCase($string) {
1429 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
1430 $lowerCamelCase = self::lcfirst($upperCamelCase);
1431 return $lowerCamelCase;
1432 }
1433
1434 /**
1435 * Returns a given CamelCasedString as an lowercase string with underscores.
1436 * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
1437 *
1438 * @param string $string: String to be converted to lowercase underscore
1439 * @return string lowercase_and_underscored_string
1440 */
1441 public static function camelCaseToLowerCaseUnderscored($string) {
1442 return self::strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
1443 }
1444
1445 /**
1446 * Converts the first char of a string to lowercase if it is a latin character (A-Z).
1447 * Example: Converts "Hello World" to "hello World"
1448 *
1449 * @param string $string: The string to be used to lowercase the first character
1450 * @return string The string with the first character as lowercase
1451 */
1452 public static function lcfirst($string) {
1453 return self::strtolower(substr($string, 0, 1)) . substr($string, 1);
1454 }
1455
1456 /**
1457 * Checks if a given string is a Uniform Resource Locator (URL).
1458 *
1459 * @param string $url: The URL to be validated
1460 * @return boolean Whether the given URL is valid
1461 */
1462 public static function isValidUrl($url) {
1463 return (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) !== FALSE);
1464 }
1465
1466
1467 /*************************
1468 *
1469 * ARRAY FUNCTIONS
1470 *
1471 *************************/
1472
1473 /**
1474 * Check if an string item exists in an array.
1475 * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
1476 *
1477 * Comparison to PHP in_array():
1478 * -> $array = array(0, 1, 2, 3);
1479 * -> variant_a := t3lib_div::inArray($array, $needle)
1480 * -> variant_b := in_array($needle, $array)
1481 * -> variant_c := in_array($needle, $array, TRUE)
1482 * +---------+-----------+-----------+-----------+
1483 * | $needle | variant_a | variant_b | variant_c |
1484 * +---------+-----------+-----------+-----------+
1485 * | '1a' | FALSE | TRUE | FALSE |
1486 * | '' | FALSE | TRUE | FALSE |
1487 * | '0' | TRUE | TRUE | FALSE |
1488 * | 0 | TRUE | TRUE | TRUE |
1489 * +---------+-----------+-----------+-----------+
1490 * Usage: 3
1491 *
1492 * @param array one-dimensional array of items
1493 * @param string item to check for
1494 * @return boolean TRUE if $item is in the one-dimensional array $in_array
1495 */
1496 public static function inArray(array $in_array, $item) {
1497 foreach ($in_array as $val) {
1498 if (!is_array($val) && !strcmp($val, $item)) {
1499 return TRUE;
1500 }
1501 }
1502 return FALSE;
1503 }
1504
1505 /**
1506 * Explodes a $string delimited by $delim and passes each item in the array through intval().
1507 * Corresponds to t3lib_div::trimExplode(), but with conversion to integers for all values.
1508 * Usage: 76
1509 *
1510 * @param string Delimiter string to explode with
1511 * @param string The string to explode
1512 * @param boolean If set, all empty values (='') will NOT be set in output
1513 * @param integer If positive, the result will contain a maximum of limit elements,
1514 * if negative, all components except the last -limit are returned,
1515 * if zero (default), the result is not limited at all
1516 * @return array Exploded values, all converted to integers
1517 */
1518 public static function intExplode($delimiter, $string, $onlyNonEmptyValues = FALSE, $limit = 0) {
1519 $explodedValues = self::trimExplode($delimiter, $string, $onlyNonEmptyValues, $limit);
1520 return array_map('intval', $explodedValues);
1521 }
1522
1523 /**
1524 * Reverse explode which explodes the string counting from behind.
1525 * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1526 * Usage: 8
1527 *
1528 * @param string Delimiter string to explode with
1529 * @param string The string to explode
1530 * @param integer Number of array entries
1531 * @return array Exploded values
1532 */
1533 public static function revExplode($delimiter, $string, $count = 0) {
1534 $explodedValues = explode($delimiter, strrev($string), $count);
1535 $explodedValues = array_map('strrev', $explodedValues);
1536 return array_reverse($explodedValues);
1537 }
1538
1539 /**
1540 * Explodes a string and trims all values for whitespace in the ends.
1541 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1542 * Usage: 256
1543 *
1544 * @param string Delimiter string to explode with
1545 * @param string The string to explode
1546 * @param boolean If set, all empty values will be removed in output
1547 * @param integer If positive, the result will contain a maximum of
1548 * $limit elements, if negative, all components except
1549 * the last -$limit are returned, if zero (default),
1550 * the result is not limited at all. Attention though
1551 * that the use of this parameter can slow down this
1552 * function.
1553 * @return array Exploded values
1554 */
1555 public static function trimExplode($delim, $string, $removeEmptyValues = FALSE, $limit = 0) {
1556 $explodedValues = explode($delim, $string);
1557
1558 $result = array_map('trim', $explodedValues);
1559
1560 if ($removeEmptyValues) {
1561 $temp = array();
1562 foreach ($result as $value) {
1563 if ($value !== '') {
1564 $temp[] = $value;
1565 }
1566 }
1567 $result = $temp;
1568 }
1569
1570 if ($limit != 0) {
1571 if ($limit < 0) {
1572 $result = array_slice($result, 0, $limit);
1573 } elseif (count($result) > $limit) {
1574 $lastElements = array_slice($result, $limit - 1);
1575 $result = array_slice($result, 0, $limit - 1);
1576 $result[] = implode($delim, $lastElements);
1577 }
1578 }
1579
1580 return $result;
1581 }
1582
1583 /**
1584 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1585 * Usage: 3
1586 *
1587 * @param array Array containing the values
1588 * @param string Value to search for and if found remove array entry where found.
1589 * @return array Output array with entries removed if search string is found
1590 */
1591 public static function removeArrayEntryByValue(array $array, $cmpValue) {
1592 foreach ($array as $k => $v) {
1593 if (is_array($v)) {
1594 $array[$k] = self::removeArrayEntryByValue($v, $cmpValue);
1595 } elseif (!strcmp($v, $cmpValue)) {
1596 unset($array[$k]);
1597 }
1598 }
1599 return $array;
1600 }
1601
1602 /**
1603 * Filters an array to reduce its elements to match the condition.
1604 * The values in $keepItems can be optionally evaluated by a custom callback function.
1605 *
1606 * Example (arguments used to call this function):
1607 * $array = array(
1608 * array('aa' => array('first', 'second'),
1609 * array('bb' => array('third', 'fourth'),
1610 * array('cc' => array('fifth', 'sixth'),
1611 * );
1612 * $keepItems = array('third');
1613 * $getValueFunc = create_function('$value', 'return $value[0];');
1614 *
1615 * Returns:
1616 * array(
1617 * array('bb' => array('third', 'fourth'),
1618 * )
1619 *
1620 * @param array $array: The initial array to be filtered/reduced
1621 * @param mixed $keepItems: The items which are allowed/kept in the array - accepts array or csv string
1622 * @param string $getValueFunc: (optional) Unique function name set by create_function() used to get the value to keep
1623 * @return array The filtered/reduced array with the kept items
1624 */
1625 public static function keepItemsInArray(array $array, $keepItems, $getValueFunc = NULL) {
1626 if ($array) {
1627 // Convert strings to arrays:
1628 if (is_string($keepItems)) {
1629 $keepItems = self::trimExplode(',', $keepItems);
1630 }
1631 // create_function() returns a string:
1632 if (!is_string($getValueFunc)) {
1633 $getValueFunc = NULL;
1634 }
1635 // Do the filtering:
1636 if (is_array($keepItems) && count($keepItems)) {
1637 foreach ($array as $key => $value) {
1638 // Get the value to compare by using the callback function:
1639 $keepValue = (isset($getValueFunc) ? $getValueFunc($value) : $value);
1640 if (!in_array($keepValue, $keepItems)) {
1641 unset($array[$key]);
1642 }
1643 }
1644 }
1645 }
1646 return $array;
1647 }
1648
1649 /**
1650 * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
1651 * Usage: 24
1652 *
1653 * @param string Name prefix for entries. Set to blank if you wish none.
1654 * @param array The (multidim) array to implode
1655 * @param string (keep blank)
1656 * @param boolean If set, parameters which were blank strings would be removed.
1657 * @param boolean If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1658 * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
1659 * @see explodeUrl2Array()
1660 */
1661 public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = FALSE, $rawurlencodeParamName = FALSE) {
1662 foreach ($theArray as $Akey => $AVal) {
1663 $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
1664 if (is_array($AVal)) {
1665 $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1666 } else {
1667 if (!$skipBlank || strcmp($AVal, '')) {
1668 $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) .
1669 '=' . rawurlencode($AVal);
1670 }
1671 }
1672 }
1673 return $str;
1674 }
1675
1676 /**
1677 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1678 *
1679 * @param string GETvars string
1680 * @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())
1681 * @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!
1682 * @see implodeArrayForUrl()
1683 */
1684 public static function explodeUrl2Array($string, $multidim = FALSE) {
1685 $output = array();
1686 if ($multidim) {
1687 parse_str($string, $output);
1688 } else {
1689 $p = explode('&', $string);
1690 foreach ($p as $v) {
1691 if (strlen($v)) {
1692 list($pK, $pV) = explode('=', $v, 2);
1693 $output[rawurldecode($pK)] = rawurldecode($pV);
1694 }
1695 }
1696 }
1697 return $output;
1698 }
1699
1700 /**
1701 * Returns an array with selected keys from incoming data.
1702 * (Better read source code if you want to find out...)
1703 * Usage: 3
1704 *
1705 * @param string List of variable/key names
1706 * @param array Array from where to get values based on the keys in $varList
1707 * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1708 * @return array Output array with selected variables.
1709 */
1710 public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = 1) {
1711 $keys = self::trimExplode(',', $varList, 1);
1712 $outArr = array();
1713 foreach ($keys as $v) {
1714 if (isset($getArray[$v])) {
1715 $outArr[$v] = $getArray[$v];
1716 } elseif ($GPvarAlt) {
1717 $outArr[$v] = self::_GP($v);
1718 }
1719 }
1720 return $outArr;
1721 }
1722
1723 /**
1724 * AddSlash array
1725 * This function traverses a multidimentional array and adds slashes to the values.
1726 * NOTE that the input array is and argument by reference.!!
1727 * Twin-function to stripSlashesOnArray
1728 * Usage: 8
1729 *
1730 * @param array Multidimensional input array, (REFERENCE!)
1731 * @return array
1732 */
1733 public static function addSlashesOnArray(array &$theArray) {
1734 foreach ($theArray as &$value) {
1735 if (is_array($value)) {
1736 self::addSlashesOnArray($value);
1737 } else {
1738 $value = addslashes($value);
1739 }
1740 }
1741 unset($value);
1742 reset($theArray);
1743 }
1744
1745 /**
1746 * StripSlash array
1747 * This function traverses a multidimentional array and strips slashes to the values.
1748 * NOTE that the input array is and argument by reference.!!
1749 * Twin-function to addSlashesOnArray
1750 * Usage: 10
1751 *
1752 * @param array Multidimensional input array, (REFERENCE!)
1753 * @return array
1754 */
1755 public static function stripSlashesOnArray(array &$theArray) {
1756 foreach ($theArray as &$value) {
1757 if (is_array($value)) {
1758 self::stripSlashesOnArray($value);
1759 } else {
1760 $value = stripslashes($value);
1761 }
1762 }
1763 unset($value);
1764 reset($theArray);
1765 }
1766
1767 /**
1768 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1769 * Usage: 0
1770 *
1771 * @param array Multidimensional input array
1772 * @param string "add" or "strip", depending on usage you wish.
1773 * @return array
1774 */
1775 public static function slashArray(array $arr, $cmd) {
1776 if ($cmd == 'strip') {
1777 self::stripSlashesOnArray($arr);
1778 }
1779 if ($cmd == 'add') {
1780 self::addSlashesOnArray($arr);
1781 }
1782 return $arr;
1783 }
1784
1785 /**
1786 * Rename Array keys with a given mapping table
1787 * @param array Array by reference which should be remapped
1788 * @param array Array with remap information, array/$oldKey => $newKey)
1789 */
1790 function remapArrayKeys(&$array, $mappingTable) {
1791 if (is_array($mappingTable)) {
1792 foreach ($mappingTable as $old => $new) {
1793 if ($new && isset($array[$old])) {
1794 $array[$new] = $array[$old];
1795 unset ($array[$old]);
1796 }
1797 }
1798 }
1799 }
1800
1801
1802 /**
1803 * Merges two arrays recursively and "binary safe" (integer keys are
1804 * overridden as well), overruling similar values in the first array
1805 * ($arr0) with the values of the second array ($arr1)
1806 * In case of identical keys, ie. keeping the values of the second.
1807 * Usage: 0
1808 *
1809 * @param array First array
1810 * @param array Second array, overruling the first array
1811 * @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.
1812 * @param boolean If set, values from $arr1 will overrule if they are empty or zero. Default: TRUE
1813 * @return array Resulting array where $arr1 values has overruled $arr0 values
1814 */
1815 public static function array_merge_recursive_overrule(array $arr0, array $arr1, $notAddKeys = 0, $includeEmptyValues = TRUE) {
1816 foreach ($arr1 as $key => $val) {
1817 if (is_array($arr0[$key])) {
1818 if (is_array($arr1[$key])) {
1819 $arr0[$key] = self::array_merge_recursive_overrule($arr0[$key], $arr1[$key], $notAddKeys, $includeEmptyValues);
1820 }
1821 } else {
1822 if ($notAddKeys) {
1823 if (isset($arr0[$key])) {
1824 if ($includeEmptyValues || $val) {
1825 $arr0[$key] = $val;
1826 }
1827 }
1828 } else {
1829 if ($includeEmptyValues || $val) {
1830 $arr0[$key] = $val;
1831 }
1832 }
1833 }
1834 }
1835 reset($arr0);
1836 return $arr0;
1837 }
1838
1839 /**
1840 * 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.
1841 * Usage: 16
1842 *
1843 * @param array First array
1844 * @param array Second array
1845 * @return array Merged result.
1846 */
1847 public static function array_merge(array $arr1, array $arr2) {
1848 return $arr2 + $arr1;
1849 }
1850
1851 /**
1852 * Filters keys off from first array that also exist in second array. Comparision is done by keys.
1853 * This method is a recursive version of php array_diff_assoc()
1854 *
1855 * @param array Source array
1856 * @param array Reduce source array by this array
1857 * @return array Source array reduced by keys also present in second array
1858 */
1859 public static function arrayDiffAssocRecursive(array $array1, array $array2) {
1860 $differenceArray = array();
1861 foreach ($array1 as $key => $value) {
1862 if (!array_key_exists($key, $array2)) {
1863 $differenceArray[$key] = $value;
1864 } elseif (is_array($value)) {
1865 if (is_array($array2[$key])) {
1866 $differenceArray[$key] = self::arrayDiffAssocRecursive($value, $array2[$key]);
1867 }
1868 }
1869 }
1870
1871 return $differenceArray;
1872 }
1873
1874 /**
1875 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1876 * Usage: 5
1877 *
1878 * @param array Input array of values
1879 * @param string Delimited, default is comman
1880 * @param string Quote-character to wrap around the values.
1881 * @return string A single line of CSV
1882 */
1883 public static function csvValues(array $row, $delim = ',', $quote = '"') {
1884 $out = array();
1885 foreach ($row as $value) {
1886 $out[] = str_replace($quote, $quote . $quote, $value);
1887 }
1888 $str = $quote . implode($quote . $delim . $quote, $out) . $quote;
1889 return $str;
1890 }
1891
1892 /**
1893 * Removes dots "." from end of a key identifier of TypoScript styled array.
1894 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1895 *
1896 * @param array $ts: TypoScript configuration array
1897 * @return array TypoScript configuration array without dots at the end of all keys
1898 */
1899 public static function removeDotsFromTS(array $ts) {
1900 $out = array();
1901 foreach ($ts as $key => $value) {
1902 if (is_array($value)) {
1903 $key = rtrim($key, '.');
1904 $out[$key] = self::removeDotsFromTS($value);
1905 } else {
1906 $out[$key] = $value;
1907 }
1908 }
1909 return $out;
1910 }
1911
1912 /**
1913 * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
1914 *
1915 * @param array $array array to be sorted recursively, passed by reference
1916 * @return boolean TRUE if param is an array
1917 */
1918 public static function naturalKeySortRecursive(&$array) {
1919 if (!is_array($array)) {
1920 return FALSE;
1921 }
1922 uksort($array, 'strnatcasecmp');
1923 foreach ($array as $key => $value) {
1924 self::naturalKeySortRecursive($array[$key]);
1925 }
1926 return TRUE;
1927 }
1928
1929
1930 /*************************
1931 *
1932 * HTML/XML PROCESSING
1933 *
1934 *************************/
1935
1936 /**
1937 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1938 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
1939 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1940 * Usage: 8
1941 *
1942 * @param string HTML-tag string (or attributes only)
1943 * @return array Array with the attribute values.
1944 */
1945 public static function get_tag_attributes($tag) {
1946 $components = self::split_tag_attributes($tag);
1947 $name = ''; // attribute name is stored here
1948 $valuemode = FALSE;
1949 $attributes = array();
1950 foreach ($components as $key => $val) {
1951 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
1952 if ($valuemode) {
1953 if ($name) {
1954 $attributes[$name] = $val;
1955 $name = '';
1956 }
1957 } else {
1958 if ($key = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $val))) {
1959 $attributes[$key] = '';
1960 $name = $key;
1961 }
1962 }
1963 $valuemode = FALSE;
1964 } else {
1965 $valuemode = TRUE;
1966 }
1967 }
1968 return $attributes;
1969 }
1970
1971 /**
1972 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1973 * Removes tag-name if found
1974 * Usage: 2
1975 *
1976 * @param string HTML-tag string (or attributes only)
1977 * @return array Array with the attribute values.
1978 */
1979 public static function split_tag_attributes($tag) {
1980 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
1981 // Removes any > in the end of the string
1982 $tag_tmp = trim(rtrim($tag_tmp, '>'));
1983
1984 $value = array();
1985 while (strcmp($tag_tmp, '')) { // Compared with empty string instead , 030102
1986 $firstChar = substr($tag_tmp, 0, 1);
1987 if (!strcmp($firstChar, '"') || !strcmp($firstChar, "'")) {
1988 $reg = explode($firstChar, $tag_tmp, 3);
1989 $value[] = $reg[1];
1990 $tag_tmp = trim($reg[2]);
1991 } elseif (!strcmp($firstChar, '=')) {
1992 $value[] = '=';
1993 $tag_tmp = trim(substr($tag_tmp, 1)); // Removes = chars.
1994 } else {
1995 // There are '' around the value. We look for the next ' ' or '>'
1996 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
1997 $value[] = trim($reg[0]);
1998 $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
1999 }
2000 }
2001 reset($value);
2002 return $value;
2003 }
2004
2005 /**
2006 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
2007 * Usage: 14
2008 *
2009 * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
2010 * @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!
2011 * @param boolean If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
2012 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
2013 */
2014 public static function implodeAttributes(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
2015 if ($xhtmlSafe) {
2016 $newArr = array();
2017 foreach ($arr as $p => $v) {
2018 if (!isset($newArr[strtolower($p)])) {
2019 $newArr[strtolower($p)] = htmlspecialchars($v);
2020 }
2021 }
2022 $arr = $newArr;
2023 }
2024 $list = array();
2025 foreach ($arr as $p => $v) {
2026 if (strcmp($v, '') || $dontOmitBlankAttribs) {
2027 $list[] = $p . '="' . $v . '"';
2028 }
2029 }
2030 return implode(' ', $list);
2031 }
2032
2033 /**
2034 * Wraps JavaScript code XHTML ready with <script>-tags
2035 * Automatic re-identing of the JS code is done by using the first line as ident reference.
2036 * This is nice for identing JS code with PHP code on the same level.
2037 *
2038 * @param string JavaScript code
2039 * @param boolean Wrap script element in linebreaks? Default is TRUE.
2040 * @return string The wrapped JS code, ready to put into a XHTML page
2041 * @author Ingmar Schlecht <ingmars@web.de>
2042 * @author René Fritz <r.fritz@colorcube.de>
2043 */
2044 public static function wrapJS($string, $linebreak = TRUE) {
2045 if (trim($string)) {
2046 // <script wrapped in nl?
2047 $cr = $linebreak ? LF : '';
2048
2049 // remove nl from the beginning
2050 $string = preg_replace('/^\n+/', '', $string);
2051 // re-ident to one tab using the first line as reference
2052 $match = array();
2053 if (preg_match('/^(\t+)/', $string, $match)) {
2054 $string = str_replace($match[1], TAB, $string);
2055 }
2056 $string = $cr . '<script type="text/javascript">
2057 /*<![CDATA[*/
2058 ' . $string . '
2059 /*]]>*/
2060 </script>' . $cr;
2061 }
2062 return trim($string);
2063 }
2064
2065
2066 /**
2067 * Parses XML input into a PHP array with associative keys
2068 * Usage: 0
2069 *
2070 * @param string XML data input
2071 * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
2072 * @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.
2073 * @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
2074 */
2075 public static function xml2tree($string, $depth = 999) {
2076 $parser = xml_parser_create();
2077 $vals = array();
2078 $index = array();
2079
2080 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2081 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
2082 xml_parse_into_struct($parser, $string, $vals, $index);
2083
2084 if (xml_get_error_code($parser)) {
2085 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2086 }
2087 xml_parser_free($parser);
2088
2089 $stack = array(array());
2090 $stacktop = 0;
2091 $startPoint = 0;
2092
2093 $tagi = array();
2094 foreach ($vals as $key => $val) {
2095 $type = $val['type'];
2096
2097 // open tag:
2098 if ($type == 'open' || $type == 'complete') {
2099 $stack[$stacktop++] = $tagi;
2100
2101 if ($depth == $stacktop) {
2102 $startPoint = $key;
2103 }
2104
2105 $tagi = array('tag' => $val['tag']);
2106
2107 if (isset($val['attributes'])) {
2108 $tagi['attrs'] = $val['attributes'];
2109 }
2110 if (isset($val['value'])) {
2111 $tagi['values'][] = $val['value'];
2112 }
2113 }
2114 // finish tag:
2115 if ($type == 'complete' || $type == 'close') {
2116 $oldtagi = $tagi;
2117 $tagi = $stack[--$stacktop];
2118 $oldtag = $oldtagi['tag'];
2119 unset($oldtagi['tag']);
2120
2121 if ($depth == ($stacktop + 1)) {
2122 if ($key - $startPoint > 0) {
2123 $partArray = array_slice(
2124 $vals,
2125 $startPoint + 1,
2126 $key - $startPoint - 1
2127 );
2128 #$oldtagi=array('XMLvalue'=>self::xmlRecompileFromStructValArray($partArray));
2129 $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
2130 } else {
2131 $oldtagi['XMLvalue'] = $oldtagi['values'][0];
2132 }
2133 }
2134
2135 $tagi['ch'][$oldtag][] = $oldtagi;
2136 unset($oldtagi);
2137 }
2138 // cdata
2139 if ($type == 'cdata') {
2140 $tagi['values'][] = $val['value'];
2141 }
2142 }
2143 return $tagi['ch'];
2144 }
2145
2146 /**
2147 * Turns PHP array into XML. See array2xml()
2148 *
2149 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2150 * @param string Alternative document tag. Default is "phparray".
2151 * @param array Options for the compilation. See array2xml() for description.
2152 * @param string Forced charset to prologue
2153 * @return string An XML string made from the input content in the array.
2154 * @see xml2array(),array2xml()
2155 */
2156 public static function array2xml_cs(array $array, $docTag = 'phparray', array $options = array(), $charset = '') {
2157
2158 // Figure out charset if not given explicitly:
2159 if (!$charset) {
2160 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) { // First priority: forceCharset! If set, this will be authoritative!
2161 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
2162 } elseif (is_object($GLOBALS['LANG'])) {
2163 $charset = $GLOBALS['LANG']->charSet; // If "LANG" is around, that will hold the current charset
2164 } else {
2165 $charset = 'iso-8859-1'; // THIS is just a hopeful guess!
2166 }
2167 }
2168
2169 // Return XML:
2170 return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF .
2171 self::array2xml($array, '', 0, $docTag, 0, $options);
2172 }
2173
2174 /**
2175 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
2176 *
2177 * Converts a PHP array into an XML string.
2178 * The XML output is optimized for readability since associative keys are used as tagnames.
2179 * 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.
2180 * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
2181 * 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
2182 * 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.
2183 * 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!
2184 * 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...
2185 * Usage: 5
2186 *
2187 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2188 * @param string tag-prefix, eg. a namespace prefix like "T3:"
2189 * @param integer Current recursion level. Don't change, stay at zero!
2190 * @param string Alternative document tag. Default is "phparray".
2191 * @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
2192 * @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')
2193 * @param string Stack data. Don't touch.
2194 * @return string An XML string made from the input content in the array.
2195 * @see xml2array()
2196 */
2197 public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = array(), array $stackData = array()) {
2198 // 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
2199 $binaryChars = chr(0) . chr(1) . chr(2) . chr(3) . chr(4) . chr(5) . chr(6) . chr(7) . chr(8) .
2200 chr(11) . chr(12) . chr(14) . chr(15) . chr(16) . chr(17) . chr(18) . chr(19) .
2201 chr(20) . chr(21) . chr(22) . chr(23) . chr(24) . chr(25) . chr(26) . chr(27) . chr(28) . chr(29) .
2202 chr(30) . chr(31);
2203 // Set indenting mode:
2204 $indentChar = $spaceInd ? ' ' : TAB;
2205 $indentN = $spaceInd > 0 ? $spaceInd : 1;
2206 $nl = ($spaceInd >= 0 ? LF : '');
2207
2208 // Init output variable:
2209 $output = '';
2210
2211 // Traverse the input array
2212 foreach ($array as $k => $v) {
2213 $attr = '';
2214 $tagName = $k;
2215
2216 // Construct the tag name.
2217 if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
2218 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2219 $tagName = (string) $options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']];
2220 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && self::testInt($tagName)) { // Use tag based on parent tag name + if current tag is numeric
2221 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2222 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM'];
2223 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) { // Use tag based on parent tag name + current tag
2224 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2225 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName];
2226 } elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
2227 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2228 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName']];
2229 } elseif (!strcmp(intval($tagName), $tagName)) { // If integer...;
2230 if ($options['useNindex']) { // If numeric key, prefix "n"
2231 $tagName = 'n' . $tagName;
2232 } else { // Use special tag for num. keys:
2233 $attr .= ' index="' . $tagName . '"';
2234 $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
2235 }
2236 } elseif ($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
2237 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2238 $tagName = $options['useIndexTagForAssoc'];
2239 }
2240
2241 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2242 $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
2243
2244 // If the value is an array then we will call this function recursively:
2245 if (is_array($v)) {
2246
2247 // Sub elements:
2248 if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
2249 $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
2250 $clearStackPath = $subOptions['clearStackPath'];
2251 } else {
2252 $subOptions = $options;
2253 $clearStackPath = FALSE;
2254 }
2255
2256 $content = $nl .
2257 self::array2xml(
2258 $v,
2259 $NSprefix,
2260 $level + 1,
2261 '',
2262 $spaceInd,
2263 $subOptions,
2264 array(
2265 'parentTagName' => $tagName,
2266 'grandParentTagName' => $stackData['parentTagName'],
2267 'path' => $clearStackPath ? '' : $stackData['path'] . '/' . $tagName,
2268 )
2269 ) .
2270 ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '');
2271 if ((int) $options['disableTypeAttrib'] != 2) { // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2272 $attr .= ' type="array"';
2273 }
2274 } else { // Just a value:
2275
2276 // Look for binary chars:
2277 $vLen = strlen($v); // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
2278 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!
2279 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2280 $content = $nl . chunk_split(base64_encode($v));
2281 $attr .= ' base64="1"';
2282 } else {
2283 // Otherwise, just htmlspecialchar the stuff:
2284 $content = htmlspecialchars($v);
2285 $dType = gettype($v);
2286 if ($dType == 'string') {
2287 if ($options['useCDATA'] && $content != $v) {
2288 $content = '<![CDATA[' . $v . ']]>';
2289 }
2290 } elseif (!$options['disableTypeAttrib']) {
2291 $attr .= ' type="' . $dType . '"';
2292 }
2293 }
2294 }
2295
2296 // Add the element to the output string:
2297 $output .= ($spaceInd >= 0 ? str_pad('', ($level + 1) * $indentN, $indentChar) : '') . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
2298 }
2299
2300 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2301 if (!$level) {
2302 $output =
2303 '<' . $docTag . '>' . $nl .
2304 $output .
2305 '</' . $docTag . '>';
2306 }
2307
2308 return $output;
2309 }
2310
2311 /**
2312 * Converts an XML string to a PHP array.
2313 * This is the reverse function of array2xml()
2314 * This is a wrapper for xml2arrayProcess that adds a two-level cache
2315 * Usage: 17
2316 *
2317 * @param string XML content to convert into an array
2318 * @param string The tag-prefix resolve, eg. a namespace like "T3:"
2319 * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2320 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2321 * @see array2xml(),xml2arrayProcess()
2322 * @author Fabrizio Branca <typo3@fabrizio-branca.de> (added caching)
2323 */
2324 public static function xml2array($string, $NSprefix = '', $reportDocTag = FALSE) {
2325 static $firstLevelCache = array();
2326
2327 $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
2328
2329 // look up in first level cache
2330 if (!empty($firstLevelCache[$identifier])) {
2331 $array = $firstLevelCache[$identifier];
2332 } else {
2333 // look up in second level cache
2334 $cacheContent = t3lib_pageSelect::getHash($identifier, 0);
2335 $array = unserialize($cacheContent);
2336
2337 if ($array === FALSE) {
2338 $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
2339 t3lib_pageSelect::storeHash($identifier, serialize($array), 'ident_xml2array');
2340 }
2341 // store content in first level cache
2342 $firstLevelCache[$identifier] = $array;
2343 }
2344 return $array;
2345 }
2346
2347 /**
2348 * Converts an XML string to a PHP array.
2349 * This is the reverse function of array2xml()
2350 * Usage: 1
2351 *
2352 * @param string XML content to convert into an array
2353 * @param string The tag-prefix resolve, eg. a namespace like "T3:"
2354 * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2355 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2356 * @see array2xml()
2357 */
2358 protected function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = FALSE) {
2359 // Create parser:
2360 $parser = xml_parser_create();
2361 $vals = array();
2362 $index = array();
2363
2364 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
2365 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
2366
2367 // default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2368 $match = array();
2369 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
2370 $theCharset = $match[1] ? $match[1] : ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'iso-8859-1');
2371 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); // us-ascii / utf-8 / iso-8859-1
2372
2373 // Parse content:
2374 xml_parse_into_struct($parser, $string, $vals, $index);
2375
2376 // If error, return error message:
2377 if (xml_get_error_code($parser)) {
2378 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2379 }
2380 xml_parser_free($parser);
2381
2382 // Init vars:
2383 $stack = array(array());
2384 $stacktop = 0;
2385 $current = array();
2386 $tagName = '';
2387 $documentTag = '';
2388
2389 // Traverse the parsed XML structure:
2390 foreach ($vals as $key => $val) {
2391
2392 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2393 $tagName = $val['tag'];
2394 if (!$documentTag) {
2395 $documentTag = $tagName;
2396 }
2397
2398 // Test for name space:
2399 $tagName = ($NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix) ? substr($tagName, strlen($NSprefix)) : $tagName;
2400
2401 // Test for numeric tag, encoded on the form "nXXX":
2402 $testNtag = substr($tagName, 1); // Closing tag.
2403 $tagName = (substr($tagName, 0, 1) == 'n' && !strcmp(intval($testNtag), $testNtag)) ? intval($testNtag) : $tagName;
2404
2405 // Test for alternative index value:
2406 if (strlen($val['attributes']['index'])) {
2407 $tagName = $val['attributes']['index'];
2408 }
2409
2410 // Setting tag-values, manage stack:
2411 switch ($val['type']) {
2412 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2413 $current[$tagName] = array(); // Setting blank place holder
2414 $stack[$stacktop++] = $current;
2415 $current = array();
2416 break;
2417 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2418 $oldCurrent = $current;
2419 $current = $stack[--$stacktop];
2420 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
2421 $current[key($current)] = $oldCurrent;
2422 unset($oldCurrent);
2423 break;
2424 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2425 if ($val['attributes']['base64']) {
2426 $current[$tagName] = base64_decode($val['value']);
2427 } else {
2428 $current[$tagName] = (string) $val['value']; // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
2429
2430 // Cast type:
2431 switch ((string) $val['attributes']['type']) {
2432 case 'integer':
2433 $current[$tagName] = (integer) $current[$tagName];
2434 break;
2435 case 'double':
2436 $current[$tagName] = (double) $current[$tagName];
2437 break;
2438 case 'boolean':
2439 $current[$tagName] = (bool) $current[$tagName];
2440 break;
2441 case 'array':
2442 $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...
2443 break;
2444 }
2445 }
2446 break;
2447 }
2448 }
2449
2450 if ($reportDocTag) {
2451 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2452 }
2453
2454 // Finally return the content of the document tag.
2455 return $current[$tagName];
2456 }
2457
2458 /**
2459 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2460 * Usage: 2
2461 *
2462 * @param array A array of XML parts, see xml2tree
2463 * @return string Re-compiled XML data.
2464 */
2465 public static function xmlRecompileFromStructValArray(array $vals) {
2466 $XMLcontent = '';
2467
2468 foreach ($vals as $val) {
2469 $type = $val['type'];
2470
2471 // open tag:
2472 if ($type == 'open' || $type == 'complete') {
2473 $XMLcontent .= '<' . $val['tag'];
2474 if (isset($val['attributes'])) {
2475 foreach ($val['attributes'] as $k => $v) {
2476 $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
2477 }
2478 }
2479 if ($type == 'complete') {
2480 if (isset($val['value'])) {
2481 $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
2482 } else {
2483 $XMLcontent .= '/>';
2484 }
2485 } else {
2486 $XMLcontent .= '>';
2487 }
2488
2489 if ($type == 'open' && isset($val['value'])) {
2490 $XMLcontent .= htmlspecialchars($val['value']);
2491 }
2492 }
2493 // finish tag:
2494 if ($type == 'close') {
2495 $XMLcontent .= '</' . $val['tag'] . '>';
2496 }
2497 // cdata
2498 if ($type == 'cdata') {
2499 $XMLcontent .= htmlspecialchars($val['value']);
2500 }
2501 }
2502
2503 return $XMLcontent;
2504 }
2505
2506 /**
2507 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2508 * Usage: 1
2509 *
2510 * @param string XML data
2511 * @return array Attributes of the xml prologue (header)
2512 */
2513 public static function xmlGetHeaderAttribs($xmlData) {
2514 $match = array();
2515 if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
2516 return self::get_tag_attributes($match[1]);
2517 }
2518 }
2519
2520 /**
2521 * Minifies JavaScript
2522 *
2523 * @param string $script Script to minify
2524 * @param string $error Error message (if any)
2525 * @return string Minified script or source string if error happened
2526 */
2527 public static function minifyJavaScript($script, &$error = '') {
2528 require_once(PATH_typo3 . 'contrib/jsmin/jsmin.php');
2529 try {
2530 $error = '';
2531 $script = trim(JSMin::minify(str_replace(CR, '', $script)));
2532 }
2533 catch (JSMinException $e) {
2534 $error = 'Error while minifying JavaScript: ' . $e->getMessage();
2535 self::devLog($error, 't3lib_div', 2,
2536 array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
2537 }
2538 return $script;
2539 }
2540
2541
2542 /*************************
2543 *
2544 * FILES FUNCTIONS
2545 *
2546 *************************/
2547
2548 /**
2549 * Reads the file or url $url and returns the content
2550 * 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.
2551 * Usage: 83
2552 *
2553 * @param string File/URL to read
2554 * @param integer Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2555 * @param array HTTP headers to be used in the request
2556 * @param array Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2557 * @return string The content from the resource given as input. FALSE if an error has occured.
2558 */
2559 public static function getUrl($url, $includeHeader = 0, $requestHeaders = FALSE, &$report = NULL) {
2560 $content = FALSE;
2561
2562 if (isset($report)) {
2563 $report['error'] = 0;
2564 $report['message'] = '';
2565 }
2566
2567 // use cURL for: http, https, ftp, ftps, sftp and scp
2568 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2569 if (isset($report)) {
2570 $report['lib'] = 'cURL';
2571 }
2572
2573 // External URL without error checking.
2574 $ch = curl_init();
2575 if (!$ch) {
2576 if (isset($report)) {
2577 $report['error'] = -1;
2578 $report['message'] = 'Couldn\'t initialize cURL.';
2579 }
2580 return FALSE;
2581 }
2582
2583 curl_setopt($ch, CURLOPT_URL, $url);
2584 curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
2585 curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
2586 curl_setopt($ch, CURLOPT_HTTPGET, $includeHeader == 2 ? 'HEAD' : 'GET');
2587 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2588 curl_setopt($ch, CURLOPT_FAILONERROR, 1);
2589 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, max(0, intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout'])));
2590
2591 $followLocation = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
2592
2593 if (is_array($requestHeaders)) {
2594 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
2595 }
2596
2597 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2598 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2599 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2600
2601 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2602 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2603 }
2604 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2605 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2606 }
2607 }
2608 $content = curl_exec($ch);
2609 if (isset($report)) {
2610 if ($content === FALSE) {
2611 $report['error'] = curl_errno($ch);
2612 $report['message'] = curl_error($ch);
2613 } else {
2614 $curlInfo = curl_getinfo($ch);
2615 // We hit a redirection but we couldn't follow it
2616 if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
2617 $report['error'] = -1;
2618 $report['message'] = 'Couldn\'t follow location redirect (PHP configuration option open_basedir is in effect).';
2619 } elseif ($includeHeader) {
2620 // Set only for $includeHeader to work exactly like PHP variant
2621 $report['http_code'] = $curlInfo['http_code'];
2622 $report['content_type'] = $curlInfo['content_type'];
2623 }
2624 }
2625 }
2626 curl_close($ch);
2627
2628 } elseif ($includeHeader) {
2629 if (isset($report)) {
2630 $report['lib'] = 'socket';
2631 }
2632 $parsedURL = parse_url($url);
2633 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2634 if (isset($report)) {
2635 $report['error'] = -1;
2636 $report['message'] = 'Reading headers is not allowed for this protocol.';
2637 }
2638 return FALSE;
2639 }
2640 $port = intval($parsedURL['port']);
2641 if ($port < 1) {
2642 if ($parsedURL['scheme'] == 'http') {
2643 $port = ($port > 0 ? $port : 80);
2644 $scheme = '';
2645 } else {
2646 $port = ($port > 0 ? $port : 443);
2647 $scheme = 'ssl://';
2648 }
2649 }
2650 $errno = 0;
2651 // $errstr = '';
2652 $fp = @fsockopen($scheme . $parsedURL['host'], $port, $errno, $errstr, 2.0);
2653 if (!$fp || $errno > 0) {
2654 if (isset($report)) {
2655 $report['error'] = $errno ? $errno : -1;
2656 $report['message'] = $errno ? ($errstr ? $errstr : 'Socket error.') : 'Socket initialization error.';
2657 }
2658 return FALSE;
2659 }
2660 $method = ($includeHeader == 2) ? 'HEAD' : 'GET';
2661 $msg = $method . ' ' . (isset($parsedURL['path']) ? $parsedURL['path'] : '/') .
2662 ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
2663 ' HTTP/1.0' . CRLF . 'Host: ' .
2664 $parsedURL['host'] . "\r\nConnection: close\r\n";
2665 if (is_array($requestHeaders)) {
2666 $msg .= implode(CRLF, $requestHeaders) . CRLF;
2667 }
2668 $msg .= CRLF;
2669
2670 fputs($fp, $msg);
2671 while (!feof($fp)) {
2672 $line = fgets($fp, 2048);
2673 if (isset($report)) {
2674 if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
2675 $report['http_code'] = $status[1];
2676 }
2677 elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2678 $report['content_type'] = $type[1];
2679 }
2680 }
2681 $content .= $line;
2682 if (!strlen(trim($line))) {
2683 break; // Stop at the first empty line (= end of header)
2684 }
2685 }
2686 if ($includeHeader != 2) {
2687 $content .= stream_get_contents($fp);
2688 }
2689 fclose($fp);
2690
2691 } elseif (is_array($requestHeaders)) {
2692 if (isset($report)) {
2693 $report['lib'] = 'file/context';
2694 }
2695 $parsedURL = parse_url($url);
2696 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2697 if (isset($report)) {
2698 $report['error'] = -1;
2699 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2700 }
2701 return FALSE;
2702 }
2703 $ctx = stream_context_create(array(
2704 'http' => array(
2705 'header' => implode(CRLF, $requestHeaders)
2706 )
2707 )
2708 );
2709 $content = @file_get_contents($url, FALSE, $ctx);
2710 if ($content === FALSE && isset($report)) {
2711 $phpError = error_get_last();
2712 $report['error'] = $phpError['type'];
2713 $report['message'] = $phpError['message'];
2714 }
2715 } else {
2716 if (isset($report)) {
2717 $report['lib'] = 'file';
2718 }
2719 $content = @file_get_contents($url);
2720 if ($content === FALSE && isset($report)) {
2721 if (function_exists('error_get_last')) {
2722 $phpError = error_get_last();
2723 $report['error'] = $phpError['type'];
2724 $report['message'] = $phpError['message'];
2725 } else {
2726 $report['error'] = -1;
2727 $report['message'] = 'Couldn\'t get URL.';
2728 }
2729 }
2730 }
2731
2732 return $content;
2733 }
2734
2735 /**
2736 * Writes $content to the file $file
2737 * Usage: 30
2738 *
2739 * @param string Filepath to write to
2740 * @param string Content to write
2741 * @return boolean TRUE if the file was successfully opened and written to.
2742 */
2743 public static function writeFile($file, $content) {
2744 if (!@is_file($file)) {
2745 $changePermissions = TRUE;
2746 }
2747
2748 if ($fd = fopen($file, 'wb')) {
2749 $res = fwrite($fd, $content);
2750 fclose($fd);
2751
2752 if ($res === FALSE) {
2753 return FALSE;
2754 }
2755
2756 if ($changePermissions) { // Change the permissions only if the file has just been created
2757 self::fixPermissions($file);
2758 }
2759
2760 return TRUE;
2761 }
2762
2763 return FALSE;
2764 }
2765
2766 /**
2767 * Sets the file system mode and group ownership of a file or a folder.
2768 *
2769 * @param string Path of file or folder, must not be escaped. Path can be absolute or relative
2770 * @param boolean If set, also fixes permissions of files and folders in the folder (if $path is a folder)
2771 * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
2772 */
2773 public static function fixPermissions($path, $recursive = FALSE) {
2774 if (TYPO3_OS != 'WIN') {
2775 $result = FALSE;
2776
2777 // Make path absolute
2778 if (!self::isAbsPath($path)) {
2779 $path = self::getFileAbsFileName($path, FALSE);
2780 }
2781
2782 if (self::isAllowedAbsPath($path)) {
2783 if (@is_file($path)) {
2784 // "@" is there because file is not necessarily OWNED by the user
2785 $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
2786 } elseif (@is_dir($path)) {
2787 // "@" is there because file is not necessarily OWNED by the user
2788 $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2789 }
2790
2791 // Set createGroup if not empty
2792 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) {
2793 // "@" is there because file is not necessarily OWNED by the user
2794 $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2795 $result = $changeGroupResult ? $result : FALSE;
2796 }
2797
2798 // Call recursive if recursive flag if set and $path is directory
2799 if ($recursive && @is_dir($path)) {
2800 $handle = opendir($path);
2801 while (($file = readdir($handle)) !== FALSE) {
2802 $recursionResult = NULL;
2803 if ($file !== '.' && $file !== '..') {
2804 if (@is_file($path . '/' . $file)) {
2805 $recursionResult = self::fixPermissions($path . '/' . $file);
2806 } elseif (@is_dir($path . '/' . $file)) {
2807 $recursionResult = self::fixPermissions($path . '/' . $file, TRUE);
2808 }
2809 if (isset($recursionResult) && !$recursionResult) {
2810 $result = FALSE;
2811 }
2812 }
2813 }
2814 closedir($handle);
2815 }
2816 }
2817 } else {
2818 $result = TRUE;
2819 }
2820 return $result;
2821 }
2822
2823 /**
2824 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2825 * Accepts an additional subdirectory in the file path!
2826 *
2827 * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2828 * @param string Content string to write
2829 * @return string Returns NULL on success, otherwise an error string telling about the problem.
2830 */
2831 public static function writeFileToTypo3tempDir($filepath, $content) {
2832
2833 // Parse filepath into directory and basename:
2834 $fI = pathinfo($filepath);
2835 $fI['dirname'] .= '/';
2836
2837 // Check parts:
2838 if (self::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename']) < 60) {
2839 if (defined('PATH_site')) {
2840 $dirName = PATH_site . 'typo3temp/'; // Setting main temporary directory name (standard)
2841 if (@is_dir($dirName)) {
2842 if (self::isFirstPartOfStr($fI['dirname'], $dirName)) {
2843
2844 // Checking if the "subdir" is found:
2845 $subdir = substr($fI['dirname'], strlen($dirName));
2846 if ($subdir) {
2847 if (preg_match('/^[[:alnum:]_]+\/$/', $subdir) || preg_match('/^[[:alnum:]_]+\/[[:alnum:]_]+\/$/', $subdir)) {
2848 $dirName .= $subdir;
2849 if (!@is_dir($dirName)) {
2850 self::mkdir_deep(PATH_site . 'typo3temp/', $subdir);
2851 }
2852 } else {
2853 return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2854 }
2855 }
2856 // Checking dir-name again (sub-dir might have been created):
2857 if (@is_dir($dirName)) {
2858 if ($filepath == $dirName . $fI['basename']) {
2859 self::writeFile($filepath, $content);
2860 if (!@is_file($filepath)) {
2861 return 'File not written to disk! Write permission error in filesystem?';
2862 }
2863 } else {
2864 return 'Calculated filelocation didn\'t match input $filepath!';
2865 }
2866 } else {
2867 return '"' . $dirName . '" is not a directory!';
2868 }
2869 } else {
2870 return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
2871 }
2872 } else {
2873 return 'PATH_site + "typo3temp/" was not a directory!';
2874 }
2875 } else {
2876 return 'PATH_site constant was NOT defined!';
2877 }
2878 } else {
2879 return 'Input filepath "' . $filepath . '" was generally invalid!';
2880 }
2881 }
2882
2883 /**
2884 * Wrapper function for mkdir.
2885 * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']
2886 * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
2887 *
2888 * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2889 * @return boolean TRUE if @mkdir went well!
2890 */
2891 public static function mkdir($newFolder) {
2892 $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2893 if ($result) {
2894 self::fixPermissions($newFolder);
2895 }
2896 return $result;
2897 }
2898
2899 /**
2900 * Creates a directory - including parent directories if necessary and
2901 * sets permissions on newly created directories.
2902 *
2903 * @param string $directory Target directory to create. Must a have trailing slash
2904 * if second parameter is given!
2905 * Example: "/root/typo3site/typo3temp/foo/"
2906 * @param string $deepDirectory Directory to create. This second parameter
2907 * is kept for backwards compatibility since 4.6 where this method
2908 * was split into a base directory and a deep directory to be created.
2909 * Example: "xx/yy/" which creates "/root/typo3site/xx/yy/" if $directory is "/root/typo3site/"
2910 * @return void
2911 * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
2912 * @throws \RuntimeException If directory could not be created
2913 */
2914 public static function mkdir_deep($directory, $deepDirectory = '') {
2915 if (!is_string($directory)) {
2916 throw new \InvalidArgumentException(
2917 'The specified directory is of type "' . gettype($directory) . '" but a string is expected.',
2918 1303662955
2919 );
2920 }
2921 if (!is_string($deepDirectory)) {
2922 throw new \InvalidArgumentException(
2923 'The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.',
2924 1303662956
2925 );
2926 }
2927
2928 $fullPath = $directory . $deepDirectory;
2929 if (!is_dir($fullPath) && strlen($fullPath) > 0) {
2930 @mkdir(
2931 $fullPath,
2932 octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']),
2933 TRUE
2934 );
2935 if (!is_dir($fullPath)) {
2936 throw new \RuntimeException(
2937 'Could not create directory!',
2938 1170251400
2939 );
2940 }
2941 }
2942 }
2943
2944 /**
2945 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2946 *
2947 * @param string Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2948 * @param boolean Allow deletion of non-empty directories
2949 * @return boolean TRUE if @rmdir went well!
2950 */
2951 public static function rmdir($path, $removeNonEmpty = FALSE) {
2952 $OK = FALSE;
2953 $path = preg_replace('|/$|', '', $path); // Remove trailing slash
2954
2955 if (file_exists($path)) {
2956 $OK = TRUE;
2957
2958 if (is_dir($path)) {
2959 if ($removeNonEmpty == TRUE && $handle = opendir($path)) {
2960 while ($OK && FALSE !== ($file = readdir($handle))) {
2961 if ($file == '.' || $file == '..') {
2962 continue;
2963 }
2964 $OK = self::rmdir($path . '/' . $file, $removeNonEmpty);
2965 }
2966 closedir($handle);
2967 }
2968 if ($OK) {
2969 $OK = rmdir($path);
2970 }
2971
2972 } else { // If $dirname is a file, simply remove it
2973 $OK = unlink($path);
2974 }
2975
2976 clearstatcache();
2977 }
2978
2979 return $OK;
2980 }
2981
2982 /**
2983 * Returns an array with the names of folders in a specific path
2984 * Will return 'error' (string) if there were an error with reading directory content.
2985 * Usage: 11
2986 *
2987 * @param string Path to list directories from
2988 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2989 */
2990 public static function get_dirs($path) {
2991 if ($path) {
2992 if (is_dir($path)) {
2993 $dir = scandir($path);
2994 $dirs = array();
2995 foreach ($dir as $entry) {
2996 if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
2997 $dirs[] = $entry;
2998 }
2999 }
3000 } else {
3001 $dirs = 'error';
3002 }
3003 }
3004 return $dirs;
3005 }
3006
3007 /**
3008 * Returns an array with the names of files in a specific path
3009 * Usage: 18
3010 *
3011 * @param string $path: Is the path to the file
3012 * @param string $extensionList is the comma list of extensions to read only (blank = all)
3013 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
3014 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
3015 * @param string A comma seperated list of filenames to exclude, no wildcards
3016 * @return array Array of the files found
3017 */
3018 public static function getFilesInDir($path, $extensionList = '', $prependPath = 0, $order = '', $excludePattern = '') {
3019
3020 // Initialize variabels:
3021 $filearray = array();
3022 $sortarray = array();
3023 $path = rtrim($path, '/');
3024
3025 // Find files+directories:
3026 if (@is_dir($path)) {
3027 $extensionList = strtolower($extensionList);
3028 $d = dir($path);
3029 if (is_object($d)) {
3030 while ($entry = $d->read()) {
3031 if (@is_file($path . '/' . $entry)) {
3032 $fI = pathinfo($entry);
3033 $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)
3034 if ((!strlen($extensionList) || self::inList($extensionList, strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^' . $excludePattern . '$/', $entry))) {
3035 $filearray[$key] = ($prependPath ? $path . '/' : '') . $entry;
3036 if ($order == 'mtime') {
3037 $sortarray[$key] = filemtime($path . '/' . $entry);
3038 }
3039 elseif ($order) {
3040 $sortarray[$key] = $entry;
3041 }
3042 }
3043 }
3044 }
3045 $d->close();
3046 } else {
3047 return 'error opening path: "' . $path . '"';
3048 }
3049 }
3050
3051 // Sort them:
3052 if ($order) {
3053 asort($sortarray);
3054 $newArr = array();
3055 foreach ($sortarray as $k => $v) {
3056 $newArr[$k] = $filearray[$k];
3057 }
3058 $filearray = $newArr;
3059 }
3060
3061 // Return result
3062 reset($filearray);
3063 return $filearray;
3064 }
3065
3066 /**
3067 * Recursively gather all files and folders of a path.
3068 * Usage: 5
3069 *
3070 * @param array $fileArr: Empty input array (will have files added to it)
3071 * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
3072 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
3073 * @param boolean $regDirs: If set, directories are also included in output.
3074 * @param integer $recursivityLevels: The number of levels to dig down...
3075 * @param string $excludePattern: regex pattern of files/directories to exclude
3076 * @return array An array with the found files/directories.
3077 */
3078 public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = 0, $recursivityLevels = 99, $excludePattern = '') {
3079 if ($regDirs) {
3080 $fileArr[] = $path;
3081 }
3082 $fileArr = array_merge($fileArr, self::getFilesInDir($path, $extList, 1, 1, $excludePattern));
3083
3084 $dirs = self::get_dirs($path);
3085 if (is_array($dirs) && $recursivityLevels > 0) {
3086 foreach ($dirs as $subdirs) {
3087 if ((string) $subdirs != '' && (!strlen($excludePattern) || !preg_match('/^' . $excludePattern . '$/', $subdirs))) {
3088 $fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
3089 }
3090 }
3091 }
3092 return $fileArr;
3093 }
3094
3095 /**
3096 * Removes the absolute part of all files/folders in fileArr
3097 * Usage: 2
3098 *
3099 * @param array $fileArr: The file array to remove the prefix from
3100 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
3101 * @return array The input $fileArr processed.
3102 */
3103 public static function removePrefixPathFromList(array $fileArr, $prefixToRemove) {
3104 foreach ($fileArr as $k => &$absFileRef) {
3105 if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
3106 $absFileRef = substr($absFileRef, strlen($prefixToRemove));
3107 } else {
3108 return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
3109 }
3110 }
3111 unset($absFileRef);
3112 return $fileArr;
3113 }
3114
3115 /**
3116 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
3117 * Usage: 2
3118 *
3119 * @param string File path to process
3120 * @return string
3121 */
3122 public static function fixWindowsFilePath($theFile) {
3123 return str_replace('//', '/', str_replace('\\', '/', $theFile));
3124 }
3125
3126 /**
3127 * Resolves "../" sections in the input path string.
3128 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
3129 * Usage: 2
3130 *
3131 * @param string File path in which "/../" is resolved
3132 * @return string
3133 */
3134 public static function resolveBackPath($pathStr) {
3135 $parts = explode('/', $pathStr);
3136 $output = array();
3137 $c = 0;
3138 foreach ($parts as $pV) {
3139 if ($pV == '..') {
3140 if ($c) {
3141 array_pop($output);
3142 $c--;
3143 } else {
3144 $output[] = $pV;
3145 }
3146 } else {
3147 $c++;
3148 $output[] = $pV;
3149 }
3150 }
3151 return implode('/', $output);
3152 }
3153
3154 /**
3155 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
3156 * - If already having a scheme, nothing is prepended
3157 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
3158 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
3159 * Usage: 30
3160 *
3161 * @param string URL / path to prepend full URL addressing to.
3162 * @return string
3163 */
3164 public static function locationHeaderUrl($path) {
3165 $uI = parse_url($path);
3166 if (substr($path, 0, 1) == '/') { // relative to HOST
3167 $path = self::getIndpEnv('TYPO3_REQUEST_HOST') . $path;
3168 } elseif (!$uI['scheme']) { // No scheme either
3169 $path = self::getIndpEnv('TYPO3_REQUEST_DIR') . $path;
3170 }
3171 return $path;
3172 }
3173
3174 /**
3175 * Returns the maximum upload size for a file that is allowed. Measured in KB.
3176 * This might be handy to find out the real upload limit that is possible for this
3177 * TYPO3 installation. The first parameter can be used to set something that overrides
3178 * the maxFileSize, usually for the TCA values.
3179 *
3180 * @param integer $localLimit: the number of Kilobytes (!) that should be used as
3181 * the initial Limit, otherwise $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize'] will be used
3182 * @return integer the maximum size of uploads that are allowed (measuered in kilobytes)
3183 */
3184 public static function getMaxUploadFileSize($localLimit = 0) {
3185 // don't allow more than the global max file size at all
3186 $t3Limit = (intval($localLimit > 0 ? $localLimit : $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize']));
3187 // as TYPO3 is handling the file size in KB, multiply by 1024 to get bytes
3188 $t3Limit = $t3Limit * 1024;
3189
3190 // check for PHP restrictions of the maximum size of one of the $_FILES
3191 $phpUploadLimit = self::getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
3192 // check for PHP restrictions of the maximum $_POST size
3193 $phpPostLimit = self::getBytesFromSizeMeasurement(ini_get('post_max_size'));
3194 // if the total amount of post data is smaller (!) than the upload_max_filesize directive,
3195 // then this is the real limit in PHP
3196 $phpUploadLimit = ($phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit);
3197
3198 // is the allowed PHP limit (upload_max_filesize) lower than the TYPO3 limit?, also: revert back to KB
3199 return floor($phpUploadLimit < $t3Limit ? $phpUploadLimit : $t3Limit) / 1024;
3200 }
3201
3202 /**
3203 * Gets the bytes value from a measurement string like "100k".
3204 *
3205 * @param string $measurement: The measurement (e.g. "100k")
3206 * @return integer The bytes value (e.g. 102400)
3207 */
3208 public static function getBytesFromSizeMeasurement($measurement) {
3209 if (stripos($measurement, 'G')) {
3210 $bytes = doubleval($measurement) * 1024 * 1024 * 1024;
3211 } else {
3212 if (stripos($measurement, 'M')) {
3213 $bytes = doubleval($measurement) * 1024 * 1024;
3214 } else {
3215 if (stripos($measurement, 'K')) {
3216 $bytes = doubleval($measurement) * 1024;
3217 } else {
3218 $bytes = doubleval($measurement);
3219 }
3220 }
3221 }
3222 return $bytes;
3223 }
3224
3225 /**
3226 * Retrieves the maximum path length that is valid in the current environment.
3227 *
3228 * @return integer The maximum available path length
3229 * @author Ingo Renner <ingo@typo3.org>
3230 */
3231 public static function getMaximumPathLength() {