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