Documentation TYPO3 par Ameos

class.t3lib_div.php

00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 1999-2007 Kasper Skaarhoj (kasperYYYY@typo3.com)
00006 *  All rights reserved
00007 *
00008 *  This script is part of the TYPO3 project. The TYPO3 project is
00009 *  free software; you can redistribute it and/or modify
00010 *  it under the terms of the GNU General Public License as published by
00011 *  the Free Software Foundation; either version 2 of the License, or
00012 *  (at your option) any later version.
00013 *
00014 *  The GNU General Public License can be found at
00015 *  http://www.gnu.org/copyleft/gpl.html.
00016 *  A copy is found in the textfile GPL.txt and important notices to the license
00017 *  from the author is found in LICENSE.txt distributed with these scripts.
00018 *
00019 *
00020 *  This script is distributed in the hope that it will be useful,
00021 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023 *  GNU General Public License for more details.
00024 *
00025 *  This copyright notice MUST APPEAR in all copies of the script!
00026 ***************************************************************/
00232 class t3lib_div {
00233 
00234 
00235 
00236 
00237 
00238         /*************************
00239          *
00240          * GET/POST Variables
00241          *
00242          * Background:
00243          * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
00244          * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
00245          * But the clean solution is that quotes are never escaped and that is what the functions below offers.
00246          * Eventually TYPO3 should provide this in the global space as well.
00247          * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
00248          *
00249          *************************/
00250 
00262         function _GP($var)      {
00263                 if(empty($var)) return;
00264                 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00265                 if (isset($value))      {
00266                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00267                 }
00268                 return $value;
00269         }
00270 
00280         function _GET($var=NULL)        {
00281                 $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
00282                 if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
00283                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00284                 }
00285                 return $value;
00286         }
00287 
00297         function _POST($var=NULL)       {
00298                 $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
00299                 if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
00300                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00301                 }
00302                 return $value;
00303         }
00304 
00313         function _GETset($inputGet,$key='')     {
00314                         // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
00315                 if (strcmp($key,''))    {
00316                         if (is_array($inputGet))        { t3lib_div::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); }
00317                         $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
00318                 } elseif (is_array($inputGet)){
00319                         t3lib_div::addSlashesOnArray($inputGet);
00320                         $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
00321                 }
00322         }
00323 
00336         function GPvar($var,$strip=0)   {
00337                 if(empty($var)) return;
00338                 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00339                 if (isset($value) && is_string($value)) { $value = stripslashes($value); }      // Originally check '&& get_magic_quotes_gpc() ' but the values of $_GET are always slashed regardless of get_magic_quotes_gpc() because HTTP_POST/GET_VARS are run through addSlashesOnArray in the very beginning of index_ts.php eg.
00340                 if ($strip && isset($value) && is_array($value)) { t3lib_div::stripSlashesOnArray($value); }
00341                 return $value;
00342         }
00343 
00353         function GParrayMerged($var)    {
00354                 $postA = is_array($_POST[$var]) ? $_POST[$var] : array();
00355                 $getA = is_array($_GET[$var]) ? $_GET[$var] : array();
00356                 $mergedA = t3lib_div::array_merge_recursive_overrule($getA,$postA);
00357                 t3lib_div::stripSlashesOnArray($mergedA);
00358                 return $mergedA;
00359         }
00360 
00361 
00362 
00363 
00364 
00365 
00366 
00367 
00368 
00369 
00370         /*************************
00371          *
00372          * IMAGE FUNCTIONS
00373          *
00374          *************************/
00375 
00376 
00397         function gif_compress($theFile, $type)  {
00398                 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
00399                 $returnCode='';
00400                 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif')      {       // GIF...
00401                         if (($type=='IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw'])       {       // IM
00402                                 $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
00403                                 exec($cmd);
00404 
00405                                 $returnCode='IM';
00406                         } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png'])       {       // GD
00407                                 $tempImage = imageCreateFromGif($theFile);
00408                                 imageGif($tempImage, $theFile);
00409                                 imageDestroy($tempImage);
00410                                 $returnCode='GD';
00411                         }
00412                 }
00413                 return $returnCode;
00414         }
00415 
00425         function png_to_gif_by_imagemagick($theFile)    {
00426                 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
00427                         && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
00428                         && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
00429                         && strtolower(substr($theFile,-4,4))=='.png'
00430                         && @is_file($theFile))  {       // IM
00431                                 $newFile = substr($theFile,0,-4).'.gif';
00432                                 $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
00433                                 exec($cmd);
00434                                 $theFile = $newFile;
00435                                         // unlink old file?? May be bad idea bacause TYPO3 would then recreate the file every time as TYPO3 thinks the file is not generated because it's missing!! So do not unlink $theFile here!!
00436                 }
00437                 return $theFile;
00438         }
00439 
00450         function read_png_gif($theFile,$output_png=0)   {
00451                 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile))     {
00452                         $ext = strtolower(substr($theFile,-4,4));
00453                         if (
00454                                         ((string)$ext=='.png' && $output_png)   ||
00455                                         ((string)$ext=='.gif' && !$output_png)
00456                                 )       {
00457                                 return $theFile;
00458                         } else {
00459                                 $newFile = PATH_site.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?'.png':'.gif');
00460                                 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'].'convert "'.$theFile.'" "'.$newFile.'"');
00461                                 if (@is_file($newFile)) return $newFile;
00462                         }
00463                 }
00464         }
00465 
00466 
00467 
00468 
00469 
00470 
00471 
00472 
00473 
00474 
00475 
00476 
00477 
00478 
00479 
00480         /*************************
00481          *
00482          * STRING FUNCTIONS
00483          *
00484          *************************/
00485 
00499         function fixed_lgd($string,$origChars,$preStr='...')    {
00500                 $chars = abs($origChars);
00501                 if ($chars >= 4)        {
00502                         if(strlen($string)>$chars)  {
00503                                 return $origChars < 0 ?
00504                                         $preStr.trim(substr($string, -($chars-3))) :
00505                                         trim(substr($string, 0, $chars-3)).$preStr;
00506                         }
00507                 }
00508                 return $string;
00509         }
00510 
00524         function fixed_lgd_pre($string,$chars)  {
00525                 return strrev(t3lib_div::fixed_lgd(strrev($string),$chars));
00526         }
00527 
00538         function fixed_lgd_cs($string,$chars)   {
00539                 if (is_object($GLOBALS['LANG']))        {
00540                         return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet,$string,$chars,'...');
00541                 } else {
00542                         return t3lib_div::fixed_lgd($string, $chars);
00543                 }
00544         }
00545 
00556         function breakTextForEmail($str,$implChar="\n",$charWidth=76)   {
00557                 $lines = explode(chr(10),$str);
00558                 $outArr=array();
00559                 while(list(,$lStr)=each($lines))        {
00560                         $outArr[] = t3lib_div::breakLinesForEmail($lStr,$implChar,$charWidth);
00561                 }
00562                 return implode(chr(10),$outArr);
00563         }
00564 
00575         function breakLinesForEmail($str,$implChar="\n",$charWidth=76)  {
00576                 $lines=array();
00577                 $l=$charWidth;
00578                 $p=0;
00579                 while(strlen($str)>$p)  {
00580                         $substr=substr($str,$p,$l);
00581                         if (strlen($substr)==$l)        {
00582                                 $count = count(explode(' ',trim(strrev($substr))));
00583                                 if ($count>1)   {       // OK...
00584                                         $parts = explode(' ',strrev($substr),2);
00585                                         $theLine = strrev($parts[1]);
00586                                 } else {
00587                                         $afterParts = explode(' ',substr($str,$l+$p),2);
00588                                         $theLine = $substr.$afterParts[0];
00589                                 }
00590                                 if (!strlen($theLine))  {break; }       // Error, because this would keep us in an endless loop.
00591                         } else {
00592                                 $theLine=$substr;
00593                         }
00594 
00595                         $lines[]=trim($theLine);
00596                         $p+=strlen($theLine);
00597                         if (!trim(substr($str,$p,$l)))  break;  // added...
00598                 }
00599                 return implode($implChar,$lines);
00600         }
00601 
00611         function cmpIP($baseIP, $list)  {
00612                 if ($list==='*')        return TRUE;
00613                 if (strstr($baseIP, ':') && t3lib_div::validIPv6($baseIP))      {
00614                         return t3lib_div::cmpIPv6($baseIP, $list);
00615                 } else {
00616                         return t3lib_div::cmpIPv4($baseIP, $list);
00617                 }
00618         }
00619 
00627         function cmpIPv4($baseIP, $list)        {
00628                 $IPpartsReq = explode('.',$baseIP);
00629                 if (count($IPpartsReq)==4)      {
00630                         $values = t3lib_div::trimExplode(',',$list,1);
00631 
00632                         foreach($values as $test)       {
00633                                 list($test,$mask) = explode('/',$test);
00634 
00635                                 if(intval($mask)) {
00636                                                 // "192.168.3.0/24"
00637                                         $lnet = ip2long($test);
00638                                         $lip = ip2long($baseIP);
00639                                         $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
00640                                         $firstpart = substr($binnet,0,$mask);
00641                                         $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
00642                                         $firstip = substr($binip,0,$mask);
00643                                         $yes = (strcmp($firstpart,$firstip)==0);
00644                                 } else {
00645                                                 // "192.168.*.*"
00646                                         $IPparts = explode('.',$test);
00647                                         $yes = 1;
00648                                         reset($IPparts);
00649                                         while(list($index,$val)=each($IPparts)) {
00650                                                 $val = trim($val);
00651                                                 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val))       {
00652                                                         $yes=0;
00653                                                 }
00654                                         }
00655                                 }
00656                                 if ($yes) return true;
00657                         }
00658                 }
00659                 return false;
00660         }
00661 
00669         function cmpIPv6($baseIP, $list)        {
00670                 $success = false;       // Policy default: Deny connection
00671                 $baseIP = t3lib_div::normalizeIPv6($baseIP);
00672 
00673                 $values = t3lib_div::trimExplode(',',$list,1);
00674                 foreach ($values as $test)      {
00675                         list($test,$mask) = explode('/',$test);
00676                         if (t3lib_div::validIPv6($test))        {
00677                                 $test = t3lib_div::normalizeIPv6($test);
00678                                 if (intval($mask))      {
00679                                         switch ($mask) {        // test on /48 /64
00680                                                 case '48':
00681                                                         $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 48);
00682                                                         $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 48);
00683                                                         $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00684                                                 break;
00685                                                 case '64':
00686                                                         $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 64);
00687                                                         $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 64);
00688                                                         $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00689                                                 break;
00690                                                 default:
00691                                                         $success = false;
00692                                         }
00693                                 } else {
00694                                         if (t3lib_div::validIPv6($test))        {       // test on full ip address 128 bits
00695                                                 $testBin = t3lib_div::IPv6Hex2Bin($test);
00696                                                 $baseIPBin = t3lib_div::IPv6Hex2Bin($baseIP);
00697                                                 $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00698                                         }
00699                                 }
00700                         }
00701                         if ($success) return true;
00702                 }
00703                 return false;
00704         }
00705 
00712         function IPv6Hex2Bin ($hex)     {
00713                 $bin = '';
00714                 $hex = str_replace(':', '', $hex);      // Replace colon to nothing
00715                 for ($i=0; $i<strlen($hex); $i=$i+2)    {
00716                         $bin.= chr(hexdec(substr($hex, $i, 2)));
00717                 }
00718                 return $bin;
00719         }
00720 
00727         function normalizeIPv6($address)        {
00728                 $normalizedAddress = '';
00729                 $stageOneAddress = '';
00730 
00731                 $chunks = explode('::', $address);      // Count 2 if if address has hidden zero blocks
00732                 if (count($chunks)==2)  {
00733                         $chunksLeft = explode(':', $chunks[0]);
00734                         $chunksRight = explode(':', $chunks[1]);
00735                         $left = count($chunksLeft);
00736                         $right = count($chunksRight);
00737 
00738                                 // Special case: leading zero-only blocks count to 1, should be 0
00739                         if ($left==1 && strlen($chunksLeft[0])==0)      $left=0;
00740 
00741                         $hiddenBlocks = 8 - ($left + $right);
00742                         $hiddenPart = '';
00743                         while ($h<$hiddenBlocks)        {
00744                                 $hiddenPart .= '0000:';
00745                                 $h++;
00746                         }
00747 
00748                         if ($left == 0) {
00749                                 $stageOneAddress = $hiddenPart . $chunks[1];
00750                         } else {
00751                                 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
00752                         }
00753                 } else $stageOneAddress = $address;
00754 
00755                         // normalize the blocks:
00756                 $blocks = explode(':', $stageOneAddress);
00757                 $divCounter = 0;
00758                 foreach ($blocks as $block)     {
00759                         $tmpBlock = '';
00760                         $i = 0;
00761                         $hiddenZeros = 4 - strlen($block);
00762                         while ($i < $hiddenZeros)       {
00763                                 $tmpBlock .= '0';
00764                                 $i++;
00765                         }
00766                         $normalizedAddress .= $tmpBlock . $block;
00767                         if ($divCounter < 7)    {
00768                                 $normalizedAddress .= ':';
00769                                 $divCounter++;
00770                         }
00771                 }
00772                 return $normalizedAddress;
00773         }
00774 
00783         function validIPv6($ip) {
00784                 $uppercaseIP = strtoupper($ip);
00785 
00786                 $regex = '/^(';
00787                 $regex.= '(([\dA-F]{1,4}:){7}[\dA-F]{1,4})|';
00788                 $regex.= '(([\dA-F]{1,4}){1}::([\dA-F]{1,4}:){1,5}[\dA-F]{1,4})|';
00789                 $regex.= '(([\dA-F]{1,4}:){2}:([\dA-F]{1,4}:){1,4}[\dA-F]{1,4})|';
00790                 $regex.= '(([\dA-F]{1,4}:){3}:([\dA-F]{1,4}:){1,3}[\dA-F]{1,4})|';
00791                 $regex.= '(([\dA-F]{1,4}:){4}:([\dA-F]{1,4}:){1,2}[\dA-F]{1,4})|';
00792                 $regex.= '(([\dA-F]{1,4}:){5}:([\dA-F]{1,4}:){0,1}[\dA-F]{1,4})|';
00793                 $regex.= '(::([\dA-F]{1,4}:){0,6}[\dA-F]{1,4})';
00794                 $regex.= ')$/';
00795 
00796                 return preg_match($regex, $uppercaseIP) ? true : false;
00797         }
00798 
00806         function cmpFQDN($baseIP, $list)        {
00807                 if (count(explode('.',$baseIP))==4)     {
00808                         $resolvedHostName = explode('.', gethostbyaddr($baseIP));
00809                         $values = t3lib_div::trimExplode(',',$list,1);
00810 
00811                         foreach($values as $test)       {
00812                                 $hostNameParts = explode('.',$test);
00813                                 $yes = 1;
00814 
00815                                 foreach($hostNameParts as $index => $val)       {
00816                                         $val = trim($val);
00817                                         if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
00818                                                 $yes=0;
00819                                         }
00820                                 }
00821                                 if ($yes) return true;
00822                         }
00823                 }
00824                 return false;
00825         }
00826 
00836         function inList($list,$item)    {
00837                 return strstr(','.$list.',', ','.$item.',') ? true : false;
00838         }
00839 
00848         function rmFromList($element,$list)     {
00849                 $items = explode(',',$list);
00850                 while(list($k,$v)=each($items)) {
00851                         if ($v==$element)       {unset($items[$k]);}
00852                 }
00853                 return implode(',',$items);
00854         }
00855 
00864         function expandList($list)      {
00865                 $items = explode(',',$list);
00866                 $list = array();
00867                 while(list(,$item)=each($items))        {
00868                         $range = explode('-',$item);
00869                         if (isset($range[1]))   {
00870                                 $runAwayBrake = 1000;
00871                                 for ($n=$range[0]; $n<=$range[1]; $n++) {
00872                                         $list[] = $n;
00873 
00874                                         $runAwayBrake--;
00875                                         if ($runAwayBrake<=0)   break;
00876                                 }
00877                         } else {
00878                                 $list[] = $item;
00879                         }
00880                 }
00881 
00882                 return implode(',',$list);
00883         }
00884 
00895         function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)  {
00896                 // Returns $theInt as an integer in the integerspace from $min to $max
00897                 $theInt = intval($theInt);
00898                 if ($zeroValue && !$theInt)     {$theInt=$zeroValue;}   // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
00899                 if ($theInt<$min){$theInt=$min;}
00900                 if ($theInt>$max){$theInt=$max;}
00901                 return $theInt;
00902         }
00903 
00911         function intval_positive($theInt)       {
00912                 $theInt = intval($theInt);
00913                 if ($theInt<0){$theInt=0;}
00914                 return $theInt;
00915         }
00916 
00924         function int_from_ver($verNumberStr)    {
00925                 $verParts = explode('.',$verNumberStr);
00926                 return intval((int)$verParts[0].str_pad((int)$verParts[1],3,'0',STR_PAD_LEFT).str_pad((int)$verParts[2],3,'0',STR_PAD_LEFT));
00927         }
00928 
00937         function compat_version($verNumberStr)  {
00938                 global $TYPO3_CONF_VARS;
00939                 $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version'] ? $TYPO3_CONF_VARS['SYS']['compat_version'] : TYPO3_branch;
00940 
00941                 if (t3lib_div::int_from_ver($currVersionStr) < t3lib_div::int_from_ver($verNumberStr))  {
00942                         return FALSE;
00943                 } else {
00944                         return TRUE;
00945                 }
00946         }
00947 
00955         function md5int($str)   {
00956                 return hexdec(substr(md5($str),0,7));
00957         }
00958 
00968         function shortMD5($input, $len=10)      {
00969                 return substr(md5($input),0,$len);
00970         }
00971 
00981         function uniqueList($in_list, $secondParameter=NULL)    {
00982                 if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
00983                 if (isset($secondParameter))    die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
00984 
00985                 return implode(',',array_unique(t3lib_div::trimExplode(',',$in_list,1)));
00986         }
00987 
00995         function split_fileref($fileref)        {
00996                 $reg = array();
00997                 if (    ereg('(.*/)(.*)$',$fileref,$reg)        )       {
00998                         $info['path'] = $reg[1];
00999                         $info['file'] = $reg[2];
01000                 } else {
01001                         $info['path'] = '';
01002                         $info['file'] = $fileref;
01003                 }
01004                 $reg='';
01005                 if (    ereg('(.*)\.([^\.]*$)',$info['file'],$reg)      )       {
01006                         $info['filebody'] = $reg[1];
01007                         $info['fileext'] = strtolower($reg[2]);
01008                         $info['realFileext'] = $reg[2];
01009                 } else {
01010                         $info['filebody'] = $info['file'];
01011                         $info['fileext'] = '';
01012                 }
01013                 reset($info);
01014                 return $info;
01015         }
01016 
01033         function dirname($path) {
01034                 $p=t3lib_div::revExplode('/',$path,2);
01035                 return count($p)==2?$p[0]:'';
01036         }
01037 
01049         function modifyHTMLColor($color,$R,$G,$B)       {
01050                 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
01051                 $nR = t3lib_div::intInRange(hexdec(substr($color,1,2))+$R,0,255);
01052                 $nG = t3lib_div::intInRange(hexdec(substr($color,3,2))+$G,0,255);
01053                 $nB = t3lib_div::intInRange(hexdec(substr($color,5,2))+$B,0,255);
01054                 return '#'.
01055                         substr('0'.dechex($nR),-2).
01056                         substr('0'.dechex($nG),-2).
01057                         substr('0'.dechex($nB),-2);
01058         }
01059 
01069         function modifyHTMLColorAll($color,$all)        {
01070                 return t3lib_div::modifyHTMLColor($color,$all,$all,$all);
01071         }
01072 
01080         function rm_endcomma($string)   {
01081                 return ereg_replace(',$','',$string);
01082         }
01083 
01093         function danish_strtoupper($string)     {
01094                 $value = strtoupper($string);
01095                 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
01096         }
01097 
01108         function convUmlauts($str)      {
01109                 $pat  = array ( '/ä/',  '/Ä/',  '/ö/',  '/Ö/',  '/ü/',  '/Ü/',  '/ß/',  '/å/',  '/Å/',  '/ø/',  '/Ø/',  '/æ/',  '/Æ/'   );
01110                 $repl = array ( 'ae',   'Ae',   'oe',   'Oe',   'ue',   'Ue',   'ss',   'aa',   'AA',   'oe',   'OE',   'ae',   'AE'    );
01111                 return preg_replace($pat,$repl,$str);
01112         }
01113 
01121         function testInt($var)  {
01122                 return !strcmp($var,intval($var));
01123         }
01124 
01133         function isFirstPartOfStr($str,$partStr)        {
01134                 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
01135                 $psLen = strlen($partStr);
01136                 if ($psLen)     {
01137                         return substr($str,0,$psLen)==(string)$partStr;
01138                 } else return false;
01139         }
01140 
01149         function formatSize($sizeInBytes,$labels='')    {
01150 
01151                         // Set labels:
01152                 if (strlen($labels) == 0) {
01153                     $labels = ' | K| M| G';
01154                 } else {
01155                     $labels = str_replace('"','',$labels);
01156                 }
01157                 $labelArr = explode('|',$labels);
01158 
01159                         // Find size:
01160                 if ($sizeInBytes>900)   {
01161                         if ($sizeInBytes>900000000)     {       // GB
01162                                 $val = $sizeInBytes/(1024*1024*1024);
01163                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
01164                         }
01165                         elseif ($sizeInBytes>900000)    {       // MB
01166                                 $val = $sizeInBytes/(1024*1024);
01167                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
01168                         } else {        // KB
01169                                 $val = $sizeInBytes/(1024);
01170                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
01171                         }
01172                 } else {        // Bytes
01173                         return $sizeInBytes.$labelArr[0];
01174                 }
01175         }
01176 
01184         function convertMicrotime($microtime)   {
01185                 $parts = explode(' ',$microtime);
01186                 return round(($parts[0]+$parts[1])*1000);
01187         }
01188 
01198         function splitCalc($string,$operators)  {
01199                 $res = Array();
01200                 $sign='+';
01201                 while($string)  {
01202                         $valueLen=strcspn($string,$operators);
01203                         $value=substr($string,0,$valueLen);
01204                         $res[] = Array($sign,trim($value));
01205                         $sign=substr($string,$valueLen,1);
01206                         $string=substr($string,$valueLen+1);
01207                 }
01208                 reset($res);
01209                 return $res;
01210         }
01211 
01220         function calcPriority($string)  {
01221                 $string=ereg_replace('[[:space:]]*','',$string);        // removing all whitespace
01222                 $string='+'.$string;    // Ensuring an operator for the first entrance
01223                 $qm='\*\/\+-^%';
01224                 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
01225                         // split the expression here:
01226                 $reg = array();
01227                 preg_match_all('/'.$regex.'/',$string,$reg);
01228 
01229                 reset($reg[2]);
01230                 $number=0;
01231                 $Msign='+';
01232                 $err='';
01233                 $buffer=doubleval(current($reg[2]));
01234                 next($reg[2]);  // Advance pointer
01235                 while(list($k,$v)=each($reg[2]))        {
01236                         $v=doubleval($v);
01237                         $sign = $reg[1][$k];
01238                         if ($sign=='+' || $sign=='-')   {
01239                                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01240                                 $Msign = $sign;
01241                                 $buffer=$v;
01242                         } else {
01243                                 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
01244                                 if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';}
01245                                 if ($sign=='*') {$buffer*=$v;}
01246                                 if ($sign=='^') {$buffer=pow($buffer,$v);}
01247                         }
01248                 }
01249                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01250                 return $err ? 'ERROR: '.$err : $number;
01251         }
01252 
01261         function calcParenthesis($string)       {
01262                 $securC=100;
01263                 do {
01264                         $valueLenO=strcspn($string,'(');
01265                         $valueLenC=strcspn($string,')');
01266                         if ($valueLenC==strlen($string) || $valueLenC < $valueLenO)     {
01267                                 $value = t3lib_div::calcPriority(substr($string,0,$valueLenC));
01268                                 $string = $value.substr($string,$valueLenC+1);
01269                                 return $string;
01270                         } else {
01271                                 $string = substr($string,0,$valueLenO).t3lib_div::calcParenthesis(substr($string,$valueLenO+1));
01272                         }
01273                                 // Security:
01274                         $securC--;
01275                         if ($securC<=0) break;
01276                 } while($valueLenO<strlen($string));
01277                 return $string;
01278         }
01279 
01287         function htmlspecialchars_decode($value)        {
01288                 $value = str_replace('&gt;','>',$value);
01289                 $value = str_replace('&lt;','<',$value);
01290                 $value = str_replace('&quot;','"',$value);
01291                 $value = str_replace('&amp;','&',$value);
01292                 return $value;
01293         }
01294 
01302         function deHSCentities($str)    {
01303                 return ereg_replace('&amp;([#[:alnum:]]*;)','&\1',$str);
01304         }
01305 
01315         function slashJS($string,$extended=0,$char="'") {
01316                 if ($extended)  {$string = str_replace ("\\", "\\\\", $string);}
01317                 return str_replace ($char, "\\".$char, $string);
01318         }
01319 
01328         function rawUrlEncodeJS($str)   {
01329                 return str_replace('%20',' ',rawurlencode($str));
01330         }
01331 
01340         function rawUrlEncodeFP($str)   {
01341                 return str_replace('%2F','/',rawurlencode($str));
01342         }
01343 
01351         function validEmail($email)     {
01352                 $email = trim ($email);
01353                 if (strstr($email,' '))  return FALSE;
01354                 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE : FALSE;
01355         }
01356 
01366         function formatForTextarea($content)    {
01367                 return chr(10).htmlspecialchars($content);
01368         }
01369 
01370 
01371 
01372 
01373 
01374 
01375 
01376 
01377 
01378 
01379 
01380 
01381         /*************************
01382          *
01383          * ARRAY FUNCTIONS
01384          *
01385          *************************/
01386 
01397         function inArray($in_array,$item)       {
01398                 if (is_array($in_array))        {
01399                         while (list(,$val)=each($in_array))     {
01400                                 if (!is_array($val) && !strcmp($val,$item)) return true;
01401                         }
01402                 }
01403         }
01404 
01414         function intExplode($delim, $string)    {
01415                 $temp = explode($delim,$string);
01416                 while(list($key,$val)=each($temp))      {
01417                         $temp[$key]=intval($val);
01418                 }
01419                 reset($temp);
01420                 return $temp;
01421         }
01422 
01433         function revExplode($delim, $string, $count=0)  {
01434                 $temp = explode($delim,strrev($string),$count);
01435                 while(list($key,$val)=each($temp))      {
01436                         $temp[$key]=strrev($val);
01437                 }
01438                 $temp=array_reverse($temp);
01439                 reset($temp);
01440                 return $temp;
01441         }
01442 
01453         function trimExplode($delim, $string, $onlyNonEmptyValues=0)    {
01454                 $temp = explode($delim,$string);
01455                 $newtemp=array();
01456                 while(list($key,$val)=each($temp))      {
01457                         if (!$onlyNonEmptyValues || strcmp('',trim($val)))      {
01458                                 $newtemp[]=trim($val);
01459                         }
01460                 }
01461                 reset($newtemp);
01462                 return $newtemp;
01463         }
01464 
01474         function uniqueArray($valueArray)       {
01475                 return array_unique($valueArray);
01476         }
01477 
01486         function removeArrayEntryByValue($array,$cmpValue)      {
01487                 if (is_array($array))   {
01488                         reset($array);
01489                         while(list($k,$v)=each($array)) {
01490                                 if (is_array($v))       {
01491                                         $array[$k] = t3lib_div::removeArrayEntryByValue($v,$cmpValue);
01492                                 } else {
01493                                         if (!strcmp($v,$cmpValue))      {
01494                                                 unset($array[$k]);
01495                                         }
01496                                 }
01497                         }
01498                 }
01499                 reset($array);
01500                 return $array;
01501         }
01502 
01515         function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)      {
01516                 if (is_array($theArray))        {
01517                         foreach($theArray as $Akey => $AVal)    {
01518                                 $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
01519                                 if (is_array($AVal))    {
01520                                         $str = t3lib_div::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
01521                                 } else {
01522                                         if (!$skipBlank || strcmp($AVal,''))    {
01523                                                 $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
01524                                                         '='.rawurlencode($AVal);
01525                                         }
01526                                 }
01527                         }
01528                 }
01529                 return $str;
01530         }
01531 
01540         function explodeUrl2Array($string,$multidim=FALSE)      {
01541                 $output = array();
01542                 if ($multidim)  {
01543                         parse_str($string,$output);
01544                 } else {
01545                         $p = explode('&',$string);
01546                         foreach($p as $v)       {
01547                                 if (strlen($v)) {
01548                                         list($pK,$pV) = explode('=',$v,2);
01549                                         $output[rawurldecode($pK)] = rawurldecode($pV);
01550                                 }
01551                         }
01552                 }
01553                 return $output;
01554         }
01555 
01566         function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)        {
01567                 $keys = t3lib_div::trimExplode(',',$varList,1);
01568                 $outArr=array();
01569                 foreach($keys as $v)    {
01570                         if (isset($getArray[$v]))       {
01571                                 $outArr[$v]=$getArray[$v];
01572                         } elseif ($GPvarAlt) {
01573                                 $outArr[$v]=t3lib_div::_GP($v);
01574                         }
01575                 }
01576                 return $outArr;
01577         }
01578 
01589         function addSlashesOnArray(&$theArray)  {
01590                 if (is_array($theArray))        {
01591                         reset($theArray);
01592                         while(list($Akey,$AVal)=each($theArray))        {
01593                                 if (is_array($AVal))    {
01594                                         t3lib_div::addSlashesOnArray($theArray[$Akey]);
01595                                 } else {
01596                                         $theArray[$Akey] = addslashes($AVal);
01597                                 }
01598                         }
01599                         reset($theArray);
01600                 }
01601         }
01602 
01613         function stripSlashesOnArray(&$theArray)        {
01614                 if (is_array($theArray))        {
01615                         reset($theArray);
01616                         while(list($Akey,$AVal)=each($theArray))        {
01617                                 if (is_array($AVal))    {
01618                                         t3lib_div::stripSlashesOnArray($theArray[$Akey]);
01619                                 } else {
01620                                         $theArray[$Akey] = stripslashes($AVal);
01621                                 }
01622                         }
01623                         reset($theArray);
01624                 }
01625         }
01626 
01635         function slashArray($arr,$cmd)  {
01636                 if ($cmd=='strip')      t3lib_div::stripSlashesOnArray($arr);
01637                 if ($cmd=='add')        t3lib_div::addSlashesOnArray($arr);
01638                 return $arr;
01639         }
01640 
01652         function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) {
01653                 reset($arr1);
01654                 while(list($key,$val) = each($arr1)) {
01655                         if(is_array($arr0[$key])) {
01656                                 if (is_array($arr1[$key]))      {
01657                                         $arr0[$key] = t3lib_div::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys);
01658                                 }
01659                         } else {
01660                                 if ($notAddKeys) {
01661                                         if (isset($arr0[$key])) {
01662                                                 if ($includeEmtpyValues OR $val) {
01663                                                         $arr0[$key] = $val;
01664                                                 }
01665                                         }
01666                                 } else {
01667                                         if ($includeEmtpyValues OR $val) {
01668                                                 $arr0[$key] = $val;
01669                                         }
01670                                 }
01671                         }
01672                 }
01673                 reset($arr0);
01674                 return $arr0;
01675         }
01676 
01685         function array_merge($arr1,$arr2)       {
01686                 return $arr2+$arr1;
01687         }
01688 
01698         function csvValues($row,$delim=',',$quote='"')  {
01699                 reset($row);
01700                 $out=array();
01701                 while(list(,$value)=each($row)) {
01702                         list($valPart) = explode(chr(10),$value);
01703                         $valPart = trim($valPart);
01704                         $out[]=str_replace($quote,$quote.$quote,$valPart);
01705                 }
01706                 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
01707                 return $str;
01708         }
01709 
01717         function removeDotsFromTS($ts) {
01718                 $out = array();
01719                 if (is_array($ts)) {
01720                         foreach ($ts as $key => $value) {
01721                                 if (is_array($value)) {
01722                                         $key = rtrim($key, '.');
01723                                         $out[$key] = t3lib_div::removeDotsFromTS($value);
01724                                 } else {
01725                                         $out[$key] = $value;
01726                                 }
01727                         }
01728                 }
01729                 return $out;
01730         }
01731 
01732 
01733 
01734 
01735 
01736 
01737 
01738 
01739 
01740 
01741 
01742 
01743 
01744 
01745 
01746 
01747         /*************************
01748          *
01749          * HTML/XML PROCESSING
01750          *
01751          *************************/
01752 
01762         function get_tag_attributes($tag)       {
01763                 $components = t3lib_div::split_tag_attributes($tag);
01764                 $name = '';      // attribute name is stored here
01765                 $valuemode = '';
01766                 if (is_array($components))      {
01767                         while (list($key,$val) = each ($components))    {
01768                                 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
01769                                         if ($valuemode) {
01770                                                 if ($name)      {
01771                                                         $attributes[$name] = $val;
01772                                                         $name = '';
01773                                                 }
01774                                         } else {
01775                                                 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val)))    {
01776                                                         $attributes[$key] = '';
01777                                                         $name = $key;
01778                                                 }
01779                                         }
01780                                         $valuemode = '';
01781                                 } else {
01782                                         $valuemode = 'on';
01783                                 }
01784                         }
01785                         if (is_array($attributes))      reset($attributes);
01786                         return $attributes;
01787                 }
01788         }
01789 
01799         function split_tag_attributes($tag)     {
01800                 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
01801                         // Removes any > in the end of the string
01802                 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
01803 
01804                 while (strcmp($tag_tmp,''))     {       // Compared with empty string instead , 030102
01805                         $firstChar=substr($tag_tmp,0,1);
01806                         if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
01807                                 $reg=explode($firstChar,$tag_tmp,3);
01808                                 $value[]=$reg[1];
01809                                 $tag_tmp=trim($reg[2]);
01810                         } elseif (!strcmp($firstChar,'=')) {
01811                                 $value[] = '=';
01812                                 $tag_tmp = trim(substr($tag_tmp,1));            // Removes = chars.
01813                         } else {
01814                                         // There are '' around the value. We look for the next ' ' or '>'
01815                                 $reg = split('[[:space:]=]',$tag_tmp,2);
01816                                 $value[] = trim($reg[0]);
01817                                 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
01818                         }
01819                 }
01820                 if (is_array($value))   reset($value);
01821                 return $value;
01822         }
01823 
01833         function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)   {
01834                 if (is_array($arr))     {
01835                         if ($xhtmlSafe) {
01836                                 $newArr=array();
01837                                 foreach($arr as $p => $v)       {
01838                                         if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
01839                                 }
01840                                 $arr = $newArr;
01841                         }
01842                         $list = array();
01843                         foreach($arr as $p => $v)       {
01844                                 if (strcmp($v,'') || $dontOmitBlankAttribs)     {$list[]=$p.'="'.$v.'"';}
01845                         }
01846                         return implode(' ',$list);
01847                 }
01848         }
01849 
01860         function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)       {
01861                 return t3lib_div::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
01862         }
01863 
01875         function wrapJS($string, $linebreak=TRUE) {
01876                 if(trim($string)) {
01877                                 // <script wrapped in nl?
01878                         $cr = $linebreak? "\n" : '';
01879 
01880                                 // remove nl from the beginning
01881                         $string = preg_replace ('/^\n+/', '', $string);
01882                                 // re-ident to one tab using the first line as reference
01883                         $match = array();
01884                         if(preg_match('/^(\t+)/',$string,$match)) {
01885                                 $string = str_replace($match[1],"\t", $string);
01886                         }
01887                         $string = $cr.'<script type="text/javascript">
01888 /*<![CDATA[*/
01889 '.$string.'
01890 /*]]>*/
01891 </script>'.$cr;
01892                 }
01893                 return trim($string);
01894         }
01895 
01896 
01906         function xml2tree($string,$depth=999) {
01907                 $parser = xml_parser_create();
01908                 $vals = array();
01909                 $index = array();
01910 
01911                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
01912                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
01913                 xml_parse_into_struct($parser, $string, $vals, $index);
01914 
01915                 if (xml_get_error_code($parser))        return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
01916                 xml_parser_free($parser);
01917 
01918                 $stack = array( array() );
01919                 $stacktop = 0;
01920                 $startPoint=0;
01921 
01922 // FIXME don't use unset() - what does that mean? Use NULL or similar.
01923                 unset($tagi);
01924                 foreach($vals as $key => $val) {
01925                         $type = $val['type'];
01926 
01927                                 // open tag:
01928                         if ($type=='open' || $type=='complete') {
01929                                 $stack[$stacktop++] = $tagi;
01930 
01931                                 if ($depth==$stacktop)  {
01932                                         $startPoint=$key;
01933                                 }
01934 
01935                                 $tagi = array('tag' => $val['tag']);
01936 
01937                                 if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
01938                                 if(isset($val['value']))        $tagi['values'][] = $val['value'];
01939                         }
01940                                 // finish tag:
01941                         if ($type=='complete' || $type=='close')        {
01942                                 $oldtagi = $tagi;
01943                                 $tagi = $stack[--$stacktop];
01944                                 $oldtag = $oldtagi['tag'];
01945                                 unset($oldtagi['tag']);
01946 
01947                                 if ($depth==($stacktop+1))      {
01948                                         if ($key-$startPoint > 0)       {
01949                                                 $partArray = array_slice(
01950                                                         $vals,
01951                                                         $startPoint+1,
01952                                                         $key-$startPoint-1
01953                                                 );
01954                                                 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
01955                                                 $oldtagi['XMLvalue']=t3lib_div::xmlRecompileFromStructValArray($partArray);
01956                                         } else {
01957                                                 $oldtagi['XMLvalue']=$oldtagi['values'][0];
01958                                         }
01959                                 }
01960 
01961                                 $tagi['ch'][$oldtag][] = $oldtagi;
01962                                 unset($oldtagi);
01963                         }
01964                                 // cdata
01965                         if($type=='cdata') {
01966                                 $tagi['values'][] = $val['value'];
01967                         }
01968                 }
01969                 return $tagi['ch'];
01970         }
01971 
01982         function array2xml_cs($array,$docTag='phparray',$options=array(),$charset='')   {
01983 
01984                         // Figure out charset if not given explicitly:
01985                 if (!$charset)  {
01986                         if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'])  {       // First priority: forceCharset! If set, this will be authoritative!
01987                                 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
01988                         } elseif (is_object($GLOBALS['LANG']))  {
01989                                 $charset = $GLOBALS['LANG']->charSet;   // If "LANG" is around, that will hold the current charset
01990                         } else {
01991                                 $charset = 'iso-8859-1';        // THIS is just a hopeful guess!
01992                         }
01993                 }
01994 
01995                         // Return XML:
01996                 return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.chr(10).
01997                                 t3lib_div::array2xml($array,'',0,$docTag,0, $options);
01998         }
01999 
02023         function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array())    {
02024                         // 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
02025                 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
02026                                                 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
02027                                                 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
02028                                                 chr(30).chr(31);
02029                         // Set indenting mode:
02030                 $indentChar = $spaceInd ? ' ' : chr(9);
02031                 $indentN = $spaceInd>0 ? $spaceInd : 1;
02032                 $nl = ($spaceInd >= 0 ? chr(10) : '');
02033 
02034                         // Init output variable:
02035                 $output='';
02036 
02037                         // Traverse the input array
02038                 if (is_array($array))   {
02039                         foreach($array as $k=>$v)       {
02040                                 $attr = '';
02041                                 $tagName = $k;
02042 
02043                                         // Construct the tag name.
02044                                 if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) {            // Use tag based on grand-parent + parent tag name
02045                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02046                                         $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
02047                                 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM']) && t3lib_div::testInt($tagName)) {              // Use tag based on parent tag name + if current tag is numeric
02048                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02049                                         $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM'];
02050                                 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) {            // Use tag based on parent tag name + current tag
02051                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02052                                         $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
02053                                 } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) {                // Use tag based on parent tag name:
02054                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02055                                         $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
02056                                 } elseif (!strcmp(intval($tagName),$tagName))   {       // If integer...;
02057                                         if ($options['useNindex']) {    // If numeric key, prefix "n"
02058                                                 $tagName = 'n'.$tagName;
02059                                         } else {        // Use special tag for num. keys:
02060                                                 $attr.=' index="'.$tagName.'"';
02061                                                 $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
02062                                         }
02063                                 } elseif($options['useIndexTagForAssoc']) {             // Use tag for all associative keys:
02064                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02065                                         $tagName = $options['useIndexTagForAssoc'];
02066                                 }
02067 
02068                                         // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
02069                                 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
02070 
02071                                         // If the value is an array then we will call this function recursively:
02072                                 if (is_array($v))       {
02073 
02074                                                 // Sub elements:
02075                                         if ($options['alt_options'][$stackData['path'].'/'.$tagName])   {
02076                                                 $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
02077                                                 $clearStackPath = $subOptions['clearStackPath'];
02078                                         } else {
02079                                                 $subOptions = $options;
02080                                                 $clearStackPath = FALSE;
02081                                         }
02082 
02083                                         $content = $nl .
02084                                                                 t3lib_div::array2xml(
02085                                                                         $v,
02086                                                                         $NSprefix,
02087                                                                         $level+1,
02088                                                                         '',
02089                                                                         $spaceInd,
02090                                                                         $subOptions,
02091                                                                         array(
02092                                                                                 'parentTagName' => $tagName,
02093                                                                                 'grandParentTagName' => $stackData['parentTagName'],
02094                                                                                 'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
02095                                                                         )
02096                                                                 ).
02097                                                                 ($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '');
02098                                         if ((int)$options['disableTypeAttrib']!=2)      {       // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
02099                                                 $attr.=' type="array"';
02100                                         }
02101                                 } else {        // Just a value:
02102 
02103                                                 // Look for binary chars:
02104                                         $vLen = strlen($v);     // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
02105                                         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!
02106                                                         // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
02107                                                 $content = $nl.chunk_split(base64_encode($v));
02108                                                 $attr.=' base64="1"';
02109                                         } else {
02110                                                         // Otherwise, just htmlspecialchar the stuff:
02111                                                 $content = htmlspecialchars($v);
02112                                                 $dType = gettype($v);
02113                                                 if ($dType == 'string') {
02114                                                         if ($options['useCDATA'] && $content != $v) {
02115                                                                 $content = '<![CDATA[' . $v . ']]>';
02116                                                         }
02117                                                 } elseif (!$options['disableTypeAttrib']) {
02118                                                         $attr.= ' type="'.$dType.'"';
02119                                                 }
02120                                         }
02121                                 }
02122 
02123                                         // Add the element to the output string:
02124                                 $output.=($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '').'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.$nl;
02125                         }
02126                 }
02127 
02128                         // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
02129                 if (!$level)    {
02130                         $output =
02131                                 '<'.$docTag.'>'.$nl.
02132                                 $output.
02133                                 '</'.$docTag.'>';
02134                 }
02135 
02136                 return $output;
02137         }
02138 
02150         function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
02151                 global $TYPO3_CONF_VARS;
02152 
02153                         // Create parser:
02154                 $parser = xml_parser_create();
02155                 $vals = array();
02156                 $index = array();
02157 
02158                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
02159                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
02160 
02161                         //  PHP4 doesn't like Unicode byte order marks (BOM), so we have to check for them
02162                         // The BOM check comes first, so that the PHP5 preg_match() below doesn't have to check for it
02163                 if(substr($string,0,3)=="\xEF\xBB\xBF") {
02164                         xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
02165                 }
02166                         // PHP 4.x: output charset is the same as the input charset, charsets are handled transparently if not specified in xml_parser_create()
02167                         // PHP 5.0.0 & 5.0.1: default output charset is ISO-8859-1, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
02168                         // PHP 5.0.2+: default output charset is UTF-8  , only ASCII, ISO-8859-1 and UTF-8 are supported!!!
02169                 elseif ((double)phpversion()>=5)        {
02170                         $match = array();
02171                         preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$match);
02172                         $theCharset = $match[1] ? $match[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
02173                         xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);  // us-ascii / utf-8 / iso-8859-1
02174                 }
02175 
02176                         // Parse content:
02177                 xml_parse_into_struct($parser, $string, $vals, $index);
02178 
02179                         // If error, return error message:
02180                 if (xml_get_error_code($parser))        {
02181                         return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
02182                 }
02183                 xml_parser_free($parser);
02184 
02185                         // Init vars:
02186                 $stack = array(array());
02187                 $stacktop = 0;
02188                 $current=array();
02189                 $tagName = '';
02190                 $documentTag = '';
02191 
02192                         // Traverse the parsed XML structure:
02193                 foreach($vals as $key => $val) {
02194 
02195                                 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
02196                         $tagName = $val['tag'];
02197                         if (!$documentTag)      $documentTag = $tagName;
02198 
02199                                 // Test for name space:
02200                         $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
02201 
02202                                 // Test for numeric tag, encoded on the form "nXXX":
02203                         $testNtag = substr($tagName,1); // Closing tag.
02204                         $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
02205 
02206                                 // Test for alternative index value:
02207                         if (strlen($val['attributes']['index']))        { $tagName = $val['attributes']['index']; }
02208 
02209                                 // Setting tag-values, manage stack:
02210                         switch($val['type'])    {
02211                                 case 'open':            // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
02212                                         $current[$tagName] = array();   // Setting blank place holder
02213                                         $stack[$stacktop++] = $current;
02214                                         $current = array();
02215                                 break;
02216                                 case 'close':   // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
02217                                         $oldCurrent = $current;
02218                                         $current = $stack[--$stacktop];
02219                                         end($current);  // Going to the end of array to get placeholder key, key($current), and fill in array next:
02220                                         $current[key($current)] = $oldCurrent;
02221                                         unset($oldCurrent);
02222                                 break;
02223                                 case 'complete':        // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
02224                                         if ($val['attributes']['base64'])       {
02225                                                 $current[$tagName] = base64_decode($val['value']);
02226                                         } else {
02227                                                 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
02228 
02229                                                         // Cast type:
02230                                                 switch((string)$val['attributes']['type'])      {
02231                                                         case 'integer':
02232                                                                 $current[$tagName] = (integer)$current[$tagName];
02233                                                         break;
02234                                                         case 'double':
02235                                                                 $current[$tagName] = (double)$current[$tagName];
02236                                                         break;
02237                                                         case 'boolean':
02238                                                                 $current[$tagName] = (bool)$current[$tagName];
02239                                                         break;
02240                                                         case 'array':
02241                                                                 $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...
02242                                                         break;
02243                                                 }
02244                                         }
02245                                 break;
02246                         }
02247                 }
02248 
02249                 if ($reportDocTag)      {
02250                         $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
02251                 }
02252 
02253                         // Finally return the content of the document tag.
02254                 return $current[$tagName];
02255         }
02256 
02264         function xmlRecompileFromStructValArray($vals)  {
02265                 $XMLcontent='';
02266 
02267                 foreach($vals as $val) {
02268                         $type = $val['type'];
02269 
02270                                 // open tag:
02271                         if ($type=='open' || $type=='complete') {
02272                                 $XMLcontent.='<'.$val['tag'];
02273                                 if(isset($val['attributes']))  {
02274                                         foreach($val['attributes'] as $k => $v) {
02275                                                 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
02276                                         }
02277                                 }
02278                                 if ($type=='complete')  {
02279                                         if(isset($val['value']))        {
02280                                                 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
02281                                         } else $XMLcontent.='/>';
02282                                 } else $XMLcontent.='>';
02283 
02284                                 if ($type=='open' && isset($val['value']))      {
02285                                         $XMLcontent.=htmlspecialchars($val['value']);
02286                                 }
02287                         }
02288                                 // finish tag:
02289                         if ($type=='close')     {
02290                                 $XMLcontent.='</'.$val['tag'].'>';
02291                         }
02292                                 // cdata
02293                         if($type=='cdata') {
02294                                 $XMLcontent.=htmlspecialchars($val['value']);
02295                         }
02296                 }
02297 
02298                 return $XMLcontent;
02299         }
02300 
02308         function xmlGetHeaderAttribs($xmlData)  {
02309                 $xmlHeader = substr(trim($xmlData),0,200);
02310                 $reg=array();
02311                 if (eregi('^<\?xml([^>]*)\?\>',$xmlHeader,$reg))        {
02312                         return t3lib_div::get_tag_attributes($reg[1]);
02313                 }
02314         }
02315 
02316 
02317 
02318 
02319 
02320 
02321 
02322 
02323 
02324 
02325 
02326         /*************************
02327          *
02328          * FILES FUNCTIONS
02329          *
02330          *************************/
02331 
02342         function getURL($url, $includeHeader = 0, $requestHeaders = false)      {
02343                 $content = false;
02344 
02345                         // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
02346                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^https?:\/\//', $url)) {
02347                                 // External URL without error checking.
02348                         $ch = curl_init();
02349                         if (!$ch)       {
02350                                 return false;
02351                         }
02352 
02353                         curl_setopt($ch, CURLOPT_URL, $url);
02354                         curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
02355                         curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
02356                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
02357                         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
02358                         curl_setopt($ch, CURLOPT_FAILONERROR, 1);
02359                         if (is_array($requestHeaders))  {
02360                                 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
02361                         }
02362 
02363                         if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer'])      {
02364                                 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
02365 
02366                                         // Not sure if this is needed
02367                                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'])      {
02368                                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
02369                                 }
02370                                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'])    {
02371                                         curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
02372                                 }
02373                         }
02374                         $content = curl_exec($ch);
02375                         curl_close($ch);
02376 
02377                 } elseif ($includeHeader)       {
02378                         $parsedURL = parse_url($url);
02379                         if (!t3lib_div::inList('ftp,ftps,http,https,gopher,telnet', $parsedURL['scheme']))      {
02380                                 return false;
02381                         }
02382 
02383                         $fp = @fsockopen($parsedURL['host'], ($parsedURL['port'] > 0 ? $parsedURL['port'] : 80), $errno, $errstr, 2.0);
02384                         if (!$fp)       {
02385                                 return false;
02386                         }
02387 
02388                         $msg = 'GET ' . $parsedURL['path'] .
02389                                         ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
02390                                         ' HTTP/1.0' . "\r\n" . 'Host: ' .
02391                                         $parsedURL['host'] . "\r\n\r\n";
02392                         fputs($fp, $msg);
02393                         while (!feof($fp))      {
02394                                 $line = fgets($fp, 2048);
02395                                 $content.= $line;
02396                                 if ($includeHeader == 2 && !strlen(trim($line)))        {
02397                                         break;  // Stop at the first empty line (= end of header)
02398                                 }
02399                         }
02400                         fclose($fp);
02401 
02402                 } elseif (is_array($requestHeaders))    {
02403                         $ctx = stream_context_create(array(
02404                                                 'http' => array(
02405                                                         'header' => implode("\r\n", $requestHeaders)
02406                                                 )
02407                                         )
02408                                 );
02409                         if (version_compare(phpversion(), '5.0', '>=')) {
02410                                 $content = @file_get_contents($url, false, $ctx);
02411                         }
02412                         elseif (false !== ($fd = @fopen($url, 'rb', false, $ctx)))      {
02413                                 $content = '';
02414                                 while (!feof($fd))      {
02415                                         $content.= @fread($fd, 4096);
02416                                 }
02417                                 fclose($fd);
02418                         }
02419                 }
02420                 else    {
02421                         $content = @file_get_contents($url);
02422                 }
02423 
02424                 return $content;
02425         }
02426 
02435         function writeFile($file,$content)      {
02436                 if (!@is_file($file))   $changePermissions = true;
02437 
02438                 if ($fd = fopen($file,'wb'))    {
02439                         $res = fwrite($fd,$content);
02440                         fclose($fd);
02441 
02442                         if ($res===false)       return false;
02443 
02444                         if ($changePermissions) {       // Change the permissions only if the file has just been created
02445                                 t3lib_div::fixPermissions($file);
02446                         }
02447 
02448                         return true;
02449                 }
02450 
02451                 return false;
02452         }
02453 
02460         function fixPermissions($file)  {
02461                 if (@is_file($file) && TYPO3_OS!='WIN') {
02462                         @chmod($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));             // "@" is there because file is not necessarily OWNED by the user
02463                         if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
02464                                 @chgrp($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);                // "@" is there because file is not necessarily OWNED by the user
02465                         }
02466                 }
02467         }
02468 
02477         function writeFileToTypo3tempDir($filepath,$content)    {
02478 
02479                         // Parse filepath into directory and basename:
02480                 $fI = pathinfo($filepath);
02481                 $fI['dirname'].= '/';
02482 
02483                         // Check parts:
02484                 if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60)        {
02485                         if (defined('PATH_site'))       {
02486                                 $dirName = PATH_site.'typo3temp/';      // Setting main temporary directory name (standard)
02487                                 if (@is_dir($dirName))  {
02488                                         if (t3lib_div::isFirstPartOfStr($fI['dirname'],$dirName))       {
02489 
02490                                                         // Checking if the "subdir" is found:
02491                                                 $subdir = substr($fI['dirname'],strlen($dirName));
02492                                                 if ($subdir)    {
02493                                                         if (ereg('^[[:alnum:]_]+\/$',$subdir) || ereg('^[[:alnum:]_]+\/[[:alnum:]_]+\/$',$subdir))      {
02494                                                                 $dirName.= $subdir;
02495                                                                 if (!@is_dir($dirName)) {
02496                                                                         t3lib_div::mkdir_deep(PATH_site.'typo3temp/', $subdir);
02497                                                                 }
02498                                                         } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or  "[[:alnum:]_]/[[:alnum:]_]/"';
02499                                                 }
02500                                                         // Checking dir-name again (sub-dir might have been created):
02501                                                 if (@is_dir($dirName))  {
02502                                                         if ($filepath == $dirName.$fI['basename'])      {
02503                                                                 t3lib_div::writeFile($filepath, $content);
02504                                                                 if (!@is_file($filepath))       return 'File not written to disk! Write permission error in filesystem?';
02505                                                         } else return 'Calculated filelocation didn\'t match input $filepath!';
02506                                                 } else return '"'.$dirName.'" is not a directory!';
02507                                         } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
02508                                 } else return 'PATH_site + "typo3temp/" was not a directory!';
02509                         } else return 'PATH_site constant was NOT defined!';
02510                 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
02511         }
02512 
02520         function mkdir($theNewFolder)   {
02521                 $theNewFolder = preg_replace('|/$|','',$theNewFolder);
02522                 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
02523                         chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
02524 
02525                         if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
02526                                 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
02527                         }
02528                         return TRUE;
02529                 }
02530         }
02531 
02539         function mkdir_deep($destination,$deepDir)      {
02540                 $allParts = t3lib_div::trimExplode('/',$deepDir,1);
02541                 $root = '';
02542                 foreach($allParts as $part)     {
02543                         $root.= $part.'/';
02544                         if (!is_dir($destination.$root))        {
02545                                 t3lib_div::mkdir($destination.$root);
02546                                 if (!@is_dir($destination.$root))       {
02547                                         return 'Error: The directory "'.$destination.$root.'" could not be created...';
02548                                 }
02549                         }
02550                 }
02551         }
02552 
02561         function get_dirs($path)        {
02562                 if ($path)      {
02563                         $d = @dir($path);
02564                         if (is_object($d))      {
02565                                 while($entry=$d->read()) {
02566                                         if (@is_dir($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
02567                                             $filearray[]=$entry;
02568                                         }
02569                                 }
02570                                 $d->close();
02571                         } else return 'error';
02572                         return $filearray;
02573                 }
02574         }
02575 
02587         function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='')     {
02588 
02589                         // Initialize variabels:
02590                 $filearray = array();
02591                 $sortarray = array();
02592                 $path = ereg_replace('\/$','',$path);
02593 
02594                         // Find files+directories:
02595                 if (@is_dir($path))     {
02596                         $extensionList = strtolower($extensionList);
02597                         $d = dir($path);
02598                         if (is_object($d))      {
02599                                 while($entry=$d->read()) {
02600                                         if (@is_file($path.'/'.$entry)) {
02601                                                 $fI = pathinfo($entry);
02602                                                 $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)
02603                                                 if ((!strlen($extensionList) || t3lib_div::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$entry))) {
02604                                                     $filearray[$key]=($prependPath?$path.'/':'').$entry;
02605                                                                 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
02606                                                                 elseif ($order) {$sortarray[$key]=$entry;}
02607                                                 }
02608                                         }
02609                                 }
02610                                 $d->close();
02611                         } else return 'error opening path: "'.$path.'"';
02612                 }
02613 
02614                         // Sort them:
02615                 if ($order) {
02616                         asort($sortarray);
02617                         reset($sortarray);
02618                         $newArr=array();
02619                         while(list($k,$v)=each($sortarray))     {
02620                                 $newArr[$k]=$filearray[$k];
02621                         }
02622                         $filearray=$newArr;
02623                 }
02624 
02625                         // Return result
02626                 reset($filearray);
02627                 return $filearray;
02628         }
02629 
02642         function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='')    {
02643                 if ($regDirs)   $fileArr[] = $path;
02644                 $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path,$extList,1,1,$excludePattern));
02645 
02646                 $dirs = t3lib_div::get_dirs($path);
02647                 if (is_array($dirs) && $recursivityLevels>0)    {
02648                         foreach ($dirs as $subdirs)     {
02649                                 if ((string)$subdirs!='' && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$subdirs)))      {
02650                                         $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1,$excludePattern);
02651                                 }
02652                         }
02653                 }
02654                 return $fileArr;
02655         }
02656 
02665         function removePrefixPathFromList($fileArr,$prefixToRemove)     {
02666                 foreach($fileArr as $k => $absFileRef)  {
02667                         if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove))    {
02668                                 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
02669                         } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
02670                 }
02671                 return $fileArr;
02672         }
02673 
02681         function fixWindowsFilePath($theFile)   {
02682                 return str_replace('//','/', str_replace('\\','/', $theFile));
02683         }
02684 
02693         function resolveBackPath($pathStr)      {
02694                 $parts = explode('/',$pathStr);
02695                 $output=array();
02696                 $c = 0;
02697                 foreach($parts as $pV)  {
02698                         if ($pV=='..')  {
02699                                 if ($c) {
02700                                         array_pop($output);
02701                                         $c--;
02702                                 } else $output[]=$pV;
02703                         } else {
02704                                 $c++;
02705                                 $output[]=$pV;
02706                         }
02707                 }
02708                 return implode('/',$output);
02709         }
02710 
02721         function locationHeaderUrl($path)       {
02722                 $uI = parse_url($path);
02723                 if (substr($path,0,1)=='/')     { // relative to HOST
02724                         $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
02725                 } elseif (!$uI['scheme'])       { // No scheme either
02726                         $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
02727                 }
02728                 return $path;
02729         }
02730 
02731 
02732 
02733 
02734 
02735 
02736 
02737 
02738 
02739 
02740 
02741 
02742 
02743 
02744 
02745 
02746         /*************************
02747          *
02748          * DEBUG helper FUNCTIONS
02749          *
02750          *************************/
02751 
02761         function debug_ordvalue($string,$characters=100)        {
02762                 if(strlen($string) < $characters)       $characters = strlen($string);
02763                 for ($i=0; $i<$characters; $i++)        {
02764                         $valuestring.=' '.ord(substr($string,$i,1));
02765                 }
02766                 return trim($valuestring);
02767         }
02768 
02778         function view_array($array_in)  {
02779                 if (is_array($array_in))        {
02780                         $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
02781                         if (!count($array_in))  {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
02782                         while (list($key,$val)=each($array_in)) {
02783                                 $result.= '<tr><td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
02784                                 if (is_array($array_in[$key]))  {
02785                                         $result.=t3lib_div::view_array($array_in[$key]);
02786                                 } else
02787                                         $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
02788                                 $result.= '</td></tr>';
02789                         }
02790                         $result.= '</table>';
02791                 } else  {
02792                         $result  = '<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">
02793                                 <tr>
02794                                         <td><font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$array_in)).'<br /></font></td>
02795                                 </tr>
02796                         </table>';      // Output it as a string.
02797                 }
02798                 return $result;
02799         }
02800 
02810         function print_array($array_in) {
02811                 echo t3lib_div::view_array($array_in);
02812         }
02813 
02825         function debug($var="",$brOrHeader=0)   {
02826                 if ($brOrHeader && !t3lib_div::testInt($brOrHeader))    {
02827                         echo '<table class="typo3-debug" border="0" cellpadding="0" cellspacing="0" bgcolor="white" style="border:0px; margin-top:3px; margin-bottom:3px;"><tr><td style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;">'.htmlspecialchars((string)$brOrHeader).'</td></tr><tr><td>';
02828                 } elseif ($brOrHeader<0)        {
02829                         for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
02830                 }
02831 
02832                 if (is_array($var))     {
02833                         t3lib_div::print_array($var);
02834                 } elseif (is_object($var))      {
02835                         echo '<b>|Object:<pre>';
02836                         print_r($var);
02837                         echo '</pre>|</b>';
02838                 } elseif ((string)$var!='')     {
02839                         echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
02840                 } else {
02841                         echo '<b>| debug |</b>';
02842                 }
02843 
02844                 if ($brOrHeader && !t3lib_div::testInt($brOrHeader))    {
02845                         echo '</td></tr></table>';
02846                 } elseif ($brOrHeader>0)        {
02847                         for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
02848                 }
02849         }
02850 
02856         function debug_trail()  {
02857                 $trail = debug_backtrace();
02858                 $trail = array_reverse($trail);
02859                 array_pop($trail);
02860 
02861                 $path = array();
02862                 foreach($trail as $dat) {
02863                         $path[] = $dat['class'].$dat['type'].$dat['function'];
02864                 }
02865 
02866                 return implode(' // ',$path);
02867         }
02868 
02876         function debugRows($rows,$header='')    {
02877                 if (is_array($rows))    {
02878                         reset($rows);
02879                         $firstEl = current($rows);
02880                         if (is_array($firstEl)) {
02881                                 $headerColumns = array_keys($firstEl);
02882                                 $tRows = array();
02883 
02884                                         // Header:
02885                                 $tRows[] = '<tr><td colspan="'.count($headerColumns).'" style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;"><strong>'.htmlspecialchars($header).'</strong></td></tr>';
02886                                 $tCells = array();
02887                                 foreach($headerColumns as $key) {
02888                                         $tCells[] = '
02889                                                         <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
02890                                 }
02891                                 $tRows[] = '
02892                                                 <tr>'.implode('',$tCells).'
02893                                                 </tr>';
02894 
02895                                         // Rows:
02896                                 foreach($rows as $singleRow)    {
02897                                         $tCells = array();
02898                                         foreach($headerColumns as $key) {
02899                                                 $tCells[] = '
02900                                                         <td><font face="Verdana,Arial" size="1">'.htmlspecialchars($singleRow[$key]).'</font></td>';
02901                                         }
02902                                         $tRows[] = '
02903                                                 <tr>'.implode('',$tCells).'
02904                                                 </tr>';
02905                                 }
02906 
02907                                 $table = '
02908                                         <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
02909                                         </table>';
02910                                 echo $table;
02911                         } else debug('Empty array of rows',$header);
02912                 } else debug('No array of rows',$header);
02913         }
02914 
02915 
02916 
02917 
02918 
02919 
02920 
02921 
02922 
02923 
02924 
02925 
02926 
02927 
02928 
02929 
02930 
02931 
02932 
02933 
02934 
02935 
02936 
02937 
02938 
02939 
02940 
02941 
02942         /*************************
02943          *
02944          * SYSTEM INFORMATION
02945          *
02946          *************************/
02947 
02954         function getThisUrl()   {
02955                 $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'));            // Url of this script
02956                 $dir=t3lib_div::dirname($p['path']).'/';        // Strip file
02957                 $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
02958                 return $url;
02959         }
02960 
02970         function linkThisScript($getParams=array())     {
02971                 $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
02972                 $params = t3lib_div::_GET();
02973 
02974                 foreach($getParams as $k => $v) {
02975                         if (strcmp($v,''))      {
02976                                 $params[$k]=$v;
02977                         } else unset($params[$k]);
02978                 }
02979 
02980                 $pString = t3lib_div::implodeArrayForUrl('',$params);
02981 
02982                 return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
02983         }
02984 
02994         function linkThisUrl($url,$getParams=array())   {
02995                 $parts = parse_url($url);
02996                 $getP = array();
02997                 if ($parts['query'])    {
02998                         parse_str($parts['query'],$getP);
02999                 }
03000                 $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
03001                 $uP = explode('?',$url);
03002 
03003                 $params = t3lib_div::implodeArrayForUrl('',$getP);
03004                 $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
03005 
03006                 return $outurl;
03007         }
03008 
03017         function getIndpEnv($getEnvName)        {
03018                 /*
03019                         Conventions:
03020                         output from parse_url():
03021                         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
03022                             [scheme] => 'http'
03023                             [user] => 'username'
03024                             [pass] => 'password'
03025                             [host] => '192.168.1.4'
03026                                 [port] => '8080'
03027                             [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
03028                             [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
03029                             [fragment] => 'link1'
03030 
03031                                 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
03032                                                                         [path_dir] = '/typo3/32/temp/phpcheck/'
03033                                                                         [path_info] = '/arg1/arg2/arg3/'
03034                                                                         [path] = [path_script/path_dir][path_info]
03035 
03036 
03037                         Keys supported:
03038 
03039                         URI______:
03040                                 REQUEST_URI             =       [path]?[query]          = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
03041                                 HTTP_HOST               =       [host][:[port]]         = 192.168.1.4:8080
03042                                 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')!
03043                                 PATH_INFO               =       [path_info]                     = /arg1/arg2/arg3/
03044                                 QUERY_STRING    =       [query]                         = arg1,arg2,arg3&p1=parameter1&p2[key]=value
03045                                 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
03046                                                                                 (Notice: NO username/password + NO fragment)
03047 
03048                         CLIENT____:
03049                                 REMOTE_ADDR             =       (client IP)
03050                                 REMOTE_HOST             =       (client host)
03051                                 HTTP_USER_AGENT =       (client user agent)
03052                                 HTTP_ACCEPT_LANGUAGE    = (client accept language)
03053 
03054                         SERVER____:
03055                                 SCRIPT_FILENAME =       Absolute filename of script             (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
03056 
03057                         Special extras:
03058                                 TYPO3_HOST_ONLY =               [host] = 192.168.1.4
03059                                 TYPO3_PORT =                    [port] = 8080 (blank if 80, taken from host value)
03060                                 TYPO3_REQUEST_HOST =    [scheme]://[host][:[port]]
03061                                 TYPO3_REQUEST_URL =             [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
03062                                 TYPO3_REQUEST_SCRIPT =  [scheme]://[host][:[port]][path_script]
03063                                 TYPO3_REQUEST_DIR =             [scheme]://[host][:[port]][path_dir]
03064                                 TYPO3_SITE_URL =                [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
03065                                 TYPO3_SITE_SCRIPT =     [script / Speaking URL] of the TYPO3 website
03066                                 TYPO3_DOCUMENT_ROOT =   Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
03067                                 TYPO3_SSL =                     Returns TRUE if this session uses SSL (HTTPS)
03068 
03069                         Notice: [fragment] is apparently NEVER available to the script!
03070 
03071 
03072                         Testing suggestions:
03073                         - Output all the values.
03074                         - 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
03075                         - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
03076 
03077                 */
03078 
03079 #               if ($getEnvName=='HTTP_REFERER')        return '';
03080 
03081                 $retVal = '';
03082 
03083                 switch ((string)$getEnvName)    {
03084                         case 'SCRIPT_NAME':
03085                                 $retVal = (php_sapi_name()=='cgi'||php_sapi_name()=='cgi-fcgi')&&($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) ? ($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) : ($_SERVER['ORIG_SCRIPT_NAME']?$_SERVER['ORIG_SCRIPT_NAME']:$_SERVER['SCRIPT_NAME']);
03086                         break;
03087                         case 'SCRIPT_FILENAME':
03088                                 $retVal = str_replace('//','/', str_replace('\\','/', (php_sapi_name()=='cgi'||php_sapi_name()=='isapi' ||php_sapi_name()=='cgi-fcgi')&&($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED'])? ($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED']):($_SERVER['ORIG_SCRIPT_FILENAME']?$_SERVER['ORIG_SCRIPT_FILENAME']:$_SERVER['SCRIPT_FILENAME'])));
03089                         break;
03090                         case 'REQUEST_URI':
03091                                         // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
03092                                 if ($GLOBALS['TYPO3_CONF_VAR']['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)
03093                                         list($v,$n) = explode('|',$GLOBALS['TYPO3_CONF_VAR']['SYS']['requestURIvar']);
03094                                         $retVal = $GLOBALS[$v][$n];
03095                                 } elseif (!$_SERVER['REQUEST_URI'])     {       // This is for ISS/CGI which does not have the REQUEST_URI available.
03096                                         $retVal = '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
03097                                                 ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
03098                                 } else $retVal = $_SERVER['REQUEST_URI'];
03099                         break;
03100                         case 'PATH_INFO':
03101                                         // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
03102                                         // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
03103                                         // IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers, then 'php_sapi_name()=='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_name()=='cgi' (see above)
03104 //                              if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1)  {
03105                                 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi')        {
03106                                         $retVal = $_SERVER['PATH_INFO'];
03107                                 }
03108                         break;
03109                                 // These are let through without modification
03110                         case 'REMOTE_ADDR':
03111                         case 'REMOTE_HOST':
03112                         case 'HTTP_REFERER':
03113                         case 'HTTP_HOST':
03114                         case 'HTTP_USER_AGENT':
03115                         case 'HTTP_ACCEPT_LANGUAGE':
03116                         case 'QUERY_STRING':
03117                                 $retVal = $_SERVER[$getEnvName];
03118                         break;
03119                         case 'TYPO3_DOCUMENT_ROOT':
03120                                 // 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.
03121                                 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
03122                                 $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
03123                                 $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
03124                                 $SFN_A = explode('/',strrev($SFN));
03125                                 $acc = array();
03126                                 while(list($kk,$vv)=each($SN_A))        {
03127                                         if (!strcmp($SFN_A[$kk],$vv))   {
03128                                                 $acc[] = $vv;
03129                                         } else break;
03130                                 }
03131                                 $commonEnd=strrev(implode('/',$acc));
03132                                 if (strcmp($commonEnd,''))      { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
03133                                 $retVal = $DR;
03134                         break;
03135                         case 'TYPO3_HOST_ONLY':
03136                                 $p = explode(':',$_SERVER['HTTP_HOST']);
03137                                 $retVal = $p[0];
03138                         break;
03139                         case 'TYPO3_PORT':
03140                                 $p = explode(':',$_SERVER['HTTP_HOST']);
03141                                 $retVal = $p[1];
03142                         break;
03143                         case 'TYPO3_REQUEST_HOST':
03144                                 $retVal = (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
03145                                         $_SERVER['HTTP_HOST'];
03146                         break;
03147                         case 'TYPO3_REQUEST_URL':
03148                                 $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
03149                         break;
03150                         case 'TYPO3_REQUEST_SCRIPT':
03151                                 $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
03152                         break;
03153                         case 'TYPO3_REQUEST_DIR':
03154                                 $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
03155                         break;
03156                         case 'TYPO3_SITE_URL':
03157                                 if (defined('PATH_thisScript') && defined('PATH_site')) {
03158                                         $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
03159                                         $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
03160                                         $siteUrl = substr($url,0,-strlen($lPath));
03161                                         if (substr($siteUrl,-1)!='/')   $siteUrl.='/';
03162                                         $retVal = $siteUrl;
03163                                 }
03164                         break;
03165                         case 'TYPO3_SITE_SCRIPT':
03166                                 $retVal = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
03167                         break;
03168                         case 'TYPO3_SSL':
03169                                 $retVal = $_SERVER['SSL_SESSION_ID'] || !strcmp($_SERVER['HTTPS'],'on') || !strcmp($_SERVER['HTTPS'],'1') ? TRUE : FALSE;       // see http://bugs.typo3.org/view.php?id=3909
03170                         break;
03171                         case '_ARRAY':
03172                                 $out = array();
03173                                         // Here, list ALL possible keys to this function for debug display.
03174                                 $envTestVars = t3lib_div::trimExplode(',','
03175                                         HTTP_HOST,
03176                                         TYPO3_HOST_ONLY,
03177                                         TYPO3_PORT,
03178                                         PATH_INFO,
03179                                         QUERY_STRING,
03180                                         REQUEST_URI,
03181                                         HTTP_REFERER,
03182                                         TYPO3_REQUEST_HOST,
03183                                         TYPO3_REQUEST_URL,
03184                                         TYPO3_REQUEST_SCRIPT,
03185                                         TYPO3_REQUEST_DIR,
03186                                         TYPO3_SITE_URL,
03187                                         TYPO3_SITE_SCRIPT,
03188                                         TYPO3_SSL,
03189                                         SCRIPT_NAME,
03190                                         TYPO3_DOCUMENT_ROOT,
03191                                         SCRIPT_FILENAME,
03192                                         REMOTE_ADDR,
03193                                         REMOTE_HOST,
03194                                         HTTP_USER_AGENT,
03195                                         HTTP_ACCEPT_LANGUAGE',1);
03196                                 reset($envTestVars);
03197                                 while(list(,$v)=each($envTestVars))     {
03198                                         $out[$v]=t3lib_div::getIndpEnv($v);
03199                                 }
03200                                 reset($out);
03201                                 $retVal = $out;
03202                         break;
03203                 }
03204                 return $retVal;
03205         }
03206 
03214         function milliseconds() {
03215                 $p=explode(' ',microtime());
03216                 return round(($p[0]+$p[1])*1000);
03217         }
03218 
03226         function clientInfo($useragent='')      {
03227                 if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
03228 
03229                 $bInfo=array();
03230                         // Which browser?
03231                 if (strstr($useragent,'Konqueror'))     {
03232                         $bInfo['BROWSER']= 'konqu';
03233                 } elseif (strstr($useragent,'Opera'))   {
03234                         $bInfo['BROWSER']= 'opera';
03235                 } elseif (preg_match('/MSIE [4567]/', $useragent))      {
03236                         $bInfo['BROWSER']= 'msie';
03237                 } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5'))     {
03238                         $bInfo['BROWSER']='net';
03239                 }
03240                 if ($bInfo['BROWSER'])  {
03241                                 // Browser version
03242                         switch($bInfo['BROWSER'])       {
03243                                 case 'net':
03244                                         $bInfo['VERSION']= doubleval(substr($useragent,8));
03245                                         if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape6/'),10));}       // Will we ever know if this was a typo or intention...?! :-(
03246                                         if (strstr($useragent,'Netscape/6')) {$bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/6'),10));}
03247                                         if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
03248                                 break;
03249                                 case 'msie':
03250                                         $tmp = strstr($useragent,'MSIE');
03251                                         $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
03252                                 break;
03253                                 case 'opera':
03254                                         $tmp = strstr($useragent,'Opera');
03255                                         $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
03256                                 break;
03257                                 case 'konqu':
03258                                         $tmp = strstr($useragent,'Konqueror/');
03259                                         $bInfo['VERSION'] = doubleval(substr($tmp,10));
03260                                 break;
03261                         }
03262                                 // Client system
03263                         if (strstr($useragent,'Win'))   {
03264                                 $bInfo['SYSTEM'] = 'win';
03265                         } elseif (strstr($useragent,'Mac'))     {
03266                                 $bInfo['SYSTEM'] = 'mac';
03267                         } elseif (strstr($useragent,'Linux') || strstr($useragent,'X11') || strstr($useragent,'SGI') || strstr($useragent,' SunOS ') || strstr($useragent,' HP-UX '))   {
03268                                 $bInfo['SYSTEM'] = 'unix';
03269                         }
03270                 }
03271                         // Is true if the browser supports css to format forms, especially the width
03272                 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
03273 
03274                 return $bInfo;
03275         }
03276 
03284         function getHostname($requestHost=TRUE) {
03285                 $host = '';
03286                 if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode))      {
03287                         $host = $_SERVER['HTTP_HOST'];
03288                 }
03289                 if (!$host)     {
03290                                 // will fail for PHP 4.1 and 4.2
03291                         $host = @php_uname('n');
03292                                 // 'n' is ignored in broken installations
03293                         if (strpos($host, ' ')) $host = '';
03294                 }
03295                         // we have not found a FQDN yet
03296                 if ($host && strpos('.',$host) === FALSE)       {
03297                         $ip = gethostbyname($host);
03298                                 // we got an IP address
03299                         if ($ip != $host)       {
03300                                 $fqdn = gethostbyaddr($ip);
03301                                 if ($ip != $fqdn)       $host = $fqdn;
03302                         }
03303                 }
03304                 if (!$host)     $host = 'localhost.localdomain';
03305 
03306                 return $host;
03307         }
03308 
03309 
03310 
03311 
03312 
03313 
03314 
03315 
03316 
03317 
03318 
03319 
03320 
03321 
03322 
03323 
03324 
03325 
03326 
03327 
03328 
03329 
03330         /*************************
03331          *
03332          * TYPO3 SPECIFIC FUNCTIONS
03333          *
03334          *************************/
03335 
03345         function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)    {
03346                 if (!strcmp($filename,''))              return '';
03347 
03348                 if ($relToTYPO3_mainDir)        {
03349                         if (!defined('PATH_typo3'))     return '';
03350                         $relPathPrefix = PATH_typo3;
03351                 } else {
03352                         $relPathPrefix = PATH_site;
03353                 }
03354                 if (substr($filename,0,4)=='EXT:')      {       // extension
03355                         list($extKey,$local) = explode('/',substr($filename,4),2);
03356                         $filename='';
03357                         if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
03358                                 $filename = t3lib_extMgm::extPath($extKey).$local;
03359                         }
03360                 } elseif (!t3lib_div::isAbsPath($filename))     {       // relative. Prepended with $relPathPrefix
03361                         $filename=$relPathPrefix.$filename;
03362                 } elseif ($onlyRelative && !t3lib_div::isFirstPartOfStr($filename,$relPathPrefix)) {    // absolute, but set to blank if not allowed
03363                         $filename='';
03364                 }
03365                 if (strcmp($filename,'') && t3lib_div::validPathStr($filename)) {       // checks backpath.
03366                         return $filename;
03367                 }
03368         }
03369 
03381         function validPathStr($theFile) {
03382                 if (!strstr($theFile,'//') && !strstr($theFile,'\\') && !preg_match('#(?:^\.\.|/\.\./)#',$theFile))     return true;
03383         }
03384 
03392         function isAbsPath($path)       {
03393                 return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' :  substr($path,0,1)=='/';
03394         }
03395 
03403         function isAllowedAbsPath($path)        {
03404                 if (t3lib_div::isAbsPath($path) &&
03405                         t3lib_div::validPathStr($path) &&
03406                                 (       t3lib_div::isFirstPartOfStr($path,PATH_site)
03407                                         ||
03408                                         ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
03409                                 )
03410                         )       return true;
03411         }
03412 
03420         function verifyFilenameAgainstDenyPattern($filename)    {
03421                 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],''))    {
03422                         $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
03423                         if ($result)    return false;   // so if a matching filename is found, return false;
03424                 }
03425                 return true;
03426         }
03427 
03438         function upload_copy_move($source,$destination) {
03439                 if (is_uploaded_file($source))  {
03440                         $uploaded = TRUE;
03441                         // 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:
03442                         $uploadedResult = move_uploaded_file($source, $destination);
03443                 } else {
03444                         $uploaded = FALSE;
03445                         @copy($source,$destination);
03446                 }
03447 
03448                 t3lib_div::fixPermissions($destination);        // Change the permissions of the file
03449 
03450                         // 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
03451                 return $uploaded ? $uploadedResult : FALSE;
03452         }
03453 
03464         function upload_to_tempfile($uploadedFileName)  {
03465                 if (is_uploaded_file($uploadedFileName))        {
03466                         $tempFile = t3lib_div::tempnam('upload_temp_');
03467                         move_uploaded_file($uploadedFileName, $tempFile);
03468                         return @is_file($tempFile) ? $tempFile : '';
03469                 }
03470         }
03471 
03482         function unlink_tempfile($uploadedTempFileName) {
03483                 if ($uploadedTempFileName && t3lib_div::validPathStr($uploadedTempFileName) && t3lib_div::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName))    {
03484                         if (unlink($uploadedTempFileName))      return TRUE;
03485                 }
03486         }
03487 
03498         function tempnam($filePrefix)   {
03499                 return tempnam(PATH_site.'typo3temp/',$filePrefix);
03500         }
03501 
03512         function stdAuthCode($uid_or_record,$fields='',$codeLength=8)   {
03513 
03514                 if (is_array($uid_or_record))   {
03515                         $recCopy_temp=array();
03516                         if ($fields)    {
03517                                 $fieldArr = t3lib_div::trimExplode(',',$fields,1);
03518                                 reset($fieldArr);
03519                                 while(list($k,$v)=each($fieldArr))      {
03520                                         $recCopy_temp[$k]=$uid_or_record[$v];
03521                                 }
03522                         } else {
03523                                 $recCopy_temp=$uid_or_record;
03524                         }
03525                         $preKey = implode('|',$recCopy_temp);
03526                 } else {
03527                         $preKey = $uid_or_record;
03528                 }
03529 
03530                 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
03531                 $authCode = substr(md5($authCode),0,$codeLength);
03532                 return $authCode;
03533         }
03534 
03543         function cHashParams($addQueryParams) {
03544                 $params = explode('&',substr($addQueryParams,1));       // Splitting parameters up
03545 
03546                         // Make array:
03547                 $pA = array();
03548                 foreach($params as $theP)       {
03549                         $pKV = explode('=', $theP);     // Splitting single param by '=' sign
03550                         if (!t3lib_div::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0]) && !preg_match('/TSFE_ADMIN_PANEL\[.*?\]/',$pKV[0]))    {
03551                                 $pA[rawurldecode($pKV[0])] = (string)rawurldecode($pKV[1]);
03552                         }
03553                 }
03554                 $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
03555                 ksort($pA);
03556 
03557                 return $pA;
03558         }
03559 
03566         function hideIfNotTranslated($l18n_cfg_fieldValue)      {
03567                 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault'])     {
03568                         return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
03569                 } else {
03570                         return $l18n_cfg_fieldValue&2 ? TRUE : FALSE;
03571                 }
03572         }
03573 
03581         function readLLfile($fileRef,$langKey)  {
03582 
03583                 $file = t3lib_div::getFileAbsFileName($fileRef);
03584                 if ($file)      {
03585                         $baseFile = ereg_replace('\.(php|xml)$', '', $file);
03586 
03587                         if (@is_file($baseFile.'.xml')) {
03588                                 $LOCAL_LANG = t3lib_div::readLLXMLfile($baseFile.'.xml', $langKey);
03589                         } elseif (@is_file($baseFile.'.php'))   {
03590                                 include($baseFile.'.php');
03591                         } else die('Filereference, "'.$file.'", not found!');
03592                 }
03593 
03594                 return is_array($LOCAL_LANG)?$LOCAL_LANG:array();
03595         }
03596 
03605         function readLLXMLfile($fileRef,$langKey)       {
03606 
03607                 if (is_object($GLOBALS['LANG']))        {
03608                         $csConvObj = &$GLOBALS['LANG']->csConvObj;
03609                 } elseif (is_object($GLOBALS['TSFE']))  {
03610                         $csConvObj = &$GLOBALS['TSFE']->csConvObj;
03611                 } else $csConvObj = NULL;
03612 
03613                 if (@is_file($fileRef) && $langKey && is_object($csConvObj))    {
03614 
03615                                 // Set charset:
03616                         $origCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
03617 
03618                                 // Cache file name:
03619                         $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.2';
03620                         $cacheFileName = PATH_site.'typo3temp/llxml/'.
03621                                                         #str_replace('_','',ereg_replace('^.*\/','',dirname($fileRef))).
03622                                                         #'_'.basename($fileRef).
03623                                                         substr(basename($fileRef),10,15).
03624                                                         '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
03625 
03626                                 // Check if cache file exists...
03627                         if (!@is_file($cacheFileName))  {       // ... if it doesn't, create content and write it:
03628 
03629                                         // Read XML, parse it.
03630                                 $xmlString = t3lib_div::getUrl($fileRef);
03631                                 $xmlContent = t3lib_div::xml2array($xmlString);
03632                                 if (!is_array($xmlContent))     {
03633                                         die($fileRef.' was not XML!: '.$xmlContent);
03634                                 }
03635 
03636                                         // Set default LOCAL_LANG array content:
03637                                 $LOCAL_LANG = array();
03638                                 $LOCAL_LANG['default'] = $xmlContent['data']['default'];
03639 
03640                                         // Converting charset of default language from utf-8 to iso-8859-1 (since that is what the system would expect for default langauge in the core due to historical reasons)
03641                                         // This conversion is unneccessary for 99,99% of all default labels since they are in english, therefore ASCII.
03642                                         // However, an extension like TemplaVoila uses an extended character in its name, even in Default language. To accommodate that (special chars for default) this conversion must be made.
03643                                         // Since the output from this function is probably always cached it is considered insignificant to do this conversion.
03644                                         // - kasper
03645                                 if (is_array($LOCAL_LANG['default']))   {
03646                                         foreach($LOCAL_LANG['default'] as $labelKey => $labelValue)     {
03647                                                 $LOCAL_LANG['default'][$labelKey] = $csConvObj->utf8_decode($labelValue,'iso-8859-1');
03648                                         }
03649                                 }
03650 
03651                                         // Specific language, convert from utf-8 to backend language charset:
03652                                         // NOTICE: Converting from utf-8 back to "native" language may be a temporary solution until we can totally discard "locallang.php" files altogether (and use utf-8 for everything). But doing this conversion is the quickest way to migrate now and the source is in utf-8 anyway which is the main point.
03653                                 if ($langKey!='default')        {
03654 
03655                                                 // 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:
03656                                         if (!isset($xmlContent['data'][$langKey]))      {
03657                                                 $LOCAL_LANG[$langKey] = t3lib_div::llXmlAutoFileName($fileRef, $langKey);
03658                                         } else {
03659                                                 $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
03660                                         }
03661 
03662                                                 // Checking if charset should be converted.
03663                                         if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8')   {
03664                                                 foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue)      {
03665                                                         $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
03666                                                 }
03667                                         }
03668                                 }
03669 
03670                                         // Cache the content now:
03671                                 $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>$LOCAL_LANG);
03672                                 $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
03673                                 if ($res)       die('ERROR: '.$res);
03674                         } else {
03675                                         // Get content from cache:
03676                                 $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
03677                                 $LOCAL_LANG = $serContent['LOCAL_LANG'];
03678                         }
03679 
03680                                 // Checking for EXTERNAL file for non-default language:
03681                         if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey]))   {
03682 
03683                                         // Look for localized file:
03684                                 $localized_file = t3lib_div::getFileAbsFileName($LOCAL_LANG[$langKey]);
03685                                 if ($localized_file && @is_file($localized_file))       {
03686 
03687                                                 // Cache file name:
03688                                         $hashSource = substr($localized_file,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($localized_file));
03689                                         $cacheFileName = PATH_site.'typo3temp/llxml/ext_'.
03690                                                                         substr(basename($localized_file),10,15).
03691                                                                         '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
03692 
03693                                                 // Check if cache file exists...
03694                                         if (!@is_file($cacheFileName))  {       // ... if it doesn't, create content and write it:
03695 
03696                                                         // Read and parse XML content:
03697                                                 $local_xmlString = t3lib_div::getUrl($localized_file);
03698                                                 $local_xmlContent = t3lib_div::xml2array($local_xmlString);
03699                                                 $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
03700 
03701                                                         // Checking if charset should be converted.
03702                                                 if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8')   {
03703                                                         foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue)      {
03704                                                                 $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
03705                                                         }
03706                                                 }
03707 
03708                                                         // Cache the content now:
03709                                                 $serContent = array('extlang'=>$langKey, 'origFile'=>$LOCAL_LANG[$langKey], 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
03710                                                 $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
03711                                                 if ($res)       die('ERROR: '.$res);
03712                                         } else {
03713                                                         // Get content from cache:
03714                                                 $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
03715                                                 $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
03716                                         }
03717                                 } else {
03718                                         $LOCAL_LANG[$langKey] = array();
03719                                 }
03720                         }
03721 
03722                         return $LOCAL_LANG;
03723                 }
03724         }
03725 
03733         function llXmlAutoFileName($fileRef,$language)  {
03734                         // Analyse file reference:
03735                 $location = 'typo3conf/l10n/'.$language.'/';    // Default location of translations
03736                 if (t3lib_div::isFirstPartOfStr($fileRef,PATH_typo3.'sysext/')) {       // Is system:
03737                         $validatedPrefix = PATH_typo3.'sysext/';
03738                         #$location = 'EXT:csh_'.$language.'/';  // For system extensions translations are found in "csh_*" extensions (language packs)
03739                 } elseif (t3lib_div::isFirstPartOfStr($fileRef,PATH_typo3.'ext/'))      {       // Is global:
03740                         $validatedPrefix = PATH_typo3.'ext/';
03741                 } elseif (t3lib_div::isFirstPartOfStr($fileRef,PATH_typo3conf.'ext/'))  {       // Is local:
03742                         $validatedPrefix = PATH_typo3conf.'ext/';
03743                 } else {
03744                         $validatedPrefix = '';
03745                 }
03746 
03747                 if ($validatedPrefix)   {
03748 
03749                                 // Divide file reference into extension key, directory (if any) and base name:
03750                         list($file_extKey,$file_extPath) = explode('/',substr($fileRef,strlen($validatedPrefix)),2);
03751                         $temp = t3lib_div::revExplode('/',$file_extPath,2);
03752                         if (count($temp)==1)    array_unshift($temp,'');        // Add empty first-entry if not there.
03753                         list($file_extPath,$file_fileName) = $temp;
03754 
03755                                 // The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
03756                         return $location.
03757                                 $file_extKey.'/'.
03758                                 ($file_extPath?$file_extPath.'/':'').
03759                                 $language.'.'.$file_fileName;
03760                 } else return NULL;
03761         }
03762 
03763 
03780         function loadTCA($table)        {
03781                 global $TCA,$LANG_GENERAL_LABELS;
03782                 if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile'])     {
03783                         if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:'))    {
03784                                 include(PATH_t3lib.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
03785                         } elseif (t3lib_div::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file($TCA[$table]['ctrl']['dynamicConfigFile']))       {       // Absolute path...
03786                                 include($TCA[$table]['ctrl']['dynamicConfigFile']);
03787                         } else include(PATH_typo3conf.$TCA[$table]['ctrl']['dynamicConfigFile']);
03788                 }
03789         }
03790 
03800         function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')    {
03801                 if (!is_array ($dataStructArray)) return 'Data structure must be an array';
03802 
03803                 if (is_array($dataStructArray['sheets']))       {
03804                         $singleSheet = FALSE;
03805                         if (!isset($dataStructArray['sheets'][$sheet])) {
03806                                 $sheet='sDEF';
03807                         }
03808                         $dataStruct =  $dataStructArray['sheets'][$sheet];
03809 
03810                                 // If not an array, but still set, then regard it as a relative reference to a file:
03811                         if ($dataStruct && !is_array($dataStruct))      {
03812                                 $file = t3lib_div::getFileAbsFileName($dataStruct);
03813                                 if ($file && @is_file($file))   {
03814                                         $dataStruct = t3lib_div::xml2array(t3lib_div::getUrl($file));
03815                                 }
03816                         }
03817                 } else {
03818                         $singleSheet = TRUE;
03819                         $dataStruct = $dataStructArray;
03820                         if (isset($dataStruct['meta'])) unset($dataStruct['meta']);     // Meta data should not appear there.
03821                         $sheet = 'sDEF';        // Default sheet
03822                 }
03823                 return array($dataStruct,$sheet,$singleSheet);
03824         }
03825 
03833         function resolveAllSheetsInDS($dataStructArray) {
03834                 if (is_array($dataStructArray['sheets']))       {
03835                         $out=array('sheets'=>array());
03836                         foreach($dataStructArray['sheets'] as $sheetId => $sDat)        {
03837                                 list($ds,$aS) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheetId);
03838                                 if ($sheetId==$aS)      {
03839                                         $out['sheets'][$aS]=$ds;
03840                                 }
03841                         }
03842                 } else {
03843                         list($ds) = t3lib_div::resolveSheetDefInDS($dataStructArray);
03844                         $out = array('sheets' => array('sDEF' => $ds));
03845                 }
03846                 return $out;
03847         }
03848 
03862         function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)      {
03863                 global $TYPO3_CONF_VARS;
03864 
03865                         // Check persistent object and if found, call directly and exit.
03866                 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName]))        {
03867                         return call_user_func_array(
03868                                                 array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
03869                                                         $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
03870                                                 array(&$params, &$ref)
03871                                         );
03872                 }
03873 
03874                         // Check file-reference prefix; if found, require_once() the file (should be library of code)
03875                 if (strstr($funcName,':'))      {
03876                         list($file,$funcRef) = t3lib_div::revExplode(':',$funcName,2);
03877                         $requireFile = t3lib_div::getFileAbsFileName($file);
03878                         if ($requireFile) t3lib_div::requireOnce($requireFile);
03879                 } else {
03880                         $funcRef = $funcName;
03881                 }
03882 
03883                         // Check for persistent object token, "&"
03884                 if (substr($funcRef,0,1)=='&')  {
03885                         $funcRef = substr($funcRef,1);
03886                         $storePersistentObject = TRUE;
03887                 } else {
03888                         $storePersistentObject = FALSE;
03889                 }
03890 
03891                         // Check prefix is valid:
03892                 if ($checkPrefix &&
03893                         !t3lib_div::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
03894                         !t3lib_div::isFirstPartOfStr(trim($funcRef),'tx_')
03895                         )       {
03896                         if (!$silent)   debug("Function/Class '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
03897                         return FALSE;
03898                 }
03899 
03900                         // Call function or method:
03901                 $parts = explode('->',$funcRef);
03902                 if (count($parts)==2)   {       // Class
03903 
03904                                 // Check if class/method exists:
03905                         if (class_exists($parts[0]))    {
03906 
03907                                         // Get/Create object of class:
03908                                 if ($storePersistentObject)     {       // Get reference to current instance of class:
03909                                         if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]]))    {
03910                                                 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = &t3lib_div::makeInstance($parts[0]);
03911                                         }
03912                                         $classObj = &$GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
03913                                 } else {        // Create new object:
03914                                         $classObj = &t3lib_div::makeInstance($parts[0]);
03915                                 }
03916 
03917                                 if (method_exists($classObj, $parts[1]))        {
03918 
03919                                                 // If persistent object should be created, set reference:
03920                                         if ($storePersistentObject)     {
03921                                                 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
03922                                                         'method' => $parts[1],
03923                                                         'obj' => &$classObj
03924                                                 );
03925                                         }
03926                                                 // Call method:
03927                                         $content = call_user_func_array(
03928                                                 array(&$classObj, $parts[1]),
03929                                                 array(&$params, &$ref)
03930                                         );
03931                                 } else {
03932                                         if (!$silent)   debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
03933                                 }
03934                         } else {
03935                                 if (!$silent)   debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
03936                         }
03937                 } else {        // Function
03938                         if (function_exists($funcRef))  {
03939                                 $content = call_user_func_array($funcRef, array(&$params, &$ref));
03940                         } else {
03941                                 if (!$silent)   debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
03942                         }
03943                 }
03944                 return $content;
03945         }
03946 
03958         function &getUserObj($classRef,$checkPrefix='user_',$silent=0)  {
03959                 global $TYPO3_CONF_VARS;
03960                         // Check persistent object and if found, call directly and exit.
03961                 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef]))     {
03962                         return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
03963                 } else {
03964 
03965                                 // Check file-reference prefix; if found, require_once() the file (should be library of code)
03966                         if (strstr($classRef,':'))      {
03967                                 list($file,$class) = t3lib_div::revExplode(':',$classRef,2);
03968                                 $requireFile = t3lib_div::getFileAbsFileName($file);
03969                                 if ($requireFile)       t3lib_div::requireOnce($requireFile);
03970                         } else {
03971                                 $class = $classRef;
03972                         }
03973 
03974                                 // Check for persistent object token, "&"
03975                         if (substr($class,0,1)=='&')    {
03976                                 $class = substr($class,1);
03977                                 $storePersistentObject = TRUE;
03978                         } else {
03979                                 $storePersistentObject = FALSE;
03980                         }
03981 
03982                                 // Check prefix is valid:
03983                         if ($checkPrefix &&
03984                                 !t3lib_div::isFirstPartOfStr(trim($class),$checkPrefix) &&
03985                                 !t3lib_div::isFirstPartOfStr(trim($class),'tx_')
03986                                 )       {
03987                                 if (!$silent)   debug("Class '".$class."' was not prepended with '".$checkPrefix."'",1);
03988                                 return FALSE;
03989                         }
03990 
03991                                 // Check if class exists:
03992                         if (class_exists($class))       {
03993                                 $classObj = &t3lib_div::makeInstance($class);
03994 
03995                                         // If persistent object should be created, set reference:
03996                                 if ($storePersistentObject)     {
03997                                         $GLOBALS['T3_VAR']['getUserObj'][$classRef] = &$classObj;
03998                                 }
03999 
04000                                 return $classObj;
04001                         } else {
04002                                 if (!$silent)   debug("<strong>ERROR:</strong> No class named: ".$class,1);
04003                         }
04004                 }
04005         }
04006 
04016         function &makeInstance($className)      {
04017 
04018                         // Load class file if not found:
04019                 if (!class_exists($className))  {
04020                         if (substr($className,0,6)=='t3lib_')   {
04021                                 t3lib_div::requireOnce(PATH_t3lib.'class.'.strtolower($className).'.php');
04022                         }
04023                 }
04024 
04025                         // Return object.
04026                 return class_exists('ux_'.$className) ? t3lib_div::makeInstance('ux_'.$className) : new $className;
04027         }
04028 
04037         function makeInstanceClassName($className)      {
04038                 return class_exists('ux_'.$className) ? t3lib_div::makeInstanceClassName('ux_'.$className) : $className;
04039         }
04040 
04051         function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())    {
04052                 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
04053 
04054                 $error = FALSE;
04055 
04056                 if (!is_array($excludeServiceKeys) ) {
04057                         $excludeServiceKeys = t3lib_div::trimExplode(',', $excludeServiceKeys, 1);
04058                 }
04059                 while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys))   {
04060 
04061                                 // Check persistent object and if found, call directly and exit.
04062                         if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]))   {
04063                                         // reset service and return object
04064                                 $T3_VAR['makeInstanceService'][$info['className']]->reset();
04065                                 return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
04066 
04067                                 // include file and create object
04068                         } else {
04069                                 $requireFile = t3lib_div::getFileAbsFileName($info['classFile']);
04070                                 if (@is_file($requireFile)) {
04071                                         t3lib_div::requireOnce ($requireFile);
04072                                         $obj = t3lib_div::makeInstance($info['className']);
04073                                         if (is_object($obj)) {
04074                                                 if(!@is_callable(array($obj,'init')))   {
04075                                                                 // use silent logging??? I don't think so.
04076                                                         die ('Broken service:'.t3lib_div::view_array($info));
04077                                                 }
04078                                                 $obj->info = $info;
04079                                                 if ($obj->init()) { // service available?
04080 
04081                                                                 // create persistent object
04082                                                         $T3_VAR['makeInstanceService'][$info['className']] = &$obj;
04083 
04084                                                                 // needed to delete temp files
04085                                                         register_shutdown_function(array(&$obj, '__destruct'));
04086 
04087                                                         return $obj; // object is passed as reference by function definition
04088                                                 }
04089                                                 $error = $obj->getLastErrorArray();
04090                                                 unset($obj);
04091                                         }
04092                                 }
04093                         }
04094                                 // deactivate the service
04095                         t3lib_extMgm::deactivateService($info['serviceType'],$info['serviceKey']);
04096                 }
04097                 return $error;
04098         }
04099 
04104         function requireOnce($requireFile)      {
04105                 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
04106 
04107                 require_once ($requireFile);
04108         }
04109 
04125         function plainMailEncoded($email,$subject,$message,$headers='',$encoding='quoted-printable',$charset='',$dontEncodeHeader=false)        {
04126                 if (!$charset)  {
04127                         $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'ISO-8859-1';
04128                 }
04129 
04130                 if (!$dontEncodeHeader) {
04131                                 // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
04132                         $newHeaders=array();
04133                         foreach (explode(chr(10),$headers) as $line)    {       // Split the header in lines and convert each line separately
04134                                 $parts = explode(': ',$line,2); // Field tags must not be encoded
04135                                 if (count($parts)==2)   {
04136                                         $parts[1] = t3lib_div::encodeHeader($parts[1],$encoding,$charset);
04137                                         $newHeaders[] = implode(': ',$parts);
04138                                 } else {
04139                                         $newHeaders[] = $line;  // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
04140                                 }
04141                         }
04142                         $headers = implode(chr(10),$newHeaders);
04143                         unset($newHeaders);
04144 
04145                         $email = t3lib_div::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>")
04146                         $subject = t3lib_div::encodeHeader($subject,$encoding,$charset);
04147                 }
04148 
04149                 switch ((string)$encoding)      {
04150                         case 'base64':
04151                                 $headers=trim($headers).chr(10).
04152                                 'Mime-Version: 1.0'.chr(10).
04153                                 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
04154                                 'Content-Transfer-Encoding: base64';
04155 
04156                                 $message=trim(chunk_split(base64_encode($message.chr(10)))).chr(10);    // Adding chr(10) because I think MS outlook 2002 wants it... may be removed later again.
04157                         break;
04158                         case '8bit':
04159                                 $headers=trim($headers).chr(10).
04160                                 'Mime-Version: 1.0'.chr(10).
04161                                 'Content-Type: text/plain; charset='.$charset.chr(10).
04162                                 'Content-Transfer-Encoding: 8bit';
04163                         break;
04164                         case 'quoted-printable':
04165                         default:
04166                                 $headers=trim($headers).chr(10).
04167                                 'Mime-Version: 1.0'.chr(10).
04168                                 'Content-Type: text/plain; charset='.$charset.chr(10).
04169                                 'Content-Transfer-Encoding: quoted-printable';
04170 
04171                                 $message=t3lib_div::quoted_printable($message);
04172                         break;
04173                 }
04174 
04175                 $linebreak = chr(10);                   // Default line break for Unix systems.
04176                 if (TYPO3_OS=='WIN')    {
04177                         $linebreak = chr(13).chr(10);   // Line break for Windows. This is needed because PHP on Windows systems send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
04178                 }
04179 
04180                 $headers=trim(implode($linebreak,t3lib_div::trimExplode(chr(10),$headers,1)));  // Make sure no empty lines are there.
04181 
04182                 mail($email,$subject,$message,$headers);
04183         }
04184 
04195         function quoted_printable($string,$maxlen=76)   {
04196                         // Make sure the string contains only Unix linebreaks
04197                 $string = str_replace(chr(13).chr(10), chr(10), $string);       // Replace Windows breaks (\r\n)
04198                 $string = str_replace(chr(13), chr(10), $string);               // Replace Mac breaks (\r)
04199 
04200                 $linebreak = chr(10);                   // Default line break for Unix systems.
04201                 if (TYPO3_OS=='WIN')    {
04202                         $linebreak = chr(13).chr(10);   // Line break for Windows. This is needed because PHP on Windows systems send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
04203                 }
04204 
04205                 $newString = '';
04206                 $theLines = explode(chr(10),$string);   // Split lines
04207                 foreach ($theLines as $val)     {
04208                         $newVal = '';
04209                         $theValLen = strlen($val);
04210                         $len = 0;
04211                         for ($index=0; $index < $theValLen; $index++)   {       // Walk through each character of this line
04212                                 $char = substr($val,$index,1);
04213                                 $ordVal = ord($char);
04214                                 if ($len>($maxlen-4) || ($len>(($maxlen-10)-4)&&$ordVal==32))   {
04215                                         $newVal.='='.$linebreak;        // Add a line break
04216                                         $len=0;                 // Reset the length counter
04217                                 }
04218                                 if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
04219                                         $newVal.=$char;         // This character is ok, add it to the message
04220                                         $len++;
04221                                 } else {
04222                                         $newVal.=sprintf('=%02X',$ordVal);      // Special character, needs to be encoded
04223                                         $len+=3;
04224                                 }
04225                         }
04226                         $newVal = preg_replace('/'.chr(32).'$/','=20',$newVal);         // Replaces a possible SPACE-character at the end of a line
04227                         $newVal = preg_replace('/'.chr(9).'$/','=09',$newVal);          // Replaces a possible TAB-character at the end of a line
04228                         $newString.=$newVal.$linebreak;
04229                 }
04230                 return preg_replace('/'.$linebreak.'$/','',$newString);         // Remove last newline
04231         }
04232 
04242         function encodeHeader($line,$enc='quoted-printable',$charset='ISO-8859-1')      {
04243                         // Avoid problems if "###" is found in $line (would conflict with the placeholder which is used below)
04244                 if (strstr($line,'###'))        return $line;
04245 
04246                         // Check if any non-ASCII characters are found - otherwise encoding is not needed
04247                 if (!preg_match('/[^'.chr(32).'-'.chr(127).']/',$line)) return $line;
04248 
04249                         // Wrap email addresses in a special marker
04250                 $line = preg_replace('/([^ ]+@[^ ]+)/', '###$1###', $line);
04251 
04252                 $matches = preg_split('/(.?###.+###.?|\(|\))/', $line, -1, PREG_SPLIT_NO_EMPTY);
04253                 foreach ($matches as $part)     {
04254                         $oldPart = $part;
04255                         switch ((string)$enc)   {
04256                                 case 'base64':
04257                                         $part = '=?'.$charset.'?B?'.base64_encode($part).'?=';
04258                                 break;
04259                                 case 'quoted-printable':
04260                                 default:
04261                                         $qpValue = t3lib_div::quoted_printable($part,1000);
04262                                         if ($part!=$qpValue)    {
04263                                                 $qpValue = str_replace(' ','_',$qpValue);       // Encoded words in the header should not contain non-encoded spaces. "_" is a shortcut for "=20". See RFC 2047 for details.
04264                                                 $part = '=?'.$charset.'?Q?'.$qpValue.'?=';
04265                                         }
04266                                 break;
04267                         }
04268                         $line = str_replace($oldPart, $part, $line);
04269                 }
04270                 $line = preg_replace('/###(.+?)###/', '$1', $line);     // Remove the wrappers
04271 
04272                 return $line;
04273         }
04274 
04286         function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')      {
04287                         // Substitute URLs with shorter links:
04288                 foreach (array('http','https') as $protocol)    {
04289                         $urlSplit = explode($protocol.'://',$message);
04290                         reset($urlSplit);
04291                         while (list($c,$v) = each($urlSplit))   {
04292                                 if ($c) {
04293                                         $newParts = preg_split('/\s|[<>"{}|\\\^`()\']/', $v, 2);
04294                                         $newURL = $protocol.'://'.$newParts[0];
04295 
04296                                         switch ((string)$urlmode)       {
04297                                                 case 'all':
04298                                                         $newURL = t3lib_div::makeRedirectUrl($newURL,0,$index_script_url);
04299                                                 break;
04300                                                 case '76':
04301                                                         $newURL = t3lib_div::makeRedirectUrl($newURL,76,$index_script_url);
04302                                                 break;
04303                                         }
04304                                         $urlSplit[$c] = $newURL . substr($v,strlen($newParts[0]));
04305                                 }
04306                         }
04307                         $message = implode('',$urlSplit);
04308                 }
04309 
04310                 return $message;
04311         }
04312 
04323         function makeRedirectUrl($inUrl,$l=0,$index_script_url='')      {
04324                 if (strlen($inUrl)>$l)  {
04325                         $md5 = substr(md5($inUrl),0,20);
04326                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params'));
04327                         if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res))  {
04328                                 $insertFields = array(
04329                                         'md5hash' => $md5,
04330                                         'tstamp' => time(),
04331                                         'type' => 2,
04332                                         'params' => $inUrl
04333                                 );
04334 
04335                                 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
04336                         }
04337                         $inUrl=($index_script_url ? $index_script_url : t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php').
04338                                 '?RDCT='.$md5;
04339                 }
04340 
04341                 return $inUrl;
04342         }
04343 
04351         function freetypeDpiComp($font_size)    {
04352                 $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
04353                 if ($dpi!=72)   $font_size = $font_size/$dpi*72;
04354                 return $font_size;
04355         }
04356 
04363         function initSysLog()   {
04364                 global $TYPO3_CONF_VARS;
04365 
04366                         // for CLI logging name is <fqdn-hostname>:<TYPO3-path>
04367                 if (defined('TYPO3_cliMode') && TYPO3_cliMode)  {
04368                         $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = t3lib_div::getHostname($requestHost=FALSE).':'.PATH_site;
04369                 }
04370                         // for Web logging name is <protocol>://<request-hostame>/<site-path>
04371                 else {
04372                         $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = t3lib_div::getIndpEnv('TYPO3_SITE_URL');
04373                 }
04374 
04375                         // init custom logging
04376                 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
04377                         $params = array('initLog'=>TRUE);
04378                         $fakeThis = FALSE;
04379                         foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod)       {
04380                                 t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
04381                         }
04382                 }
04383 
04384                         // init TYPO3 logging
04385                 foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log)   {
04386                         list($type,$destination) = explode(',',$log,3);
04387 
04388                         if ($type == 'syslog')  {
04389                                 define_syslog_variables();
04390                                 if (TYPO3_OS == 'WIN')  {
04391                                         $facility = LOG_USER;
04392                                 } else {
04393                                         $facility = constant('LOG_'.strtoupper($destination));
04394                                 }
04395                                 openlog($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'], LOG_ODELAY, $facility);
04396                         }
04397                 }
04398 
04399                 $TYPO3_CONF_VARS['SYS']['systemLogLevel'] = t3lib_div::intInRange($TYPO3_CONF_VARS['SYS']['systemLogLevel'],0,4);
04400                 $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
04401         }
04402 
04413         function sysLog($msg, $extKey, $severity=0) {
04414                 global $TYPO3_CONF_VARS;
04415 
04416                 $severity = t3lib_div::intInRange($severity,0,4);
04417 
04418                         // is message worth logging?
04419                 if (intval($TYPO3_CONF_VARS['SYS']['systemLogLevel']) > $severity)      return;
04420 
04421                         // initialize logging
04422                 if (!$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'])      {
04423                         t3lib_div::initSysLog();
04424                 }
04425 
04426                         // do custom logging
04427                 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
04428                         $params = array('msg'=>$msg, 'extKey'=>$extKey, 'backTrace'=>debug_backtrace());
04429                         $fakeThis = FALSE;
04430                         foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod)       {
04431                                 t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
04432                         }
04433                 }
04434 
04435                         // TYPO3 logging enabled?
04436                 if (!$TYPO3_CONF_VARS['SYS']['systemLog'])      return;
04437 
04438                 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
04439                 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
04440 
04441                         // use all configured logging options
04442                 foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log)   {
04443                         list($type,$destination,$level) = explode(',',$log,4);
04444 
04445                                 // is message worth logging for this log type?
04446                         if (intval($level) > $severity) continue;
04447 
04448                         $msgLine = ' - '.$extKey.': '.$msg;
04449 
04450                                 // write message to a file
04451                         if ($type == 'file')    {
04452                                 $file = fopen($destination, 'a');
04453                                 if ($file)     {
04454                                         flock($file, LOCK_EX);  // try locking, but ignore if not available (eg. on NFS and FAT)
04455                                         fwrite($file, date($dateFormat.' '.$timeFormat).$msgLine.chr(10));
04456                                         flock($file, LOCK_UN);    // release the lock
04457                                         fclose($file);
04458                                 }
04459                         }
04460                                 // send message per mail
04461                         elseif ($type == 'mail')        {
04462                                 list($to,$from) = explode('/',$destination);
04463                                 mail($to, 'Warning - error in TYPO3 installation',
04464                                         'Host: '.$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost']."\n".
04465                                         'Extension: '.$extKey."\n".
04466                                         'Severity: '.$severity."\n".
04467                                         "\n".$msg,
04468                                         ($from ? 'From: '.$from : '')
04469                                 );
04470                         }
04471                                 // use the PHP error log
04472                         elseif ($type == 'error_log')   {
04473                                 error_log($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'].$msgLine, 0);
04474                         }
04475                                 // use the system log
04476                         elseif ($type == 'syslog')      {
04477                                 $priority = array(LOG_INFO,LOG_NOTICE,LOG_WARNING,LOG_ERR,LOG_CRIT);
04478                                 syslog($priority[(int)$severity], $msgLine);
04479                         }
04480                 }
04481         }
04482 
04496         function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)     {
04497                 global $TYPO3_CONF_VARS;
04498 
04499                 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog']))    {
04500                         $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
04501                         $fakeThis = FALSE;
04502                         foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod)   {
04503                                 t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
04504                         }
04505                 }
04506         }
04507 
04517         function arrayToLogString($arr, $valueList=array(), $valueLength=20) {
04518                 $str = '';
04519                 if (is_array($arr))     {
04520                         if (!is_array($valueList))      {
04521                                 $valueList = t3lib_div::trimExplode(',', $valueList, 1);
04522                         }
04523                         $valListCnt = count($valueList);
04524                         foreach ($arr as $key => $value)        {
04525                                 if (!$valListCnt || in_array($key, $valueList)) {
04526                                         $str .= (string)$key.trim(': '.t3lib_div::fixed_lgd(str_replace("\n",'|',(string)$value), $valueLength)).'; ';
04527                                 }
04528                         }
04529                 }
04530                 return $str;
04531         }
04532 
04541         function imageMagickCommand($command, $parameters, $path='')    {
04542                 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
04543                 $isExt = (TYPO3_OS=='WIN' ? '.exe' : '');
04544                 $switchCompositeParameters=false;
04545 
04546                 if(!$path)      { $path = $gfxConf['im_path']; }
04547 
04548                 $im_version = strtolower($gfxConf['im_version_5']);
04549                 $combineScript = $gfxConf['im_combine_filename'] ? trim($gfxConf['im_combine_filename']) : 'combine';
04550 
04551                 if($command==='combine')        {       // This is only used internally, has no effect outside
04552                         $command = 'composite';
04553                 }
04554 
04555                         // Compile the path & command
04556                 if($im_version==='gm')  {
04557                         $switchCompositeParameters=true;
04558                         $path .= 'gm'.$isExt.' '.$command;
04559                 } else  {
04560                         if($im_version==='im6') { $switchCompositeParameters=true; }
04561                         $path .= (($command=='composite') ? $combineScript : $command).$isExt;
04562                 }
04563 
04564                 $cmdLine = $path.' '.$parameters;
04565 
04566                 if($command=='composite' && $switchCompositeParameters) {       // Because of some weird incompatibilities between ImageMagick 4 and 6 (plus GraphicsMagick), it is needed to change the parameters order under some preconditions
04567                         $paramsArr = t3lib_div::unQuoteFilenames($parameters);
04568 
04569                         if(count($paramsArr)>5) {       // The mask image has been specified => swap the parameters
04570                                 $tmp = $paramsArr[count($paramsArr)-3];
04571                                 $paramsArr[count($paramsArr)-3] = $paramsArr[count($paramsArr)-4];
04572                                 $paramsArr[count($paramsArr)-4] = $tmp;
04573                         }
04574 
04575                         $cmdLine = $path.' '.implode(' ', $paramsArr);
04576                 }
04577 
04578                 return $cmdLine;
04579         }
04580 
04588         function unQuoteFilenames($parameters,$unQuote=FALSE)   {
04589                 $paramsArr = explode(' ', trim($parameters));
04590 
04591                 $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.
04592                 foreach($paramsArr as $k=>$v)   {
04593                         if($quoteActive > -1)   {
04594                                 $paramsArr[$quoteActive] .= ' '.$v;
04595                                 unset($paramsArr[$k]);
04596                                 if(ereg('"$', $v))      { $quoteActive = -1; }
04597 
04598                         } elseif(!trim($v))     {
04599                                 unset($paramsArr[$k]);  // Remove empty elements
04600 
04601                         } elseif(ereg('^"', $v))        {
04602                                 $quoteActive = $k;
04603                         }
04604                 }
04605 
04606                 if($unQuote) {
04607                         foreach($paramsArr as $key=>$val) {
04608                                 $paramsArr[$key]=preg_replace('/(^"|"$)/','',$val);
04609                         }
04610                 }
04611                 return $paramsArr;
04612         }
04613 
04614 
04622         function quoteJSvalue($value, $inScriptTags = false)    {
04623                 $value = addcslashes($value, '\''.chr(10).chr(13));
04624                 if (!$inScriptTags)     {
04625                         $value = htmlspecialchars($value);
04626                 }
04627                 return '\''.$value.'\'';
04628         }
04629 
04630 
04631 }
04632 
04633 ?>


Généré par Le spécialiste TYPO3 avec  doxygen 1.4.6