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