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