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