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