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