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