2 /***************************************************************
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
29 define('TAB', chr(9));
31 define('LF', chr(10));
33 define('CR', chr(13));
34 // a CR-LF combination
35 define('CRLF', CR
. LF
);
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!
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()'
49 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
53 final class t3lib_div
{
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;
63 * Singleton instances returned by makeInstance, using the class names as
66 * @var array<t3lib_Singleton>
68 protected static $singletonInstances = array();
71 * Instances returned by makeInstance, using the class names as array keys
73 * @var array<array><object>
75 protected static $nonSingletonInstances = array();
78 * Register for makeInstance with given class name and final class names to reduce number of class_exists() calls
80 * @var array Given class name => final class name
82 protected static $finalClassNameRegister = array();
84 /*************************
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.
95 *************************/
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!
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.
106 public static function _GP($var) {
110 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
112 if (is_array($value)) {
113 self
::stripSlashesOnArray($value);
115 $value = stripslashes($value);
122 * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
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.
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();
131 $mergedParameters = self
::array_merge_recursive_overrule($getParameter, $postParameter);
132 self
::stripSlashesOnArray($mergedParameters);
134 return $mergedParameters;
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!
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()
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);
151 $value = stripslashes($value);
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!
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!*
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);
171 $value = stripslashes($value);
178 * Writes input value to $_GET.
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).
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))
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);
200 $inputGet = addslashes($inputGet);
204 if (strpos($key, '|') !== FALSE) {
205 $pieces = explode('|', $key);
208 foreach ($pieces as $piece) {
209 $pointer =& $pointer[$piece];
211 $pointer = $inputGet;
212 $mergedGet = self
::array_merge_recursive_overrule(
217 $GLOBALS['HTTP_GET_VARS'] = $mergedGet;
219 $_GET[$key] = $inputGet;
220 $GLOBALS['HTTP_GET_VARS'][$key] = $inputGet;
222 } elseif (is_array($inputGet)) {
224 $GLOBALS['HTTP_GET_VARS'] = $inputGet;
229 * Wrapper for the RemoveXSS function.
230 * Removes potential XSS code from an input string.
232 * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
234 * @param string $string Input string
235 * @return string Input string with potential XSS code removed
237 public static function removeXSS($string) {
238 require_once(PATH_typo3
. 'contrib/RemoveXSS/RemoveXSS.php');
239 $string = RemoveXSS
::process($string);
244 /*************************
248 *************************/
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)
255 * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
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
262 * $theFile is expected to be a valid GIF-file!
263 * The function returns a code for the operation.
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.
269 public static function gif_compress($theFile, $type) {
270 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
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);
284 if (@is_file
($theFile)) {
285 self
::fixPermissions($theFile);
287 } elseif (($type == 'GD' ||
!$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
288 $tempImage = imageCreateFromGif($theFile);
289 imageGif($tempImage, $theFile);
290 imageDestroy($tempImage);
292 if (@is_file
($theFile)) {
293 self
::fixPermissions($theFile);
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.
304 * @param string $theFile the filename with path
305 * @return string new filename
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);
317 if (@is_file
($newFile)) {
318 self
::fixPermissions($newFile);
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!!
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.
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
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));
338 ((string) $ext == '.png' && $output_png) ||
339 ((string) $ext == '.gif' && !$output_png)
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);
355 /*************************
359 *************************/
362 * Truncates a string with appended/prepended "..." and takes current character set into consideration.
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
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);
376 // this case should not happen
377 $csConvObj = self
::makeInstance('t3lib_cs');
378 return $csConvObj->crop('iso-8859-1', $string, $chars, $appendString);
383 * Breaks up a single line of text for emails
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::breakLinesForEmail()
391 public static function breakLinesForEmail($str, $newlineChar = LF
, $lineWidth = 76) {
392 self
::logDeprecatedFunction();
393 return t3lib_utility_Mail
::breakLinesForEmail($str, $newlineChar, $lineWidth);
397 * Match IP number with list of numbers with wildcard
398 * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
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
404 public static function cmpIP($baseIP, $list) {
408 } elseif ($list === '*') {
411 if (strpos($baseIP, ':') !== FALSE && self
::validIPv6($baseIP)) {
412 return self
::cmpIPv6($baseIP, $list);
414 return self
::cmpIPv4($baseIP, $list);
419 * Match IPv4 number with list of numbers with wildcard
421 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
422 * @param string $list is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168), could also contain IPv6 addresses
423 * @return boolean TRUE if an IP-mask from $list matches $baseIP
425 public static function cmpIPv4($baseIP, $list) {
426 $IPpartsReq = explode('.', $baseIP);
427 if (count($IPpartsReq) == 4) {
428 $values = self
::trimExplode(',', $list, 1);
430 foreach ($values as $test) {
431 $testList = explode('/', $test);
432 if (count($testList) == 2) {
433 list($test, $mask) = $testList;
440 $lnet = ip2long($test);
441 $lip = ip2long($baseIP);
442 $binnet = str_pad(decbin($lnet), 32, '0', STR_PAD_LEFT
);
443 $firstpart = substr($binnet, 0, $mask);
444 $binip = str_pad(decbin($lip), 32, '0', STR_PAD_LEFT
);
445 $firstip = substr($binip, 0, $mask);
446 $yes = (strcmp($firstpart, $firstip) == 0);
449 $IPparts = explode('.', $test);
451 foreach ($IPparts as $index => $val) {
453 if (($val !== '*') && ($IPpartsReq[$index] !== $val)) {
467 * Match IPv6 address with a list of IPv6 prefixes
469 * @param string $baseIP is the current remote IP address for instance
470 * @param string $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
471 * @return boolean TRUE if an baseIP matches any prefix
473 public static function cmpIPv6($baseIP, $list) {
474 $success = FALSE; // Policy default: Deny connection
475 $baseIP = self
::normalizeIPv6($baseIP);
477 $values = self
::trimExplode(',', $list, 1);
478 foreach ($values as $test) {
479 $testList = explode('/', $test);
480 if (count($testList) == 2) {
481 list($test, $mask) = $testList;
486 if (self
::validIPv6($test)) {
487 $test = self
::normalizeIPv6($test);
488 $maskInt = intval($mask) ?
intval($mask) : 128;
489 if ($mask === '0') { // special case; /0 is an allowed mask - equals a wildcard
491 } elseif ($maskInt == 128) {
492 $success = ($test === $baseIP);
494 $testBin = self
::IPv6Hex2Bin($test);
495 $baseIPBin = self
::IPv6Hex2Bin($baseIP);
498 // modulo is 0 if this is a 8-bit-boundary
499 $maskIntModulo = $maskInt %
8;
500 $numFullCharactersUntilBoundary = intval($maskInt / 8);
502 if (substr($testBin, 0, $numFullCharactersUntilBoundary) !== substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) {
504 } elseif ($maskIntModulo > 0) {
505 // if not an 8-bit-boundary, check bits of last character
506 $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT
);
507 $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT
);
508 if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) {
522 * Transform a regular IPv6 address from hex-representation into binary
524 * @param string $hex IPv6 address in hex-presentation
525 * @return string Binary representation (16 characters, 128 characters)
528 public static function IPv6Hex2Bin($hex) {
529 // use PHP-function if PHP was compiled with IPv6-support
530 if (defined('AF_INET6')) {
531 $bin = inet_pton($hex);
533 $hex = self
::normalizeIPv6($hex);
534 $hex = str_replace(':', '', $hex); // Replace colon to nothing
535 $bin = pack("H*" , $hex);
541 * Transform an IPv6 address from binary to hex-representation
543 * @param string $bin IPv6 address in hex-presentation
544 * @return string Binary representation (16 characters, 128 characters)
547 public static function IPv6Bin2Hex($bin) {
548 // use PHP-function if PHP was compiled with IPv6-support
549 if (defined('AF_INET6')) {
550 $hex = inet_ntop($bin);
552 $hex = unpack("H*" , $bin);
553 $hex = chunk_split($hex[1], 4, ':');
554 // strip last colon (from chunk_split)
555 $hex = substr($hex, 0, -1);
556 // IPv6 is now in normalized form
557 // compress it for easier handling and to match result from inet_ntop()
558 $hex = self
::compressIPv6($hex);
565 * Normalize an IPv6 address to full length
567 * @param string $address Given IPv6 address
568 * @return string Normalized address
569 * @see compressIPv6()
571 public static function normalizeIPv6($address) {
572 $normalizedAddress = '';
573 $stageOneAddress = '';
575 // according to RFC lowercase-representation is recommended
576 $address = strtolower($address);
578 // normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000)
579 if (strlen($address) == 39) {
580 // already in full expanded form
584 $chunks = explode('::', $address); // Count 2 if if address has hidden zero blocks
585 if (count($chunks) == 2) {
586 $chunksLeft = explode(':', $chunks[0]);
587 $chunksRight = explode(':', $chunks[1]);
588 $left = count($chunksLeft);
589 $right = count($chunksRight);
591 // Special case: leading zero-only blocks count to 1, should be 0
592 if ($left == 1 && strlen($chunksLeft[0]) == 0) {
596 $hiddenBlocks = 8 - ($left +
$right);
599 while ($h < $hiddenBlocks) {
600 $hiddenPart .= '0000:';
605 $stageOneAddress = $hiddenPart . $chunks[1];
607 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
610 $stageOneAddress = $address;
613 // normalize the blocks:
614 $blocks = explode(':', $stageOneAddress);
616 foreach ($blocks as $block) {
619 $hiddenZeros = 4 - strlen($block);
620 while ($i < $hiddenZeros) {
624 $normalizedAddress .= $tmpBlock . $block;
625 if ($divCounter < 7) {
626 $normalizedAddress .= ':';
630 return $normalizedAddress;
635 * Compress an IPv6 address to the shortest notation
637 * @param string $address Given IPv6 address
638 * @return string Compressed address
639 * @see normalizeIPv6()
641 public static function compressIPv6($address) {
642 // use PHP-function if PHP was compiled with IPv6-support
643 if (defined('AF_INET6')) {
644 $bin = inet_pton($address);
645 $address = inet_ntop($bin);
647 $address = self
::normalizeIPv6($address);
649 // append one colon for easier handling
650 // will be removed later
653 // according to IPv6-notation the longest match
654 // of a package of '0000:' may be replaced with ':'
655 // (resulting in something like '1234::abcd')
656 for ($counter = 8; $counter > 1; $counter--) {
657 $search = str_repeat('0000:', $counter);
658 if (($pos = strpos($address, $search)) !== FALSE) {
659 $address = substr($address, 0, $pos) . ':' . substr($address, $pos +
($counter*5));
664 // up to 3 zeros in the first part may be removed
665 $address = preg_replace('/^0{1,3}/', '', $address);
666 // up to 3 zeros at the beginning of other parts may be removed
667 $address = preg_replace('/:0{1,3}/', ':', $address);
669 // strip last colon (from chunk_split)
670 $address = substr($address, 0, -1);
676 * Validate a given IP address.
678 * Possible format are IPv4 and IPv6.
680 * @param string $ip IP address to be tested
681 * @return boolean TRUE if $ip is either of IPv4 or IPv6 format.
683 public static function validIP($ip) {
684 return (filter_var($ip, FILTER_VALIDATE_IP
) !== FALSE);
688 * Validate a given IP address to the IPv4 address format.
690 * Example for possible format: 10.0.45.99
692 * @param string $ip IP address to be tested
693 * @return boolean TRUE if $ip is of IPv4 format.
695 public static function validIPv4($ip) {
696 return (filter_var($ip, FILTER_VALIDATE_IP
, FILTER_FLAG_IPV4
) !== FALSE);
700 * Validate a given IP address to the IPv6 address format.
702 * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
704 * @param string $ip IP address to be tested
705 * @return boolean TRUE if $ip is of IPv6 format.
707 public static function validIPv6($ip) {
708 return (filter_var($ip, FILTER_VALIDATE_IP
, FILTER_FLAG_IPV6
) !== FALSE);
712 * Match fully qualified domain name with list of strings with wildcard
714 * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)
715 * @param string $list A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong)
716 * @return boolean TRUE if a domain name mask from $list matches $baseIP
718 public static function cmpFQDN($baseHost, $list) {
719 $baseHost = trim($baseHost);
720 if (empty($baseHost)) {
723 if (self
::validIPv4($baseHost) || self
::validIPv6($baseHost)) {
725 // note: this is reverse-lookup and can be randomly set as soon as somebody is able to set
726 // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR)
727 $baseHostName = gethostbyaddr($baseHost);
728 if ($baseHostName === $baseHost) {
729 // unable to resolve hostname
733 $baseHostName = $baseHost;
735 $baseHostNameParts = explode('.', $baseHostName);
737 $values = self
::trimExplode(',', $list, 1);
739 foreach ($values as $test) {
740 $hostNameParts = explode('.', $test);
742 // to match hostNameParts can only be shorter (in case of wildcards) or equal
743 if (count($hostNameParts) > count($baseHostNameParts)) {
748 foreach ($hostNameParts as $index => $val) {
751 // wildcard valid for one or more hostname-parts
753 $wildcardStart = $index +
1;
754 // wildcard as last/only part always matches, otherwise perform recursive checks
755 if ($wildcardStart < count($hostNameParts)) {
756 $wildcardMatched = FALSE;
757 $tempHostName = implode('.', array_slice($hostNameParts, $index +
1));
758 while (($wildcardStart < count($baseHostNameParts)) && (!$wildcardMatched)) {
759 $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart));
760 $wildcardMatched = self
::cmpFQDN($tempBaseHostName, $tempHostName);
763 if ($wildcardMatched) {
764 // match found by recursive compare
770 } elseif ($baseHostNameParts[$index] !== $val) {
771 // in case of no match
783 * Checks if a given URL matches the host that currently handles this HTTP request.
784 * Scheme, hostname and (optional) port of the given URL are compared.
786 * @param string $url: URL to compare with the TYPO3 request host
787 * @return boolean Whether the URL matches the TYPO3 request host
789 public static function isOnCurrentHost($url) {
790 return (stripos($url . '/', self
::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0);
794 * Check for item in list
795 * Check if an item exists in a comma-separated list of items.
797 * @param string $list comma-separated list of items (string)
798 * @param string $item item to check for
799 * @return boolean TRUE if $item is in $list
801 public static function inList($list, $item) {
802 return (strpos(',' . $list . ',', ',' . $item . ',') !== FALSE ?
TRUE : FALSE);
806 * Removes an item from a comma-separated list of items.
808 * @param string $element element to remove
809 * @param string $list comma-separated list of items (string)
810 * @return string new comma-separated list of items
812 public static function rmFromList($element, $list) {
813 $items = explode(',', $list);
814 foreach ($items as $k => $v) {
815 if ($v == $element) {
819 return implode(',', $items);
823 * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
824 * Ranges are limited to 1000 values per range.
826 * @param string $list comma-separated list of integers with ranges (string)
827 * @return string new comma-separated list of items
829 public static function expandList($list) {
830 $items = explode(',', $list);
832 foreach ($items as $item) {
833 $range = explode('-', $item);
834 if (isset($range[1])) {
835 $runAwayBrake = 1000;
836 for ($n = $range[0]; $n <= $range[1]; $n++
) {
840 if ($runAwayBrake <= 0) {
848 return implode(',', $list);
852 * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'FALSE' then the $zeroValue is applied.
854 * @param integer $theInt Input value
855 * @param integer $min Lower limit
856 * @param integer $max Higher limit
857 * @param integer $zeroValue Default value if input is FALSE.
858 * @return integer The input value forced into the boundaries of $min and $max
859 * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - Use t3lib_utility_Math::forceIntegerInRange() instead
861 public static function intInRange($theInt, $min, $max = 2000000000, $zeroValue = 0) {
862 self
::logDeprecatedFunction();
863 return t3lib_utility_Math
::forceIntegerInRange($theInt, $min, $max, $zeroValue);
867 * Returns the $integer if greater than zero, otherwise returns zero.
869 * @param integer $theInt Integer string to process
871 * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - Use t3lib_utility_Math::convertToPositiveInteger() instead
873 public static function intval_positive($theInt) {
874 self
::logDeprecatedFunction();
875 return t3lib_utility_Math
::convertToPositiveInteger($theInt);
879 * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
881 * @param string $verNumberStr Version number on format x.x.x
882 * @return integer Integer version of version number (where each part can count to 999)
883 * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.9 - Use t3lib_utility_VersionNumber::convertVersionNumberToInteger() instead
885 public static function int_from_ver($verNumberStr) {
886 // Deprecation log is activated only for TYPO3 4.7 and above
887 if (t3lib_utility_VersionNumber
::convertVersionNumberToInteger(TYPO3_version
) >= 4007000) {
888 self
::logDeprecatedFunction();
890 return t3lib_utility_VersionNumber
::convertVersionNumberToInteger($verNumberStr);
894 * Returns TRUE if the current TYPO3 version (or compatibility version) is compatible to the input version
895 * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
897 * @param string $verNumberStr Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
898 * @return boolean Returns TRUE if this setup is compatible with the provided version number
899 * @todo Still needs a function to convert versions to branches
901 public static function compat_version($verNumberStr) {
902 $currVersionStr = $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] ?
$GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] : TYPO3_branch
;
904 if (t3lib_utility_VersionNumber
::convertVersionNumberToInteger($currVersionStr) < t3lib_utility_VersionNumber
::convertVersionNumberToInteger($verNumberStr)) {
912 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
914 * @param string $str String to md5-hash
915 * @return integer Returns 28bit integer-hash
917 public static function md5int($str) {
918 return hexdec(substr(md5($str), 0, 7));
922 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
924 * @param string $input Input string to be md5-hashed
925 * @param integer $len The string-length of the output
926 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
928 public static function shortMD5($input, $len = 10) {
929 return substr(md5($input), 0, $len);
933 * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
935 * @param string $input Input string to create HMAC from
936 * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
938 public static function hmac($input) {
939 $hashAlgorithm = 'sha1';
943 if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
944 $hmac = hash_hmac($hashAlgorithm, $input, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']);
947 $opad = str_repeat(chr(0x5C), $hashBlocksize);
949 $ipad = str_repeat(chr(0x36), $hashBlocksize);
950 if (strlen($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) > $hashBlocksize) {
951 // keys longer than block size are shorten
952 $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])), $hashBlocksize, chr(0x00));
954 // keys shorter than block size are zero-padded
955 $key = str_pad($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], $hashBlocksize, chr(0x00));
957 $hmac = call_user_func($hashAlgorithm, ($key ^
$opad) . pack('H*', call_user_func($hashAlgorithm, ($key ^
$ipad) . $input)));
963 * Takes comma-separated lists and arrays and removes all duplicates
964 * If a value in the list is trim(empty), the value is ignored.
966 * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
967 * @param mixed $secondParameter: Dummy field, which if set will show a warning!
968 * @return string Returns the list without any duplicates of values, space around values are trimmed
970 public static function uniqueList($in_list, $secondParameter = NULL) {
971 if (is_array($in_list)) {
972 throw new InvalidArgumentException(
973 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!',
977 if (isset($secondParameter)) {
978 throw new InvalidArgumentException(
979 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!',
984 return implode(',', array_unique(self
::trimExplode(',', $in_list, 1)));
988 * Splits a reference to a file in 5 parts
990 * @param string $fileref Filename/filepath to be analysed
991 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
993 public static function split_fileref($fileref) {
995 if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
996 $info['path'] = $reg[1];
997 $info['file'] = $reg[2];
1000 $info['file'] = $fileref;
1004 if (!is_dir($fileref) && preg_match('/(.*)\.([^\.]*$)/', $info['file'], $reg)) {
1005 $info['filebody'] = $reg[1];
1006 $info['fileext'] = strtolower($reg[2]);
1007 $info['realFileext'] = $reg[2];
1009 $info['filebody'] = $info['file'];
1010 $info['fileext'] = '';
1017 * Returns the directory part of a path without trailing slash
1018 * If there is no dir-part, then an empty string is returned.
1021 * '/dir1/dir2/script.php' => '/dir1/dir2'
1022 * '/dir1/' => '/dir1'
1023 * 'dir1/script.php' => 'dir1'
1024 * 'd/script.php' => 'd'
1025 * '/script.php' => ''
1028 * @param string $path Directory name / path
1029 * @return string Processed input value. See function description.
1031 public static function dirname($path) {
1032 $p = self
::revExplode('/', $path, 2);
1033 return count($p) == 2 ?
$p[0] : '';
1037 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
1039 * @param string $color A hexadecimal color code, #xxxxxx
1040 * @param integer $R Offset value 0-255
1041 * @param integer $G Offset value 0-255
1042 * @param integer $B Offset value 0-255
1043 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1044 * @see modifyHTMLColorAll()
1046 public static function modifyHTMLColor($color, $R, $G, $B) {
1047 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
1048 $nR = t3lib_utility_Math
::forceIntegerInRange(hexdec(substr($color, 1, 2)) +
$R, 0, 255);
1049 $nG = t3lib_utility_Math
::forceIntegerInRange(hexdec(substr($color, 3, 2)) +
$G, 0, 255);
1050 $nB = t3lib_utility_Math
::forceIntegerInRange(hexdec(substr($color, 5, 2)) +
$B, 0, 255);
1052 substr('0' . dechex($nR), -2) .
1053 substr('0' . dechex($nG), -2) .
1054 substr('0' . dechex($nB), -2);
1058 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
1060 * @param string $color A hexadecimal color code, #xxxxxx
1061 * @param integer $all Offset value 0-255 for all three channels.
1062 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1063 * @see modifyHTMLColor()
1065 public static function modifyHTMLColorAll($color, $all) {
1066 return self
::modifyHTMLColor($color, $all, $all, $all);
1070 * Tests if the input can be interpreted as integer.
1072 * @param mixed $var Any input variable to test
1073 * @return boolean Returns TRUE if string is an integer
1074 * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - Use t3lib_utility_Math::canBeInterpretedAsInteger() instead
1076 public static function testInt($var) {
1077 self
::logDeprecatedFunction();
1079 return t3lib_utility_Math
::canBeInterpretedAsInteger($var);
1083 * Returns TRUE if the first part of $str matches the string $partStr
1085 * @param string $str Full string to check
1086 * @param string $partStr Reference string which must be found as the "first part" of the full string
1087 * @return boolean TRUE if $partStr was found to be equal to the first part of $str
1089 public static function isFirstPartOfStr($str, $partStr) {
1090 return $partStr != '' && strpos((string) $str, (string) $partStr, 0) === 0;
1094 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
1096 * @param integer $sizeInBytes Number of bytes to format.
1097 * @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)
1098 * @return string Formatted representation of the byte number, for output.
1100 public static function formatSize($sizeInBytes, $labels = '') {
1103 if (strlen($labels) == 0) {
1104 $labels = ' | K| M| G';
1106 $labels = str_replace('"', '', $labels);
1108 $labelArr = explode('|', $labels);
1111 if ($sizeInBytes > 900) {
1112 if ($sizeInBytes > 900000000) { // GB
1113 $val = $sizeInBytes / (1024 * 1024 * 1024);
1114 return number_format($val, (($val < 20) ?
1 : 0), '.', '') . $labelArr[3];
1116 elseif ($sizeInBytes > 900000) { // MB
1117 $val = $sizeInBytes / (1024 * 1024);
1118 return number_format($val, (($val < 20) ?
1 : 0), '.', '') . $labelArr[2];
1120 $val = $sizeInBytes / (1024);
1121 return number_format($val, (($val < 20) ?
1 : 0), '.', '') . $labelArr[1];
1124 return $sizeInBytes . $labelArr[0];
1129 * Returns microtime input to milliseconds
1131 * @param string $microtime Microtime
1132 * @return integer Microtime input string converted to an integer (milliseconds)
1134 public static function convertMicrotime($microtime) {
1135 $parts = explode(' ', $microtime);
1136 return round(($parts[0] +
$parts[1]) * 1000);
1140 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
1142 * @param string $string Input string, eg "123 + 456 / 789 - 4"
1143 * @param string $operators Operators to split by, typically "/+-*"
1144 * @return array Array with operators and operands separated.
1145 * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
1147 public static function splitCalc($string, $operators) {
1151 $valueLen = strcspn($string, $operators);
1152 $value = substr($string, 0, $valueLen);
1153 $res[] = Array($sign, trim($value));
1154 $sign = substr($string, $valueLen, 1);
1155 $string = substr($string, $valueLen +
1);
1162 * Calculates the input by +,-,*,/,%,^ with priority to + and -
1164 * @param string $string Input string, eg "123 + 456 / 789 - 4"
1165 * @return integer Calculated value. Or error string.
1166 * @see calcParenthesis()
1167 * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - Use t3lib_utility_Math::calculateWithPriorityToAdditionAndSubtraction() instead
1169 public static function calcPriority($string) {
1170 self
::logDeprecatedFunction();
1172 return t3lib_utility_Math
::calculateWithPriorityToAdditionAndSubtraction($string);
1176 * Calculates the input with parenthesis levels
1178 * @param string $string Input string, eg "(123 + 456) / 789 - 4"
1179 * @return integer Calculated value. Or error string.
1180 * @see calcPriority(), tslib_cObj::stdWrap()
1181 * @deprecated since TYPO3 4.6, will be removed in TYPO3 4.8 - Use t3lib_utility_Math::calculateWithParentheses() instead
1183 public static function calcParenthesis($string) {
1184 self
::logDeprecatedFunction();
1186 return t3lib_utility_Math
::calculateWithParentheses($string);
1190 * Inverse version of htmlspecialchars()
1192 * @param string $value Value where >, <, " and & should be converted to regular chars.
1193 * @return string Converted result.
1195 public static function htmlspecialchars_decode($value) {
1196 $value = str_replace('>', '>', $value);
1197 $value = str_replace('<', '<', $value);
1198 $value = str_replace('"', '"', $value);
1199 $value = str_replace('&', '&', $value);
1204 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1206 * @param string $str String which contains eg. "&amp;" which should stay "&". Or "&#1234;" to "Ӓ". Or "&#x1b;" to ""
1207 * @return string Converted result.
1209 public static function deHSCentities($str) {
1210 return preg_replace('/&([#[:alnum:]]*;)/', '&\1', $str);
1214 * This function is used to escape any ' -characters when transferring text to JavaScript!
1216 * @param string $string String to escape
1217 * @param boolean $extended If set, also backslashes are escaped.
1218 * @param string $char The character to escape, default is ' (single-quote)
1219 * @return string Processed input string
1221 public static function slashJS($string, $extended = FALSE, $char = "'") {
1223 $string = str_replace("\\", "\\\\", $string);
1225 return str_replace($char, "\\" . $char, $string);
1229 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1230 * Useful when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1232 * @param string $str String to raw-url-encode with spaces preserved
1233 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1235 public static function rawUrlEncodeJS($str) {
1236 return str_replace('%20', ' ', rawurlencode($str));
1240 * rawurlencode which preserves "/" chars
1241 * Useful when file paths should keep the "/" chars, but have all other special chars encoded.
1243 * @param string $str Input string
1244 * @return string Output string
1246 public static function rawUrlEncodeFP($str) {
1247 return str_replace('%2F', '/', rawurlencode($str));
1251 * Checking syntax of input email address
1253 * @param string $email Input string to evaluate
1254 * @return boolean Returns TRUE if the $email address (input string) is valid
1256 public static function validEmail($email) {
1257 // enforce maximum length to prevent libpcre recursion crash bug #52929 in PHP
1258 // fixed in PHP 5.3.4; length restriction per SMTP RFC 2821
1259 if (strlen($email) > 320) {
1262 return (filter_var($email, FILTER_VALIDATE_EMAIL
) !== FALSE);
1266 * Checks if current e-mail sending method does not accept recipient/sender name
1267 * in a call to PHP mail() function. Windows version of mail() and mini_sendmail
1268 * program are known not to process such input correctly and they cause SMTP
1269 * errors. This function will return TRUE if current mail sending method has
1270 * problem with recipient name in recipient/sender argument for mail().
1272 * TODO: 4.3 should have additional configuration variable, which is combined
1273 * by || with the rest in this function.
1275 * @return boolean TRUE if mail() does not accept recipient name
1277 public static function isBrokenEmailEnvironment() {
1278 return TYPO3_OS
== 'WIN' ||
(FALSE !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
1282 * Changes from/to arguments for mail() function to work in any environment.
1284 * @param string $address Address to adjust
1285 * @return string Adjusted address
1286 * @see t3lib_::isBrokenEmailEnvironment()
1288 public static function normalizeMailAddress($address) {
1289 if (self
::isBrokenEmailEnvironment() && FALSE !== ($pos1 = strrpos($address, '<'))) {
1290 $pos2 = strpos($address, '>', $pos1);
1291 $address = substr($address, $pos1 +
1, ($pos2 ?
$pos2 : strlen($address)) - $pos1 - 1);
1297 * Formats a string for output between <textarea>-tags
1298 * All content outputted in a textarea form should be passed through this function
1299 * 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!
1301 * @param string $content Input string to be formatted.
1302 * @return string Formatted for <textarea>-tags
1304 public static function formatForTextarea($content) {
1305 return LF
. htmlspecialchars($content);
1309 * Converts string to uppercase
1310 * The function converts all Latin characters (a-z, but no accents, etc) to
1311 * uppercase. It is safe for all supported character sets (incl. utf-8).
1312 * Unlike strtoupper() it does not honour the locale.
1314 * @param string $str Input string
1315 * @return string Uppercase String
1317 public static function strtoupper($str) {
1318 return strtr((string) $str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
1322 * Converts string to lowercase
1323 * The function converts all Latin characters (A-Z, but no accents, etc) to
1324 * lowercase. It is safe for all supported character sets (incl. utf-8).
1325 * Unlike strtolower() it does not honour the locale.
1327 * @param string $str Input string
1328 * @return string Lowercase String
1330 public static function strtolower($str) {
1331 return strtr((string) $str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1335 * Returns a string of highly randomized bytes (over the full 8-bit range).
1337 * Note: Returned values are not guaranteed to be crypto-safe,
1338 * most likely they are not, depending on the used retrieval method.
1340 * @param integer $bytesToReturn Number of characters (bytes) to return
1341 * @return string Random Bytes
1342 * @see http://bugs.php.net/bug.php?id=52523
1343 * @see http://www.php-security.org/2010/05/09/mops-submission-04-generating-unpredictable-session-ids-and-hashes/index.html
1345 public static function generateRandomBytes($bytesToReturn) {
1346 // Cache 4k of the generated bytestream.
1348 $bytesToGenerate = max(4096, $bytesToReturn);
1350 // if we have not enough random bytes cached, we generate new ones
1351 if (!isset($bytes{$bytesToReturn - 1})) {
1352 if (TYPO3_OS
=== 'WIN') {
1353 // Openssl seems to be deadly slow on Windows, so try to use mcrypt
1354 // Windows PHP versions have a bug when using urandom source (see #24410)
1355 $bytes .= self
::generateRandomBytesMcrypt($bytesToGenerate, MCRYPT_RAND
);
1357 // Try to use native PHP functions first, precedence has openssl
1358 $bytes .= self
::generateRandomBytesOpenSsl($bytesToGenerate);
1360 if (!isset($bytes{$bytesToReturn - 1})) {
1361 $bytes .= self
::generateRandomBytesMcrypt($bytesToGenerate, MCRYPT_DEV_URANDOM
);
1364 // If openssl and mcrypt failed, try /dev/urandom
1365 if (!isset($bytes{$bytesToReturn - 1})) {
1366 $bytes .= self
::generateRandomBytesUrandom($bytesToGenerate);
1370 // Fall back if other random byte generation failed until now
1371 if (!isset($bytes{$bytesToReturn - 1})) {
1372 $bytes .= self
::generateRandomBytesFallback($bytesToReturn);
1376 // get first $bytesToReturn and remove it from the byte cache
1377 $output = substr($bytes, 0, $bytesToReturn);
1378 $bytes = substr($bytes, $bytesToReturn);
1384 * Generate random bytes using openssl if available
1386 * @param string $bytesToGenerate
1389 protected static function generateRandomBytesOpenSsl($bytesToGenerate) {
1390 if (!function_exists('openssl_random_pseudo_bytes')) {
1394 return (string) openssl_random_pseudo_bytes($bytesToGenerate, $isStrong);
1398 * Generate random bytes using mcrypt if available
1400 * @param $bytesToGenerate
1401 * @param $randomSource
1404 protected static function generateRandomBytesMcrypt($bytesToGenerate, $randomSource) {
1405 if (!function_exists('mcrypt_create_iv')) {
1408 return (string) @mcrypt_create_iv
($bytesToGenerate, $randomSource);
1412 * Read random bytes from /dev/urandom if it is accessible
1414 * @param $bytesToGenerate
1417 protected static function generateRandomBytesUrandom($bytesToGenerate) {
1419 $fh = @fopen
('/dev/urandom', 'rb');
1421 // PHP only performs buffered reads, so in reality it will always read
1422 // at least 4096 bytes. Thus, it costs nothing extra to read and store
1423 // that much so as to speed any additional invocations.
1424 $bytes = fread($fh, $bytesToGenerate);
1432 * Generate pseudo random bytes as last resort
1434 * @param $bytesToReturn
1437 protected static function generateRandomBytesFallback($bytesToReturn) {
1439 // We initialize with somewhat random.
1440 $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . base_convert(memory_get_usage() %
pow(10, 6), 10, 2) . microtime() . uniqid('') . getmypid();
1441 while (!isset($bytes{$bytesToReturn - 1})) {
1442 $randomState = sha1(microtime() . mt_rand() . $randomState);
1443 $bytes .= sha1(mt_rand() . $randomState, TRUE);
1449 * Returns a hex representation of a random byte string.
1451 * @param integer $count Number of hex characters to return
1452 * @return string Random Bytes
1454 public static function getRandomHexString($count) {
1455 return substr(bin2hex(self
::generateRandomBytes(intval(($count +
1) / 2))), 0, $count);
1459 * Returns a given string with underscores as UpperCamelCase.
1460 * Example: Converts blog_example to BlogExample
1462 * @param string $string: String to be converted to camel case
1463 * @return string UpperCamelCasedWord
1465 public static function underscoredToUpperCamelCase($string) {
1466 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self
::strtolower($string))));
1467 return $upperCamelCase;
1471 * Returns a given string with underscores as lowerCamelCase.
1472 * Example: Converts minimal_value to minimalValue
1474 * @param string $string: String to be converted to camel case
1475 * @return string lowerCamelCasedWord
1477 public static function underscoredToLowerCamelCase($string) {
1478 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self
::strtolower($string))));
1479 $lowerCamelCase = self
::lcfirst($upperCamelCase);
1480 return $lowerCamelCase;
1484 * Returns a given CamelCasedString as an lowercase string with underscores.
1485 * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
1487 * @param string $string String to be converted to lowercase underscore
1488 * @return string lowercase_and_underscored_string
1490 public static function camelCaseToLowerCaseUnderscored($string) {
1491 return self
::strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
1495 * Converts the first char of a string to lowercase if it is a latin character (A-Z).
1496 * Example: Converts "Hello World" to "hello World"
1498 * @param string $string The string to be used to lowercase the first character
1499 * @return string The string with the first character as lowercase
1501 public static function lcfirst($string) {
1502 return self
::strtolower(substr($string, 0, 1)) . substr($string, 1);
1506 * Checks if a given string is a Uniform Resource Locator (URL).
1508 * @param string $url The URL to be validated
1509 * @return boolean Whether the given URL is valid
1511 public static function isValidUrl($url) {
1512 return (filter_var($url, FILTER_VALIDATE_URL
, FILTER_FLAG_SCHEME_REQUIRED
) !== FALSE);
1516 /*************************
1520 *************************/
1523 * Check if an string item exists in an array.
1524 * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
1526 * Comparison to PHP in_array():
1527 * -> $array = array(0, 1, 2, 3);
1528 * -> variant_a := t3lib_div::inArray($array, $needle)
1529 * -> variant_b := in_array($needle, $array)
1530 * -> variant_c := in_array($needle, $array, TRUE)
1531 * +---------+-----------+-----------+-----------+
1532 * | $needle | variant_a | variant_b | variant_c |
1533 * +---------+-----------+-----------+-----------+
1534 * | '1a' | FALSE | TRUE | FALSE |
1535 * | '' | FALSE | TRUE | FALSE |
1536 * | '0' | TRUE | TRUE | FALSE |
1537 * | 0 | TRUE | TRUE | TRUE |
1538 * +---------+-----------+-----------+-----------+
1540 * @param array $in_array one-dimensional array of items
1541 * @param string $item item to check for
1542 * @return boolean TRUE if $item is in the one-dimensional array $in_array
1544 public static function inArray(array $in_array, $item) {
1545 foreach ($in_array as $val) {
1546 if (!is_array($val) && !strcmp($val, $item)) {
1554 * Explodes a $string delimited by $delim and passes each item in the array through intval().
1555 * Corresponds to t3lib_div::trimExplode(), but with conversion to integers for all values.
1557 * @param string $delimiter Delimiter string to explode with
1558 * @param string $string The string to explode
1559 * @param boolean $onlyNonEmptyValues If set, all empty values (='') will NOT be set in output
1560 * @param integer $limit If positive, the result will contain a maximum of limit elements,
1561 * if negative, all components except the last -limit are returned,
1562 * if zero (default), the result is not limited at all
1563 * @return array Exploded values, all converted to integers
1565 public static function intExplode($delimiter, $string, $onlyNonEmptyValues = FALSE, $limit = 0) {
1566 $explodedValues = self
::trimExplode($delimiter, $string, $onlyNonEmptyValues, $limit);
1567 return array_map('intval', $explodedValues);
1571 * Reverse explode which explodes the string counting from behind.
1572 * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1574 * @param string $delimiter Delimiter string to explode with
1575 * @param string $string The string to explode
1576 * @param integer $count Number of array entries
1577 * @return array Exploded values
1579 public static function revExplode($delimiter, $string, $count = 0) {
1580 $explodedValues = explode($delimiter, strrev($string), $count);
1581 $explodedValues = array_map('strrev', $explodedValues);
1582 return array_reverse($explodedValues);
1586 * Explodes a string and trims all values for whitespace in the ends.
1587 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1589 * @param string $delim Delimiter string to explode with
1590 * @param string $string The string to explode
1591 * @param boolean $removeEmptyValues If set, all empty values will be removed in output
1592 * @param integer $limit If positive, the result will contain a maximum of
1593 * $limit elements, if negative, all components except
1594 * the last -$limit are returned, if zero (default),
1595 * the result is not limited at all. Attention though
1596 * that the use of this parameter can slow down this
1598 * @return array Exploded values
1600 public static function trimExplode($delim, $string, $removeEmptyValues = FALSE, $limit = 0) {
1601 $explodedValues = explode($delim, $string);
1603 $result = array_map('trim', $explodedValues);
1605 if ($removeEmptyValues) {
1607 foreach ($result as $value) {
1608 if ($value !== '') {
1617 $result = array_slice($result, 0, $limit);
1618 } elseif (count($result) > $limit) {
1619 $lastElements = array_slice($result, $limit - 1);
1620 $result = array_slice($result, 0, $limit - 1);
1621 $result[] = implode($delim, $lastElements);
1629 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1631 * @param array $array Array containing the values
1632 * @param string $cmpValue Value to search for and if found remove array entry where found.
1633 * @return array Output array with entries removed if search string is found
1635 public static function removeArrayEntryByValue(array $array, $cmpValue) {
1636 foreach ($array as $k => $v) {
1638 $array[$k] = self
::removeArrayEntryByValue($v, $cmpValue);
1639 } elseif (!strcmp($v, $cmpValue)) {
1647 * Filters an array to reduce its elements to match the condition.
1648 * The values in $keepItems can be optionally evaluated by a custom callback function.
1650 * Example (arguments used to call this function):
1652 * array('aa' => array('first', 'second'),
1653 * array('bb' => array('third', 'fourth'),
1654 * array('cc' => array('fifth', 'sixth'),
1656 * $keepItems = array('third');
1657 * $getValueFunc = create_function('$value', 'return $value[0];');
1661 * array('bb' => array('third', 'fourth'),
1664 * @param array $array: The initial array to be filtered/reduced
1665 * @param mixed $keepItems: The items which are allowed/kept in the array - accepts array or csv string
1666 * @param string $getValueFunc: (optional) Unique function name set by create_function() used to get the value to keep
1667 * @return array The filtered/reduced array with the kept items
1669 public static function keepItemsInArray(array $array, $keepItems, $getValueFunc = NULL) {
1671 // Convert strings to arrays:
1672 if (is_string($keepItems)) {
1673 $keepItems = self
::trimExplode(',', $keepItems);
1675 // create_function() returns a string:
1676 if (!is_string($getValueFunc)) {
1677 $getValueFunc = NULL;
1679 // Do the filtering:
1680 if (is_array($keepItems) && count($keepItems)) {
1681 foreach ($array as $key => $value) {
1682 // Get the value to compare by using the callback function:
1683 $keepValue = (isset($getValueFunc) ?
$getValueFunc($value) : $value);
1684 if (!in_array($keepValue, $keepItems)) {
1685 unset($array[$key]);
1694 * Implodes a multidim-array into GET-parameters (eg. ¶m[key][key2]=value2¶m[key][key3]=value3)
1696 * @param string $name Name prefix for entries. Set to blank if you wish none.
1697 * @param array $theArray The (multidimensional) array to implode
1698 * @param string $str (keep blank)
1699 * @param boolean $skipBlank If set, parameters which were blank strings would be removed.
1700 * @param boolean $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1701 * @return string Imploded result, fx. ¶m[key][key2]=value2¶m[key][key3]=value3
1702 * @see explodeUrl2Array()
1704 public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = FALSE, $rawurlencodeParamName = FALSE) {
1705 foreach ($theArray as $Akey => $AVal) {
1706 $thisKeyName = $name ?
$name . '[' . $Akey . ']' : $Akey;
1707 if (is_array($AVal)) {
1708 $str = self
::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1710 if (!$skipBlank ||
strcmp($AVal, '')) {
1711 $str .= '&' . ($rawurlencodeParamName ?
rawurlencode($thisKeyName) : $thisKeyName) .
1712 '=' . rawurlencode($AVal);
1720 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1722 * @param string $string GETvars string
1723 * @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())
1724 * @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!
1725 * @see implodeArrayForUrl()
1727 public static function explodeUrl2Array($string, $multidim = FALSE) {
1730 parse_str($string, $output);
1732 $p = explode('&', $string);
1733 foreach ($p as $v) {
1735 list($pK, $pV) = explode('=', $v, 2);
1736 $output[rawurldecode($pK)] = rawurldecode($pV);
1744 * Returns an array with selected keys from incoming data.
1745 * (Better read source code if you want to find out...)
1747 * @param string $varList List of variable/key names
1748 * @param array $getArray Array from where to get values based on the keys in $varList
1749 * @param boolean $GPvarAlt If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1750 * @return array Output array with selected variables.
1752 public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = TRUE) {
1753 $keys = self
::trimExplode(',', $varList, 1);
1755 foreach ($keys as $v) {
1756 if (isset($getArray[$v])) {
1757 $outArr[$v] = $getArray[$v];
1758 } elseif ($GPvarAlt) {
1759 $outArr[$v] = self
::_GP($v);
1767 * This function traverses a multidimensional array and adds slashes to the values.
1768 * NOTE that the input array is and argument by reference.!!
1769 * Twin-function to stripSlashesOnArray
1771 * @param array $theArray Multidimensional input array, (REFERENCE!)
1774 public static function addSlashesOnArray(array &$theArray) {
1775 foreach ($theArray as &$value) {
1776 if (is_array($value)) {
1777 self
::addSlashesOnArray($value);
1779 $value = addslashes($value);
1788 * This function traverses a multidimensional array and strips slashes to the values.
1789 * NOTE that the input array is and argument by reference.!!
1790 * Twin-function to addSlashesOnArray
1792 * @param array $theArray Multidimensional input array, (REFERENCE!)
1795 public static function stripSlashesOnArray(array &$theArray) {
1796 foreach ($theArray as &$value) {
1797 if (is_array($value)) {
1798 self
::stripSlashesOnArray($value);
1800 $value = stripslashes($value);
1808 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1810 * @param array $arr Multidimensional input array
1811 * @param string $cmd "add" or "strip", depending on usage you wish.
1814 public static function slashArray(array $arr, $cmd) {
1815 if ($cmd == 'strip') {
1816 self
::stripSlashesOnArray($arr);
1818 if ($cmd == 'add') {
1819 self
::addSlashesOnArray($arr);
1825 * Rename Array keys with a given mapping table
1827 * @param array $array Array by reference which should be remapped
1828 * @param array $mappingTable Array with remap information, array/$oldKey => $newKey)
1830 public static function remapArrayKeys(&$array, $mappingTable) {
1831 if (is_array($mappingTable)) {
1832 foreach ($mappingTable as $old => $new) {
1833 if ($new && isset($array[$old])) {
1834 $array[$new] = $array[$old];
1835 unset ($array[$old]);
1843 * Merges two arrays recursively and "binary safe" (integer keys are
1844 * overridden as well), overruling similar values in the first array
1845 * ($arr0) with the values of the second array ($arr1)
1846 * In case of identical keys, ie. keeping the values of the second.
1848 * @param array $arr0 First array
1849 * @param array $arr1 Second array, overruling the first array
1850 * @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.
1851 * @param boolean $includeEmptyValues If set, values from $arr1 will overrule if they are empty or zero. Default: TRUE
1852 * @return array Resulting array where $arr1 values has overruled $arr0 values
1854 public static function array_merge_recursive_overrule(array $arr0, array $arr1, $notAddKeys = FALSE, $includeEmptyValues = TRUE) {
1855 foreach ($arr1 as $key => $val) {
1856 if (is_array($arr0[$key])) {
1857 if (is_array($arr1[$key])) {
1858 $arr0[$key] = self
::array_merge_recursive_overrule($arr0[$key], $arr1[$key], $notAddKeys, $includeEmptyValues);
1862 if (isset($arr0[$key])) {
1863 if ($includeEmptyValues ||
$val) {
1868 if ($includeEmptyValues ||
$val) {
1879 * 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.
1881 * @param array $arr1 First array
1882 * @param array $arr2 Second array
1883 * @return array Merged result.
1885 public static function array_merge(array $arr1, array $arr2) {
1886 return $arr2 +
$arr1;
1890 * Filters keys off from first array that also exist in second array. Comparison is done by keys.
1891 * This method is a recursive version of php array_diff_assoc()
1893 * @param array $array1 Source array
1894 * @param array $array2 Reduce source array by this array
1895 * @return array Source array reduced by keys also present in second array
1897 public static function arrayDiffAssocRecursive(array $array1, array $array2) {
1898 $differenceArray = array();
1899 foreach ($array1 as $key => $value) {
1900 if (!array_key_exists($key, $array2)) {
1901 $differenceArray[$key] = $value;
1902 } elseif (is_array($value)) {
1903 if (is_array($array2[$key])) {
1904 $differenceArray[$key] = self
::arrayDiffAssocRecursive($value, $array2[$key]);
1909 return $differenceArray;
1913 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1915 * @param array $row Input array of values
1916 * @param string $delim Delimited, default is comma
1917 * @param string $quote Quote-character to wrap around the values.
1918 * @return string A single line of CSV
1920 public static function csvValues(array $row, $delim = ',', $quote = '"') {
1922 foreach ($row as $value) {
1923 $out[] = str_replace($quote, $quote . $quote, $value);
1925 $str = $quote . implode($quote . $delim . $quote, $out) . $quote;
1930 * Removes dots "." from end of a key identifier of TypoScript styled array.
1931 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1933 * @param array $ts: TypoScript configuration array
1934 * @return array TypoScript configuration array without dots at the end of all keys
1936 public static function removeDotsFromTS(array $ts) {
1938 foreach ($ts as $key => $value) {
1939 if (is_array($value)) {
1940 $key = rtrim($key, '.');
1941 $out[$key] = self
::removeDotsFromTS($value);
1943 $out[$key] = $value;
1950 * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
1952 * @param array $array array to be sorted recursively, passed by reference
1953 * @return boolean TRUE if param is an array
1955 public static function naturalKeySortRecursive(&$array) {
1956 if (!is_array($array)) {
1959 uksort($array, 'strnatcasecmp');
1960 foreach ($array as $key => $value) {
1961 self
::naturalKeySortRecursive($array[$key]);
1967 /*************************
1969 * HTML/XML PROCESSING
1971 *************************/
1974 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1975 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1976 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1978 * @param string $tag HTML-tag string (or attributes only)
1979 * @return array Array with the attribute values.
1981 public static function get_tag_attributes($tag) {
1982 $components = self
::split_tag_attributes($tag);
1983 $name = ''; // attribute name is stored here
1985 $attributes = array();
1986 foreach ($components as $key => $val) {
1987 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
1990 $attributes[$name] = $val;
1994 if ($key = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $val))) {
1995 $attributes[$key] = '';
2008 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
2009 * Removes tag-name if found
2011 * @param string $tag HTML-tag string (or attributes only)
2012 * @return array Array with the attribute values.
2014 public static function split_tag_attributes($tag) {
2015 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
2016 // Removes any > in the end of the string
2017 $tag_tmp = trim(rtrim($tag_tmp, '>'));
2020 while (strcmp($tag_tmp, '')) { // Compared with empty string instead , 030102
2021 $firstChar = substr($tag_tmp, 0, 1);
2022 if (!strcmp($firstChar, '"') ||
!strcmp($firstChar, "'")) {
2023 $reg = explode($firstChar, $tag_tmp, 3);
2025 $tag_tmp = trim($reg[2]);
2026 } elseif (!strcmp($firstChar, '=')) {
2028 $tag_tmp = trim(substr($tag_tmp, 1)); // Removes = chars.
2030 // There are '' around the value. We look for the next ' ' or '>'
2031 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
2032 $value[] = trim($reg[0]);
2033 $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
2041 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
2043 * @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
2044 * @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!
2045 * @param boolean $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
2046 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
2048 public static function implodeAttributes(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
2051 foreach ($arr as $p => $v) {
2052 if (!isset($newArr[strtolower($p)])) {
2053 $newArr[strtolower($p)] = htmlspecialchars($v);
2059 foreach ($arr as $p => $v) {
2060 if (strcmp($v, '') ||
$dontOmitBlankAttribs) {
2061 $list[] = $p . '="' . $v . '"';
2064 return implode(' ', $list);
2068 * Wraps JavaScript code XHTML ready with <script>-tags
2069 * Automatic re-indenting of the JS code is done by using the first line as indent reference.
2070 * This is nice for indenting JS code with PHP code on the same level.
2072 * @param string $string JavaScript code
2073 * @param boolean $linebreak Wrap script element in line breaks? Default is TRUE.
2074 * @return string The wrapped JS code, ready to put into a XHTML page
2076 public static function wrapJS($string, $linebreak = TRUE) {
2077 if (trim($string)) {
2078 // <script wrapped in nl?
2079 $cr = $linebreak ? LF
: '';
2081 // remove nl from the beginning
2082 $string = preg_replace('/^\n+/', '', $string);
2083 // re-ident to one tab using the first line as reference
2085 if (preg_match('/^(\t+)/', $string, $match)) {
2086 $string = str_replace($match[1], TAB
, $string);
2088 $string = $cr . '<script type="text/javascript">
2094 return trim($string);
2099 * Parses XML input into a PHP array with associative keys
2101 * @param string $string XML data input
2102 * @param integer $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
2103 * @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.
2104 * @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
2106 public static function xml2tree($string, $depth = 999) {
2107 $parser = xml_parser_create();
2111 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
2112 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
2113 xml_parse_into_struct($parser, $string, $vals, $index);
2115 if (xml_get_error_code($parser)) {
2116 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2118 xml_parser_free($parser);
2120 $stack = array(array());
2125 foreach ($vals as $key => $val) {
2126 $type = $val['type'];
2129 if ($type == 'open' ||
$type == 'complete') {
2130 $stack[$stacktop++
] = $tagi;
2132 if ($depth == $stacktop) {
2136 $tagi = array('tag' => $val['tag']);
2138 if (isset($val['attributes'])) {
2139 $tagi['attrs'] = $val['attributes'];
2141 if (isset($val['value'])) {
2142 $tagi['values'][] = $val['value'];
2146 if ($type == 'complete' ||
$type == 'close') {
2148 $tagi = $stack[--$stacktop];
2149 $oldtag = $oldtagi['tag'];
2150 unset($oldtagi['tag']);
2152 if ($depth == ($stacktop +
1)) {
2153 if ($key - $startPoint > 0) {
2154 $partArray = array_slice(
2157 $key - $startPoint - 1
2159 $oldtagi['XMLvalue'] = self
::xmlRecompileFromStructValArray($partArray);
2161 $oldtagi['XMLvalue'] = $oldtagi['values'][0];
2165 $tagi['ch'][$oldtag][] = $oldtagi;
2169 if ($type == 'cdata') {
2170 $tagi['values'][] = $val['value'];
2177 * Turns PHP array into XML. See array2xml()
2179 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2180 * @param string $docTag Alternative document tag. Default is "phparray".
2181 * @param array $options Options for the compilation. See array2xml() for description.
2182 * @param string $charset Forced charset to prologue
2183 * @return string An XML string made from the input content in the array.
2184 * @see xml2array(),array2xml()
2186 public static function array2xml_cs(array $array, $docTag = 'phparray', array $options = array(), $charset = '') {
2188 // Figure out charset if not given explicitly:
2190 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) { // First priority: forceCharset! If set, this will be authoritative!
2191 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
2192 } elseif (is_object($GLOBALS['LANG'])) {
2193 $charset = $GLOBALS['LANG']->charSet
; // If "LANG" is around, that will hold the current charset
2195 $charset = 'iso-8859-1'; // THIS is just a hopeful guess!
2200 return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF
.
2201 self
::array2xml($array, '', 0, $docTag, 0, $options);
2205 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
2207 * Converts a PHP array into an XML string.
2208 * The XML output is optimized for readability since associative keys are used as tag names.
2209 * 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.
2210 * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
2211 * 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
2212 * 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.
2213 * 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!
2214 * 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...
2216 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2217 * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
2218 * @param integer $level Current recursion level. Don't change, stay at zero!
2219 * @param string $docTag Alternative document tag. Default is "phparray".
2220 * @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
2221 * @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')
2222 * @param array $stackData Stack data. Don't touch.
2223 * @return string An XML string made from the input content in the array.
2226 public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = array(), array $stackData = array()) {
2227 // 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
2228 $binaryChars = chr(0) . chr(1) . chr(2) . chr(3) . chr(4) . chr(5) . chr(6) . chr(7) . chr(8) .
2229 chr(11) . chr(12) . chr(14) . chr(15) . chr(16) . chr(17) . chr(18) . chr(19) .
2230 chr(20) . chr(21) . chr(22) . chr(23) . chr(24) . chr(25) . chr(26) . chr(27) . chr(28) . chr(29) .
2232 // Set indenting mode:
2233 $indentChar = $spaceInd ?
' ' : TAB
;
2234 $indentN = $spaceInd > 0 ?
$spaceInd : 1;
2235 $nl = ($spaceInd >= 0 ? LF
: '');
2237 // Init output variable:
2240 // Traverse the input array
2241 foreach ($array as $k => $v) {
2245 // Construct the tag name.
2246 if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
2247 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2248 $tagName = (string) $options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']];
2249 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM']) && t3lib_utility_Math
::canBeInterpretedAsInteger($tagName)) { // Use tag based on parent tag name + if current tag is numeric
2250 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2251 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM'];
2252 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) { // Use tag based on parent tag name + current tag
2253 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2254 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName];
2255 } elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
2256 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2257 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName']];
2258 } elseif (!strcmp(intval($tagName), $tagName)) { // If integer...;
2259 if ($options['useNindex']) { // If numeric key, prefix "n"
2260 $tagName = 'n' . $tagName;
2261 } else { // Use special tag for num. keys:
2262 $attr .= ' index="' . $tagName . '"';
2263 $tagName = $options['useIndexTagForNum'] ?
$options['useIndexTagForNum'] : 'numIndex';
2265 } elseif ($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
2266 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2267 $tagName = $options['useIndexTagForAssoc'];
2270 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2271 $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
2273 // If the value is an array then we will call this function recursively:
2277 if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
2278 $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
2279 $clearStackPath = $subOptions['clearStackPath'];
2281 $subOptions = $options;
2282 $clearStackPath = FALSE;
2294 'parentTagName' => $tagName,
2295 'grandParentTagName' => $stackData['parentTagName'],
2296 'path' => $clearStackPath ?
'' : $stackData['path'] . '/' . $tagName,
2299 ($spaceInd >= 0 ?
str_pad('', ($level +
1) * $indentN, $indentChar) : '');
2300 if ((int) $options['disableTypeAttrib'] != 2) { // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2301 $attr .= ' type="array"';
2303 } else { // Just a value:
2305 // Look for binary chars:
2306 $vLen = strlen($v); // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
2307 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!
2308 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2309 $content = $nl . chunk_split(base64_encode($v));
2310 $attr .= ' base64="1"';
2312 // Otherwise, just htmlspecialchar the stuff:
2313 $content = htmlspecialchars($v);
2314 $dType = gettype($v);
2315 if ($dType == 'string') {
2316 if ($options['useCDATA'] && $content != $v) {
2317 $content = '<![CDATA[' . $v . ']]>';
2319 } elseif (!$options['disableTypeAttrib']) {
2320 $attr .= ' type="' . $dType . '"';
2325 // Add the element to the output string:
2326 $output .= ($spaceInd >= 0 ?
str_pad('', ($level +
1) * $indentN, $indentChar) : '') . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
2329 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2332 '<' . $docTag . '>' . $nl .
2334 '</' . $docTag . '>';
2341 * Converts an XML string to a PHP array.
2342 * This is the reverse function of array2xml()
2343 * This is a wrapper for xml2arrayProcess that adds a two-level cache
2345 * @param string $string XML content to convert into an array
2346 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2347 * @param boolean $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2348 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2349 * @see array2xml(),xml2arrayProcess()
2351 public static function xml2array($string, $NSprefix = '', $reportDocTag = FALSE) {
2352 static $firstLevelCache = array();
2354 $identifier = md5($string . $NSprefix . ($reportDocTag ?
'1' : '0'));
2356 // look up in first level cache
2357 if (!empty($firstLevelCache[$identifier])) {
2358 $array = $firstLevelCache[$identifier];
2360 // look up in second level cache
2361 $cacheContent = t3lib_pageSelect
::getHash($identifier, 0);
2362 $array = unserialize($cacheContent);
2364 if ($array === FALSE) {
2365 $array = self
::xml2arrayProcess($string, $NSprefix, $reportDocTag);
2366 t3lib_pageSelect
::storeHash($identifier, serialize($array), 'ident_xml2array');
2368 // store content in first level cache
2369 $firstLevelCache[$identifier] = $array;
2375 * Converts an XML string to a PHP array.
2376 * This is the reverse function of array2xml()
2378 * @param string $string XML content to convert into an array
2379 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2380 * @param boolean $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2381 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2384 protected static function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = FALSE) {
2386 $parser = xml_parser_create();
2390 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
2391 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
2393 // default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2395 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
2396 $theCharset = $match[1] ?
$match[1] : ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ?
$GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'iso-8859-1');
2397 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING
, $theCharset); // us-ascii / utf-8 / iso-8859-1
2400 xml_parse_into_struct($parser, $string, $vals, $index);
2402 // If error, return error message:
2403 if (xml_get_error_code($parser)) {
2404 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2406 xml_parser_free($parser);
2409 $stack = array(array());
2415 // Traverse the parsed XML structure:
2416 foreach ($vals as $key => $val) {
2418 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2419 $tagName = $val['tag'];
2420 if (!$documentTag) {
2421 $documentTag = $tagName;
2424 // Test for name space:
2425 $tagName = ($NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix) ?
substr($tagName, strlen($NSprefix)) : $tagName;
2427 // Test for numeric tag, encoded on the form "nXXX":
2428 $testNtag = substr($tagName, 1); // Closing tag.
2429 $tagName = (substr($tagName, 0, 1) == 'n' && !strcmp(intval($testNtag), $testNtag)) ?
intval($testNtag) : $tagName;
2431 // Test for alternative index value:
2432 if (strlen($val['attributes']['index'])) {
2433 $tagName = $val['attributes']['index'];
2436 // Setting tag-values, manage stack:
2437 switch ($val['type']) {
2438 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2439 $current[$tagName] = array(); // Setting blank place holder
2440 $stack[$stacktop++
] = $current;
2443 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2444 $oldCurrent = $current;
2445 $current = $stack[--$stacktop];
2446 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
2447 $current[key($current)] = $oldCurrent;
2450 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2451 if ($val['attributes']['base64']) {
2452 $current[$tagName] = base64_decode($val['value']);
2454 $current[$tagName] = (string) $val['value']; // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
2457 switch ((string) $val['attributes']['type']) {
2459 $current[$tagName] = (integer) $current[$tagName];
2462 $current[$tagName] = (double) $current[$tagName];
2465 $current[$tagName] = (bool) $current[$tagName];
2468 $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...
2476 if ($reportDocTag) {
2477 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2480 // Finally return the content of the document tag.
2481 return $current[$tagName];
2485 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2487 * @param array $vals An array of XML parts, see xml2tree
2488 * @return string Re-compiled XML data.
2490 public static function xmlRecompileFromStructValArray(array $vals) {
2493 foreach ($vals as $val) {
2494 $type = $val['type'];
2497 if ($type == 'open' ||
$type == 'complete') {
2498 $XMLcontent .= '<' . $val['tag'];
2499 if (isset($val['attributes'])) {
2500 foreach ($val['attributes'] as $k => $v) {
2501 $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
2504 if ($type == 'complete') {
2505 if (isset($val['value'])) {
2506 $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
2508 $XMLcontent .= '/>';
2514 if ($type == 'open' && isset($val['value'])) {
2515 $XMLcontent .= htmlspecialchars($val['value']);
2519 if ($type == 'close') {
2520 $XMLcontent .= '</' . $val['tag'] . '>';
2523 if ($type == 'cdata') {
2524 $XMLcontent .= htmlspecialchars($val['value']);
2532 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2534 * @param string $xmlData XML data
2535 * @return array Attributes of the xml prologue (header)
2537 public static function xmlGetHeaderAttribs($xmlData) {
2539 if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
2540 return self
::get_tag_attributes($match[1]);
2545 * Minifies JavaScript
2547 * @param string $script Script to minify
2548 * @param string $error Error message (if any)
2549 * @return string Minified script or source string if error happened
2551 public static function minifyJavaScript($script, &$error = '') {
2552 require_once(PATH_typo3
. 'contrib/jsmin/jsmin.php');
2555 $script = trim(JSMin
::minify(str_replace(CR
, '', $script)));
2557 catch (JSMinException
$e) {
2558 $error = 'Error while minifying JavaScript: ' . $e->getMessage();
2559 self
::devLog($error, 't3lib_div', 2,
2560 array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
2566 /*************************
2570 *************************/
2573 * Reads the file or url $url and returns the content
2574 * 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.
2576 * @param string $url File/URL to read
2577 * @param integer $includeHeader Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2578 * @param array $requestHeaders HTTP headers to be used in the request
2579 * @param array $report Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2580 * @return mixed The content from the resource given as input. FALSE if an error has occured.
2582 public static function getUrl($url, $includeHeader = 0, $requestHeaders = FALSE, &$report = NULL) {
2585 if (isset($report)) {
2586 $report['error'] = 0;
2587 $report['message'] = '';
2590 // use cURL for: http, https, ftp, ftps, sftp and scp
2591 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2592 if (isset($report)) {
2593 $report['lib'] = 'cURL';
2596 // External URL without error checking.
2597 if (!function_exists('curl_init') ||
!($ch = curl_init())) {
2598 if (isset($report)) {
2599 $report['error'] = -1;
2600 $report['message'] = 'Couldn\'t initialize cURL.';
2605 curl_setopt($ch, CURLOPT_URL
, $url);
2606 curl_setopt($ch, CURLOPT_HEADER
, $includeHeader ?
1 : 0);
2607 curl_setopt($ch, CURLOPT_NOBODY
, $includeHeader == 2 ?
1 : 0);
2608 curl_setopt($ch, CURLOPT_HTTPGET
, $includeHeader == 2 ?
'HEAD' : 'GET');
2609 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
2610 curl_setopt($ch, CURLOPT_FAILONERROR
, 1);
2611 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, max(0, intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout'])));
2613 $followLocation = @curl_setopt
($ch, CURLOPT_FOLLOWLOCATION
, 1);
2615 if (is_array($requestHeaders)) {
2616 curl_setopt($ch, CURLOPT_HTTPHEADER
, $requestHeaders);
2619 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2620 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2621 curl_setopt($ch, CURLOPT_PROXY
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2623 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2624 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2626 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2627 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2630 $content = curl_exec($ch);
2631 if (isset($report)) {
2632 if ($content === FALSE) {
2633 $report['error'] = curl_errno($ch);
2634 $report['message'] = curl_error($ch);
2636 $curlInfo = curl_getinfo($ch);
2637 // We hit a redirection but we couldn't follow it
2638 if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
2639 $report['error'] = -1;
2640 $report['message'] = 'Couldn\'t follow location redirect (PHP configuration option open_basedir is in effect).';
2641 } elseif ($includeHeader) {
2642 // Set only for $includeHeader to work exactly like PHP variant
2643 $report['http_code'] = $curlInfo['http_code'];
2644 $report['content_type'] = $curlInfo['content_type'];
2650 } elseif ($includeHeader) {
2651 if (isset($report)) {
2652 $report['lib'] = 'socket';
2654 $parsedURL = parse_url($url);
2655 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2656 if (isset($report)) {
2657 $report['error'] = -1;
2658 $report['message'] = 'Reading headers is not allowed for this protocol.';
2662 $port = intval($parsedURL['port']);
2664 if ($parsedURL['scheme'] == 'http') {
2665 $port = ($port > 0 ?
$port : 80);
2668 $port = ($port > 0 ?
$port : 443);
2674 $fp = @fsockopen
($scheme . $parsedURL['host'], $port, $errno, $errstr, 2.0);
2675 if (!$fp ||
$errno > 0) {
2676 if (isset($report)) {
2677 $report['error'] = $errno ?
$errno : -1;
2678 $report['message'] = $errno ?
($errstr ?
$errstr : 'Socket error.') : 'Socket initialization error.';
2682 $method = ($includeHeader == 2) ?
'HEAD' : 'GET';
2683 $msg = $method . ' ' . (isset($parsedURL['path']) ?
$parsedURL['path'] : '/') .
2684 ($parsedURL['query'] ?
'?' . $parsedURL['query'] : '') .
2685 ' HTTP/1.0' . CRLF
. 'Host: ' .
2686 $parsedURL['host'] . "\r\nConnection: close\r\n";
2687 if (is_array($requestHeaders)) {
2688 $msg .= implode(CRLF
, $requestHeaders) . CRLF
;
2693 while (!feof($fp)) {
2694 $line = fgets($fp, 2048);
2695 if (isset($report)) {
2696 if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
2697 $report['http_code'] = $status[1];
2699 elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2700 $report['content_type'] = $type[1];
2704 if (!strlen(trim($line))) {
2705 break; // Stop at the first empty line (= end of header)
2708 if ($includeHeader != 2) {
2709 $content .= stream_get_contents($fp);
2713 } elseif (is_array($requestHeaders)) {
2714 if (isset($report)) {
2715 $report['lib'] = 'file/context';
2717 $parsedURL = parse_url($url);
2718 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2719 if (isset($report)) {
2720 $report['error'] = -1;
2721 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2725 $ctx = stream_context_create(array(
2727 'header' => implode(CRLF
, $requestHeaders)
2731 $content = @file_get_contents
($url, FALSE, $ctx);
2732 if ($content === FALSE && isset($report)) {
2733 $phpError = error_get_last();
2734 $report['error'] = $phpError['type'];
2735 $report['message'] = $phpError['message'];
2738 if (isset($report)) {
2739 $report['lib'] = 'file';
2741 $content = @file_get_contents
($url);
2742 if ($content === FALSE && isset($report)) {
2743 if (function_exists('error_get_last')) {
2744 $phpError = error_get_last();
2745 $report['error'] = $phpError['type'];
2746 $report['message'] = $phpError['message'];
2748 $report['error'] = -1;
2749 $report['message'] = 'Couldn\'t get URL.';
2758 * Writes $content to the file $file
2760 * @param string $file Filepath to write to
2761 * @param string $content Content to write
2762 * @return boolean TRUE if the file was successfully opened and written to.
2764 public static function writeFile($file, $content) {
2765 if (!@is_file
($file)) {
2766 $changePermissions = TRUE;
2769 if ($fd = fopen($file, 'wb')) {
2770 $res = fwrite($fd, $content);
2773 if ($res === FALSE) {
2777 if ($changePermissions) { // Change the permissions only if the file has just been created
2778 self
::fixPermissions($file);
2788 * Sets the file system mode and group ownership of a file or a folder.
2790 * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
2791 * @param boolean $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
2792 * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
2794 public static function fixPermissions($path, $recursive = FALSE) {
2795 if (TYPO3_OS
!= 'WIN') {
2798 // Make path absolute
2799 if (!self
::isAbsPath($path)) {
2800 $path = self
::getFileAbsFileName($path, FALSE);
2803 if (self
::isAllowedAbsPath($path)) {
2804 if (@is_file
($path)) {
2805 // "@" is there because file is not necessarily OWNED by the user
2806 $result = @chmod
($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
2807 } elseif (@is_dir
($path)) {
2808 // "@" is there because file is not necessarily OWNED by the user
2809 $result = @chmod
($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2812 // Set createGroup if not empty
2813 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) {
2814 // "@" is there because file is not necessarily OWNED by the user
2815 $changeGroupResult = @chgrp
($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2816 $result = $changeGroupResult ?
$result : FALSE;
2819 // Call recursive if recursive flag if set and $path is directory
2820 if ($recursive && @is_dir
($path)) {
2821 $handle = opendir($path);
2822 while (($file = readdir($handle)) !== FALSE) {
2823 $recursionResult = NULL;
2824 if ($file !== '.' && $file !== '..') {
2825 if (@is_file
($path . '/' . $file)) {
2826 $recursionResult = self
::fixPermissions($path . '/' . $file);
2827 } elseif (@is_dir
($path . '/' . $file)) {
2828 $recursionResult = self
::fixPermissions($path . '/' . $file, TRUE);
2830 if (isset($recursionResult) && !$recursionResult) {
2845 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2846 * Accepts an additional subdirectory in the file path!
2848 * @param string $filepath Absolute file path to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2849 * @param string $content Content string to write
2850 * @return string Returns NULL on success, otherwise an error string telling about the problem.
2852 public static function writeFileToTypo3tempDir($filepath, $content) {
2854 // Parse filepath into directory and basename:
2855 $fI = pathinfo($filepath);
2856 $fI['dirname'] .= '/';
2859 if (self
::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename']) < 60) {
2860 if (defined('PATH_site')) {
2861 $dirName = PATH_site
. 'typo3temp/'; // Setting main temporary directory name (standard)
2862 if (@is_dir
($dirName)) {
2863 if (self
::isFirstPartOfStr($fI['dirname'], $dirName)) {
2865 // Checking if the "subdir" is found:
2866 $subdir = substr($fI['dirname'], strlen($dirName));
2868 if (preg_match('/^[[:alnum:]_]+\/$/', $subdir) ||
preg_match('/^[[:alnum:]_]+\/[[:alnum:]_]+\/$/', $subdir)) {
2869 $dirName .= $subdir;
2870 if (!@is_dir
($dirName)) {
2871 self
::mkdir_deep(PATH_site
. 'typo3temp/', $subdir);
2874 return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2877 // Checking dir-name again (sub-dir might have been created):
2878 if (@is_dir
($dirName)) {
2879 if ($filepath == $dirName . $fI['basename']) {
2880 self
::writeFile($filepath, $content);
2881 if (!@is_file
($filepath)) {
2882 return 'The file was not written to the disk. Please, check that you have write permissions to the typo3temp/ directory.';
2885 return 'Calculated filelocation didn\'t match input $filepath!';
2888 return '"' . $dirName . '" is not a directory!';
2891 return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
2894 return 'PATH_site + "typo3temp/" was not a directory!';
2897 return 'PATH_site constant was NOT defined!';
2900 return 'Input filepath "' . $filepath . '" was generally invalid!';
2905 * Wrapper function for mkdir.
2906 * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']
2907 * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
2909 * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2910 * @return boolean TRUE if @mkdir went well!
2912 public static function mkdir($newFolder) {
2913 $result = @mkdir
($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2915 self
::fixPermissions($newFolder);
2921 * Creates a directory - including parent directories if necessary and
2922 * sets permissions on newly created directories.
2924 * @param string $directory Target directory to create. Must a have trailing slash
2925 * if second parameter is given!
2926 * Example: "/root/typo3site/typo3temp/foo/"
2927 * @param string $deepDirectory Directory to create. This second parameter
2928 * is kept for backwards compatibility since 4.6 where this method
2929 * was split into a base directory and a deep directory to be created.
2930 * Example: "xx/yy/" which creates "/root/typo3site/xx/yy/" if $directory is "/root/typo3site/"
2932 * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
2933 * @throws \RuntimeException If directory could not be created
2935 public static function mkdir_deep($directory, $deepDirectory = '') {
2936 if (!is_string($directory)) {
2937 throw new \
InvalidArgumentException(
2938 'The specified directory is of type "' . gettype($directory) . '" but a string is expected.',
2942 if (!is_string($deepDirectory)) {
2943 throw new \
InvalidArgumentException(
2944 'The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.',
2949 $fullPath = $directory . $deepDirectory;
2950 if (!is_dir($fullPath) && strlen($fullPath) > 0) {
2951 $firstCreatedPath = self
::createDirectoryPath($fullPath);
2952 if ($firstCreatedPath !== '') {
2953 self
::fixPermissions($firstCreatedPath, TRUE);
2959 * Creates directories for the specified paths if they do not exist. This
2960 * functions sets proper permission mask but does not set proper user and
2964 * @param string $fullDirectoryPath
2965 * @return string Path to the the first created directory in the hierarchy
2966 * @see t3lib_div::mkdir_deep
2967 * @throws \RuntimeException If directory could not be created
2969 protected static function createDirectoryPath($fullDirectoryPath) {
2970 $currentPath = $fullDirectoryPath;
2971 $firstCreatedPath = '';
2972 $permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']);
2973 if (!@is_dir
($currentPath)) {
2975 $firstCreatedPath = $currentPath;
2976 $separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR
);
2977 $currentPath = substr($currentPath, 0, $separatorPosition);
2978 } while (!is_dir($currentPath) && $separatorPosition !== FALSE);
2980 $result = @mkdir
($fullDirectoryPath, $permissionMask, TRUE);
2982 throw new \
RuntimeException('Could not create directory!', 1170251400);
2985 return $firstCreatedPath;
2989 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2991 * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2992 * @param boolean $removeNonEmpty Allow deletion of non-empty directories
2993 * @return boolean TRUE if @rmdir went well!
2995 public static function rmdir($path, $removeNonEmpty = FALSE) {
2997 $path = preg_replace('|/$|', '', $path); // Remove trailing slash
2999 if (file_exists($path)) {
3002 if (is_dir($path)) {
3003 if ($removeNonEmpty == TRUE && $handle = opendir($path)) {
3004 while ($OK && FALSE !== ($file = readdir($handle))) {
3005 if ($file == '.' ||
$file == '..') {
3008 $OK = self
::rmdir($path . '/' . $file, $removeNonEmpty);
3016 } else { // If $dirname is a file, simply remove it
3017 $OK = unlink($path);
3027 * Returns an array with the names of folders in a specific path
3028 * Will return 'error' (string) if there were an error with reading directory content.
3030 * @param string $path Path to list directories from
3031 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
3033 public static function get_dirs($path) {
3035 if (is_dir($path)) {
3036 $dir = scandir($path);
3038 foreach ($dir as $entry) {
3039 if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
3051 * Returns an array with the names of files in a specific path
3053 * @param string $path Is the path to the file
3054 * @param string $extensionList is the comma list of extensions to read only (blank = all)
3055 * @param boolean $prependPath If set, then the path is prepended the file names. Otherwise only the file names are returned in the array
3056 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
3058 * @param string $excludePattern A comma separated list of file names to exclude, no wildcards
3059 * @return array Array of the files found
3061 public static function getFilesInDir($path, $extensionList = '', $prependPath = FALSE, $order = '', $excludePattern = '') {
3063 // Initialize variables:
3064 $filearray = array();
3065 $sortarray = array();
3066 $path = rtrim($path, '/');
3068 // Find files+directories:
3069 if (@is_dir
($path)) {
3070 $extensionList = strtolower($extensionList);
3072 if (is_object($d)) {
3073 while ($entry = $d->read()) {
3074 if (@is_file
($path . '/' . $entry)) {
3075 $fI = pathinfo($entry);
3076 $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)
3077 if ((!strlen($extensionList) || self
::inList($extensionList, strtolower($fI['extension']))) && (!strlen($excludePattern) ||
!preg_match('/^' . $excludePattern . '$/', $entry))) {
3078 $filearray[$key] = ($prependPath ?
$path . '/' : '') . $entry;
3079 if ($order == 'mtime') {
3080 $sortarray[$key] = filemtime($path . '/' . $entry);
3083 $sortarray[$key] = $entry;
3090 return 'error opening path: "' . $path . '"';
3098 foreach ($sortarray as $k => $v) {
3099 $newArr[$k] = $filearray[$k];
3101 $filearray = $newArr;
3110 * Recursively gather all files and folders of a path.
3112 * @param array $fileArr Empty input array (will have files added to it)
3113 * @param string $path The path to read recursively from (absolute) (include trailing slash!)
3114 * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
3115 * @param boolean $regDirs If set, directories are also included in output.
3116 * @param integer $recursivityLevels The number of levels to dig down...
3117 * @param string $excludePattern regex pattern of files/directories to exclude
3118 * @return array An array with the found files/directories.
3120 public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = FALSE, $recursivityLevels = 99, $excludePattern = '') {
3124 $fileArr = array_merge($fileArr, self
::getFilesInDir($path, $extList, 1, 1, $excludePattern));
3126 $dirs = self
::get_dirs($path);
3127 if (is_array($dirs) && $recursivityLevels > 0) {
3128 foreach ($dirs as $subdirs) {
3129 if ((string) $subdirs != '' && (!strlen($excludePattern) ||
!preg_match('/^' . $excludePattern . '$/', $subdirs))) {
3130 $fileArr = self
::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
3138 * Removes the absolute part of all files/folders in fileArr
3140 * @param array $fileArr: The file array to remove the prefix from
3141 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
3142 * @return array The input $fileArr processed.
3144 public static function removePrefixPathFromList(array $fileArr, $prefixToRemove) {
3145 foreach ($fileArr as $k => &$absFileRef) {
3146 if (self
::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
3147 $absFileRef = substr($absFileRef, strlen($prefixToRemove));
3149 return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
3157 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
3159 * @param string $theFile File path to process
3162 public static function fixWindowsFilePath($theFile) {
3163 return str_replace('//', '/', str_replace('\\', '/', $theFile));
3167 * Resolves "../" sections in the input path string.
3168 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
3170 * @param string $pathStr File path in which "/../" is resolved
3173 public static function resolveBackPath($pathStr) {
3174 $parts = explode('/', $pathStr);
3177 foreach ($parts as $pV) {
3190 return implode('/', $output);
3194 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
3195 * - If already having a scheme, nothing is prepended
3196 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
3197 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
3199 * @param string $path URL / path to prepend full URL addressing to.
3202 public static function locationHeaderUrl($path) {
3203 $uI = parse_url($path);
3204 if (substr($path, 0, 1) == '/') { // relative to HOST
3205 $path = self
::getIndpEnv('TYPO3_REQUEST_HOST') . $path;