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('utf-8', $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 6.0 - 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 6.0 - 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 6.0 - 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 6.1 - 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 * @param string $additionalSecret additionalSecret to prevent hmac beeing used in a different context
937 * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
939 public static function hmac($input, $additionalSecret = '') {
940 $hashAlgorithm = 'sha1';
943 $secret = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . $additionalSecret;
944 if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
945 $hmac = hash_hmac($hashAlgorithm, $input, $secret);
948 $opad = str_repeat(chr(0x5C), $hashBlocksize);
950 $ipad = str_repeat(chr(0x36), $hashBlocksize);
951 if (strlen($secret) > $hashBlocksize) {
952 // keys longer than block size are shorten
953 $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $secret)), $hashBlocksize, chr(0));
955 // keys shorter than block size are zero-padded
956 $key = str_pad($secret, $hashBlocksize, chr(0));
958 $hmac = call_user_func($hashAlgorithm, ($key ^
$opad) . pack('H*', call_user_func($hashAlgorithm, ($key ^
$ipad) . $input)));
964 * Takes comma-separated lists and arrays and removes all duplicates
965 * If a value in the list is trim(empty), the value is ignored.
967 * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays.
968 * @param mixed $secondParameter: Dummy field, which if set will show a warning!
969 * @return string Returns the list without any duplicates of values, space around values are trimmed
971 public static function uniqueList($in_list, $secondParameter = NULL) {
972 if (is_array($in_list)) {
973 throw new InvalidArgumentException(
974 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!',
978 if (isset($secondParameter)) {
979 throw new InvalidArgumentException(
980 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!',
985 return implode(',', array_unique(self
::trimExplode(',', $in_list, 1)));
989 * Splits a reference to a file in 5 parts
991 * @param string $fileref Filename/filepath to be analysed
992 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
994 public static function split_fileref($fileref) {
996 if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
997 $info['path'] = $reg[1];
998 $info['file'] = $reg[2];
1001 $info['file'] = $fileref;
1005 if (!is_dir($fileref) && preg_match('/(.*)\.([^\.]*$)/', $info['file'], $reg)) {
1006 $info['filebody'] = $reg[1];
1007 $info['fileext'] = strtolower($reg[2]);
1008 $info['realFileext'] = $reg[2];
1010 $info['filebody'] = $info['file'];
1011 $info['fileext'] = '';
1018 * Returns the directory part of a path without trailing slash
1019 * If there is no dir-part, then an empty string is returned.
1022 * '/dir1/dir2/script.php' => '/dir1/dir2'
1023 * '/dir1/' => '/dir1'
1024 * 'dir1/script.php' => 'dir1'
1025 * 'd/script.php' => 'd'
1026 * '/script.php' => ''
1029 * @param string $path Directory name / path
1030 * @return string Processed input value. See function description.
1032 public static function dirname($path) {
1033 $p = self
::revExplode('/', $path, 2);
1034 return count($p) == 2 ?
$p[0] : '';
1038 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
1040 * @param string $color A hexadecimal color code, #xxxxxx
1041 * @param integer $R Offset value 0-255
1042 * @param integer $G Offset value 0-255
1043 * @param integer $B Offset value 0-255
1044 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1045 * @see modifyHTMLColorAll()
1047 public static function modifyHTMLColor($color, $R, $G, $B) {
1048 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
1049 $nR = t3lib_utility_Math
::forceIntegerInRange(hexdec(substr($color, 1, 2)) +
$R, 0, 255);
1050 $nG = t3lib_utility_Math
::forceIntegerInRange(hexdec(substr($color, 3, 2)) +
$G, 0, 255);
1051 $nB = t3lib_utility_Math
::forceIntegerInRange(hexdec(substr($color, 5, 2)) +
$B, 0, 255);
1053 substr('0' . dechex($nR), -2) .
1054 substr('0' . dechex($nG), -2) .
1055 substr('0' . dechex($nB), -2);
1059 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
1061 * @param string $color A hexadecimal color code, #xxxxxx
1062 * @param integer $all Offset value 0-255 for all three channels.
1063 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1064 * @see modifyHTMLColor()
1066 public static function modifyHTMLColorAll($color, $all) {
1067 return self
::modifyHTMLColor($color, $all, $all, $all);
1071 * Tests if the input can be interpreted as integer.
1073 * @param mixed $var Any input variable to test
1074 * @return boolean Returns TRUE if string is an integer
1075 * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - Use t3lib_utility_Math::canBeInterpretedAsInteger() instead
1077 public static function testInt($var) {
1078 self
::logDeprecatedFunction();
1080 return t3lib_utility_Math
::canBeInterpretedAsInteger($var);
1084 * Returns TRUE if the first part of $str matches the string $partStr
1086 * @param string $str Full string to check
1087 * @param string $partStr Reference string which must be found as the "first part" of the full string
1088 * @return boolean TRUE if $partStr was found to be equal to the first part of $str
1090 public static function isFirstPartOfStr($str, $partStr) {
1091 return $partStr != '' && strpos((string) $str, (string) $partStr, 0) === 0;
1095 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
1097 * @param integer $sizeInBytes Number of bytes to format.
1098 * @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)
1099 * @return string Formatted representation of the byte number, for output.
1101 public static function formatSize($sizeInBytes, $labels = '') {
1104 if (strlen($labels) == 0) {
1105 $labels = ' | K| M| G';
1107 $labels = str_replace('"', '', $labels);
1109 $labelArr = explode('|', $labels);
1112 if ($sizeInBytes > 900) {
1113 if ($sizeInBytes > 900000000) { // GB
1114 $val = $sizeInBytes / (1024 * 1024 * 1024);
1115 return number_format($val, (($val < 20) ?
1 : 0), '.', '') . $labelArr[3];
1117 elseif ($sizeInBytes > 900000) { // MB
1118 $val = $sizeInBytes / (1024 * 1024);
1119 return number_format($val, (($val < 20) ?
1 : 0), '.', '') . $labelArr[2];
1121 $val = $sizeInBytes / (1024);
1122 return number_format($val, (($val < 20) ?
1 : 0), '.', '') . $labelArr[1];
1125 return $sizeInBytes . $labelArr[0];
1130 * Returns microtime input to milliseconds
1132 * @param string $microtime Microtime
1133 * @return integer Microtime input string converted to an integer (milliseconds)
1135 public static function convertMicrotime($microtime) {
1136 $parts = explode(' ', $microtime);
1137 return round(($parts[0] +
$parts[1]) * 1000);
1141 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
1143 * @param string $string Input string, eg "123 + 456 / 789 - 4"
1144 * @param string $operators Operators to split by, typically "/+-*"
1145 * @return array Array with operators and operands separated.
1146 * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
1148 public static function splitCalc($string, $operators) {
1152 $valueLen = strcspn($string, $operators);
1153 $value = substr($string, 0, $valueLen);
1154 $res[] = Array($sign, trim($value));
1155 $sign = substr($string, $valueLen, 1);
1156 $string = substr($string, $valueLen +
1);
1163 * Calculates the input by +,-,*,/,%,^ with priority to + and -
1165 * @param string $string Input string, eg "123 + 456 / 789 - 4"
1166 * @return integer Calculated value. Or error string.
1167 * @see calcParenthesis()
1168 * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - Use t3lib_utility_Math::calculateWithPriorityToAdditionAndSubtraction() instead
1170 public static function calcPriority($string) {
1171 self
::logDeprecatedFunction();
1173 return t3lib_utility_Math
::calculateWithPriorityToAdditionAndSubtraction($string);
1177 * Calculates the input with parenthesis levels
1179 * @param string $string Input string, eg "(123 + 456) / 789 - 4"
1180 * @return integer Calculated value. Or error string.
1181 * @see calcPriority(), tslib_cObj::stdWrap()
1182 * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - Use t3lib_utility_Math::calculateWithParentheses() instead
1184 public static function calcParenthesis($string) {
1185 self
::logDeprecatedFunction();
1187 return t3lib_utility_Math
::calculateWithParentheses($string);
1191 * Inverse version of htmlspecialchars()
1193 * @param string $value Value where >, <, " and & should be converted to regular chars.
1194 * @return string Converted result.
1196 public static function htmlspecialchars_decode($value) {
1197 $value = str_replace('>', '>', $value);
1198 $value = str_replace('<', '<', $value);
1199 $value = str_replace('"', '"', $value);
1200 $value = str_replace('&', '&', $value);
1205 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1207 * @param string $str String which contains eg. "&amp;" which should stay "&". Or "&#1234;" to "Ӓ". Or "&#x1b;" to ""
1208 * @return string Converted result.
1210 public static function deHSCentities($str) {
1211 return preg_replace('/&([#[:alnum:]]*;)/', '&\1', $str);
1215 * This function is used to escape any ' -characters when transferring text to JavaScript!
1217 * @param string $string String to escape
1218 * @param boolean $extended If set, also backslashes are escaped.
1219 * @param string $char The character to escape, default is ' (single-quote)
1220 * @return string Processed input string
1222 public static function slashJS($string, $extended = FALSE, $char = "'") {
1224 $string = str_replace("\\", "\\\\", $string);
1226 return str_replace($char, "\\" . $char, $string);
1230 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1231 * Useful when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1233 * @param string $str String to raw-url-encode with spaces preserved
1234 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1236 public static function rawUrlEncodeJS($str) {
1237 return str_replace('%20', ' ', rawurlencode($str));
1241 * rawurlencode which preserves "/" chars
1242 * Useful when file paths should keep the "/" chars, but have all other special chars encoded.
1244 * @param string $str Input string
1245 * @return string Output string
1247 public static function rawUrlEncodeFP($str) {
1248 return str_replace('%2F', '/', rawurlencode($str));
1252 * Checking syntax of input email address
1254 * @param string $email Input string to evaluate
1255 * @return boolean Returns TRUE if the $email address (input string) is valid
1257 public static function validEmail($email) {
1258 // enforce maximum length to prevent libpcre recursion crash bug #52929 in PHP
1259 // fixed in PHP 5.3.4; length restriction per SMTP RFC 2821
1260 if (strlen($email) > 320) {
1263 require_once(PATH_typo3
. 'contrib/idna/idna_convert.class.php');
1264 $IDN = new idna_convert(array('idn_version' => 2008));
1266 return (filter_var($IDN->encode($email), FILTER_VALIDATE_EMAIL
) !== FALSE);
1270 * Checks if current e-mail sending method does not accept recipient/sender name
1271 * in a call to PHP mail() function. Windows version of mail() and mini_sendmail
1272 * program are known not to process such input correctly and they cause SMTP
1273 * errors. This function will return TRUE if current mail sending method has
1274 * problem with recipient name in recipient/sender argument for mail().
1276 * TODO: 4.3 should have additional configuration variable, which is combined
1277 * by || with the rest in this function.
1279 * @return boolean TRUE if mail() does not accept recipient name
1281 public static function isBrokenEmailEnvironment() {
1282 return TYPO3_OS
== 'WIN' ||
(FALSE !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
1286 * Changes from/to arguments for mail() function to work in any environment.
1288 * @param string $address Address to adjust
1289 * @return string Adjusted address
1290 * @see t3lib_::isBrokenEmailEnvironment()
1292 public static function normalizeMailAddress($address) {
1293 if (self
::isBrokenEmailEnvironment() && FALSE !== ($pos1 = strrpos($address, '<'))) {
1294 $pos2 = strpos($address, '>', $pos1);
1295 $address = substr($address, $pos1 +
1, ($pos2 ?
$pos2 : strlen($address)) - $pos1 - 1);
1301 * Formats a string for output between <textarea>-tags
1302 * All content outputted in a textarea form should be passed through this function
1303 * 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!
1305 * @param string $content Input string to be formatted.
1306 * @return string Formatted for <textarea>-tags
1308 public static function formatForTextarea($content) {
1309 return LF
. htmlspecialchars($content);
1313 * Converts string to uppercase
1314 * The function converts all Latin characters (a-z, but no accents, etc) to
1315 * uppercase. It is safe for all supported character sets (incl. utf-8).
1316 * Unlike strtoupper() it does not honour the locale.
1318 * @param string $str Input string
1319 * @return string Uppercase String
1321 public static function strtoupper($str) {
1322 return strtr((string) $str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
1326 * Converts string to lowercase
1327 * The function converts all Latin characters (A-Z, but no accents, etc) to
1328 * lowercase. It is safe for all supported character sets (incl. utf-8).
1329 * Unlike strtolower() it does not honour the locale.
1331 * @param string $str Input string
1332 * @return string Lowercase String
1334 public static function strtolower($str) {
1335 return strtr((string) $str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1339 * Returns a string of highly randomized bytes (over the full 8-bit range).
1341 * Note: Returned values are not guaranteed to be crypto-safe,
1342 * most likely they are not, depending on the used retrieval method.
1344 * @param integer $bytesToReturn Number of characters (bytes) to return
1345 * @return string Random Bytes
1346 * @see http://bugs.php.net/bug.php?id=52523
1347 * @see http://www.php-security.org/2010/05/09/mops-submission-04-generating-unpredictable-session-ids-and-hashes/index.html
1349 public static function generateRandomBytes($bytesToReturn) {
1350 // Cache 4k of the generated bytestream.
1352 $bytesToGenerate = max(4096, $bytesToReturn);
1354 // if we have not enough random bytes cached, we generate new ones
1355 if (!isset($bytes{$bytesToReturn - 1})) {
1356 if (TYPO3_OS
=== 'WIN') {
1357 // Openssl seems to be deadly slow on Windows, so try to use mcrypt
1358 // Windows PHP versions have a bug when using urandom source (see #24410)
1359 $bytes .= self
::generateRandomBytesMcrypt($bytesToGenerate, MCRYPT_RAND
);
1361 // Try to use native PHP functions first, precedence has openssl
1362 $bytes .= self
::generateRandomBytesOpenSsl($bytesToGenerate);
1364 if (!isset($bytes{$bytesToReturn - 1})) {
1365 $bytes .= self
::generateRandomBytesMcrypt($bytesToGenerate, MCRYPT_DEV_URANDOM
);
1368 // If openssl and mcrypt failed, try /dev/urandom
1369 if (!isset($bytes{$bytesToReturn - 1})) {
1370 $bytes .= self
::generateRandomBytesUrandom($bytesToGenerate);
1374 // Fall back if other random byte generation failed until now
1375 if (!isset($bytes{$bytesToReturn - 1})) {
1376 $bytes .= self
::generateRandomBytesFallback($bytesToReturn);
1380 // get first $bytesToReturn and remove it from the byte cache
1381 $output = substr($bytes, 0, $bytesToReturn);
1382 $bytes = substr($bytes, $bytesToReturn);
1388 * Generate random bytes using openssl if available
1390 * @param string $bytesToGenerate
1393 protected static function generateRandomBytesOpenSsl($bytesToGenerate) {
1394 if (!function_exists('openssl_random_pseudo_bytes')) {
1398 return (string) openssl_random_pseudo_bytes($bytesToGenerate, $isStrong);
1402 * Generate random bytes using mcrypt if available
1404 * @param $bytesToGenerate
1405 * @param $randomSource
1408 protected static function generateRandomBytesMcrypt($bytesToGenerate, $randomSource) {
1409 if (!function_exists('mcrypt_create_iv')) {
1412 return (string) @mcrypt_create_iv
($bytesToGenerate, $randomSource);
1416 * Read random bytes from /dev/urandom if it is accessible
1418 * @param $bytesToGenerate
1421 protected static function generateRandomBytesUrandom($bytesToGenerate) {
1423 $fh = @fopen
('/dev/urandom', 'rb');
1425 // PHP only performs buffered reads, so in reality it will always read
1426 // at least 4096 bytes. Thus, it costs nothing extra to read and store
1427 // that much so as to speed any additional invocations.
1428 $bytes = fread($fh, $bytesToGenerate);
1436 * Generate pseudo random bytes as last resort
1438 * @param $bytesToReturn
1441 protected static function generateRandomBytesFallback($bytesToReturn) {
1443 // We initialize with somewhat random.
1444 $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . base_convert(memory_get_usage() %
pow(10, 6), 10, 2) . microtime() . uniqid('') . getmypid();
1445 while (!isset($bytes{$bytesToReturn - 1})) {
1446 $randomState = sha1(microtime() . mt_rand() . $randomState);
1447 $bytes .= sha1(mt_rand() . $randomState, TRUE);
1453 * Returns a hex representation of a random byte string.
1455 * @param integer $count Number of hex characters to return
1456 * @return string Random Bytes
1458 public static function getRandomHexString($count) {
1459 return substr(bin2hex(self
::generateRandomBytes(intval(($count +
1) / 2))), 0, $count);
1463 * Returns a given string with underscores as UpperCamelCase.
1464 * Example: Converts blog_example to BlogExample
1466 * @param string $string: String to be converted to camel case
1467 * @return string UpperCamelCasedWord
1469 public static function underscoredToUpperCamelCase($string) {
1470 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self
::strtolower($string))));
1471 return $upperCamelCase;
1475 * Returns a given string with underscores as lowerCamelCase.
1476 * Example: Converts minimal_value to minimalValue
1478 * @param string $string: String to be converted to camel case
1479 * @return string lowerCamelCasedWord
1481 public static function underscoredToLowerCamelCase($string) {
1482 $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self
::strtolower($string))));
1483 $lowerCamelCase = self
::lcfirst($upperCamelCase);
1484 return $lowerCamelCase;
1488 * Returns a given CamelCasedString as an lowercase string with underscores.
1489 * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
1491 * @param string $string String to be converted to lowercase underscore
1492 * @return string lowercase_and_underscored_string
1494 public static function camelCaseToLowerCaseUnderscored($string) {
1495 return self
::strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
1499 * Converts the first char of a string to lowercase if it is a latin character (A-Z).
1500 * Example: Converts "Hello World" to "hello World"
1502 * @param string $string The string to be used to lowercase the first character
1503 * @return string The string with the first character as lowercase
1505 public static function lcfirst($string) {
1506 return self
::strtolower(substr($string, 0, 1)) . substr($string, 1);
1510 * Checks if a given string is a Uniform Resource Locator (URL).
1512 * @param string $url The URL to be validated
1513 * @return boolean Whether the given URL is valid
1515 public static function isValidUrl($url) {
1516 require_once(PATH_typo3
. 'contrib/idna/idna_convert.class.php');
1517 $IDN = new idna_convert(array('idn_version' => 2008));
1519 return (filter_var($IDN->encode($url), FILTER_VALIDATE_URL
, FILTER_FLAG_SCHEME_REQUIRED
) !== FALSE);
1523 /*************************
1527 *************************/
1530 * Check if an string item exists in an array.
1531 * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
1533 * Comparison to PHP in_array():
1534 * -> $array = array(0, 1, 2, 3);
1535 * -> variant_a := t3lib_div::inArray($array, $needle)
1536 * -> variant_b := in_array($needle, $array)
1537 * -> variant_c := in_array($needle, $array, TRUE)
1538 * +---------+-----------+-----------+-----------+
1539 * | $needle | variant_a | variant_b | variant_c |
1540 * +---------+-----------+-----------+-----------+
1541 * | '1a' | FALSE | TRUE | FALSE |
1542 * | '' | FALSE | TRUE | FALSE |
1543 * | '0' | TRUE | TRUE | FALSE |
1544 * | 0 | TRUE | TRUE | TRUE |
1545 * +---------+-----------+-----------+-----------+
1547 * @param array $in_array one-dimensional array of items
1548 * @param string $item item to check for
1549 * @return boolean TRUE if $item is in the one-dimensional array $in_array
1551 public static function inArray(array $in_array, $item) {
1552 foreach ($in_array as $val) {
1553 if (!is_array($val) && !strcmp($val, $item)) {
1561 * Explodes a $string delimited by $delim and passes each item in the array through intval().
1562 * Corresponds to t3lib_div::trimExplode(), but with conversion to integers for all values.
1564 * @param string $delimiter Delimiter string to explode with
1565 * @param string $string The string to explode
1566 * @param boolean $onlyNonEmptyValues If set, all empty values (='') will NOT be set in output
1567 * @param integer $limit If positive, the result will contain a maximum of limit elements,
1568 * if negative, all components except the last -limit are returned,
1569 * if zero (default), the result is not limited at all
1570 * @return array Exploded values, all converted to integers
1572 public static function intExplode($delimiter, $string, $onlyNonEmptyValues = FALSE, $limit = 0) {
1573 $explodedValues = self
::trimExplode($delimiter, $string, $onlyNonEmptyValues, $limit);
1574 return array_map('intval', $explodedValues);
1578 * Reverse explode which explodes the string counting from behind.
1579 * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1581 * @param string $delimiter Delimiter string to explode with
1582 * @param string $string The string to explode
1583 * @param integer $count Number of array entries
1584 * @return array Exploded values
1586 public static function revExplode($delimiter, $string, $count = 0) {
1587 $explodedValues = explode($delimiter, strrev($string), $count);
1588 $explodedValues = array_map('strrev', $explodedValues);
1589 return array_reverse($explodedValues);
1593 * Explodes a string and trims all values for whitespace in the ends.
1594 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1596 * @param string $delim Delimiter string to explode with
1597 * @param string $string The string to explode
1598 * @param boolean $removeEmptyValues If set, all empty values will be removed in output
1599 * @param integer $limit If positive, the result will contain a maximum of
1600 * $limit elements, if negative, all components except
1601 * the last -$limit are returned, if zero (default),
1602 * the result is not limited at all. Attention though
1603 * that the use of this parameter can slow down this
1605 * @return array Exploded values
1607 public static function trimExplode($delim, $string, $removeEmptyValues = FALSE, $limit = 0) {
1608 $explodedValues = explode($delim, $string);
1610 $result = array_map('trim', $explodedValues);
1612 if ($removeEmptyValues) {
1614 foreach ($result as $value) {
1615 if ($value !== '') {
1624 $result = array_slice($result, 0, $limit);
1625 } elseif (count($result) > $limit) {
1626 $lastElements = array_slice($result, $limit - 1);
1627 $result = array_slice($result, 0, $limit - 1);
1628 $result[] = implode($delim, $lastElements);
1636 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1638 * @param array $array Array containing the values
1639 * @param string $cmpValue Value to search for and if found remove array entry where found.
1640 * @return array Output array with entries removed if search string is found
1642 public static function removeArrayEntryByValue(array $array, $cmpValue) {
1643 foreach ($array as $k => $v) {
1645 $array[$k] = self
::removeArrayEntryByValue($v, $cmpValue);
1646 } elseif (!strcmp($v, $cmpValue)) {
1654 * Filters an array to reduce its elements to match the condition.
1655 * The values in $keepItems can be optionally evaluated by a custom callback function.
1657 * Example (arguments used to call this function):
1659 * array('aa' => array('first', 'second'),
1660 * array('bb' => array('third', 'fourth'),
1661 * array('cc' => array('fifth', 'sixth'),
1663 * $keepItems = array('third');
1664 * $getValueFunc = create_function('$value', 'return $value[0];');
1668 * array('bb' => array('third', 'fourth'),
1671 * @param array $array: The initial array to be filtered/reduced
1672 * @param mixed $keepItems: The items which are allowed/kept in the array - accepts array or csv string
1673 * @param string $getValueFunc: (optional) Unique function name set by create_function() used to get the value to keep
1674 * @return array The filtered/reduced array with the kept items
1676 public static function keepItemsInArray(array $array, $keepItems, $getValueFunc = NULL) {
1678 // Convert strings to arrays:
1679 if (is_string($keepItems)) {
1680 $keepItems = self
::trimExplode(',', $keepItems);
1682 // create_function() returns a string:
1683 if (!is_string($getValueFunc)) {
1684 $getValueFunc = NULL;
1686 // Do the filtering:
1687 if (is_array($keepItems) && count($keepItems)) {
1688 foreach ($array as $key => $value) {
1689 // Get the value to compare by using the callback function:
1690 $keepValue = (isset($getValueFunc) ?
$getValueFunc($value) : $value);
1691 if (!in_array($keepValue, $keepItems)) {
1692 unset($array[$key]);
1701 * Implodes a multidim-array into GET-parameters (eg. ¶m[key][key2]=value2¶m[key][key3]=value3)
1703 * @param string $name Name prefix for entries. Set to blank if you wish none.
1704 * @param array $theArray The (multidimensional) array to implode
1705 * @param string $str (keep blank)
1706 * @param boolean $skipBlank If set, parameters which were blank strings would be removed.
1707 * @param boolean $rawurlencodeParamName If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1708 * @return string Imploded result, fx. ¶m[key][key2]=value2¶m[key][key3]=value3
1709 * @see explodeUrl2Array()
1711 public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = FALSE, $rawurlencodeParamName = FALSE) {
1712 foreach ($theArray as $Akey => $AVal) {
1713 $thisKeyName = $name ?
$name . '[' . $Akey . ']' : $Akey;
1714 if (is_array($AVal)) {
1715 $str = self
::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
1717 if (!$skipBlank ||
strcmp($AVal, '')) {
1718 $str .= '&' . ($rawurlencodeParamName ?
rawurlencode($thisKeyName) : $thisKeyName) .
1719 '=' . rawurlencode($AVal);
1727 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1729 * @param string $string GETvars string
1730 * @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())
1731 * @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!
1732 * @see implodeArrayForUrl()
1734 public static function explodeUrl2Array($string, $multidim = FALSE) {
1737 parse_str($string, $output);
1739 $p = explode('&', $string);
1740 foreach ($p as $v) {
1742 list($pK, $pV) = explode('=', $v, 2);
1743 $output[rawurldecode($pK)] = rawurldecode($pV);
1751 * Returns an array with selected keys from incoming data.
1752 * (Better read source code if you want to find out...)
1754 * @param string $varList List of variable/key names
1755 * @param array $getArray Array from where to get values based on the keys in $varList
1756 * @param boolean $GPvarAlt If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1757 * @return array Output array with selected variables.
1759 public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = TRUE) {
1760 $keys = self
::trimExplode(',', $varList, 1);
1762 foreach ($keys as $v) {
1763 if (isset($getArray[$v])) {
1764 $outArr[$v] = $getArray[$v];
1765 } elseif ($GPvarAlt) {
1766 $outArr[$v] = self
::_GP($v);
1774 * This function traverses a multidimensional array and adds slashes to the values.
1775 * NOTE that the input array is and argument by reference.!!
1776 * Twin-function to stripSlashesOnArray
1778 * @param array $theArray Multidimensional input array, (REFERENCE!)
1781 public static function addSlashesOnArray(array &$theArray) {
1782 foreach ($theArray as &$value) {
1783 if (is_array($value)) {
1784 self
::addSlashesOnArray($value);
1786 $value = addslashes($value);
1795 * This function traverses a multidimensional array and strips slashes to the values.
1796 * NOTE that the input array is and argument by reference.!!
1797 * Twin-function to addSlashesOnArray
1799 * @param array $theArray Multidimensional input array, (REFERENCE!)
1802 public static function stripSlashesOnArray(array &$theArray) {
1803 foreach ($theArray as &$value) {
1804 if (is_array($value)) {
1805 self
::stripSlashesOnArray($value);
1807 $value = stripslashes($value);
1815 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1817 * @param array $arr Multidimensional input array
1818 * @param string $cmd "add" or "strip", depending on usage you wish.
1821 public static function slashArray(array $arr, $cmd) {
1822 if ($cmd == 'strip') {
1823 self
::stripSlashesOnArray($arr);
1825 if ($cmd == 'add') {
1826 self
::addSlashesOnArray($arr);
1832 * Rename Array keys with a given mapping table
1834 * @param array $array Array by reference which should be remapped
1835 * @param array $mappingTable Array with remap information, array/$oldKey => $newKey)
1837 public static function remapArrayKeys(&$array, $mappingTable) {
1838 if (is_array($mappingTable)) {
1839 foreach ($mappingTable as $old => $new) {
1840 if ($new && isset($array[$old])) {
1841 $array[$new] = $array[$old];
1842 unset ($array[$old]);
1850 * Merges two arrays recursively and "binary safe" (integer keys are
1851 * overridden as well), overruling similar values in the first array
1852 * ($arr0) with the values of the second array ($arr1)
1853 * In case of identical keys, ie. keeping the values of the second.
1855 * @param array $arr0 First array
1856 * @param array $arr1 Second array, overruling the first array
1857 * @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.
1858 * @param boolean $includeEmptyValues If set, values from $arr1 will overrule if they are empty or zero. Default: TRUE
1859 * @param boolean $enableUnsetFeature If set, special values "__UNSET" can be used in the second array in order to unset array keys in the resulting array.
1860 * @return array Resulting array where $arr1 values has overruled $arr0 values
1862 public static function array_merge_recursive_overrule(array $arr0, array $arr1, $notAddKeys = FALSE, $includeEmptyValues = TRUE, $enableUnsetFeature = TRUE) {
1863 foreach ($arr1 as $key => $val) {
1864 if ($enableUnsetFeature && $val === '__UNSET') {
1868 if (is_array($arr0[$key])) {
1869 if (is_array($arr1[$key])) {
1870 $arr0[$key] = self
::array_merge_recursive_overrule(
1874 $includeEmptyValues,
1879 (!$notAddKeys ||
isset($arr0[$key])) &&
1880 ($includeEmptyValues ||
$val)
1891 * 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.
1893 * @param array $arr1 First array
1894 * @param array $arr2 Second array
1895 * @return array Merged result.
1897 public static function array_merge(array $arr1, array $arr2) {
1898 return $arr2 +
$arr1;
1902 * Filters keys off from first array that also exist in second array. Comparison is done by keys.
1903 * This method is a recursive version of php array_diff_assoc()
1905 * @param array $array1 Source array
1906 * @param array $array2 Reduce source array by this array
1907 * @return array Source array reduced by keys also present in second array
1909 public static function arrayDiffAssocRecursive(array $array1, array $array2) {
1910 $differenceArray = array();
1911 foreach ($array1 as $key => $value) {
1912 if (!array_key_exists($key, $array2)) {
1913 $differenceArray[$key] = $value;
1914 } elseif (is_array($value)) {
1915 if (is_array($array2[$key])) {
1916 $differenceArray[$key] = self
::arrayDiffAssocRecursive($value, $array2[$key]);
1921 return $differenceArray;
1925 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1927 * @param array $row Input array of values
1928 * @param string $delim Delimited, default is comma
1929 * @param string $quote Quote-character to wrap around the values.
1930 * @return string A single line of CSV
1932 public static function csvValues(array $row, $delim = ',', $quote = '"') {
1934 foreach ($row as $value) {
1935 $out[] = str_replace($quote, $quote . $quote, $value);
1937 $str = $quote . implode($quote . $delim . $quote, $out) . $quote;
1942 * Removes dots "." from end of a key identifier of TypoScript styled array.
1943 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1945 * @param array $ts: TypoScript configuration array
1946 * @return array TypoScript configuration array without dots at the end of all keys
1948 public static function removeDotsFromTS(array $ts) {
1950 foreach ($ts as $key => $value) {
1951 if (is_array($value)) {
1952 $key = rtrim($key, '.');
1953 $out[$key] = self
::removeDotsFromTS($value);
1955 $out[$key] = $value;
1962 * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
1964 * @param array $array array to be sorted recursively, passed by reference
1965 * @return boolean TRUE if param is an array
1967 public static function naturalKeySortRecursive(&$array) {
1968 if (!is_array($array)) {
1971 uksort($array, 'strnatcasecmp');
1972 foreach ($array as $key => $value) {
1973 self
::naturalKeySortRecursive($array[$key]);
1979 /*************************
1981 * HTML/XML PROCESSING
1983 *************************/
1986 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1987 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>')
1988 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1990 * @param string $tag HTML-tag string (or attributes only)
1991 * @return array Array with the attribute values.
1993 public static function get_tag_attributes($tag) {
1994 $components = self
::split_tag_attributes($tag);
1995 $name = ''; // attribute name is stored here
1997 $attributes = array();
1998 foreach ($components as $key => $val) {
1999 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
2002 $attributes[$name] = $val;
2006 if ($key = strtolower(preg_replace('/[^[:alnum:]_\:\-]/', '', $val))) {
2007 $attributes[$key] = '';
2020 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
2021 * Removes tag-name if found
2023 * @param string $tag HTML-tag string (or attributes only)
2024 * @return array Array with the attribute values.
2026 public static function split_tag_attributes($tag) {
2027 $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
2028 // Removes any > in the end of the string
2029 $tag_tmp = trim(rtrim($tag_tmp, '>'));
2032 while (strcmp($tag_tmp, '')) { // Compared with empty string instead , 030102
2033 $firstChar = substr($tag_tmp, 0, 1);
2034 if (!strcmp($firstChar, '"') ||
!strcmp($firstChar, "'")) {
2035 $reg = explode($firstChar, $tag_tmp, 3);
2037 $tag_tmp = trim($reg[2]);
2038 } elseif (!strcmp($firstChar, '=')) {
2040 $tag_tmp = trim(substr($tag_tmp, 1)); // Removes = chars.
2042 // There are '' around the value. We look for the next ' ' or '>'
2043 $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
2044 $value[] = trim($reg[0]);
2045 $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
2053 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
2055 * @param array $arr Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
2056 * @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!
2057 * @param boolean $dontOmitBlankAttribs If TRUE, don't check if values are blank. Default is to omit attributes with blank values.
2058 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
2060 public static function implodeAttributes(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
2063 foreach ($arr as $p => $v) {
2064 if (!isset($newArr[strtolower($p)])) {
2065 $newArr[strtolower($p)] = htmlspecialchars($v);
2071 foreach ($arr as $p => $v) {
2072 if (strcmp($v, '') ||
$dontOmitBlankAttribs) {
2073 $list[] = $p . '="' . $v . '"';
2076 return implode(' ', $list);
2080 * Wraps JavaScript code XHTML ready with <script>-tags
2081 * Automatic re-indenting of the JS code is done by using the first line as indent reference.
2082 * This is nice for indenting JS code with PHP code on the same level.
2084 * @param string $string JavaScript code
2085 * @param boolean $linebreak Wrap script element in line breaks? Default is TRUE.
2086 * @return string The wrapped JS code, ready to put into a XHTML page
2088 public static function wrapJS($string, $linebreak = TRUE) {
2089 if (trim($string)) {
2090 // <script wrapped in nl?
2091 $cr = $linebreak ? LF
: '';
2093 // remove nl from the beginning
2094 $string = preg_replace('/^\n+/', '', $string);
2095 // re-ident to one tab using the first line as reference
2097 if (preg_match('/^(\t+)/', $string, $match)) {
2098 $string = str_replace($match[1], TAB
, $string);
2100 $string = $cr . '<script type="text/javascript">
2106 return trim($string);
2111 * Parses XML input into a PHP array with associative keys
2113 * @param string $string XML data input
2114 * @param integer $depth Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
2115 * @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.
2116 * @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
2118 public static function xml2tree($string, $depth = 999) {
2119 $parser = xml_parser_create();
2123 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
2124 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
2125 xml_parse_into_struct($parser, $string, $vals, $index);
2127 if (xml_get_error_code($parser)) {
2128 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2130 xml_parser_free($parser);
2132 $stack = array(array());
2137 foreach ($vals as $key => $val) {
2138 $type = $val['type'];
2141 if ($type == 'open' ||
$type == 'complete') {
2142 $stack[$stacktop++
] = $tagi;
2144 if ($depth == $stacktop) {
2148 $tagi = array('tag' => $val['tag']);
2150 if (isset($val['attributes'])) {
2151 $tagi['attrs'] = $val['attributes'];
2153 if (isset($val['value'])) {
2154 $tagi['values'][] = $val['value'];
2158 if ($type == 'complete' ||
$type == 'close') {
2160 $tagi = $stack[--$stacktop];
2161 $oldtag = $oldtagi['tag'];
2162 unset($oldtagi['tag']);
2164 if ($depth == ($stacktop +
1)) {
2165 if ($key - $startPoint > 0) {
2166 $partArray = array_slice(
2169 $key - $startPoint - 1
2171 $oldtagi['XMLvalue'] = self
::xmlRecompileFromStructValArray($partArray);
2173 $oldtagi['XMLvalue'] = $oldtagi['values'][0];
2177 $tagi['ch'][$oldtag][] = $oldtagi;
2181 if ($type == 'cdata') {
2182 $tagi['values'][] = $val['value'];
2189 * Turns PHP array into XML. See array2xml()
2191 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2192 * @param string $docTag Alternative document tag. Default is "phparray".
2193 * @param array $options Options for the compilation. See array2xml() for description.
2194 * @param string $charset Forced charset to prologue
2195 * @return string An XML string made from the input content in the array.
2196 * @see xml2array(),array2xml()
2198 public static function array2xml_cs(array $array, $docTag = 'phparray', array $options = array(), $charset = '') {
2200 // Set default charset unless explicitly specified
2201 $charset = $charset ?
$charset : 'utf-8';
2204 return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF
.
2205 self
::array2xml($array, '', 0, $docTag, 0, $options);
2209 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
2211 * Converts a PHP array into an XML string.
2212 * The XML output is optimized for readability since associative keys are used as tag names.
2213 * 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.
2214 * Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats)
2215 * 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
2216 * 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.
2217 * 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!
2218 * 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...
2220 * @param array $array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2221 * @param string $NSprefix tag-prefix, eg. a namespace prefix like "T3:"
2222 * @param integer $level Current recursion level. Don't change, stay at zero!
2223 * @param string $docTag Alternative document tag. Default is "phparray".
2224 * @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
2225 * @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')
2226 * @param array $stackData Stack data. Don't touch.
2227 * @return string An XML string made from the input content in the array.
2230 public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = array(), array $stackData = array()) {
2231 // 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
2232 $binaryChars = chr(0) . chr(1) . chr(2) . chr(3) . chr(4) . chr(5) . chr(6) . chr(7) . chr(8) .
2233 chr(11) . chr(12) . chr(14) . chr(15) . chr(16) . chr(17) . chr(18) . chr(19) .
2234 chr(20) . chr(21) . chr(22) . chr(23) . chr(24) . chr(25) . chr(26) . chr(27) . chr(28) . chr(29) .
2236 // Set indenting mode:
2237 $indentChar = $spaceInd ?
' ' : TAB
;
2238 $indentN = $spaceInd > 0 ?
$spaceInd : 1;
2239 $nl = ($spaceInd >= 0 ? LF
: '');
2241 // Init output variable:
2244 // Traverse the input array
2245 foreach ($array as $k => $v) {
2249 // Construct the tag name.
2250 if (isset($options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
2251 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2252 $tagName = (string) $options['grandParentTagMap'][$stackData['grandParentTagName'] . '/' . $stackData['parentTagName']];
2253 } 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
2254 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2255 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName'] . ':_IS_NUM'];
2256 } elseif (isset($options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName])) { // Use tag based on parent tag name + current tag
2257 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2258 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName'] . ':' . $tagName];
2259 } elseif (isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
2260 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2261 $tagName = (string) $options['parentTagMap'][$stackData['parentTagName']];
2262 } elseif (!strcmp(intval($tagName), $tagName)) { // If integer...;
2263 if ($options['useNindex']) { // If numeric key, prefix "n"
2264 $tagName = 'n' . $tagName;
2265 } else { // Use special tag for num. keys:
2266 $attr .= ' index="' . $tagName . '"';
2267 $tagName = $options['useIndexTagForNum'] ?
$options['useIndexTagForNum'] : 'numIndex';
2269 } elseif ($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
2270 $attr .= ' index="' . htmlspecialchars($tagName) . '"';
2271 $tagName = $options['useIndexTagForAssoc'];
2274 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2275 $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
2277 // If the value is an array then we will call this function recursively:
2281 if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
2282 $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
2283 $clearStackPath = $subOptions['clearStackPath'];
2285 $subOptions = $options;
2286 $clearStackPath = FALSE;
2298 'parentTagName' => $tagName,
2299 'grandParentTagName' => $stackData['parentTagName'],
2300 'path' => $clearStackPath ?
'' : $stackData['path'] . '/' . $tagName,
2303 ($spaceInd >= 0 ?
str_pad('', ($level +
1) * $indentN, $indentChar) : '');
2304 if ((int) $options['disableTypeAttrib'] != 2) { // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2305 $attr .= ' type="array"';
2307 } else { // Just a value:
2309 // Look for binary chars:
2310 $vLen = strlen($v); // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
2311 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!
2312 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2313 $content = $nl . chunk_split(base64_encode($v));
2314 $attr .= ' base64="1"';
2316 // Otherwise, just htmlspecialchar the stuff:
2317 $content = htmlspecialchars($v);
2318 $dType = gettype($v);
2319 if ($dType == 'string') {
2320 if ($options['useCDATA'] && $content != $v) {
2321 $content = '<![CDATA[' . $v . ']]>';
2323 } elseif (!$options['disableTypeAttrib']) {
2324 $attr .= ' type="' . $dType . '"';
2329 // Add the element to the output string:
2330 $output .= ($spaceInd >= 0 ?
str_pad('', ($level +
1) * $indentN, $indentChar) : '') . '<' . $NSprefix . $tagName . $attr . '>' . $content . '</' . $NSprefix . $tagName . '>' . $nl;
2333 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2336 '<' . $docTag . '>' . $nl .
2338 '</' . $docTag . '>';
2345 * Converts an XML string to a PHP array.
2346 * This is the reverse function of array2xml()
2347 * This is a wrapper for xml2arrayProcess that adds a two-level cache
2349 * @param string $string XML content to convert into an array
2350 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2351 * @param boolean $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2352 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2353 * @see array2xml(),xml2arrayProcess()
2355 public static function xml2array($string, $NSprefix = '', $reportDocTag = FALSE) {
2356 static $firstLevelCache = array();
2358 $identifier = md5($string . $NSprefix . ($reportDocTag ?
'1' : '0'));
2360 // look up in first level cache
2361 if (!empty($firstLevelCache[$identifier])) {
2362 $array = $firstLevelCache[$identifier];
2364 // look up in second level cache
2365 $cacheContent = t3lib_pageSelect
::getHash($identifier, 0);
2366 $array = unserialize($cacheContent);
2368 if ($array === FALSE) {
2369 $array = self
::xml2arrayProcess($string, $NSprefix, $reportDocTag);
2370 t3lib_pageSelect
::storeHash($identifier, serialize($array), 'ident_xml2array');
2372 // store content in first level cache
2373 $firstLevelCache[$identifier] = $array;
2379 * Converts an XML string to a PHP array.
2380 * This is the reverse function of array2xml()
2382 * @param string $string XML content to convert into an array
2383 * @param string $NSprefix The tag-prefix resolve, eg. a namespace like "T3:"
2384 * @param boolean $reportDocTag If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2385 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2388 protected static function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = FALSE) {
2390 $parser = xml_parser_create();
2394 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
2395 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
2397 // default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2399 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/', substr($string, 0, 200), $match);
2400 $theCharset = $match[1] ?
$match[1] : 'utf-8';
2401 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING
, $theCharset); // us-ascii / utf-8 / iso-8859-1
2404 xml_parse_into_struct($parser, $string, $vals, $index);
2406 // If error, return error message:
2407 if (xml_get_error_code($parser)) {
2408 return 'Line ' . xml_get_current_line_number($parser) . ': ' . xml_error_string(xml_get_error_code($parser));
2410 xml_parser_free($parser);
2413 $stack = array(array());
2419 // Traverse the parsed XML structure:
2420 foreach ($vals as $key => $val) {
2422 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2423 $tagName = $val['tag'];
2424 if (!$documentTag) {
2425 $documentTag = $tagName;
2428 // Test for name space:
2429 $tagName = ($NSprefix && substr($tagName, 0, strlen($NSprefix)) == $NSprefix) ?
substr($tagName, strlen($NSprefix)) : $tagName;
2431 // Test for numeric tag, encoded on the form "nXXX":
2432 $testNtag = substr($tagName, 1); // Closing tag.
2433 $tagName = (substr($tagName, 0, 1) == 'n' && !strcmp(intval($testNtag), $testNtag)) ?
intval($testNtag) : $tagName;
2435 // Test for alternative index value:
2436 if (strlen($val['attributes']['index'])) {
2437 $tagName = $val['attributes']['index'];
2440 // Setting tag-values, manage stack:
2441 switch ($val['type']) {
2442 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2443 $current[$tagName] = array(); // Setting blank place holder
2444 $stack[$stacktop++
] = $current;
2447 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2448 $oldCurrent = $current;
2449 $current = $stack[--$stacktop];
2450 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
2451 $current[key($current)] = $oldCurrent;
2454 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2455 if ($val['attributes']['base64']) {
2456 $current[$tagName] = base64_decode($val['value']);
2458 $current[$tagName] = (string) $val['value']; // Had to cast it as a string - otherwise it would be evaluate FALSE if tested with isset()!!
2461 switch ((string) $val['attributes']['type']) {
2463 $current[$tagName] = (integer) $current[$tagName];
2466 $current[$tagName] = (double) $current[$tagName];
2469 $current[$tagName] = (bool) $current[$tagName];
2472 $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...
2480 if ($reportDocTag) {
2481 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2484 // Finally return the content of the document tag.
2485 return $current[$tagName];
2489 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2491 * @param array $vals An array of XML parts, see xml2tree
2492 * @return string Re-compiled XML data.
2494 public static function xmlRecompileFromStructValArray(array $vals) {
2497 foreach ($vals as $val) {
2498 $type = $val['type'];
2501 if ($type == 'open' ||
$type == 'complete') {
2502 $XMLcontent .= '<' . $val['tag'];
2503 if (isset($val['attributes'])) {
2504 foreach ($val['attributes'] as $k => $v) {
2505 $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
2508 if ($type == 'complete') {
2509 if (isset($val['value'])) {
2510 $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
2512 $XMLcontent .= '/>';
2518 if ($type == 'open' && isset($val['value'])) {
2519 $XMLcontent .= htmlspecialchars($val['value']);
2523 if ($type == 'close') {
2524 $XMLcontent .= '</' . $val['tag'] . '>';
2527 if ($type == 'cdata') {
2528 $XMLcontent .= htmlspecialchars($val['value']);
2536 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2538 * @param string $xmlData XML data
2539 * @return array Attributes of the xml prologue (header)
2541 public static function xmlGetHeaderAttribs($xmlData) {
2543 if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
2544 return self
::get_tag_attributes($match[1]);
2549 * Minifies JavaScript
2551 * @param string $script Script to minify
2552 * @param string $error Error message (if any)
2553 * @return string Minified script or source string if error happened
2555 public static function minifyJavaScript($script, &$error = '') {
2556 require_once(PATH_typo3
. 'contrib/jsmin/jsmin.php');
2559 $script = trim(JSMin
::minify(str_replace(CR
, '', $script)));
2561 catch (JSMinException
$e) {
2562 $error = 'Error while minifying JavaScript: ' . $e->getMessage();
2563 self
::devLog($error, 't3lib_div', 2,
2564 array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
2570 /*************************
2574 *************************/
2577 * Reads the file or url $url and returns the content
2578 * 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.
2580 * @param string $url File/URL to read
2581 * @param integer $includeHeader Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2582 * @param array $requestHeaders HTTP headers to be used in the request
2583 * @param array $report Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2584 * @return mixed The content from the resource given as input. FALSE if an error has occured.
2586 public static function getUrl($url, $includeHeader = 0, $requestHeaders = FALSE, &$report = NULL) {
2589 if (isset($report)) {
2590 $report['error'] = 0;
2591 $report['message'] = '';
2594 // use cURL for: http, https, ftp, ftps, sftp and scp
2595 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2596 if (isset($report)) {
2597 $report['lib'] = 'cURL';
2600 // External URL without error checking.
2601 if (!function_exists('curl_init') ||
!($ch = curl_init())) {
2602 if (isset($report)) {
2603 $report['error'] = -1;
2604 $report['message'] = 'Couldn\'t initialize cURL.';
2609 curl_setopt($ch, CURLOPT_URL
, $url);
2610 curl_setopt($ch, CURLOPT_HEADER
, $includeHeader ?
1 : 0);
2611 curl_setopt($ch, CURLOPT_NOBODY
, $includeHeader == 2 ?
1 : 0);
2612 curl_setopt($ch, CURLOPT_HTTPGET
, $includeHeader == 2 ?
'HEAD' : 'GET');
2613 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
2614 curl_setopt($ch, CURLOPT_FAILONERROR
, 1);
2615 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, max(0, intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout'])));
2617 $followLocation = @curl_setopt
($ch, CURLOPT_FOLLOWLOCATION
, 1);
2619 if (is_array($requestHeaders)) {
2620 curl_setopt($ch, CURLOPT_HTTPHEADER
, $requestHeaders);
2623 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2624 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2625 curl_setopt($ch, CURLOPT_PROXY
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2627 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2628 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2630 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2631 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2634 $content = curl_exec($ch);
2635 if (isset($report)) {
2636 if ($content === FALSE) {
2637 $report['error'] = curl_errno($ch);
2638 $report['message'] = curl_error($ch);
2640 $curlInfo = curl_getinfo($ch);
2641 // We hit a redirection but we couldn't follow it
2642 if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
2643 $report['error'] = -1;
2644 $report['message'] = 'Couldn\'t follow location redirect (PHP configuration option open_basedir is in effect).';
2645 } elseif ($includeHeader) {
2646 // Set only for $includeHeader to work exactly like PHP variant
2647 $report['http_code'] = $curlInfo['http_code'];
2648 $report['content_type'] = $curlInfo['content_type'];
2654 } elseif ($includeHeader) {
2655 if (isset($report)) {
2656 $report['lib'] = 'socket';
2658 $parsedURL = parse_url($url);
2659 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2660 if (isset($report)) {
2661 $report['error'] = -1;
2662 $report['message'] = 'Reading headers is not allowed for this protocol.';
2666 $port = intval($parsedURL['port']);
2668 if ($parsedURL['scheme'] == 'http') {
2669 $port = ($port > 0 ?
$port : 80);
2672 $port = ($port > 0 ?
$port : 443);
2678 $fp = @fsockopen
($scheme . $parsedURL['host'], $port, $errno, $errstr, 2.0);
2679 if (!$fp ||
$errno > 0) {
2680 if (isset($report)) {
2681 $report['error'] = $errno ?
$errno : -1;
2682 $report['message'] = $errno ?
($errstr ?
$errstr : 'Socket error.') : 'Socket initialization error.';
2686 $method = ($includeHeader == 2) ?
'HEAD' : 'GET';
2687 $msg = $method . ' ' . (isset($parsedURL['path']) ?
$parsedURL['path'] : '/') .
2688 ($parsedURL['query'] ?
'?' . $parsedURL['query'] : '') .
2689 ' HTTP/1.0' . CRLF
. 'Host: ' .
2690 $parsedURL['host'] . "\r\nConnection: close\r\n";
2691 if (is_array($requestHeaders)) {
2692 $msg .= implode(CRLF
, $requestHeaders) . CRLF
;
2697 while (!feof($fp)) {
2698 $line = fgets($fp, 2048);
2699 if (isset($report)) {
2700 if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
2701 $report['http_code'] = $status[1];
2703 elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2704 $report['content_type'] = $type[1];
2708 if (!strlen(trim($line))) {
2709 break; // Stop at the first empty line (= end of header)
2712 if ($includeHeader != 2) {
2713 $content .= stream_get_contents($fp);
2717 } elseif (is_array($requestHeaders)) {
2718 if (isset($report)) {
2719 $report['lib'] = 'file/context';
2721 $parsedURL = parse_url($url);
2722 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2723 if (isset($report)) {
2724 $report['error'] = -1;
2725 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2729 $ctx = stream_context_create(array(
2731 'header' => implode(CRLF
, $requestHeaders)
2736 $content = @file_get_contents
($url, FALSE, $ctx);
2738 if ($content === FALSE && isset($report)) {
2739 $report['error'] = -1;
2740 $report['message'] = 'Couldn\'t get URL: ' . implode(LF
, $http_response_header);
2743 if (isset($report)) {
2744 $report['lib'] = 'file';
2747 $content = @file_get_contents
($url);
2749 if ($content === FALSE && isset($report)) {
2750 $report['error'] = -1;
2751 $report['message'] = 'Couldn\'t get URL: ' . implode(LF
, $http_response_header);
2759 * Writes $content to the file $file
2761 * @param string $file Filepath to write to
2762 * @param string $content Content to write
2763 * @return boolean TRUE if the file was successfully opened and written to.
2765 public static function writeFile($file, $content) {
2766 if (!@is_file
($file)) {
2767 $changePermissions = TRUE;
2770 if ($fd = fopen($file, 'wb')) {
2771 $res = fwrite($fd, $content);
2774 if ($res === FALSE) {
2778 if ($changePermissions) { // Change the permissions only if the file has just been created
2779 self
::fixPermissions($file);
2789 * Sets the file system mode and group ownership of a file or a folder.
2791 * @param string $path Path of file or folder, must not be escaped. Path can be absolute or relative
2792 * @param boolean $recursive If set, also fixes permissions of files and folders in the folder (if $path is a folder)
2793 * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
2795 public static function fixPermissions($path, $recursive = FALSE) {
2796 if (TYPO3_OS
!= 'WIN') {
2799 // Make path absolute
2800 if (!self
::isAbsPath($path)) {
2801 $path = self
::getFileAbsFileName($path, FALSE);
2804 if (self
::isAllowedAbsPath($path)) {
2805 if (@is_file
($path)) {
2806 // "@" is there because file is not necessarily OWNED by the user
2807 $result = @chmod
($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
2808 } elseif (@is_dir
($path)) {
2809 // "@" is there because file is not necessarily OWNED by the user
2810 $result = @chmod
($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2813 // Set createGroup if not empty
2814 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) {
2815 // "@" is there because file is not necessarily OWNED by the user
2816 $changeGroupResult = @chgrp
($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2817 $result = $changeGroupResult ?
$result : FALSE;
2820 // Call recursive if recursive flag if set and $path is directory
2821 if ($recursive && @is_dir
($path)) {
2822 $handle = opendir($path);
2823 while (($file = readdir($handle)) !== FALSE) {
2824 $recursionResult = NULL;
2825 if ($file !== '.' && $file !== '..') {
2826 if (@is_file
($path . '/' . $file)) {
2827 $recursionResult = self
::fixPermissions($path . '/' . $file);
2828 } elseif (@is_dir
($path . '/' . $file)) {
2829 $recursionResult = self
::fixPermissions($path . '/' . $file, TRUE);
2831 if (isset($recursionResult) && !$recursionResult) {
2846 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2847 * Accepts an additional subdirectory in the file path!
2849 * @param string $filepath Absolute file path to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2850 * @param string $content Content string to write
2851 * @return string Returns NULL on success, otherwise an error string telling about the problem.
2853 public static function writeFileToTypo3tempDir($filepath, $content) {
2855 // Parse filepath into directory and basename:
2856 $fI = pathinfo($filepath);
2857 $fI['dirname'] .= '/';
2860 if (self
::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename']) < 60) {
2861 if (defined('PATH_site')) {
2862 $dirName = PATH_site
. 'typo3temp/'; // Setting main temporary directory name (standard)
2863 if (@is_dir
($dirName)) {
2864 if (self
::isFirstPartOfStr($fI['dirname'], $dirName)) {
2866 // Checking if the "subdir" is found:
2867 $subdir = substr($fI['dirname'], strlen($dirName));
2869 if (preg_match('/^[[:alnum:]_]+\/$/', $subdir) ||
preg_match('/^[[:alnum:]_]+\/[[:alnum:]_]+\/$/', $subdir)) {
2870 $dirName .= $subdir;
2871 if (!@is_dir
($dirName)) {
2872 self
::mkdir_deep(PATH_site
. 'typo3temp/', $subdir);
2875 return 'Subdir, "' . $subdir . '", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2878 // Checking dir-name again (sub-dir might have been created):
2879 if (@is_dir
($dirName)) {
2880 if ($filepath == $dirName . $fI['basename']) {
2881 self
::writeFile($filepath, $content);
2882 if (!@is_file
($filepath)) {
2883 return 'The file was not written to the disk. Please, check that you have write permissions to the typo3temp/ directory.';
2886 return 'Calculated filelocation didn\'t match input $filepath!';
2889 return '"' . $dirName . '" is not a directory!';
2892 return '"' . $fI['dirname'] . '" was not within directory PATH_site + "typo3temp/"';
2895 return 'PATH_site + "typo3temp/" was not a directory!';
2898 return 'PATH_site constant was NOT defined!';
2901 return 'Input filepath "' . $filepath . '" was generally invalid!';
2906 * Wrapper function for mkdir.
2907 * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']
2908 * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
2910 * @param string $newFolder Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2911 * @return boolean TRUE if @mkdir went well!
2913 public static function mkdir($newFolder) {
2914 $result = @mkdir
($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
2916 self
::fixPermissions($newFolder);
2922 * Creates a directory - including parent directories if necessary and
2923 * sets permissions on newly created directories.
2925 * @param string $directory Target directory to create. Must a have trailing slash
2926 * if second parameter is given!
2927 * Example: "/root/typo3site/typo3temp/foo/"
2928 * @param string $deepDirectory Directory to create. This second parameter
2929 * is kept for backwards compatibility since 4.6 where this method
2930 * was split into a base directory and a deep directory to be created.
2931 * Example: "xx/yy/" which creates "/root/typo3site/xx/yy/" if $directory is "/root/typo3site/"
2933 * @throws \InvalidArgumentException If $directory or $deepDirectory are not strings
2934 * @throws \RuntimeException If directory could not be created
2936 public static function mkdir_deep($directory, $deepDirectory = '') {
2937 if (!is_string($directory)) {
2938 throw new \
InvalidArgumentException(
2939 'The specified directory is of type "' . gettype($directory) . '" but a string is expected.',
2943 if (!is_string($deepDirectory)) {
2944 throw new \
InvalidArgumentException(
2945 'The specified directory is of type "' . gettype($deepDirectory) . '" but a string is expected.',
2950 $fullPath = $directory . $deepDirectory;
2951 if (!is_dir($fullPath) && strlen($fullPath) > 0) {
2952 $firstCreatedPath = self
::createDirectoryPath($fullPath);
2953 if ($firstCreatedPath !== '') {
2954 self
::fixPermissions($firstCreatedPath, TRUE);
2960 * Creates directories for the specified paths if they do not exist. This
2961 * functions sets proper permission mask but does not set proper user and
2965 * @param string $fullDirectoryPath
2966 * @return string Path to the the first created directory in the hierarchy
2967 * @see t3lib_div::mkdir_deep
2968 * @throws \RuntimeException If directory could not be created
2970 protected static function createDirectoryPath($fullDirectoryPath) {
2971 $currentPath = $fullDirectoryPath;
2972 $firstCreatedPath = '';
2973 $permissionMask = octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']);
2974 if (!@is_dir
($currentPath)) {
2976 $firstCreatedPath = $currentPath;
2977 $separatorPosition = strrpos($currentPath, DIRECTORY_SEPARATOR
);
2978 $currentPath = substr($currentPath, 0, $separatorPosition);
2979 } while (!is_dir($currentPath) && $separatorPosition !== FALSE);
2981 $result = @mkdir
($fullDirectoryPath, $permissionMask, TRUE);
2983 throw new \
RuntimeException('Could not create directory "' . $fullDirectoryPath . '"!', 1170251400);
2986 return $firstCreatedPath;
2990 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2992 * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2993 * @param boolean $removeNonEmpty Allow deletion of non-empty directories
2994 * @return boolean TRUE if @rmdir went well!
2996 public static function rmdir($path, $removeNonEmpty = FALSE) {
2998 $path = preg_replace('|/$|', '', $path); // Remove trailing slash
3000 if (file_exists($path)) {
3003 if (is_dir($path)) {
3004 if ($removeNonEmpty == TRUE && $handle = opendir($path)) {
3005 while ($OK && FALSE !== ($file = readdir($handle))) {
3006 if ($file == '.' ||
$file == '..') {
3009 $OK = self
::rmdir($path . '/' . $file, $removeNonEmpty);
3017 } else { // If $dirname is a file, simply remove it
3018 $OK = unlink($path);
3028 * Returns an array with the names of folders in a specific path
3029 * Will return 'error' (string) if there were an error with reading directory content.
3031 * @param string $path Path to list directories from
3032 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
3034 public static function get_dirs($path) {
3036 if (is_dir($path)) {
3037 $dir = scandir($path);
3039 foreach ($dir as $entry) {
3040 if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
3052 * Returns an array with the names of files in a specific path
3054 * @param string $path Is the path to the file
3055 * @param string $extensionList is the comma list of extensions to read only (blank = all)
3056 * @param boolean $prependPath If set, then the path is prepended the file names. Otherwise only the file names are returned in the array
3057 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
3059 * @param string $excludePattern A comma separated list of file names to exclude, no wildcards
3060 * @return array Array of the files found
3062 public static function getFilesInDir($path, $extensionList = '', $prependPath = FALSE, $order = '', $excludePattern = '') {
3064 // Initialize variables:
3065 $filearray = array();
3066 $sortarray = array();
3067 $path = rtrim($path, '/');
3069 // Find files+directories:
3070 if (@is_dir
($path)) {
3071 $extensionList = strtolower($extensionList);
3073 if (is_object($d)) {
3074 while ($entry = $d->read()) {
3075 if (@is_file
($path . '/' . $entry)) {
3076 $fI = pathinfo($entry);
3077 $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)
3078 if ((!strlen($extensionList) || self
::inList($extensionList, strtolower($fI['extension']))) && (!strlen($excludePattern) ||
!preg_match('/^' . $excludePattern . '$/', $entry))) {
3079 $filearray[$key] = ($prependPath ?
$path . '/' : '') . $entry;
3080 if ($order == 'mtime') {
3081 $sortarray[$key] = filemtime($path . '/' . $entry);
3084 $sortarray[$key] = strtolower($entry);
3091 return 'error opening path: "' . $path . '"';
3099 foreach ($sortarray as $k => $v) {
3100 $newArr[$k] = $filearray[$k];
3102 $filearray = $newArr;
3111 * Recursively gather all files and folders of a path.
3113 * @param array $fileArr Empty input array (will have files added to it)
3114 * @param string $path The path to read recursively from (absolute) (include trailing slash!)
3115 * @param string $extList Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
3116 * @param boolean $regDirs If set, directories are also included in output.
3117 * @param integer $recursivityLevels The number of levels to dig down...
3118 * @param string $excludePattern regex pattern of files/directories to exclude
3119 * @return array An array with the found files/directories.
3121 public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = FALSE, $recursivityLevels = 99, $excludePattern = '') {
3125 $fileArr = array_merge($fileArr, self
::getFilesInDir($path, $extList, 1, 1, $excludePattern));
3127 $dirs = self
::get_dirs($path);
3128 if (is_array($dirs) && $recursivityLevels > 0) {
3129 foreach ($dirs as $subdirs) {
3130 if ((string) $subdirs != '' && (!strlen($excludePattern) ||
!preg_match('/^' . $excludePattern . '$/', $subdirs))) {
3131 $fileArr = self
::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
3139 * Removes the absolute part of all files/folders in fileArr
3141 * @param array $fileArr: The file array to remove the prefix from
3142 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
3143 * @return array The input $fileArr processed.
3145 public static function removePrefixPathFromList(array $fileArr, $prefixToRemove) {
3146 foreach ($fileArr as $k => &$absFileRef) {
3147 if (self
::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
3148 $absFileRef = substr($absFileRef, strlen($prefixToRemove));
3150 return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
3158 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
3160 * @param string $theFile File path to process
3163 public static function fixWindowsFilePath($theFile) {
3164 return str_replace('//', '/', str_replace('\\', '/', $theFile));
3168 * Resolves "../" sections in the input path string.
3169 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
3171 * @param string $pathStr File path in which "/../" is resolved
3174 public static function resolveBackPath($pathStr) {
3175 $parts = explode('/', $pathStr);
3178 foreach ($parts as $pV) {
3191 return implode('/', $output);
3195 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
3196 * - If already having a scheme, nothing is prepended
3197 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
3198 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
3200 * @param string $path URL / path to prepend full URL addressing to.
3203 public static function locationHeaderUrl($path) {
3204 $uI = parse_url($path);
3205 if (substr($path, 0, 1) == '/') { // relative to HOST
3206 $path = self
::getIndpEnv('TYPO3_REQUEST_HOST') . $path;
3207 } elseif (!$uI['scheme']) { // No scheme either
3208 $path = self
::getIndpEnv('TYPO3_REQUEST_DIR') . $path;
3214 * Returns the maximum upload size for a file that is allowed. Measured in KB.
3215 * This might be handy to find out the real upload limit that is possible for this
3216 * TYPO3 installation. The first parameter can be used to set something that overrides
3217 * the maxFileSize, usually for the TCA values.
3219 * @param integer $localLimit: the number of Kilobytes (!) that should be used as
3220 * the initial Limit, otherwise $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize'] will be used
3221 * @return integer the maximum size of uploads that are allowed (measured in kilobytes)
3223 public static function getMaxUploadFileSize($localLimit = 0) {
3224 // don't allow more than the global max file size at all
3225 $t3Limit = (intval($localLimit > 0 ?
$localLimit : $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize']));
3226 // as TYPO3 is handling the file size in KB, multiply by 1024 to get bytes
3227 $t3Limit = $t3Limit * 1024;
3229 // check for PHP restrictions of the maximum size of one of the $_FILES
3230 $phpUploadLimit = self
::getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
3231 // check for PHP restrictions of the maximum $_POST size
3232 $phpPostLimit = self
::getBytesFromSizeMeasurement(ini_get('post_max_size'));
3233 // if the total amount of post data is smaller (!) than the upload_max_filesize directive,
3234 // then this is the real limit in PHP
3235 $phpUploadLimit = ($phpPostLimit < $phpUploadLimit ?
$phpPostLimit : $phpUploadLimit);
3237 // is the allowed PHP limit (upload_max_filesize) lower than the TYPO3 limit?, also: revert back to KB
3238 return floor($phpUploadLimit < $t3Limit ?
$phpUploadLimit : $t3Limit) / 1024;
3242 * Gets the bytes value from a measurement string like "100k".
3244 * @param string $measurement: The measurement (e.g. "100k")
3245 * @return integer The bytes value (e.g. 102400)
3247 public static function getBytesFromSizeMeasurement($measurement) {
3248 $bytes = doubleval($measurement);
3249 if (stripos($measurement, 'G')) {
3250 $bytes *= 1024 * 1024 * 1024;
3251 } elseif (stripos($measurement, 'M')) {
3252 $bytes *= 1024 * 1024;
3253 } elseif (stripos($measurement, 'K')) {
3260 * Retrieves the maximum path length that is valid in the current environment.
3262 * @return integer The maximum available path length
3264 public static function getMaximumPathLength() {
3265 return PHP_MAXPATHLEN
;
3270 * Function for static version numbers on files, based on the filemtime
3272 * This will make the filename automatically change when a file is
3273 * changed, and by that re-cached by the browser. If the file does not
3274 * exist physically the original file passed to the function is
3275 * returned without the timestamp.
3277 * Behaviour is influenced by the setting
3278 * TYPO3_CONF_VARS[TYPO3_MODE][versionNumberInFilename]
3279 * = TRUE (BE) / "embed" (FE) : modify filename
3280 * = FALSE (BE) / "querystring" (FE) : add timestamp as parameter
3282 * @param string $file Relative path to file including all potential query parameters (not htmlspecialchared yet)
3283 * @param boolean $forceQueryString If settings would suggest to embed in filename, this parameter allows us to force the versioning to occur in the query string. This is needed for scriptaculous.js which cannot have a different filename in order to load its modules (?load=...)
3284 * @return Relative path with version filename including the timestamp
3286 public static function createVersionNumberedFilename($file, $forceQueryString = FALSE) {
3287 $lookupFile = explode('?', $file);
3288 $path = self
::resolveBackPath(self
::dirname(PATH_thisScript
) . '/' . $lookupFile[0]);
3290 if (TYPO3_MODE
== 'FE') {
3291 $mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE
]['versionNumberInFilename']);
3292 if ($mode === 'embed') {
3295 if ($mode === 'querystring') {
3302 $mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE
]['versionNumberInFilename'];
3305 if (!file_exists($path) ||
$doNothing) {
3306 // File not found, return filename unaltered
3310 if (!$mode ||
$forceQueryString) {
3311 // If use of .htaccess rule is not configured,
3312 // we use the default query-string method
3313 if ($lookupFile[1]) {
3318 $fullName = $file . $separator . filemtime($path);
3321 // Change the filename
3322 $name = explode('.', $lookupFile[0]);
3323 $extension = array_pop($name);
3325 array_push($name, filemtime($path), $extension);
3326 $fullName = implode('.', $name);
3327 // append potential query string
3328 $fullName .= $lookupFile[1] ?
'?' . $lookupFile[1] : '';
3335 /*************************
3337 * SYSTEM INFORMATION
3339 *************************/
3342 * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
3346 public static function getThisUrl() {
3347 $p = parse_url(self
::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
3348 $dir = self
::dirname($p['path']) . '/'; // Strip file
3349 $url = str_replace('//', '/', $p['host'] . ($p['port'] ?
':' . $p['port'] : '') . $dir);
3354 * Returns the link-url to the current script.
3355 * In $getParams you can set associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL.
3356 * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
3358 * @param array $getParams Array of GET parameters to include
3361 public static function linkThisScript(array $getParams = array()) {
3362 $parts = self
::getIndpEnv('SCRIPT_NAME');
3363 $params = self
::_GET();
3365 foreach ($getParams as $key => $value) {
3366 if ($value !== '') {
3367 $params[$key] = $value;
3369 unset($params[$key]);
3373 $pString = self
::implodeArrayForUrl('', $params);
3375 return $pString ?
$parts . '?' . preg_replace('/^&/', '', $pString) : $parts;
3379 * Takes a full URL, $url, possibly with a querystring and overlays the $getParams arrays values onto the quirystring, packs it all together and returns the URL again.
3380 * So basically it adds the parameters in $getParams to an existing URL, $url
3382 * @param string $url URL string
3383 * @param array $getParams Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
3384 * @return string Output URL with added getParams.
3386 public static function linkThisUrl($url, array $getParams = array()) {
3387 $parts = parse_url($url);
3389 if ($parts['query']) {
3390 parse_str($parts['query'], $getP);
3392 $getP = self
::array_merge_recursive_overrule($getP, $getParams);
3393 $uP = explode('?', $url);
3395 $params = self
::implodeArrayForUrl('', $getP);
3396 $outurl = $uP[0] . ($params ?
'?' . substr($params, 1) : '');
3402 * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
3403 * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
3405 * @param string $getEnvName Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY
3406 * @return string Value based on the input key, independent of server/os environment.
3408 public static function getIndpEnv($getEnvName) {
3411 output from parse_url():
3412 URL: http://username:password@192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1
3414 [user] => 'username'
3415 [pass] => 'password'
3416 [host] => '192.168.1.4'
3418 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
3419 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
3420 [fragment] => 'link1'
3422 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
3423 [path_dir] = '/typo3/32/temp/phpcheck/'
3424 [path_info] = '/arg1/arg2/arg3/'
3425 [path] = [path_script/path_dir][path_info]
3430 REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
3431 HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
3432 SCRIPT_NAME = [path_script]++ = /typo3/32/temp/phpcheck/index.php // NOTICE THAT SCRIPT_NAME will return the php-script name ALSO. [path_script] may not do that (eg. '/somedir/' may result in SCRIPT_NAME '/somedir/index.php')!
3433 PATH_INFO = [path_info] = /arg1/arg2/arg3/
3434 QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
3435 HTTP_REFERER = [scheme]://[host][:[port]][path] = http://192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
3436 (Notice: NO username/password + NO fragment)
3439 REMOTE_ADDR = (client IP)
3440 REMOTE_HOST = (client host)
3441 HTTP_USER_AGENT = (client user agent)
3442 HTTP_ACCEPT_LANGUAGE = (client accept language)
3445 SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
3448 TYPO3_HOST_ONLY = [host] = 192.168.1.4
3449 TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
3450 TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
3451 TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
3452 TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
3453 TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
3454 TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
3455 TYPO3_SITE_PATH = [path_dir] of the TYPO3 website frontend
3456 TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
3457 TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
3458 TYPO3_SSL = Returns TRUE if this session uses SSL/TLS (https)
3459 TYPO3_PROXY = Returns TRUE if this session runs over a well known proxy
3461 Notice: [fragment] is apparently NEVER available to the script!
3463 Testing suggestions:
3464 - Output all the values.
3465 - In the script, make a link to the script it self, maybe add some parameters and click the link a few times so HTTP_REFERER is seen
3466 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
3471 switch ((string) $getEnvName) {
3473 $retVal = (PHP_SAPI
== 'fpm-fcgi' || PHP_SAPI
== 'cgi' || PHP_SAPI
== 'cgi-fcgi') &&
3474 ($_SERVER['ORIG_PATH_INFO'] ?
$_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) ?
3475 ($_SERVER['ORIG_PATH_INFO'] ?
$_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']) :
3476 ($_SERVER['ORIG_SCRIPT_NAME'] ?
$_SERVER['ORIG_SCRIPT_NAME'] : $_SERVER['SCRIPT_NAME']);
3477 // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
3478 if (self
::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
3479 if (self
::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
3480 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
3481 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
3482 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
3486 case 'SCRIPT_FILENAME':
3487 $retVal = str_replace('//', '/', str_replace('\\', '/',
3488 (PHP_SAPI
== 'fpm-fcgi' || PHP_SAPI
== 'cgi' || PHP_SAPI
== 'isapi' || PHP_SAPI
== 'cgi-fcgi') &&
3489 ($_SERVER['ORIG_PATH_TRANSLATED'] ?
$_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
3490 ($_SERVER['ORIG_PATH_TRANSLATED'] ?
$_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
3491 ($_SERVER['ORIG_SCRIPT_FILENAME'] ?
$_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME'])));
3495 // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
3496 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']) { // This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL)
3497 list($v, $n) = explode('|', $GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
3498 $retVal = $GLOBALS[$v][$n];
3499 } elseif (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
3500 $retVal = '/' . ltrim(self
::getIndpEnv('SCRIPT_NAME'), '/') .
3501 ($_SERVER['QUERY_STRING'] ?
'?' . $_SERVER['QUERY_STRING'] : '');
3503 $retVal = $_SERVER['REQUEST_URI'];
3505 // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
3506 if (self
::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
3507 if (self
::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
3508 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
3509 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
3510 $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
3515 // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
3516 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
3517 // IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers, then 'PHP_SAPI=='cgi'' might be a better check. Right now strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) will always return FALSE for CGI-versions, but that is only as long as SCRIPT_NAME is set equal to PATH_INFO because of PHP_SAPI=='cgi' (see above)
3518 // if (strcmp($_SERVER['PATH_INFO'],self::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
3519 if (PHP_SAPI
!= 'cgi' && PHP_SAPI
!= 'cgi-fcgi' && PHP_SAPI
!= 'fpm-fcgi') {
3520 $retVal = $_SERVER['PATH_INFO'];
3523 case 'TYPO3_REV_PROXY':
3524 $retVal = self
::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
3527 $retVal = $_SERVER['REMOTE_ADDR'];
3528 if (self
::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
3529 $ip = self
::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
3530 // choose which IP in list to use
3532 switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
3534 $ip = array_pop($ip);
3537 $ip = array_shift($ip);
3545 if (self
::validIP($ip)) {
3551 $retVal = $_SERVER['HTTP_HOST'];
3552 if (self
::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
3553 $host = self
::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
3554 // choose which host in list to use
3556 switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
3558 $host = array_pop($host);
3561 $host = array_shift($host);
3574 // These are let through without modification
3575 case 'HTTP_REFERER':
3576 case 'HTTP_USER_AGENT':
3577 case 'HTTP_ACCEPT_ENCODING':
3578 case 'HTTP_ACCEPT_LANGUAGE':
3580 case 'QUERY_STRING':
3581 $retVal = $_SERVER[$getEnvName];
3583 case 'TYPO3_DOCUMENT_ROOT':
3584 // Get the web root (it is not the root of the TYPO3 installation)
3585 // The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME
3586 // Some CGI-versions (LA13CGI) and mod-rewrite rules on MODULE versions will deliver a 'wrong' DOCUMENT_ROOT (according to our description). Further various aliases/mod_rewrite rules can disturb this as well.
3587 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
3588 $SFN = self
::getIndpEnv('SCRIPT_FILENAME');
3589 $SN_A = explode('/', strrev(self
::getIndpEnv('SCRIPT_NAME')));
3590 $SFN_A = explode('/', strrev($SFN));
3592 foreach ($SN_A as $kk => $vv) {
3593 if (!strcmp($SFN_A[$kk], $vv)) {
3599 $commonEnd = strrev(implode('/', $acc));
3600 if (strcmp($commonEnd, '')) {
3601 $DR = substr($SFN, 0, -(strlen($commonEnd) +
1));
3605 case 'TYPO3_HOST_ONLY':
3606 $httpHost = self
::getIndpEnv('HTTP_HOST');
3607 $httpHostBracketPosition = strpos($httpHost, ']');
3608 $httpHostParts = explode(':', $httpHost);
3609 $retVal = ($httpHostBracketPosition !== FALSE) ?
substr($httpHost, 0, ($httpHostBracketPosition +
1)) : array_shift($httpHostParts);
3612 $httpHost = self
::getIndpEnv('HTTP_HOST');
3613 $httpHostOnly = self
::getIndpEnv('TYPO3_HOST_ONLY');
3614 $retVal = (strlen($httpHost) > strlen($httpHostOnly)) ?
substr($httpHost, strlen($httpHostOnly) +
1) : '';
3616 case 'TYPO3_REQUEST_HOST':
3617 $retVal = (self
::getIndpEnv('TYPO3_SSL') ?
'https://' : 'http://') .
3618 self
::getIndpEnv('HTTP_HOST');
3620 case 'TYPO3_REQUEST_URL':
3621 $retVal = self
::getIndpEnv('TYPO3_REQUEST_HOST') . self
::getIndpEnv('REQUEST_URI');
3623 case 'TYPO3_REQUEST_SCRIPT':
3624 $retVal = self
::getIndpEnv('TYPO3_REQUEST_HOST') . self
::getIndpEnv('SCRIPT_NAME');
3626 case 'TYPO3_REQUEST_DIR':
3627 $retVal = self
::getIndpEnv('TYPO3_REQUEST_HOST') . self
::dirname(self
::getIndpEnv('SCRIPT_NAME')) . '/';
3629 case 'TYPO3_SITE_URL':
3630 if (defined('PATH_thisScript') && defined('PATH_site')) {
3631 $lPath = substr(dirname(PATH_thisScript
), strlen(PATH_site
)) . '/';
3632 $url = self
::getIndpEnv('TYPO3_REQUEST_DIR');
3633 $siteUrl = substr($url, 0, -strlen($lPath));
3634 if (substr($siteUrl, -1) != '/') {
3640 case 'TYPO3_SITE_PATH':
3641 $retVal = substr(self
::getIndpEnv('TYPO3_SITE_URL'), strlen(self
::getIndpEnv('TYPO3_REQUEST_HOST')));
3643 case 'TYPO3_SITE_SCRIPT':
3644 $retVal = substr(self
::getIndpEnv('TYPO3_REQUEST_URL'), strlen(self
::getIndpEnv('TYPO3_SITE_URL')));
3647 $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']);
3648 if ($proxySSL == '*') {
3649 $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
3651 if (self
::cmpIP(self
::getIndpEnv('REMOTE_ADDR'), $proxySSL)) {
3654 $retVal = $_SERVER['SSL_SESSION_ID'] ||
!strcasecmp($_SERVER['HTTPS'], 'on') ||
!strcmp($_SERVER['HTTPS'], '1') ?
TRUE : FALSE; // see http://bugs.typo3.org/view.php?id=3909
3659 // Here, list ALL possible keys to this function for debug display.
3660 $envTestVars = self
::trimExplode(',', '
3670 TYPO3_REQUEST_SCRIPT,
3677 TYPO3_DOCUMENT_ROOT,
3682 HTTP_ACCEPT_LANGUAGE', 1);
3683 foreach ($envTestVars as $v) {
3684 $out[$v] = self
::getIndpEnv($v);
3694 * Gets the unixtime as milliseconds.
3696 * @return integer The unixtime as milliseconds
3698 public static function milliseconds() {
3699 return round(microtime(TRUE) * 1000);
3703 * Client Browser Information
3705 * @param string $useragent Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
3706 * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
3708 public static function clientInfo($useragent = '') {
3710 $useragent = self
::getIndpEnv('HTTP_USER_AGENT');
3715 if (strpos($useragent, 'Konqueror') !== FALSE) {
3716 $bInfo['BROWSER'] = 'konqu';
3717 } elseif (strpos($useragent, 'Opera') !== FALSE) {
3718 $bInfo['BROWSER'] = 'opera';
3719 } elseif (strpos($useragent, 'MSIE') !== FALSE) {
3720 $bInfo['BROWSER'] = 'msie';
3721 } elseif (strpos($useragent, 'Mozilla') !== FALSE) {
3722 $bInfo['BROWSER'] = 'net';
3723 } elseif (strpos($useragent, 'Flash') !== FALSE) {
3724 $bInfo['BROWSER'] = 'flash';
3726 if ($bInfo['BROWSER']) {
3728 switch ($bInfo['BROWSER']) {
3730 $bInfo['VERSION'] = doubleval(substr($useragent, 8));
3731 if (strpos($useragent, 'Netscape6/') !== FALSE) {
3732 $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape6/'), 10));
3733 } // Will we ever know if this was a typo or intention...?! :-(
3734 if (strpos($useragent, 'Netscape/6') !== FALSE) {
3735 $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/6'), 10));
3737 if (strpos($useragent, 'Netscape/7') !== FALSE) {
3738 $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/7'), 9));
3742 $tmp = strstr($useragent, 'MSIE');
3743 $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 4)));
3746 $tmp = strstr($useragent, 'Opera');
3747 $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 5)));
3750 $tmp = strstr($useragent, 'Konqueror/');
3751 $bInfo['VERSION'] = doubleval(substr($tmp, 10));
3755 if (strpos($useragent, 'Win') !== FALSE) {
3756 $bInfo['SYSTEM'] = 'win';
3757 } elseif (strpos($useragent, 'Mac') !== FALSE) {
3758 $bInfo['SYSTEM'] = 'mac';
3759 } elseif (strpos($useragent, 'Linux') !== FALSE ||
strpos($useragent, 'X11') !== FALSE ||
strpos($useragent, 'SGI') !== FALSE ||
strpos($useragent, ' SunOS ') !== FALSE ||
strpos($useragent, ' HP-UX ') !== FALSE) {
3760 $bInfo['SYSTEM'] = 'unix';
3763 // Is TRUE if the browser supports css to format forms, especially the width
3764 $bInfo['FORMSTYLE'] = ($bInfo['BROWSER'] == 'msie' ||
($bInfo['BROWSER'] == 'net' && $bInfo['VERSION'] >= 5) ||
$bInfo['BROWSER'] == 'opera' ||
$bInfo['BROWSER'] == 'konqu');
3770 * Get the fully-qualified domain name of the host.
3772 * @param boolean $requestHost Use request host (when not in CLI mode).
3773 * @return string The fully-qualified host name.
3775 public static function getHostname($requestHost = TRUE) {
3777 // If not called from the command-line, resolve on getIndpEnv()
3778 // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
3779 if ($requestHost && (!defined('TYPO3_cliMode') ||
!TYPO3_cliMode
)) {
3780 $host = self
::getIndpEnv('HTTP_HOST');
3783 // will fail for PHP 4.1 and 4.2
3784 $host = @php_uname
('n');
3785 // 'n' is ignored in broken installations
3786 if (strpos($host, ' ')) {
3790 // we have not found a FQDN yet
3791 if ($host && strpos($host, '.') === FALSE) {
3792 $ip = gethostbyname($host);
3793 // we got an IP address
3795 $fqdn = gethostbyaddr($ip);
3802 $host = 'localhost.localdomain';
3809 /*************************
3811 * TYPO3 SPECIFIC FUNCTIONS
3813 *************************/
3816 * Returns the absolute filename of a relative reference, resolves the "EXT:" prefix (way of referring to files inside extensions) and checks that the file is inside the PATH_site of the TYPO3 installation and implies a check with t3lib_div::validPathStr(). Returns FALSE if checks failed. Does not check if the file exists.
3818 * @param string $filename The input filename/filepath to evaluate
3819 * @param boolean $onlyRelative If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
3820 * @param boolean $relToTYPO3_mainDir If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
3821 * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
3823 public static function getFileAbsFileName($filename, $onlyRelative = TRUE, $relToTYPO3_mainDir = FALSE) {
3824 if (!strcmp($filename, '')) {
3828 if ($relToTYPO3_mainDir) {
3829 if (!defined('PATH_typo3')) {
3832 $relPathPrefix = PATH_typo3
;
3834 $relPathPrefix = PATH_site
;
3836 if (substr($filename, 0, 4) == 'EXT:') { // extension
3837 list($extKey, $local) = explode('/', substr($filename, 4), 2);
3839 if (strcmp($extKey, '') && t3lib_extMgm
::isLoaded($extKey) && strcmp($local, '')) {
3840 $filename = t3lib_extMgm
::extPath($extKey) . $local;
3842 } elseif (!self
::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
3843 $filename = $relPathPrefix . $filename;
3844 } elseif ($onlyRelative && !self
::isFirstPartOfStr($filename, $relPathPrefix)) { // absolute, but set to blank if not allowed
3847 if (strcmp($filename, '') && self
::validPathStr($filename)) { // checks backpath.
3853 * Checks for malicious file paths.
3855 * Returns TRUE if no '//', '..', '\' or control characters are found in the $theFile.
3856 * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
3857 * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
3859 * @param string $theFile File path to evaluate
3860 * @return boolean TRUE, $theFile is allowed path string, FALSE otherwise
3861 * @see http://php.net/manual/en/security.filesystem.nullbytes.php
3862 * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded?
3864 public static function validPathStr($theFile) {
3865 if (strpos($theFile, '//') === FALSE && strpos($theFile, '\\') === FALSE && !preg_match('#(?:^\.\.|/\.\./|[[:cntrl:]])#u', $theFile)) {
3873 * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns TRUE if so.
3875 * @param string $path File path to evaluate
3878 public static function isAbsPath($path) {
3879 // on Windows also a path starting with a drive letter is absolute: X:/
3880 if (TYPO3_OS
=== 'WIN' && substr($path, 1, 2) === ':/') {
3884 // path starting with a / is always absolute, on every system
3885 return (substr($path, 0, 1) === '/');
3889 * Returns TRUE if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
3891 * @param string $path File path to evaluate
3894 public static function isAllowedAbsPath($path) {
3895 if (self
::isAbsPath($path) &&
3896 self
::validPathStr($path) &&
3897 (self
::isFirstPartOfStr($path, PATH_site
)
3899 ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && self
::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
3907 * Verifies the input filename against the 'fileDenyPattern'. Returns TRUE if OK.
3909 * @param string $filename File path to evaluate
3912 public static function verifyFilenameAgainstDenyPattern($filename) {
3913 // Filenames are not allowed to contain control characters
3914 if (preg_match('/[[:cntrl:]]/', $filename)) {
3918 if (strcmp($filename, '') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'], '')) {
3919 $result = preg_match('/' . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] . '/i', $filename);
3922 } // so if a matching filename is found, return FALSE;
3928 * Checks if a given string is a valid frame URL to be loaded in the
3931 * @param string $url potential URL to check
3932 * @return string either $url if $url is considered to be harmless, or an
3933 * empty string otherwise
3935 public static function sanitizeLocalUrl($url = '') {
3937 $decodedUrl = rawurldecode($url);
3939 if (!empty($url) && self
::removeXSS($decodedUrl) === $decodedUrl) {
3940 $testAbsoluteUrl = self
::resolveBackPath($decodedUrl);
3941 $testRelativeUrl = self
::resolveBackPath(
3942 self
::dirname(self
::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl
3945 // Pass if URL is on the current host:
3946 if (self
::isValidUrl($decodedUrl)) {
3947 if (self
::isOnCurrentHost($decodedUrl) && strpos($decodedUrl, self
::getIndpEnv('TYPO3_SITE_URL')) === 0) {
3948 $sanitizedUrl = $url;
3950 // Pass if URL is an absolute file path:
3951 } elseif (self
::isAbsPath($decodedUrl) && self
::isAllowedAbsPath($decodedUrl)) {
3952 $sanitizedUrl = $url;
3953 // Pass if URL is absolute and below TYPO3 base directory:
3954 } elseif (strpos($testAbsoluteUrl, self
::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) === '/') {
3955 $sanitizedUrl = $url;
3956 // Pass if URL is relative and below TYPO3 base directory:
3957 } elseif (strpos($testRelativeUrl, self
::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) !== '/') {
3958 $sanitizedUrl = $url;
3962 if (!empty($url) && empty($sanitizedUrl)) {
3963 self
::sysLog('The URL "' . $url . '" is not considered to be local and was denied.', 'Core', self
::SYSLOG_SEVERITY_NOTICE
);
3966 return $sanitizedUrl;
3970 * Moves $source file to $destination if uploaded, otherwise try to make a copy
3972 * @param string $source Source file, absolute path
3973 * @param string $destination Destination file, absolute path
3974 * @return boolean Returns TRUE if the file was moved.
3975 * @coauthor Dennis Petersen <fessor@software.dk>
3976 * @see upload_to_tempfile()
3978 public static function upload_copy_move($source, $destination) {
3979 if (is_uploaded_file($source)) {
3981 // Return the value of move_uploaded_file, and if FALSE the temporary $source is still around so the user can use unlink to delete it:
3982 $uploadedResult = move_uploaded_file($source, $destination);
3985 @copy
($source, $destination);
3988 self
::fixPermissions($destination); // Change the permissions of the file
3990 // If here the file is copied and the temporary $source is still around, so when returning FALSE the user can try unlink to delete the $source
3991 return $uploaded ?
$uploadedResult : FALSE;
3995 * Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in PATH_site."typo3temp/" from where TYPO3 can use it.
3996 * Use this function to move uploaded files to where you can work on them.
3997 * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
3999 * @param string $uploadedFileName The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
4000 * @return string If a new file was successfully created, return its filename, otherwise blank string.
4001 * @see unlink_tempfile(), upload_copy_move()
4003 public static function upload_to_tempfile($uploadedFileName) {
4004 if (is_uploaded_file($uploadedFileName)) {
4005 $tempFile = self
::tempnam('upload_temp_');
4006 move_uploaded_file($uploadedFileName, $tempFile);
4007 return @is_file
($tempFile) ?
$tempFile : '';
4012 * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
4013 * The function will check that the file exists, is in PATH_site."typo3temp/" and does not contain back-spaces ("../") so it should be pretty safe.
4014 * Use this after upload_to_tempfile() or tempnam() from this class!
4016 * @param string $uploadedTempFileName Filepath for a file in PATH_site."typo3temp/". Must be absolute.
4017 * @return boolean Returns TRUE if the file was unlink()'ed
4018 * @see upload_to_tempfile(), tempnam()
4020 public static function unlink_tempfile($uploadedTempFileName) {
4021 if ($uploadedTempFileName) {
4022 $uploadedTempFileName = self
::fixWindowsFilePath($uploadedTempFileName);
4023 if (self
::validPathStr($uploadedTempFileName) && self
::isFirstPartOfStr($uploadedTempFileName, PATH_site
. 'typo3temp/') && @is_file
($uploadedTempFileName)) {
4024 if (unlink($uploadedTempFileName)) {
4032 * Create temporary filename (Create file with unique file name)
4033 * This function should be used for getting temporary file names - will make your applications safe for open_basedir = on
4034 * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
4036 * @param string $filePrefix Prefix to temp file (which will have no extension btw)
4037 * @return string result from PHP function tempnam() with PATH_site . 'typo3temp/' set for temp path.
4038 * @see unlink_tempfile(), upload_to_tempfile()
4040 public static function tempnam($filePrefix) {
4041 return tempnam(PATH_site
. 'typo3temp/', $filePrefix);
4045 * Standard authentication code (used in Direct Mail, checkJumpUrl and setfixed links computations)
4047 * @param mixed $uid_or_record Uid (integer) or record (array)
4048 * @param string $fields List of fields from the record if that is given.
4049 * @param integer $codeLength Length of returned authentication code.
4050 * @return string MD5 hash of 8 chars.
4052 public static function stdAuthCode($uid_or_record, $fields = '', $codeLength = 8) {
4054 if (is_array($uid_or_record)) {
4055 $recCopy_temp = array();
4057 $fieldArr = self
::trimExplode(',', $fields, 1);
4058 foreach ($fieldArr as $k => $v) {
4059 $recCopy_temp[$k] = $uid_or_record[$v];
4062 $recCopy_temp = $uid_or_record;
4064 $preKey = implode('|', $recCopy_temp);
4066 $preKey = $uid_or_record;
4069 $authCode = $preKey . '||' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
4070 $authCode = substr(md5($authCode), 0, $codeLength);
4075 * Splits the input query-parameters into an array with certain parameters filtered out.
4076 * Used to create the cHash value
4078 * @param string $addQueryParams Query-parameters: "&xxx=yyy&zzz=uuu"
4079 * @return array Array with key/value pairs of query-parameters WITHOUT a certain list of variable names (like id, type, no_cache etc.) and WITH a variable, encryptionKey, specific for this server/installation
4080 * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink(), t3lib_div::calculateCHash()
4081 * @deprecated since TYPO3 4.7 - will be removed in TYPO3 6.1 - use t3lib_cacheHash instead
4083 public static function cHashParams($addQueryParams) {
4084 t3lib_div
::logDeprecatedFunction();
4085 $params = explode('&', substr($addQueryParams, 1)); // Splitting parameters up
4086 /* @var $cacheHash t3lib_cacheHash */
4087 $cacheHash = t3lib_div
::makeInstance('t3lib_cacheHash');
4088 $pA = $cacheHash->getRelevantParameters($addQueryParams);
4090 // Hook: Allows to manipulate the parameters which are taken to build the chash:
4091 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'])) {
4092 $cHashParamsHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'];
4093 if (is_array($cHashParamsHook)) {
4094 $hookParameters = array(
4095 'addQueryParams' => &$addQueryParams,
4096 'params' => &$params,
4099 $hookReference = NULL;
4100 foreach ($cHashParamsHook as $hookFunction) {
4101 self
::callUserFunction($hookFunction, $hookParameters, $hookReference);
4110 * Returns the cHash based on provided query parameters and added values from internal call
4112 * @param string $addQueryParams Query-parameters: "&xxx=yyy&zzz=uuu"
4113 * @return string Hash of all the values
4114 * @see t3lib_div::cHashParams(), t3lib_div::calculateCHash()
4115 * @deprecated since TYPO3 4.7 - will be removed in TYPO3 6.1 - use t3lib_cacheHash instead
4117 public static function generateCHash($addQueryParams) {
4118 t3lib_div
::logDeprecatedFunction();
4119 /* @var $cacheHash t3lib_cacheHash */
4120 $cacheHash = t3lib_div
::makeInstance('t3lib_cacheHash');
4121 return $cacheHash->generateForParameters($addQueryParams);
4125 * Calculates the cHash based on the provided parameters
4127 * @param array $params Array of key-value pairs
4128 * @return string Hash of all the values
4129 * @deprecated since TYPO3 4.7 - will be removed in TYPO3 6.1 - use t3lib_cacheHash instead
4131 public static function calculateCHash($params) {
4132 t3lib_div
::logDeprecatedFunction();
4133 /* @var $cacheHash t3lib_cacheHash */
4134 $cacheHash = t3lib_div
::makeInstance('t3lib_cacheHash');
4135 return $cacheHash->calculateCacheHash($params);
4139 * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
4141 * @param integer $l18n_cfg_fieldValue Value from "l18n_cfg" field of a page record
4142 * @return boolean TRUE if the page should be hidden
4144 public static function hideIfNotTranslated($l18n_cfg_fieldValue) {
4145 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
4146 return $l18n_cfg_fieldValue & 2 ?
FALSE : TRUE;
4148 return $l18n_cfg_fieldValue & 2 ?
TRUE : FALSE;
4153 * Returns true if the "l18n_cfg" field value is not set to hide
4154 * pages in the default language
4156 * @param int $localizationConfiguration
4159 public static function hideIfDefaultLanguage($localizationConfiguration) {
4160 return ($localizationConfiguration & 1);
4164 * Includes a locallang file and returns the $LOCAL_LANG array found inside.
4166 * @param string $fileRef Input is a file-reference (see t3lib_div::getFileAbsFileName). That file is expected to be a 'locallang.php' file containing a $LOCAL_LANG array (will be included!) or a 'locallang.xml' file conataining a valid XML TYPO3 language structure.
4167 * @param string $langKey Language key
4168 * @param string $charset Character set (option); if not set, determined by the language key
4169 * @param integer $errorMode Error mode (when file could not be found): 0 - syslog entry, 1 - do nothing, 2 - throw an exception
4170 * @return array Value of $LOCAL_LANG found in the included file. If that array is found it will returned.
4171 * Otherwise an empty array and it is FALSE in error case.
4173 public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0) {
4174 /** @var $languageFactory t3lib_l10n_Factory */
4175 $languageFactory = t3lib_div
::makeInstance('t3lib_l10n_Factory');
4176 return $languageFactory->getParsedData($fileRef, $langKey, $charset, $errorMode);
4180 * Includes a locallang-php file and returns the $LOCAL_LANG array
4181 * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
4183 * @param string $fileRef Absolute reference to locallang-PHP file
4184 * @param string $langKey TYPO3 language key, eg. "dk" or "de" or "default"
4185 * @param string $charset Character set (optional)
4186 * @return array LOCAL_LANG array in return.
4187 * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - use t3lib_l10n_parser_Llphp::getParsedData() from now on
4189 public static function readLLPHPfile($fileRef, $langKey, $charset = '') {
4190 t3lib_div
::logDeprecatedFunction();
4192 if (is_object($GLOBALS['LANG'])) {
4193 $csConvObj = $GLOBALS['LANG']->csConvObj
;
4194 } elseif (is_object($GLOBALS['TSFE'])) {
4195 $csConvObj = $GLOBALS['TSFE']->csConvObj
;
4197 $csConvObj = self
::makeInstance('t3lib_cs');
4200 if (@is_file
($fileRef) && $langKey) {
4203 $sourceCharset = $csConvObj->parse_charset($csConvObj->charSetArray
[$langKey] ?
$csConvObj->charSetArray
[$langKey] : 'utf-8');
4205 $targetCharset = $csConvObj->parse_charset($charset);
4207 $targetCharset = 'utf-8';
4211 $hashSource = substr($fileRef, strlen(PATH_site
)) . '|' . date('d-m-Y H:i:s', filemtime($fileRef)) . '|version=2.3';
4212 $cacheFileName = PATH_site
. 'typo3temp/llxml/' .
4213 substr(basename($fileRef), 10, 15) .
4214 '_' . self
::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
4215 // Check if cache file exists...
4216 if (!@is_file
($cacheFileName)) { // ... if it doesn't, create content and write it:
4220 if (!is_array($LOCAL_LANG)) {
4221 $fileName = substr($fileRef, strlen(PATH_site
));
4222 throw new RuntimeException(
4223 'TYPO3 Fatal Error: "' . $fileName . '" is no TYPO3 language file!',
4228 // converting the default language (English)
4229 // this needs to be done for a few accented loan words and extension names
4230 if (is_array($LOCAL_LANG['default']) && $targetCharset != 'utf-8') {
4231 foreach ($LOCAL_LANG['default'] as &$labelValue) {
4232 $labelValue = $csConvObj->conv($labelValue, 'utf-8', $targetCharset);
4237 if ($langKey != 'default' && is_array($LOCAL_LANG[$langKey]) && $sourceCharset != $targetCharset) {
4238 foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
4239 $labelValue = $csConvObj->conv($labelValue, $sourceCharset, $targetCharset);
4244 // Cache the content now:
4245 $serContent = array('origFile' => $hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'], $langKey => $LOCAL_LANG[$langKey]));
4246 $res = self
::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
4248 throw new RuntimeException(
4249 'TYPO3 Fatal Error: "' . $res,
4254 // Get content from cache:
4255 $serContent = unserialize(self
::getUrl($cacheFileName));
4256 $LOCAL_LANG = $serContent['LOCAL_LANG'];
4264 * Includes a locallang-xml file and returns the $LOCAL_LANG array
4265 * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
4267 * @param string $fileRef Absolute reference to locallang-XML file
4268 * @param string $langKey TYPO3 language key, eg. "dk" or "de" or "default"
4269 * @param string $charset Character set (optional)
4270 * @return array LOCAL_LANG array in return.
4271 * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.0 - use t3lib_l10n_parser_Llxml::getParsedData() from now on
4273 public static function readLLXMLfile($fileRef, $langKey, $charset = '') {
4274 t3lib_div
::logDeprecatedFunction();
4276 if (is_object($GLOBALS['LANG'])) {
4277 $csConvObj = $GLOBALS['LANG']->csConvObj
;
4278 } elseif (is_object($GLOBALS['TSFE'])) {
4279 $csConvObj = $GLOBALS['TSFE']->csConvObj
;
4281 $csConvObj = self
::makeInstance('t3lib_cs');
4285 if (@is_file
($fileRef) && $langKey) {
4289 $targetCharset = $csConvObj->parse_charset($charset);
4291 $targetCharset = 'utf-8';
4295 $hashSource = substr($fileRef, strlen(PATH_site
)) . '|' . date('d-m-Y H:i:s', filemtime($fileRef)) . '|version=2.3';
4296 $cacheFileName = PATH_site
. 'typo3temp/llxml/' .
4297 substr(basename($fileRef), 10, 15) .
4298 '_' . self
::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
4300 // Check if cache file exists...
4301 if (!@is_file
($cacheFileName)) { // ... if it doesn't, create content and write it:
4303 // Read XML, parse it.
4304 $xmlString = self
::getUrl($fileRef);
4305 $xmlContent = self
::xml2array($xmlString);
4306 if (!is_array($xmlContent)) {
4307 $fileName = substr($fileRef, strlen(PATH_site
));
4308 throw new RuntimeException(
4309 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
4314 // Set default LOCAL_LANG array content:
4315 $LOCAL_LANG = array();
4316 $LOCAL_LANG['default'] = $xmlContent['data']['default'];
4318 // converting the default language (English)
4319 // this needs to be done for a few accented loan words and extension names
4320 // NOTE: no conversion is done when in UTF-8 mode!
4321 if (is_array($LOCAL_LANG['default']) && $targetCharset != 'utf-8') {
4322 foreach ($LOCAL_LANG['default'] as &$labelValue) {
4323 $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
4328 // converting other languages to their "native" charsets
4329 // NOTE: no conversion is done when in UTF-8 mode!
4330 if ($langKey != 'default') {
4332 // If no entry is found for the language key, then force a value depending on meta-data setting. By default an automated filename will be used:
4333 $LOCAL_LANG[$langKey] = self
::llXmlAutoFileName($fileRef, $langKey);
4334 $localized_file = self
::getFileAbsFileName($LOCAL_LANG[$langKey]);
4335 if (!@is_file
($localized_file) && isset($xmlContent['data'][$langKey])) {
4336 $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
4339 // Checking if charset should be converted.
4340 if (is_array($LOCAL_LANG[$langKey]) && $targetCharset != 'utf-8') {
4341 foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
4342 $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
4348 // Cache the content now:
4349 $serContent = array('origFile' => $hashSource, 'LOCAL_LANG' => array('default' => $LOCAL_LANG['default'], $langKey => $LOCAL_LANG[$langKey]));
4350 $res = self
::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
4352 throw new RuntimeException(
4353 'TYPO3 Fatal Error: ' . $res,
4358 // Get content from cache:
4359 $serContent = unserialize(self
::getUrl($cacheFileName));
4360 $LOCAL_LANG = $serContent['LOCAL_LANG'];
4363 // Checking for EXTERNAL file for non-default language:
4364 if ($langKey != 'default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
4366 // Look for localized file:
4367 $localized_file = self
::getFileAbsFileName($LOCAL_LANG[$langKey]);
4368 if ($localized_file && @is_file
($localized_file)) {
4371 $hashSource = substr($localized_file, strlen(PATH_site
)) . '|' . date('d-m-Y H:i:s', filemtime($localized_file)) . '|version=2.3';
4372 $cacheFileName = PATH_site
. 'typo3temp/llxml/EXT_' .
4373 substr(basename($localized_file), 10, 15) .
4374 '_' . self
::shortMD5($hashSource) . '.' . $langKey . '.' . $targetCharset . '.cache';
4376 // Check if cache file exists...
4377 if (!@is_file
($cacheFileName)) { // ... if it doesn't, create content and write it:
4379 // Read and parse XML content:
4380 $local_xmlString = self
::getUrl($localized_file);
4381 $local_xmlContent = self
::xml2array($local_xmlString);
4382 if (!is_array($local_xmlContent)) {
4383 $fileName = substr($localized_file, strlen(PATH_site
));
4384 throw new RuntimeException(
4385 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
4389 $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ?
$local_xmlContent['data'][$langKey] : array();
4391 // Checking if charset should be converted.
4392 if (is_array($LOCAL_LANG[$langKey]) && $targetCharset != 'utf-8') {
4393 foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
4394 $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
4399 // Cache the content now:
4400 $serContent = array('extlang' => $langKey, 'origFile' => $hashSource, 'EXT_DATA' => $LOCAL_LANG[$langKey]);
4401 $res = self
::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
4403 throw new RuntimeException(
4404 'TYPO3 Fatal Error: ' . $res,
4409 // Get content from cache:
4410 $serContent = unserialize(self
::getUrl($cacheFileName));
4411 $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
4414 $LOCAL_LANG[$langKey] = array();
4418 // Convert the $LOCAL_LANG array to XLIFF structure
4419 foreach ($LOCAL_LANG as &$keysLabels) {
4420 foreach ($keysLabels as &$label) {
4421 $label = array(0 => array(
4434 * Returns auto-filename for locallang-XML localizations.
4436 * @param string $fileRef Absolute file reference to locallang-XML file. Must be inside system/global/local extension
4437 * @param string $language Language key
4438 * @param boolean $sameLocation if TRUE, then locallang-XML localization file name will be returned with same directory as $fileRef
4439 * @return string Returns the filename reference for the language unless error occurred (or local mode is used) in which case it will be NULL
4441 public static function llXmlAutoFileName($fileRef, $language, $sameLocation = FALSE) {
4442 if ($sameLocation) {
4445 $location = 'typo3conf/l10n/' . $language . '/'; // Default location of translations
4448 // Analyse file reference:
4449 if (self
::isFirstPartOfStr($fileRef, PATH_typo3
. 'sysext/')) { // Is system:
4450 $validatedPrefix = PATH_typo3
. 'sysext/';
4451 #$location = 'EXT:csh_'.$language.'/'; // For system extensions translations are found in "csh_*" extensions (language packs)
4452 } elseif (self
::isFirstPartOfStr($fileRef, PATH_typo3
. 'ext/')) { // Is global:
4453 $validatedPrefix = PATH_typo3
. 'ext/';
4454 } elseif (self
::isFirstPartOfStr($fileRef, PATH_typo3conf
. 'ext/')) { // Is local:
4455 $validatedPrefix = PATH_typo3conf
. 'ext/';
4456 } elseif (self
::isFirstPartOfStr($fileRef, PATH_site
. 'typo3_src/tests/')) { // Is test:
4457 $validatedPrefix = PATH_site
. 'typo3_src/tests/';
4458 $location = $validatedPrefix;
4460 $validatedPrefix = '';
4463 if ($validatedPrefix) {
4465 // Divide file reference into extension key, directory (if any) and base name:
4466 list($file_extKey, $file_extPath) = explode('/', substr($fileRef, strlen($validatedPrefix)), 2);
4467 $temp = self
::revExplode('/', $file_extPath, 2);
4468 if (count($temp) == 1) {
4469 array_unshift($temp, '');
4470 } // Add empty first-entry if not there.
4471 list($file_extPath, $file_fileName) = $temp;
4473 // If $fileRef is already prefix with "[language key]" then we should return it as this
4474 if (substr($file_fileName, 0, strlen($language) +
1) === $language . '.') {
4478 // The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
4480 $file_extKey . '/' .
4481 ($file_extPath ?
$file_extPath . '/' : '') .
4482 $language . '.' . $file_fileName;
4490 * Loads the $GLOBALS['TCA'] (Table Configuration Array) for the $table
4493 * 1) must be configured table (the ctrl-section configured),
4494 * 2) columns must not be an array (which it is always if whole table loaded), and
4495 * 3) there is a value for dynamicConfigFile (filename in typo3conf)
4497 * Note: For the frontend this loads only 'ctrl' and 'feInterface' parts.
4498 * For complete TCA use $GLOBALS['TSFE']->includeTCA() instead.
4500 * @param string $table Table name for which to load the full TCA array part into $GLOBALS['TCA']
4503 public static function loadTCA($table) {
4504 //needed for inclusion of the dynamic config files.
4506 if (isset($TCA[$table])) {
4507 $tca = &$TCA[$table];
4508 if (!$tca['columns']) {
4509 $dcf = $tca['ctrl']['dynamicConfigFile'];
4511 if (!strcmp(substr($dcf, 0, 6), 'T3LIB:')) {
4512 include(PATH_t3lib
. 'stddb/' . substr($dcf, 6));
4513 } elseif (self
::isAbsPath($dcf) && @is_file
($dcf)) { // Absolute path...
4516 include(PATH_typo3conf
. $dcf);
4524 * Looks for a sheet-definition in the input data structure array. If found it will return the data structure for the sheet given as $sheet (if found).
4525 * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
4527 * @param array $dataStructArray Input data structure, possibly with a sheet-definition and references to external data source files.
4528 * @param string $sheet The sheet to return, preferably.
4529 * @return array An array with two num. keys: key0: The data structure is returned in this key (array) UNLESS an error occurred in which case an error string is returned (string). key1: The used sheet key value!
4531 public static function resolveSheetDefInDS($dataStructArray, $sheet = 'sDEF') {
4532 if (!is_array($dataStructArray)) {
4533 return 'Data structure must be an array';
4536 if (is_array($dataStructArray['sheets'])) {
4537 $singleSheet = FALSE;
4538 if (!isset($dataStructArray['sheets'][$sheet])) {
4541 $dataStruct = $dataStructArray['sheets'][$sheet];
4543 // If not an array, but still set, then regard it as a relative reference to a file:
4544 if ($dataStruct && !is_array($dataStruct)) {
4545 $file = self
::getFileAbsFileName($dataStruct);
4546 if ($file && @is_file
($file)) {
4547 $dataStruct = self
::xml2array(self
::getUrl($file));
4551 $singleSheet = TRUE;
4552 $dataStruct = $dataStructArray;
4553 if (isset($dataStruct['meta'])) {
4554 unset($dataStruct['meta']);
4555 } // Meta data should not appear there.
4556 $sheet = 'sDEF'; // Default sheet
4558 return array($dataStruct, $sheet, $singleSheet);
4562 * Resolves ALL sheet definitions in dataStructArray
4563 * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
4565 * @param array $dataStructArray Input data structure, possibly with a sheet-definition and references to external data source files.
4566 * @return array Output data structure with all sheets resolved as arrays.
4568 public static function resolveAllSheetsInDS(array $dataStructArray) {
4569 if (is_array($dataStructArray['sheets'])) {
4570 $out = array('sheets' => array());
4571 foreach ($dataStructArray['sheets'] as $sheetId => $sDat) {
4572 list($ds, $aS) = self
::resolveSheetDefInDS($dataStructArray, $sheetId);
4573 if ($sheetId == $aS) {
4574 $out['sheets'][$aS] = $ds;
4578 list($ds) = self
::resolveSheetDefInDS($dataStructArray);
4579 $out = array('sheets' => array('sDEF' => $ds));
4585 * Calls a user-defined function/method in class
4586 * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
4588 * @param string $funcName Function/Method reference, '[file-reference":"]["&"]class/function["->"method-name]'. You can prefix this reference with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl->encodeSpURL". Finally; you can prefix the class name with "&" if you want to reuse a former instance of the same object call ("singleton").
4589 * @param mixed $params Parameters to be pass along (typically an array) (REFERENCE!)
4590 * @param mixed $ref Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
4591 * @param string $checkPrefix Alternative allowed prefix of class or function name
4592 * @param integer $errorMode Error mode (when class/function could not be found): 0 - call debug(), 1 - do nothing, 2 - raise an exception (allows to call a user function that may return FALSE)
4593 * @return mixed Content from method/function call or FALSE if the class/method/function was not found
4596 public static function callUserFunction($funcName, &$params, &$ref, $checkPrefix = 'user_', $errorMode = 0) {
4599 // Check persistent object and if found, call directly and exit.
4600 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
4601 return call_user_func_array(
4602 array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
4603 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
4604 array(&$params, &$ref)
4608 // Check file-reference prefix; if found, require_once() the file (should be library of code)
4609 if (strpos($funcName, ':') !== FALSE) {
4610 list($file, $funcRef) = self
::revExplode(':', $funcName, 2);
4611 $requireFile = self
::getFileAbsFileName($file);
4613 self
::requireOnce($requireFile);
4616 $funcRef = $funcName;
4619 // Check for persistent object token, "&"
4620 if (substr($funcRef, 0, 1) == '&') {
4621 $funcRef = substr($funcRef, 1);
4622 $storePersistentObject = TRUE;
4624 $storePersistentObject = FALSE;
4627 // Check prefix is valid:
4628 if ($checkPrefix && !self
::hasValidClassPrefix($funcRef, array($checkPrefix))) {
4629 $errorMsg = "Function/class '$funcRef' was not prepended with '$checkPrefix'";
4630 if ($errorMode == 2) {
4631 throw new InvalidArgumentException($errorMsg, 1294585864);
4632 } elseif (!$errorMode) {
4633 debug($errorMsg, 't3lib_div::callUserFunction');
4638 // Call function or method:
4639 $parts = explode('->', $funcRef);
4640 if (count($parts) == 2) { // Class
4642 // Check if class/method exists:
4643 if (class_exists($parts[0])) {
4645 // Get/Create object of class:
4646 if ($storePersistentObject) { // Get reference to current instance of class:
4647 if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
4648 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = self
::makeInstance($parts[0]);
4650 $classObj = $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
4651 } else { // Create new object:
4652 $classObj = self
::makeInstance($parts[0]);
4655 if (method_exists($classObj, $parts[1])) {
4657 // If persistent object should be created, set reference:
4658 if ($storePersistentObject) {
4659 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array(
4660 'method' => $parts[1],
4665 $content = call_user_func_array(
4666 array(&$classObj, $parts[1]),
4667 array(&$params, &$ref)
4670 $errorMsg = "No method name '" . $parts[1] . "' in class " . $parts[0];
4671 if ($errorMode == 2) {
4672 throw new InvalidArgumentException($errorMsg, 1294585865);
4673 } elseif (!$errorMode) {
4674 debug($errorMsg, 't3lib_div::callUserFunction');
4678 $errorMsg = 'No class named ' . $parts[0];
4679 if ($errorMode == 2) {
4680 throw new InvalidArgumentException($errorMsg, 1294585866);
4681 } elseif (!$errorMode) {
4682 debug($errorMsg, 't3lib_div::callUserFunction');
4685 } else { // Function
4686 if (function_exists($funcRef)) {
4687 $content = call_user_func_array($funcRef, array(&$params, &$ref));
4689 $errorMsg = 'No function named: ' . $funcRef;
4690 if ($errorMode == 2) {
4691 throw new InvalidArgumentException($errorMsg, 1294585867);
4692 } elseif (!$errorMode) {
4693 debug($errorMsg, 't3lib_div::callUserFunction');
4701 * Creates and returns reference to a user defined object.
4702 * This function can return an object reference if you like. Just prefix the function call with "&": "$objRef = &t3lib_div::getUserObj('EXT:myext/class.tx_myext_myclass.php:&tx_myext_myclass');". This will work ONLY if you prefix the class name with "&" as well. See description of function arguments.
4704 * @param string $classRef Class reference, '[file-reference":"]["&"]class-name'. You can prefix the class name with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl". Finally; for the class name you can prefix it with "&" and you will reuse the previous instance of the object identified by the full reference string (meaning; if you ask for the same $classRef later in another place in the code you will get a reference to the first created one!).
4705 * @param string $checkPrefix Required prefix of class name. By default "tx_" and "Tx_" are allowed.
4706 * @param boolean $silent If set, no debug() error message is shown if class/function is not present.
4707 * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
4708 * @see callUserFunction()
4710 public static function getUserObj($classRef, $checkPrefix = 'user_', $silent = FALSE) {
4711 // Check persistent object and if found, call directly and exit.
4712 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
4713 return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
4716 // Check file-reference prefix; if found, require_once() the file (should be library of code)
4717 if (strpos($classRef, ':') !== FALSE) {
4718 list($file, $class) = self
::revExplode(':', $classRef, 2);
4719 $requireFile = self
::getFileAbsFileName($file);
4721 self
::requireOnce($requireFile);
4727 // Check for persistent object token, "&"
4728 if (substr($class, 0, 1) == '&') {
4729 $class = substr($class, 1);
4730 $storePersistentObject = TRUE;
4732 $storePersistentObject = FALSE;
4735 // Check prefix is valid:
4736 if ($checkPrefix && !self
::hasValidClassPrefix($class, array($checkPrefix))) {
4738 debug("Class '" . $class . "' was not prepended with '" . $checkPrefix . "'", 't3lib_div::getUserObj');
4743 // Check if class exists:
4744 if (class_exists($class)) {
4745 $classObj = self
::makeInstance($class);
4747 // If persistent object should be created, set reference:
4748 if ($storePersistentObject) {
4749 $GLOBALS['T3_VAR']['getUserObj'][$classRef] = $classObj;
4755 debug("<strong>ERROR:</strong> No class named: " . $class, 't3lib_div::getUserObj');
4762 * Checks if a class or function has a valid prefix: tx_, Tx_ or custom, e.g. user_
4764 * @param string $classRef The class or function to check
4765 * @param array $additionalPrefixes Additional allowed prefixes, mostly this will be user_
4766 * @return bool TRUE if name is allowed
4768 public static function hasValidClassPrefix($classRef, array $additionalPrefixes = array()) {
4769 if (empty($classRef)) {
4772 if (!is_string($classRef)) {
4773 throw new InvalidArgumentException('$classRef has to be of type string', 1313917992);
4775 $hasValidPrefix = FALSE;
4776 $validPrefixes = self
::getValidClassPrefixes();
4777 $classRef = trim($classRef);
4779 if (count($additionalPrefixes)) {
4780 $validPrefixes = array_merge($validPrefixes, $additionalPrefixes);
4782 foreach ($validPrefixes as $prefixToCheck) {
4783 if (self
::isFirstPartOfStr($classRef, $prefixToCheck) ||
$prefixToCheck === '') {
4784 $hasValidPrefix = TRUE;
4789 return $hasValidPrefix;
4793 * Returns all valid class prefixes.
4795 * @return array Array of valid prefixed of class names
4797 public static function getValidClassPrefixes() {
4798 $validPrefixes = array('tx_', 'Tx_', 'user_', 'User_');
4800 isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['additionalAllowedClassPrefixes'])
4801 && is_string($GLOBALS['TYPO3_CONF_VARS']['SYS']['additionalAllowedClassPrefixes'])
4803 $validPrefixes = array_merge(
4805 t3lib_div
::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['SYS']['additionalAllowedClassPrefixes'])
4808 return $validPrefixes;
4812 * Creates an instance of a class taking into account the class-extensions
4813 * API of TYPO3. USE THIS method instead of the PHP "new" keyword.
4814 * Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
4816 * You can also pass arguments for a constructor:
4817 * t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
4819 * @throws InvalidArgumentException if classname is an empty string
4820 * @param string $className
4821 * name of the class to instantiate, must not be empty
4822 * @return object the created instance
4824 public static function makeInstance($className) {
4825 if (!is_string($className) ||
empty($className)) {
4826 throw new InvalidArgumentException('$className must be a non empty string.', 1288965219);
4829 // Determine final class name which must be instantiated, this takes XCLASS handling
4830 // into account. Cache in a local array to save some cycles for consecutive calls.
4831 if (!isset(self
::$finalClassNameRegister[$className])) {
4832 self
::$finalClassNameRegister[$className] = self
::getClassName($className);
4834 $finalClassName = self
::$finalClassNameRegister[$className];
4836 // Return singleton instance if it is already registered
4837 if (isset(self
::$singletonInstances[$finalClassName])) {
4838 return self
::$singletonInstances[$finalClassName];
4841 // Return instance if it has been injected by addInstance()
4842 if (isset(self
::$nonSingletonInstances[$finalClassName])
4843 && !empty(self
::$nonSingletonInstances[$finalClassName])
4845 return array_shift(self
::$nonSingletonInstances[$finalClassName]);
4848 // Create new instance and call constructor with parameters
4849 if (func_num_args() > 1) {
4850 $constructorArguments = func_get_args();
4851 array_shift($constructorArguments);
4853 $reflectedClass = new ReflectionClass($finalClassName);
4854 $instance = $reflectedClass->newInstanceArgs($constructorArguments);
4856 $instance = new $finalClassName;
4859 // Register new singleton instance
4860 if ($instance instanceof t3lib_Singleton
) {
4861 self
::$singletonInstances[$finalClassName] = $instance;
4868 * Returns the class name for a new instance, taking into account the
4869 * class-extension API.
4871 * @param string $className Base class name to evaluate
4872 * @return string Final class name to instantiate with "new [classname]"
4874 protected static function getClassName($className) {
4875 if (class_exists($className)) {
4876 while (class_exists('ux_' . $className, FALSE)) {
4877 $className = 'ux_' . $className;
4885 * Sets the instance of a singleton class to be returned by makeInstance.
4887 * If this function is called multiple times for the same $className,
4888 * makeInstance will return the last set instance.
4890 * Warning: This is a helper method for unit tests. Do not call this directly in production code!
4893 * @param string $className
4894 * the name of the class to set, must not be empty
4895 * @param t3lib_Singleton $instance
4896 * the instance to set, must be an instance of $className
4899 public static function setSingletonInstance($className, t3lib_Singleton
$instance) {
4900 self
::checkInstanceClassName($className, $instance);
4901 self
::$singletonInstances[$className] = $instance;
4905 * Sets the instance of a non-singleton class to be returned by makeInstance.
4907 * If this function is called multiple times for the same $className,
4908 * makeInstance will return the instances in the order in which they have
4909 * been added (FIFO).
4911 * Warning: This is a helper method for unit tests. Do not call this directly in production code!
4914 * @throws InvalidArgumentException if class extends t3lib_Singleton
4915 * @param string $className
4916 * the name of the class to set, must not be empty
4917 * @param object $instance
4918 * the instance to set, must be an instance of $className
4921 public static function addInstance($className, $instance) {
4922 self
::checkInstanceClassName($className, $instance);
4924 if ($instance instanceof t3lib_Singleton
) {
4925 throw new InvalidArgumentException(
4926 '$instance must not be an instance of t3lib_Singleton. ' .
4927 'For setting singletons, please use setSingletonInstance.',
4932 if (!isset(self
::$nonSingletonInstances[$className])) {
4933 self
::$nonSingletonInstances[$className] = array();
4935 self
::$nonSingletonInstances[$className][] = $instance;
4939 * Checks that $className is non-empty and that $instance is an instance of
4942 * @throws InvalidArgumentException if $className is empty or if $instance is no instance of $className
4943 * @param string $className a class name
4944 * @param object $instance an object
4947 protected static function checkInstanceClassName($className, $instance) {
4948 if ($className === '') {
4949 throw new InvalidArgumentException('$className must not be empty.', 1288967479);
4951 if (!($instance instanceof $className)) {
4952 throw new InvalidArgumentException(
4953 '$instance must be an instance of ' . $className . ', but actually is an instance of ' . get_class($instance) . '.',
4960 * Purge all instances returned by makeInstance.
4962 * This function is most useful when called from tearDown in a test case
4963 * to drop any instances that have been created by the tests.
4965 * Warning: This is a helper method for unit tests. Do not call this directly in production code!
4970 public static function purgeInstances() {
4971 self
::$singletonInstances = array();
4972 self
::$nonSingletonInstances = array();
4976 * Find the best service and check if it works.
4977 * Returns object of the service class.
4979 * @param string $serviceType Type of service (service key).
4980 * @param string $serviceSubType Sub type like file extensions or similar. Defined by the service.
4981 * @param mixed $excludeServiceKeys List of service keys which should be excluded in the search for a service. Array or comma list.
4982 * @return object The service object or an array with error info's.
4984 public static function makeInstanceService($serviceType, $serviceSubType = '', $excludeServiceKeys = array()) {
4987 if (!is_array($excludeServiceKeys)) {
4988 $excludeServiceKeys = self
::trimExplode(',', $excludeServiceKeys, 1);
4991 $requestInfo = array(
4992 'requestedServiceType' => $serviceType,
4993 'requestedServiceSubType' => $serviceSubType,
4994 'requestedExcludeServiceKeys' => $excludeServiceKeys,
4997 while ($info = t3lib_extMgm
::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
4999 // provide information about requested service to service object
5000 $info = array_merge($info, $requestInfo);
5002 // Check persistent object and if found, call directly and exit.
5003 if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) {
5005 // update request info in persistent object
5006 $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]->info
= $info;
5008 // reset service and return object
5009 $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]->reset();
5010 return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
5012 // include file and create object
5014 $requireFile = self
::getFileAbsFileName($info['classFile']);
5015 if (@is_file
($requireFile)) {
5016 self
::requireOnce($requireFile);
5017 $obj = self
::makeInstance($info['className']);
5018 if (is_object($obj)) {
5019 if (!@is_callable
(array($obj, 'init'))) {
5020 // use silent logging??? I don't think so.
5021 die ('Broken service:' . t3lib_utility_Debug
::viewArray($info));
5024 if ($obj->init()) { // service available?
5026 // create persistent object
5027 $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']] = $obj;
5029 // needed to delete temp files
5030 register_shutdown_function(array(&$obj, '__destruct'));
5032 return $obj; // object is passed as reference by function definition
5034 $error = $obj->getLastErrorArray();
5039 // deactivate the service
5040 t3lib_extMgm
::deactivateService($info['serviceType'], $info['serviceKey']);
5046 * Require a class for TYPO3
5047 * Useful to require classes from inside other classes (not global scope). A limited set of global variables are available (see function)
5049 * @param string $requireFile: Path of the file to be included
5052 public static function requireOnce($requireFile) {
5053 // Needed for require_once
5054 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
5056 require_once ($requireFile);
5060 * Requires a class for TYPO3
5061 * Useful to require classes from inside other classes (not global scope).
5062 * A limited set of global variables are available (see function)
5064 * @param string $requireFile: Path of the file to be included
5067 public static function requireFile($requireFile) {
5068 // Needed for require
5069 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
5070 require $requireFile;
5074 * Simple substitute for the PHP function mail() which allows you to specify encoding and character set
5075 * The fifth parameter ($encoding) will allow you to specify 'base64' encryption for the output (set $encoding=base64)
5076 * Further the output has the charset set to UTF-8 by default.
5078 * @param string $email Email address to send to. (see PHP function mail())
5079 * @param string $subject Subject line, non-encoded. (see PHP function mail())
5080 * @param string $message Message content, non-encoded. (see PHP function mail())
5081 * @param string $headers Headers, separated by LF
5082 * @param string $encoding Encoding type: "base64", "quoted-printable", "8bit". Default value is "quoted-printable".
5083 * @param string $charset Charset used in encoding-headers (only if $encoding is set to a valid value which produces such a header)
5084 * @param boolean $dontEncodeHeader If set, the header content will not be encoded.
5085 * @return boolean TRUE if mail was accepted for delivery, FALSE otherwise
5087 public static function plainMailEncoded($email, $subject, $message, $headers = '', $encoding = 'quoted-printable', $charset = '', $dontEncodeHeader = FALSE) {
5092 $email = self
::normalizeMailAddress($email);
5093 if (!$dontEncodeHeader) {
5094 // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
5095 $newHeaders = array();
5096 foreach (explode(LF
, $headers) as $line) { // Split the header in lines and convert each line separately
5097 $parts = explode(': ', $line, 2); // Field tags must not be encoded
5098 if (count($parts) == 2) {
5099 if (0 == strcasecmp($parts[0], 'from')) {
5100 $parts[1] = self
::normalizeMailAddress($parts[1]);
5102 $parts[1] = self
::encodeHeader($parts[1], $encoding, $charset);
5103 $newHeaders[] = implode(': ', $parts);
5105 $newHeaders[] = $line; // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
5108 $headers = implode(LF
, $newHeaders);
5111 $email = self
::encodeHeader($email, $encoding, $charset); // Email address must not be encoded, but it could be appended by a name which should be so (e.g. "Kasper Skårhøj <kasperYYYY@typo3.com>")
5112 $subject = self
::encodeHeader($subject, $encoding, $charset);
5115 switch ((string) $encoding) {
5117 $headers = trim($headers) . LF
.
5118 'Mime-Version: 1.0' . LF
.
5119 'Content-Type: text/plain; charset="' . $charset . '"' . LF
.
5120 'Content-Transfer-Encoding: base64';
5122 $message = trim(chunk_split(base64_encode($message . LF
))) . LF
; // Adding LF because I think MS outlook 2002 wants it... may be removed later again.
5125 $headers = trim($headers) . LF
.
5126 'Mime-Version: 1.0' . LF
.
5127 'Content-Type: text/plain; charset=' . $charset . LF
.
5128 'Content-Transfer-Encoding: 8bit';
5130 case 'quoted-printable':
5132 $headers = trim($headers) . LF
.
5133 'Mime-Version: 1.0' . LF
.
5134 'Content-Type: text/plain; charset=' . $charset . LF
.
5135 'Content-Transfer-Encoding: quoted-printable';
5137 $message = self
::quoted_printable($message);
5141 // Headers must be separated by CRLF according to RFC 2822, not just LF.
5142 // But many servers (Gmail, for example) behave incorrectly and want only LF.
5143 // So we stick to LF in all cases.
5144 $headers = trim(implode(LF
, self
::trimExplode(LF
, $headers, TRUE))); // Make sure no empty lines are there.
5146 return t3lib_utility_Mail
::mail($email, $subject, $message, $headers);
5150 * Implementation of quoted-printable encode.
5151 * See RFC 1521, section 5.1 Quoted-Printable Content-Transfer-Encoding
5153 * @param string $string Content to encode
5154 * @param integer $maxlen Length of the lines, default is 76
5155 * @return string The QP encoded string
5157 public static function quoted_printable($string, $maxlen = 76) {
5158 // Make sure the string contains only Unix line breaks
5159 $string = str_replace(CRLF
, LF
, $string); // Replace Windows breaks (\r\n)
5160 $string = str_replace(CR
, LF
, $string); // Replace Mac breaks (\r)
5162 $linebreak = LF
; // Default line break for Unix systems.
5163 if (TYPO3_OS
== 'WIN') {
5164 $linebreak = CRLF
; // Line break for Windows. This is needed because PHP on Windows systems send mails via SMTP instead of using sendmail, and thus the line break needs to be \r\n.
5168 $theLines = explode(LF
, $string); // Split lines
5169 foreach ($theLines as $val) {
5171 $theValLen = strlen($val);
5173 for ($index = 0; $index < $theValLen; $index++
) { // Walk through each character of this line
5174 $char = substr($val, $index, 1);
5175 $ordVal = ord($char);
5176 if ($len > ($maxlen - 4) ||
($len > ($maxlen - 14) && $ordVal == 32)) {
5177 $newVal .= '=' . $linebreak; // Add a line break
5178 $len = 0; // Reset the length counter
5180 if (($ordVal >= 33 && $ordVal <= 60) ||
($ordVal >= 62 && $ordVal <= 126) ||
$ordVal == 9 ||
$ordVal == 32) {
5181 $newVal .= $char; // This character is ok, add it to the message
5184 $newVal .= sprintf('=%02X', $ordVal); // Special character, needs to be encoded
5188 $newVal = preg_replace('/' . chr(32) . '$/', '=20', $newVal); // Replaces a possible SPACE-character at the end of a line
5189 $newVal = preg_replace('/' . TAB
. '$/', '=09', $newVal); // Replaces a possible TAB-character at the end of a line
5190 $newString .= $newVal . $linebreak;
5192 return preg_replace('/' . $linebreak . '$/', '', $newString); // Remove last newline
5196 * Encode header lines
5197 * Email headers must be ASCII, therefore they will be encoded to quoted_printable (default) or base64.
5199 * @param string $line Content to encode
5200 * @param string $enc Encoding type: "base64" or "quoted-printable". Default value is "quoted-printable".
5201 * @param string $charset Charset used for encoding
5202 * @return string The encoded string
5204 public static function encodeHeader($line, $enc = 'quoted-printable', $charset = 'utf-8') {
5205 // Avoid problems if "###" is found in $line (would conflict with the placeholder which is used below)
5206 if (strpos($line, '###') !== FALSE) {
5209 // Check if any non-ASCII characters are found - otherwise encoding is not needed
5210 if (!preg_match('/[^' . chr(32) . '-' . chr(127) . ']/', $line)) {
5213 // Wrap email addresses in a special marker
5214 $line = preg_replace('/([^ ]+@[^ ]+)/', '###$1###', $line);
5216 $matches = preg_split('/(.?###.+###.?|\(|\))/', $line, -1, PREG_SPLIT_NO_EMPTY
);
5217 foreach ($matches as $part) {
5219 $partWasQuoted = ($part{0} == '"');
5220 $part = trim($part, '"');
5221 switch ((string) $enc) {
5223 $part = '=?' . $charset . '?B?' . base64_encode($part) . '?=';
5225 case 'quoted-printable':
5227 $qpValue = self
::quoted_printable($part, 1000);
5228 if ($part != $qpValue) {
5229 // Encoded words in the header should not contain non-encoded:
5230 // * spaces. "_" is a shortcut for "=20". See RFC 2047 for details.
5231 // * question mark. See RFC 1342 (http://tools.ietf.org/html/rfc1342)
5232 $search = array(' ', '?');
5233 $replace = array('_', '=3F');
5234 $qpValue = str_replace($search, $replace, $qpValue);
5235 $part = '=?' . $charset . '?Q?' . $qpValue . '?=';
5239 if ($partWasQuoted) {
5240 $part = '"' . $part . '"';
5242 $line = str_replace($oldPart, $part, $line);
5244 $line = preg_replace('/###(.+?)###/', '$1', $line); // Remove the wrappers
5250 * Takes a clear-text message body for a plain text email, finds all 'http://' links and if they are longer than 76 chars they are converted to a shorter URL with a hash parameter. The real parameter is stored in the database and the hash-parameter/URL will be redirected to the real parameter when the link is clicked.
5251 * This function is about preserving long links in messages.
5253 * @param string $message Message content
5254 * @param string $urlmode URL mode; "76" or "all"
5255 * @param string $index_script_url URL of index script (see makeRedirectUrl())
5256 * @return string Processed message content
5257 * @see makeRedirectUrl()
5259 public static function substUrlsInPlainText($message, $urlmode = '76', $index_script_url = '') {
5260 $lengthLimit = FALSE;
5262 switch ((string) $urlmode) {
5264 $lengthLimit = FALSE;
5271 $lengthLimit = (int) $urlmode;
5274 if ($lengthLimit === FALSE) {
5276 $messageSubstituted = $message;
5278 $messageSubstituted = preg_replace(
5279 '/(http|https):\/\/.+(?=[\]\.\?]*([\! \'"()<>]+|$))/eiU',
5280 'self::makeRedirectUrl("\\0",' . $lengthLimit . ',"' . $index_script_url . '")',
5285 return $messageSubstituted;
5289 * Sub-function for substUrlsInPlainText() above.
5291 * @param string $inUrl Input URL
5292 * @param integer $l URL string length limit
5293 * @param string $index_script_url URL of "index script" - the prefix of the "?RDCT=..." parameter. If not supplied it will default to t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php'
5294 * @return string Processed URL
5296 public static function makeRedirectUrl($inUrl, $l = 0, $index_script_url = '') {
5297 if (strlen($inUrl) > $l) {
5298 $md5 = substr(md5($inUrl), 0, 20);
5299 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
5302 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params')
5305 $insertFields = array(
5307 'tstamp' => $GLOBALS['EXEC_TIME'],
5312 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
5314 $inUrl = ($index_script_url ?
$index_script_url : self
::getIndpEnv('TYPO3_REQUEST_DIR') . 'index.php') .
5322 * Function to compensate for FreeType2 96 dpi
5324 * @param integer $font_size Fontsize for freetype function call
5325 * @return integer Compensated fontsize based on $GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']
5327 public static function freetypeDpiComp($font_size) {
5328 $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
5330 $font_size = $font_size / $dpi * 72;
5336 * Initialize the system log.
5341 public static function initSysLog() {
5342 // for CLI logging name is <fqdn-hostname>:<TYPO3-path>
5343 // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
5344 if (defined('TYPO3_cliMode') && TYPO3_cliMode
) {
5345 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self
::getHostname($requestHost = FALSE) . ':' . PATH_site
;
5347 // for Web logging name is <protocol>://<request-hostame>/<site-path>
5349 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self
::getIndpEnv('TYPO3_SITE_URL');
5352 // init custom logging
5353 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
5354 $params = array('initLog' => TRUE);
5356 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
5357 self
::callUserFunction($hookMethod, $params, $fakeThis);
5361 // init TYPO3 logging
5362 foreach (explode(';', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog'], 2) as $log) {
5363 list($type, $destination) = explode(',', $log, 3);
5365 if ($type == 'syslog') {
5366 if (TYPO3_OS
== 'WIN') {
5367 $facility = LOG_USER
;
5369 $facility = constant('LOG_' . strtoupper($destination));
5371 openlog($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'], LOG_ODELAY
, $facility);
5375 $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'] = t3lib_utility_Math
::forceIntegerInRange($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel'], 0, 4);
5376 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
5380 * Logs message to the system log.
5381 * This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors.
5382 * If you want to implement the sysLog in your applications, simply add lines like:
5383 * t3lib_div::sysLog('[write message in English here]', 'extension_key', 'severity');
5385 * @param string $msg Message (in English).
5386 * @param string $extKey Extension key (from which extension you are calling the log) or "Core"
5387 * @param integer $severity Severity: 0 is info, 1 is notice, 2 is warning, 3 is error, 4 is fatal error
5390 public static function sysLog($msg, $extKey, $severity = 0) {
5391 $severity = t3lib_utility_Math
::forceIntegerInRange($severity, 0, 4);
5393 // is message worth logging?
5394 if (intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLogLevel']) > $severity) {
5398 // initialize logging
5399 if (!$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) {
5403 // do custom logging
5404 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog']) &&
5405 is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
5406 $params = array('msg' => $msg, 'extKey' => $extKey, 'backTrace' => debug_backtrace(), 'severity' => $severity);
5408 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
5409 self
::callUserFunction($hookMethod, $params, $fakeThis);
5413 // TYPO3 logging enabled?
5414 if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog']) {
5418 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
5419 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
5421 // use all configured logging options
5422 foreach (explode(';', $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLog'], 2) as $log) {
5423 list($type, $destination, $level) = explode(',', $log, 4);
5425 // is message worth logging for this log type?
5426 if (intval($level) > $severity) {
5430 $msgLine = ' - ' . $extKey . ': ' . $msg;
5432 // write message to a file
5433 if ($type == 'file') {
5434 $lockObject = t3lib_div
::makeInstance('t3lib_lock', $destination, $GLOBALS['TYPO3_CONF_VARS']['SYS']['lockingMode']);
5435 /** @var t3lib_lock $lockObject */
5436 $lockObject->setEnableLogging(FALSE);
5437 $lockObject->acquire();
5438 $file = fopen($destination, 'a');
5440 fwrite($file, date($dateFormat . ' ' . $timeFormat) . $msgLine . LF
);
5442 self
::fixPermissions($destination);
5444 $lockObject->release();
5446 // send message per mail
5447 elseif ($type == 'mail') {
5448 list($to, $from) = explode('/', $destination);
5449 if (!t3lib_div
::validEmail($from)) {
5450 $from = t3lib_utility_Mail
::getSystemFrom();
5452 /** @var $mail t3lib_mail_Message */
5453 $mail = t3lib_div
::makeInstance('t3lib_mail_Message');
5456 ->setSubject('Warning - error in TYPO3 installation')
5457 ->setBody('Host: ' . $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . LF
.
5458 'Extension: ' . $extKey . LF
.
5459 'Severity: ' . $severity . LF
.
5464 // use the PHP error log
5465 elseif ($type == 'error_log') {
5466 error_log($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . $msgLine, 0);
5468 // use the system log
5469 elseif ($type == 'syslog') {
5470 $priority = array(LOG_INFO
, LOG_NOTICE
, LOG_WARNING
, LOG_ERR
, LOG_CRIT
);
5471 syslog($priority[(int) $severity], $msgLine);
5477 * Logs message to the development log.
5478 * This should be implemented around the source code, both frontend and backend, logging everything from the flow through an application, messages, results from comparisons to fatal errors.
5479 * The result is meant to make sense to developers during development or debugging of a site.
5480 * The idea is that this function is only a wrapper for external extensions which can set a hook which will be allowed to handle the logging of the information to any format they might wish and with any kind of filter they would like.
5481 * If you want to implement the devLog in your applications, simply add lines like:
5482 * if (TYPO3_DLOG) t3lib_div::devLog('[write message in english here]', 'extension key');
5484 * @param string $msg Message (in english).
5485 * @param string $extKey Extension key (from which extension you are calling the log)
5486 * @param integer $severity Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
5487 * @param mixed $dataVar Additional data you want to pass to the logger.
5490 public static function devLog($msg, $extKey, $severity = 0, $dataVar = FALSE) {
5491 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
5492 $params = array('msg' => $msg, 'extKey' => $extKey, 'severity' => $severity, 'dataVar' => $dataVar);
5494 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) {
5495 self
::callUserFunction($hookMethod, $params, $fakeThis);
5501 * Writes a message to the deprecation log.
5503 * @param string $msg Message (in English).
5506 public static function deprecationLog($msg) {
5507 if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
5511 $log = $GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog'];
5512 $date = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ': ');
5514 // legacy values (no strict comparison, $log can be boolean, string or int)
5515 if ($log === TRUE ||
$log == '1') {
5519 if (stripos($log, 'file') !== FALSE) {
5520 // In case lock is acquired before autoloader was defined:
5521 if (class_exists('t3lib_lock') === FALSE) {
5522 require_once PATH_t3lib
. 'class.t3lib_lock.php';
5524 // write a longer message to the deprecation log
5525 $destination = self
::getDeprecationLogFileName();
5526 $lockObject = t3lib_div
::makeInstance('t3lib_lock', $destination, $GLOBALS['TYPO3_CONF_VARS']['SYS']['lockingMode']);
5527 /** @var t3lib_lock $lockObject */
5528 $lockObject->setEnableLogging(FALSE);
5529 $lockObject->acquire();
5530 $file = @fopen
($destination, 'a');
5532 @fwrite
($file, $date . $msg . LF
);
5534 self
::fixPermissions($destination);
5536 $lockObject->release();
5539 if (stripos($log, 'devlog') !== FALSE) {
5540 // copy message also to the developer log
5541 self
::devLog($msg, 'Core', self
::SYSLOG_SEVERITY_WARNING
);
5544 // do not use console in login screen
5545 if (stripos($log, 'console') !== FALSE && isset($GLOBALS['BE_USER']->user
['uid'])) {
5546 t3lib_utility_Debug
::debug($msg, $date, 'Deprecation Log');
5551 * Gets the absolute path to the deprecation log file.
5553 * @return string absolute path to the deprecation log file
5555 public static function getDeprecationLogFileName() {
5556 return PATH_typo3conf
.
5559 PATH_site
. $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
5565 * Logs a call to a deprecated function.
5566 * The log message will be taken from the annotation.
5569 public static function logDeprecatedFunction() {
5570 if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
5574 // This require_once is needed for deprecation calls
5575 // thrown early during bootstrap, if the autoloader is
5576 // not instantiated yet. This can happen for example if
5577 // ext_localconf triggers a deprecation.
5578 require_once __DIR__
.'/class.t3lib_utility_debug.php';
5580 $trail = debug_backtrace();
5582 if ($trail[1]['type']) {
5583 $function = new ReflectionMethod($trail[1]['class'], $trail[1]['function']);
5585 $function = new ReflectionFunction($trail[1]['function']);
5589 if (preg_match('/@deprecated\s+(.*)/', $function->getDocComment(), $match)) {
5593 // trigger PHP error with a short message: <function> is deprecated (called from <source>, defined in <source>)
5594 $errorMsg = 'Function ' . $trail[1]['function'];
5595 if ($trail[1]['class']) {
5596 $errorMsg .= ' of class ' . $trail[1]['class'];
5598 $errorMsg .= ' is deprecated (called from ' . $trail[1]['file'] . '#' . $trail[1]['line'] . ', defined in ' . $function->getFileName() . '#' . $function->getStartLine() . ')';
5600 // write a longer message to the deprecation log: <function> <annotion> - <trace> (<source>)
5601 $logMsg = $trail[1]['class'] . $trail[1]['type'] . $trail[1]['function'];
5602 $logMsg .= '() - ' . $msg.' - ' . t3lib_utility_Debug
::debugTrail();
5603 $logMsg .= ' (' . substr($function->getFileName(), strlen(PATH_site
)) . '#' . $function->getStartLine() . ')';
5604 self
::deprecationLog($logMsg);
5608 * Converts a one dimensional array to a one line string which can be used for logging or debugging output
5609 * Example: "loginType: FE; refInfo: Array; HTTP_HOST: www.example.org; REMOTE_ADDR: 192.168.1.5; REMOTE_HOST:; security_level:; showHiddenRecords: 0;"
5611 * @param array $arr Data array which should be outputted
5612 * @param mixed $valueList List of keys which should be listed in the output string. Pass a comma list or an array. An empty list outputs the whole array.
5613 * @param integer $valueLength Long string values are shortened to this length. Default: 20
5614 * @return string Output string with key names and their value as string
5616 public static function arrayToLogString(array $arr, $valueList = array(), $valueLength = 20) {
5618 if (!is_array($valueList)) {
5619 $valueList = self
::trimExplode(',', $valueList, 1);
5621 $valListCnt = count($valueList);
5622 foreach ($arr as $key => $value) {
5623 if (!$valListCnt ||
in_array($key, $valueList)) {
5624 $str .= (string) $key . trim(': ' . self
::fixed_lgd_cs(str_replace(LF
, '|', (string) $value), $valueLength)) . '; ';
5631 * Compile the command for running ImageMagick/GraphicsMagick.
5633 * @param string $command Command to be run: identify, convert or combine/composite
5634 * @param string $parameters The parameters string
5635 * @param string $path Override the default path (e.g. used by the install tool)
5636 * @return string Compiled command that deals with IM6 & GraphicsMagick
5638 public static function imageMagickCommand($command, $parameters, $path = '') {
5639 return t3lib_utility_Command
::imageMagickCommand($command, $parameters, $path);
5643 * Explode a string (normally a list of filenames) with whitespaces by considering quotes in that string. This is mostly needed by the imageMagickCommand function above.
5645 * @param string $parameters The whole parameters string
5646 * @param boolean $unQuote If set, the elements of the resulting array are unquoted.
5647 * @return array Exploded parameters
5649 public static function unQuoteFilenames($parameters, $unQuote = FALSE) {
5650 $paramsArr = explode(' ', trim($parameters));
5652 $quoteActive = -1; // Whenever a quote character (") is found, $quoteActive is set to the element number inside of $params. A value of -1 means that there are not open quotes at the current position.
5653 foreach ($paramsArr as $k => $v) {
5654 if ($quoteActive > -1) {
5655 $paramsArr[$quoteActive] .= ' ' . $v;
5656 unset($paramsArr[$k]);
5657 if (substr($v, -1) === $paramsArr[$quoteActive][0]) {
5660 } elseif (!trim($v)) {
5661 unset($paramsArr[$k]); // Remove empty elements
5663 } elseif (preg_match('/^(["\'])/', $v) && substr($v, -1) !== $v[0]) {
5669 foreach ($paramsArr as $key => &$val) {
5670 $val = preg_replace('/(^"|"$)/', '', $val);
5671 $val = preg_replace('/(^\'|\'$)/', '', $val);
5676 // return reindexed array
5677 return array_values($paramsArr);
5682 * Quotes a string for usage as JS parameter.
5684 * @param string $value the string to encode, may be empty
5686 * @return string the encoded value already quoted (with single quotes),
5689 public static function quoteJSvalue($value) {
5690 $escapedValue = t3lib_div
::makeInstance('t3lib_codec_JavaScriptEncoder')->encode($value);
5691 return '\'' . $escapedValue . '\'';
5696 * Ends and cleans all output buffers
5700 public static function cleanOutputBuffers() {
5701 while (ob_end_clean()) {
5704 header('Content-Encoding: None', TRUE);
5709 * Ends and flushes all output buffers
5713 public static function flushOutputBuffers() {
5716 while ($content = ob_get_clean()) {
5717 $obContent .= $content;
5720 // if previously a "Content-Encoding: whatever" has been set, we have to unset it
5721 if (!headers_sent()) {
5722 $headersList = headers_list();
5723 foreach ($headersList as $header) {
5724 // split it up at the :
5725 list($key, $value) = self
::trimExplode(':', $header, TRUE);
5726 // check if we have a Content-Encoding other than 'None'
5727 if (strtolower($key) === 'content-encoding' && strtolower($value) !== 'none') {
5728 header('Content-Encoding: None');