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