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