"TYPO3 4.0.1: typo3_src-4.0.1/t3lib/class.t3lib_div.php Source File", "datetime" => "Sat Dec 2 19:22:17 2006", "date" => "2 Dec 2006", "doxygenversion" => "1.4.6", "projectname" => "TYPO3 4.0.1", "projectnumber" => "4.0.1" ); get_header($doxygen_vars); ?>

class.t3lib_div.php

00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 1999-2006 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 
00555         function breakTextForEmail($str,$implChar="\n",$charWidth=76)   {
00556                 $lines = explode(chr(10),$str);
00557                 $outArr=array();
00558                 while(list(,$lStr)=each($lines))        {
00559                         $outArr = array_merge($outArr,t3lib_div::breakLinesForEmail($lStr,$implChar,$charWidth));
00560                 }
00561                 return implode(chr(10),$outArr);
00562         }
00563 
00574         function breakLinesForEmail($str,$implChar="\n",$charWidth=76)  {
00575                 $lines=array();
00576                 $l=$charWidth;
00577                 $p=0;
00578                 while(strlen($str)>$p)  {
00579                         $substr=substr($str,$p,$l);
00580                         if (strlen($substr)==$l)        {
00581                                 $count = count(explode(' ',trim(strrev($substr))));
00582                                 if ($count>1)   {       // OK...
00583                                         $parts = explode(' ',strrev($substr),2);
00584                                         $theLine = strrev($parts[1]);
00585                                 } else {
00586                                         $afterParts = explode(' ',substr($str,$l+$p),2);
00587                                         $theLine = $substr.$afterParts[0];
00588                                 }
00589                                 if (!strlen($theLine))  {break; }       // Error, because this would keep us in an endless loop.
00590                         } else {
00591                                 $theLine=$substr;
00592                         }
00593 
00594                         $lines[]=trim($theLine);
00595                         $p+=strlen($theLine);
00596                         if (!trim(substr($str,$p,$l)))  break;  // added...
00597                 }
00598                 return implode($implChar,$lines);
00599         }
00600 
00610         function cmpIP($baseIP, $list)  {
00611                 if ($list==='*')        return TRUE;
00612                 if (strstr($baseIP, ':') && t3lib_div::validIPv6($baseIP))      {
00613                         return t3lib_div::cmpIPv6($baseIP, $list);
00614                 } else {
00615                         return t3lib_div::cmpIPv4($baseIP, $list);
00616                 }
00617         }
00618 
00626         function cmpIPv4($baseIP, $list)        {
00627                 $IPpartsReq = explode('.',$baseIP);
00628                 if (count($IPpartsReq)==4)      {
00629                         $values = t3lib_div::trimExplode(',',$list,1);
00630 
00631                         foreach($values as $test)       {
00632                                 list($test,$mask) = explode('/',$test);
00633 
00634                                 if(intval($mask)) {
00635                                                 // "192.168.3.0/24"
00636                                         $lnet = ip2long($test);
00637                                         $lip = ip2long($baseIP);
00638                                         $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
00639                                         $firstpart = substr($binnet,0,$mask);
00640                                         $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
00641                                         $firstip = substr($binip,0,$mask);
00642                                         $yes = (strcmp($firstpart,$firstip)==0);
00643                                 } else {
00644                                                 // "192.168.*.*"
00645                                         $IPparts = explode('.',$test);
00646                                         $yes = 1;
00647                                         reset($IPparts);
00648                                         while(list($index,$val)=each($IPparts)) {
00649                                                 $val = trim($val);
00650                                                 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val))       {
00651                                                         $yes=0;
00652                                                 }
00653                                         }
00654                                 }
00655                                 if ($yes) return true;
00656                         }
00657                 }
00658                 return false;
00659         }
00660 
00668         function cmpIPv6($baseIP, $list)        {
00669                 $success = false;       // Policy default: Deny connection
00670                 $baseIP = t3lib_div::normalizeIPv6($baseIP);
00671 
00672                 $values = t3lib_div::trimExplode(',',$list,1);
00673                 foreach ($values as $test)      {
00674                         list($test,$mask) = explode('/',$test);
00675                         if (t3lib_div::validIPv6($test))        {
00676                                 $test = t3lib_div::normalizeIPv6($test);
00677                                 if (intval($mask))      {
00678                                         switch ($mask) {        // test on /48 /64
00679                                                 case '48':
00680                                                         $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 48);
00681                                                         $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 48);
00682                                                         $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00683                                                 break;
00684                                                 case '64':
00685                                                         $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 64);
00686                                                         $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 64);
00687                                                         $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00688                                                 break;
00689                                                 default:
00690                                                         $success = false;
00691                                         }
00692                                 } else {
00693                                         if (t3lib_div::validIPv6($test))        {       // test on full ip address 128 bits
00694                                                 $testBin = t3lib_div::IPv6Hex2Bin($test);
00695                                                 $baseIPBin = t3lib_div::IPv6Hex2Bin($baseIP);
00696                                                 $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00697                                         }
00698                                 }
00699                         }
00700                         if ($success) return true;
00701                 }
00702                 return false;
00703         }
00704 
00711         function IPv6Hex2Bin ($hex)     {
00712                 $bin = '';
00713                 $hex = str_replace(':', '', $hex);      // Replace colon to nothing
00714                 for ($i=0; $i<strlen($hex); $i=$i+2)    {
00715                         $bin.= chr(hexdec(substr($hex, $i, 2)));
00716                 }
00717                 return $bin;
00718         }
00719 
00726         function normalizeIPv6($address)        {
00727                 $normalizedAddress = '';
00728                 $stageOneAddress = '';
00729 
00730                 $chunks = explode('::', $address);      // Count 2 if if address has hidden zero blocks
00731                 if (count($chunks)==2)  {
00732                         $chunksLeft = explode(':', $chunks[0]);
00733                         $chunksRight = explode(':', $chunks[1]);
00734                         $left = count($chunksLeft);
00735                         $right = count($chunksRight);
00736 
00737                                 // Special case: leading zero-only blocks count to 1, should be 0
00738                         if ($left==1 && strlen($chunksLeft[0])==0)      $left=0;
00739 
00740                         $hiddenBlocks = 8 - ($left + $right);
00741                         $hiddenPart = '';
00742                         while ($h<$hiddenBlocks)        {
00743                                 $hiddenPart .= '0000:';
00744                                 $h++;
00745                         }
00746 
00747                         if ($left == 0) {
00748                                 $stageOneAddress = $hiddenPart . $chunks[1];
00749                         } else {
00750                                 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
00751                         }
00752                 } else $stageOneAddress = $address;
00753 
00754                         // normalize the blocks:
00755                 $blocks = explode(':', $stageOneAddress);
00756                 $divCounter = 0;
00757                 foreach ($blocks as $block)     {
00758                         $tmpBlock = '';
00759                         $i = 0;
00760                         $hiddenZeros = 4 - strlen($block);
00761                         while ($i < $hiddenZeros)       {
00762                                 $tmpBlock .= '0';
00763                                 $i++;
00764                         }
00765                         $normalizedAddress .= $tmpBlock . $block;
00766                         if ($divCounter < 7)    {
00767                                 $normalizedAddress .= ':';
00768                                 $divCounter++;
00769                         }
00770                 }
00771                 return $normalizedAddress;
00772         }
00773 
00782         function validIPv6($ip) {
00783                 $uppercaseIP = strtoupper($ip);
00784 
00785                 $regex = '/^(';
00786                 $regex.= '(([\dA-F]{1,4}:){7}[\dA-F]{1,4})|';
00787                 $regex.= '(([\dA-F]{1,4}){1}::([\dA-F]{1,4}:){1,5}[\dA-F]{1,4})|';
00788                 $regex.= '(([\dA-F]{1,4}:){2}:([\dA-F]{1,4}:){1,4}[\dA-F]{1,4})|';
00789                 $regex.= '(([\dA-F]{1,4}:){3}:([\dA-F]{1,4}:){1,3}[\dA-F]{1,4})|';
00790                 $regex.= '(([\dA-F]{1,4}:){4}:([\dA-F]{1,4}:){1,2}[\dA-F]{1,4})|';
00791                 $regex.= '(([\dA-F]{1,4}:){5}:([\dA-F]{1,4}:){0,1}[\dA-F]{1,4})|';
00792                 $regex.= '(::([\dA-F]{1,4}:){0,6}[\dA-F]{1,4})';
00793                 $regex.= ')$/';
00794 
00795                 return preg_match($regex, $uppercaseIP) ? true : false;
00796         }
00797 
00805         function cmpFQDN($baseIP, $list)        {
00806                 if (count(explode('.',$baseIP))==4)     {
00807                         $resolvedHostName = explode('.', gethostbyaddr($baseIP));
00808                         $values = t3lib_div::trimExplode(',',$list,1);
00809 
00810                         foreach($values as $test)       {
00811                                 $hostNameParts = explode('.',$test);
00812                                 $yes = 1;
00813 
00814                                 foreach($hostNameParts as $index => $val)       {
00815                                         $val = trim($val);
00816                                         if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
00817                                                 $yes=0;
00818                                         }
00819                                 }
00820                                 if ($yes) return true;
00821                         }
00822                 }
00823                 return false;
00824         }
00825 
00835         function inList($list,$item)    {
00836                 return strstr(','.$list.',', ','.$item.',') ? true : false;
00837         }
00838 
00847         function rmFromList($element,$list)     {
00848                 $items = explode(',',$list);
00849                 while(list($k,$v)=each($items)) {
00850                         if ($v==$element)       {unset($items[$k]);}
00851                 }
00852                 return implode(',',$items);
00853         }
00854 
00863         function expandList($list)      {
00864                 $items = explode(',',$list);
00865                 $list = array();
00866                 while(list(,$item)=each($items))        {
00867                         $range = explode('-',$item);
00868                         if (isset($range[1]))   {
00869                                 $runAwayBrake = 1000;
00870                                 for ($n=$range[0]; $n<=$range[1]; $n++) {
00871                                         $list[] = $n;
00872 
00873                                         $runAwayBrake--;
00874                                         if ($runAwayBrake<=0)   break;
00875                                 }
00876                         } else {
00877                                 $list[] = $item;
00878                         }
00879                 }
00880 
00881                 return implode(',',$list);
00882         }
00883 
00894         function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)  {
00895                 // Returns $theInt as an integer in the integerspace from $min to $max
00896                 $theInt = intval($theInt);
00897                 if ($zeroValue && !$theInt)     {$theInt=$zeroValue;}   // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
00898                 if ($theInt<$min){$theInt=$min;}
00899                 if ($theInt>$max){$theInt=$max;}
00900                 return $theInt;
00901         }
00902 
00910         function intval_positive($theInt)       {
00911                 $theInt = intval($theInt);
00912                 if ($theInt<0){$theInt=0;}
00913                 return $theInt;
00914         }
00915 
00923         function int_from_ver($verNumberStr)    {
00924                 $verParts = explode('.',$verNumberStr);
00925                 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));
00926         }
00927 
00936         function compat_version($verNumberStr)  {
00937                 global $TYPO3_CONF_VARS;
00938                 $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version'] ? $TYPO3_CONF_VARS['SYS']['compat_version'] : TYPO3_branch;
00939 
00940                 if (t3lib_div::int_from_ver($currVersionStr) < t3lib_div::int_from_ver($verNumberStr))  {
00941                         return FALSE;
00942                 } else {
00943                         return TRUE;
00944                 }
00945         }
00946 
00954         function md5int($str)   {
00955                 return hexdec(substr(md5($str),0,7));
00956         }
00957 
00967         function shortMD5($input, $len=10)      {
00968                 return substr(md5($input),0,$len);
00969         }
00970 
00980         function uniqueList($in_list, $secondParameter=NULL)    {
00981                 if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
00982                 if (isset($secondParameter))    die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
00983 
00984                 return implode(',',array_unique(t3lib_div::trimExplode(',',$in_list,1)));
00985         }
00986 
00994         function split_fileref($fileref)        {
00995                 $reg = array();
00996                 if (    ereg('(.*/)(.*)$',$fileref,$reg)        )       {
00997                         $info['path'] = $reg[1];
00998                         $info['file'] = $reg[2];
00999                 } else {
01000                         $info['path'] = '';
01001                         $info['file'] = $fileref;
01002                 }
01003                 $reg='';
01004                 if (    ereg('(.*)\.([^\.]*$)',$info['file'],$reg)      )       {
01005                         $info['filebody'] = $reg[1];
01006                         $info['fileext'] = strtolower($reg[2]);
01007                         $info['realFileext'] = $reg[2];
01008                 } else {
01009                         $info['filebody'] = $info['file'];
01010                         $info['fileext'] = '';
01011                 }
01012                 reset($info);
01013                 return $info;
01014         }
01015 
01032         function dirname($path) {
01033                 $p=t3lib_div::revExplode('/',$path,2);
01034                 return count($p)==2?$p[0]:'';
01035         }
01036 
01048         function modifyHTMLColor($color,$R,$G,$B)       {
01049                 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
01050                 $nR = t3lib_div::intInRange(hexdec(substr($color,1,2))+$R,0,255);
01051                 $nG = t3lib_div::intInRange(hexdec(substr($color,3,2))+$G,0,255);
01052                 $nB = t3lib_div::intInRange(hexdec(substr($color,5,2))+$B,0,255);
01053                 return '#'.
01054                         substr('0'.dechex($nR),-2).
01055                         substr('0'.dechex($nG),-2).
01056                         substr('0'.dechex($nB),-2);
01057         }
01058 
01068         function modifyHTMLColorAll($color,$all)        {
01069                 return t3lib_div::modifyHTMLColor($color,$all,$all,$all);
01070         }
01071 
01079         function rm_endcomma($string)   {
01080                 return ereg_replace(',$','',$string);
01081         }
01082 
01092         function danish_strtoupper($string)     {
01093                 $value = strtoupper($string);
01094                 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
01095         }
01096 
01107         function convUmlauts($str)      {
01108                 $pat  = array ( '/ä/',  '/Ä/',  '/ö/',  '/Ö/',  '/ü/',  '/Ü/',  '/ß/',  '/å/',  '/Å/',  '/ø/',  '/Ø/',  '/æ/',  '/Æ/'   );
01109                 $repl = array ( 'ae',   'Ae',   'oe',   'Oe',   'ue',   'Ue',   'ss',   'aa',   'AA',   'oe',   'OE',   'ae',   'AE'    );
01110                 return preg_replace($pat,$repl,$str);
01111         }
01112 
01120         function testInt($var)  {
01121                 return !strcmp($var,intval($var));
01122         }
01123 
01132         function isFirstPartOfStr($str,$partStr)        {
01133                 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
01134                 $psLen = strlen($partStr);
01135                 if ($psLen)     {
01136                         return substr($str,0,$psLen)==(string)$partStr;
01137                 } else return false;
01138         }
01139 
01148         function formatSize($sizeInBytes,$labels='')    {
01149 
01150                         // Set labels:
01151                 if (strlen($labels) == 0) {
01152                     $labels = ' | K| M| G';
01153                 } else {
01154                     $labels = str_replace('"','',$labels);
01155                 }
01156                 $labelArr = explode('|',$labels);
01157 
01158                         // Find size:
01159                 if ($sizeInBytes>900)   {
01160                         if ($sizeInBytes>900000000)     {       // GB
01161                                 $val = $sizeInBytes/(1024*1024*1024);
01162                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
01163                         }
01164                         elseif ($sizeInBytes>900000)    {       // MB
01165                                 $val = $sizeInBytes/(1024*1024);
01166                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
01167                         } else {        // KB
01168                                 $val = $sizeInBytes/(1024);
01169                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
01170                         }
01171                 } else {        // Bytes
01172                         return $sizeInBytes.$labelArr[0];
01173                 }
01174         }
01175 
01183         function convertMicrotime($microtime)   {
01184                 $parts = explode(' ',$microtime);
01185                 return round(($parts[0]+$parts[1])*1000);
01186         }
01187 
01197         function splitCalc($string,$operators)  {
01198                 $res = Array();
01199                 $sign='+';
01200                 while($string)  {
01201                         $valueLen=strcspn($string,$operators);
01202                         $value=substr($string,0,$valueLen);
01203                         $res[] = Array($sign,trim($value));
01204                         $sign=substr($string,$valueLen,1);
01205                         $string=substr($string,$valueLen+1);
01206                 }
01207                 reset($res);
01208                 return $res;
01209         }
01210 
01219         function calcPriority($string)  {
01220                 $string=ereg_replace('[[:space:]]*','',$string);        // removing all whitespace
01221                 $string='+'.$string;    // Ensuring an operator for the first entrance
01222                 $qm='\*\/\+-^%';
01223                 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
01224                         // split the expression here:
01225                 $reg = array();
01226                 preg_match_all('/'.$regex.'/',$string,$reg);
01227 
01228                 reset($reg[2]);
01229                 $number=0;
01230                 $Msign='+';
01231                 $err='';
01232                 $buffer=doubleval(current($reg[2]));
01233                 next($reg[2]);  // Advance pointer
01234                 while(list($k,$v)=each($reg[2]))        {
01235                         $v=doubleval($v);
01236                         $sign = $reg[1][$k];
01237                         if ($sign=='+' || $sign=='-')   {
01238                                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01239                                 $Msign = $sign;
01240                                 $buffer=$v;
01241                         } else {
01242                                 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
01243                                 if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';}
01244                                 if ($sign=='*') {$buffer*=$v;}
01245                                 if ($sign=='^') {$buffer=pow($buffer,$v);}
01246                         }
01247                 }
01248                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01249                 return $err ? 'ERROR: '.$err : $number;
01250         }
01251 
01260         function calcParenthesis($string)       {
01261                 $securC=100;
01262                 do {
01263                         $valueLenO=strcspn($string,'(');
01264                         $valueLenC=strcspn($string,')');
01265                         if ($valueLenC==strlen($string) || $valueLenC < $valueLenO)     {
01266                                 $value = t3lib_div::calcPriority(substr($string,0,$valueLenC));
01267                                 $string = $value.substr($string,$valueLenC+1);
01268                                 return $string;
01269                         } else {
01270                                 $string = substr($string,0,$valueLenO).t3lib_div::calcParenthesis(substr($string,$valueLenO+1));
01271                         }
01272                                 // Security:
01273                         $securC--;
01274                         if ($securC<=0) break;
01275                 } while($valueLenO<strlen($string));
01276                 return $string;
01277         }
01278 
01286         function htmlspecialchars_decode($value)        {
01287                 $value = str_replace('&gt;','>',$value);
01288                 $value = str_replace('&lt;','<',$value);
01289                 $value = str_replace('&quot;','"',$value);
01290                 $value = str_replace('&amp;','&',$value);
01291                 return $value;
01292         }
01293 
01301         function deHSCentities($str)    {
01302                 return ereg_replace('&amp;([#[:alnum:]]*;)','&\1',$str);
01303         }
01304 
01314         function slashJS($string,$extended=0,$char="'") {
01315                 if ($extended)  {$string = str_replace ("\\", "\\\\", $string);}
01316                 return str_replace ($char, "\\".$char, $string);
01317         }
01318 
01327         function rawUrlEncodeJS($str)   {
01328                 return str_replace('%20',' ',rawurlencode($str));
01329         }
01330 
01339         function rawUrlEncodeFP($str)   {
01340                 return str_replace('%2F','/',rawurlencode($str));
01341         }
01342 
01350         function validEmail($email)     {
01351                 $email = trim ($email);
01352                 if (strstr($email,' '))  return FALSE;
01353                 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE : FALSE;
01354         }
01355 
01365         function formatForTextarea($content)    {
01366                 return chr(10).htmlspecialchars($content);
01367         }
01368 
01369 
01370 
01371 
01372 
01373 
01374 
01375 
01376 
01377 
01378 
01379 
01380         /*************************
01381          *
01382          * ARRAY FUNCTIONS
01383          *
01384          *************************/
01385 
01396         function inArray($in_array,$item)       {
01397                 if (is_array($in_array))        {
01398                         while (list(,$val)=each($in_array))     {
01399                                 if (!is_array($val) && !strcmp($val,$item)) return true;
01400                         }
01401                 }
01402         }
01403 
01413         function intExplode($delim, $string)    {
01414                 $temp = explode($delim,$string);
01415                 while(list($key,$val)=each($temp))      {
01416                         $temp[$key]=intval($val);
01417                 }
01418                 reset($temp);
01419                 return $temp;
01420         }
01421 
01432         function revExplode($delim, $string, $count=0)  {
01433                 $temp = explode($delim,strrev($string),$count);
01434                 while(list($key,$val)=each($temp))      {
01435                         $temp[$key]=strrev($val);
01436                 }
01437                 $temp=array_reverse($temp);
01438                 reset($temp);
01439                 return $temp;
01440         }
01441 
01452         function trimExplode($delim, $string, $onlyNonEmptyValues=0)    {
01453                 $temp = explode($delim,$string);
01454                 $newtemp=array();
01455                 while(list($key,$val)=each($temp))      {
01456                         if (!$onlyNonEmptyValues || strcmp('',trim($val)))      {
01457                                 $newtemp[]=trim($val);
01458                         }
01459                 }
01460                 reset($newtemp);
01461                 return $newtemp;
01462         }
01463 
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 
01710 
01711 
01712 
01713 
01714 
01715 
01716 
01717 
01718 
01719 
01720 
01721 
01722 
01723 
01724 
01725         /*************************
01726          *
01727          * HTML/XML PROCESSING
01728          *
01729          *************************/
01730 
01740         function get_tag_attributes($tag)       {
01741                 $components = t3lib_div::split_tag_attributes($tag);
01742                 $name = '';      // attribute name is stored here
01743                 $valuemode = '';
01744                 if (is_array($components))      {
01745                         while (list($key,$val) = each ($components))    {
01746                                 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
01747                                         if ($valuemode) {
01748                                                 if ($name)      {
01749                                                         $attributes[$name] = $val;
01750                                                         $name = '';
01751                                                 }
01752                                         } else {
01753                                                 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val)))    {
01754                                                         $attributes[$key] = '';
01755                                                         $name = $key;
01756                                                 }
01757                                         }
01758                                         $valuemode = '';
01759                                 } else {
01760                                         $valuemode = 'on';
01761                                 }
01762                         }
01763                         if (is_array($attributes))      reset($attributes);
01764                         return $attributes;
01765                 }
01766         }
01767 
01777         function split_tag_attributes($tag)     {
01778                 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
01779                         // Removes any > in the end of the string
01780                 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
01781 
01782                 while (strcmp($tag_tmp,''))     {       // Compared with empty string instead , 030102
01783                         $firstChar=substr($tag_tmp,0,1);
01784                         if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
01785                                 $reg=explode($firstChar,$tag_tmp,3);
01786                                 $value[]=$reg[1];
01787                                 $tag_tmp=trim($reg[2]);
01788                         } elseif (!strcmp($firstChar,'=')) {
01789                                 $value[] = '=';
01790                                 $tag_tmp = trim(substr($tag_tmp,1));            // Removes = chars.
01791                         } else {
01792                                         // There are '' around the value. We look for the next ' ' or '>'
01793                                 $reg = split('[[:space:]=]',$tag_tmp,2);
01794                                 $value[] = trim($reg[0]);
01795                                 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
01796                         }
01797                 }
01798                 if (is_array($value))   reset($value);
01799                 return $value;
01800         }
01801 
01811         function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)   {
01812                 if (is_array($arr))     {
01813                         if ($xhtmlSafe) {
01814                                 $newArr=array();
01815                                 foreach($arr as $p => $v)       {
01816                                         if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
01817                                 }
01818                                 $arr = $newArr;
01819                         }
01820                         $list = array();
01821                         foreach($arr as $p => $v)       {
01822                                 if (strcmp($v,'') || $dontOmitBlankAttribs)     {$list[]=$p.'="'.$v.'"';}
01823                         }
01824                         return implode(' ',$list);
01825                 }
01826         }
01827 
01838         function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)       {
01839                 return t3lib_div::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
01840         }
01841 
01853         function wrapJS($string, $linebreak=TRUE) {
01854                 if(trim($string)) {
01855                                 // <script wrapped in nl?
01856                         $cr = $linebreak? "\n" : '';
01857 
01858                                 // remove nl from the beginning
01859                         $string = preg_replace ('/^\n+/', '', $string);
01860                                 // re-ident to one tab using the first line as reference
01861                         $match = array();
01862                         if(preg_match('/^(\t+)/',$string,$match)) {
01863                                 $string = str_replace($match[1],"\t", $string);
01864                         }
01865                         $string = $cr.'<script type="text/javascript">
01866 /*<![CDATA[*/
01867 '.$string.'
01868 /*]]>*/
01869 </script>'.$cr;
01870                 }
01871                 return trim($string);
01872         }
01873 
01874 
01884         function xml2tree($string,$depth=999) {
01885                 $parser = xml_parser_create();
01886                 $vals = array();
01887                 $index = array();
01888 
01889                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
01890                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
01891                 xml_parse_into_struct($parser, $string, $vals, $index);
01892 
01893                 if (xml_get_error_code($parser))        return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
01894                 xml_parser_free($parser);
01895 
01896                 $stack = array( array() );
01897                 $stacktop = 0;
01898                 $startPoint=0;
01899 
01900 // FIXME don't use unset() - what does that mean? Use NULL or similar.
01901                 unset($tagi);
01902                 foreach($vals as $key => $val) {
01903                         $type = $val['type'];
01904 
01905                                 // open tag:
01906                         if ($type=='open' || $type=='complete') {
01907                                 $stack[$stacktop++] = $tagi;
01908 
01909                                 if ($depth==$stacktop)  {
01910                                         $startPoint=$key;
01911                                 }
01912 
01913                                 $tagi = array('tag' => $val['tag']);
01914 
01915                                 if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
01916                                 if(isset($val['value']))        $tagi['values'][] = $val['value'];
01917                         }
01918                                 // finish tag:
01919                         if ($type=='complete' || $type=='close')        {
01920                                 $oldtagi = $tagi;
01921                                 $tagi = $stack[--$stacktop];
01922                                 $oldtag = $oldtagi['tag'];
01923                                 unset($oldtagi['tag']);
01924 
01925                                 if ($depth==($stacktop+1))      {
01926                                         if ($key-$startPoint > 0)       {
01927                                                 $partArray = array_slice(
01928                                                         $vals,
01929                                                         $startPoint+1,
01930                                                         $key-$startPoint-1
01931                                                 );
01932                                                 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
01933                                                 $oldtagi['XMLvalue']=t3lib_div::xmlRecompileFromStructValArray($partArray);
01934                                         } else {
01935                                                 $oldtagi['XMLvalue']=$oldtagi['values'][0];
01936                                         }
01937                                 }
01938 
01939                                 $tagi['ch'][$oldtag][] = $oldtagi;
01940                                 unset($oldtagi);
01941                         }
01942                                 // cdata
01943                         if($type=='cdata') {
01944                                 $tagi['values'][] = $val['value'];
01945                         }
01946                 }
01947                 return $tagi['ch'];
01948         }
01949 
01960         function array2xml_cs($array,$docTag='phparray',$options=array(),$charset='')   {
01961 
01962                         // Figure out charset if not given explicitly:
01963                 if (!$charset)  {
01964                         if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'])  {       // First priority: forceCharset! If set, this will be authoritative!
01965                                 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
01966                         } elseif (is_object($GLOBALS['LANG']))  {
01967                                 $charset = $GLOBALS['LANG']->charSet;   // If "LANG" is around, that will hold the current charset
01968                         } else {
01969                                 $charset = 'iso-8859-1';        // THIS is just a hopeful guess!
01970                         }
01971                 }
01972 
01973                         // Return XML:
01974                 return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.chr(10).
01975                                 t3lib_div::array2xml($array,'',0,$docTag,0, $options);
01976         }
01977 
02001         function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array())    {
02002                         // 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
02003                 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
02004                                                 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
02005                                                 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
02006                                                 chr(30).chr(31);
02007                         // Set indenting mode:
02008                 $indentChar = $spaceInd ? ' ' : chr(9);
02009                 $indentN = $spaceInd>0 ? $spaceInd : 1;
02010 
02011                         // Init output variable:
02012                 $output='';
02013 
02014                         // Traverse the input array
02015                 if (is_array($array))   {
02016                         foreach($array as $k=>$v)       {
02017                                 $attr = '';
02018                                 $tagName = $k;
02019 
02020                                         // Construct the tag name.
02021                                 if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) {            // Use tag based on grand-parent + parent tag name
02022                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02023                                         $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
02024                                 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM']) && t3lib_div::testInt($tagName)) {              // Use tag based on parent tag name + if current tag is numeric
02025                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02026                                         $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM'];
02027                                 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) {            // Use tag based on parent tag name + current tag
02028                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02029                                         $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
02030                                 } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) {                // Use tag based on parent tag name:
02031                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02032                                         $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
02033                                 } elseif (!strcmp(intval($tagName),$tagName))   {       // If integer...;
02034                                         if ($options['useNindex']) {    // If numeric key, prefix "n"
02035                                                 $tagName = 'n'.$tagName;
02036                                         } else {        // Use special tag for num. keys:
02037                                                 $attr.=' index="'.$tagName.'"';
02038                                                 $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
02039                                         }
02040                                 } elseif($options['useIndexTagForAssoc']) {             // Use tag for all associative keys:
02041                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
02042                                         $tagName = $options['useIndexTagForAssoc'];
02043                                 }
02044 
02045                                         // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
02046                                 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
02047 
02048                                         // If the value is an array then we will call this function recursively:
02049                                 if (is_array($v))       {
02050 
02051                                                 // Sub elements:
02052                                         if ($options['alt_options'][$stackData['path'].'/'.$tagName])   {
02053                                                 $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
02054                                                 $clearStackPath = $subOptions['clearStackPath'];
02055                                         } else {
02056                                                 $subOptions = $options;
02057                                                 $clearStackPath = FALSE;
02058                                         }
02059 
02060                                         $content = chr(10).
02061                                                                 t3lib_div::array2xml(
02062                                                                         $v,
02063                                                                         $NSprefix,
02064                                                                         $level+1,
02065                                                                         '',
02066                                                                         $spaceInd,
02067                                                                         $subOptions,
02068                                                                         array(
02069                                                                                 'parentTagName' => $tagName,
02070                                                                                 'grandParentTagName' => $stackData['parentTagName'],
02071                                                                                 'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
02072                                                                         )
02073                                                                 ).
02074                                                                 str_pad('',($level+1)*$indentN,$indentChar);
02075                                         if ((int)$options['disableTypeAttrib']!=2)      {       // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
02076                                                 $attr.=' type="array"';
02077                                         }
02078                                 } else {        // Just a value:
02079 
02080                                                 // Look for binary chars:
02081                                         if (strcspn($v,$binaryChars) != strlen($v))     {       // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
02082                                                         // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
02083                                                 $content = chr(10).chunk_split(base64_encode($v));
02084                                                 $attr.=' base64="1"';
02085                                         } else {
02086                                                         // Otherwise, just htmlspecialchar the stuff:
02087                                                 $content = htmlspecialchars($v);
02088                                                 $dType = gettype($v);
02089                                                 if ($dType!='string' && !$options['disableTypeAttrib']) { $attr.=' type="'.$dType.'"'; }
02090                                         }
02091                                 }
02092 
02093                                         // Add the element to the output string:
02094                                 $output.=str_pad('',($level+1)*$indentN,$indentChar).'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.chr(10);
02095                         }
02096                 }
02097 
02098                         // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
02099                 if (!$level)    {
02100                         $output =
02101                                 '<'.$docTag.'>'.chr(10).
02102                                 $output.
02103                                 '</'.$docTag.'>';
02104                 }
02105 
02106                 return $output;
02107         }
02108 
02120         function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
02121                 global $TYPO3_CONF_VARS;
02122 
02123                         // Create parser:
02124                 $parser = xml_parser_create();
02125                 $vals = array();
02126                 $index = array();
02127 
02128                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
02129                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
02130 
02131                         // PHP5 fix of charset awareness:
02132                         // Problem is: PHP5 apparently detects the charset of the XML file (or defaults to utf-8) and will AUTOMATICALLY convert the content to either utf-8, iso-8859-1 or us-ascii. PHP4 just passed the content through without taking action regarding the charset.
02133                         // In TYPO3 we expect that the charset of XML content is NOT handled in the parser but internally in TYPO3 instead. Therefore it would be very nice if PHP5 could be configured to NOT process the charset of the files. But this is not possible for now.
02134                         // What we do here fixes the problem but ONLY if the charset is utf-8, iso-8859-1 or us-ascii. That should work for most TYPO3 installations, in particular if people use utf-8 which we highly recommend.
02135                 if ((double)phpversion()>=5)    {
02136                         $ereg_result = array();
02137                         ereg('^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"',substr($string,0,200),$ereg_result);
02138                         $theCharset = $ereg_result[1] ? $ereg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
02139                         xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);  // us-ascii / utf-8 / iso-8859-1
02140                 }
02141 
02142                         // Parse content:
02143                 xml_parse_into_struct($parser, $string, $vals, $index);
02144 
02145                         // If error, return error message:
02146                 if (xml_get_error_code($parser))        {
02147                         return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
02148                 }
02149                 xml_parser_free($parser);
02150 
02151                         // Init vars:
02152                 $stack = array(array());
02153                 $stacktop = 0;
02154                 $current=array();
02155                 $tagName = '';
02156                 $documentTag = '';
02157 
02158                         // Traverse the parsed XML structure:
02159                 foreach($vals as $key => $val) {
02160 
02161                                 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
02162                         $tagName = $val['tag'];
02163                         if (!$documentTag)      $documentTag = $tagName;
02164 
02165                                 // Test for name space:
02166                         $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
02167 
02168                                 // Test for numeric tag, encoded on the form "nXXX":
02169                         $testNtag = substr($tagName,1); // Closing tag.
02170                         $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
02171 
02172                                 // Test for alternative index value:
02173                         if (strlen($val['attributes']['index']))        { $tagName = $val['attributes']['index']; }
02174 
02175                                 // Setting tag-values, manage stack:
02176                         switch($val['type'])    {
02177                                 case 'open':            // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
02178                                         $current[$tagName] = array();   // Setting blank place holder
02179                                         $stack[$stacktop++] = $current;
02180                                         $current = array();
02181                                 break;
02182                                 case 'close':   // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
02183                                         $oldCurrent = $current;
02184                                         $current = $stack[--$stacktop];
02185                                         end($current);  // Going to the end of array to get placeholder key, key($current), and fill in array next:
02186                                         $current[key($current)] = $oldCurrent;
02187                                         unset($oldCurrent);
02188                                 break;
02189                                 case 'complete':        // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
02190                                         if ($val['attributes']['base64'])       {
02191                                                 $current[$tagName] = base64_decode($val['value']);
02192                                         } else {
02193                                                 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
02194 
02195                                                         // Cast type:
02196                                                 switch((string)$val['attributes']['type'])      {
02197                                                         case 'integer':
02198                                                                 $current[$tagName] = (integer)$current[$tagName];
02199                                                         break;
02200                                                         case 'double':
02201                                                                 $current[$tagName] = (double)$current[$tagName];
02202                                                         break;
02203                                                         case 'boolean':
02204                                                                 $current[$tagName] = (bool)$current[$tagName];
02205                                                         break;
02206                                                         case 'array':
02207                                                                 $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...
02208                                                         break;
02209                                                 }
02210                                         }
02211                                 break;
02212                         }
02213                 }
02214 
02215                 if ($reportDocTag)      {
02216                         $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
02217                 }
02218 
02219                         // Finally return the content of the document tag.
02220                 return $current[$tagName];
02221         }
02222 
02230         function xmlRecompileFromStructValArray($vals)  {
02231                 $XMLcontent='';
02232 
02233                 foreach($vals as $val) {
02234                         $type = $val['type'];
02235 
02236                                 // open tag:
02237                         if ($type=='open' || $type=='complete') {
02238                                 $XMLcontent.='<'.$val['tag'];
02239                                 if(isset($val['attributes']))  {
02240                                         foreach($val['attributes'] as $k => $v) {
02241                                                 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
02242                                         }
02243                                 }
02244                                 if ($type=='complete')  {
02245                                         if(isset($val['value']))        {
02246                                                 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
02247                                         } else $XMLcontent.='/>';
02248                                 } else $XMLcontent.='>';
02249 
02250                                 if ($type=='open' && isset($val['value']))      {
02251                                         $XMLcontent.=htmlspecialchars($val['value']);
02252                                 }
02253                         }
02254                                 // finish tag:
02255                         if ($type=='close')     {
02256                                 $XMLcontent.='</'.$val['tag'].'>';
02257                         }
02258                                 // cdata
02259                         if($type=='cdata') {
02260                                 $XMLcontent.=htmlspecialchars($val['value']);
02261                         }
02262                 }
02263 
02264                 return $XMLcontent;
02265         }
02266 
02274         function xmlGetHeaderAttribs($xmlData)  {
02275                 $xmlHeader = substr(trim($xmlData),0,200);
02276                 $reg=array();
02277                 if (eregi('^<\?xml([^>]*)\?\>',$xmlHeader,$reg))        {
02278                         return t3lib_div::get_tag_attributes($reg[1]);
02279                 }
02280         }
02281 
02282 
02283 
02284 
02285 
02286 
02287 
02288 
02289 
02290 
02291 
02292         /*************************
02293          *
02294          * FILES FUNCTIONS
02295          *
02296          *************************/
02297 
02308         function getURL($url, $includeHeader = 0, $requestHeaders = false)      {
02309                 $content = false;
02310 
02311                         // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
02312                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^https?:\/\//', $url)) {
02313                                 // External URL without error checking.
02314                         $ch = curl_init();
02315                         if (!$ch)       {
02316                                 return false;
02317                         }
02318 
02319                         curl_setopt($ch, CURLOPT_URL, $url);
02320                         curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
02321                         curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
02322                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
02323                         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
02324                         if (is_array($requestHeaders))  {
02325                                 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
02326                         }
02327 
02328                         if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer'])      {
02329                                 curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
02330 
02331                                         // Not sure if this is needed
02332                                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'])      {
02333                                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
02334                                 }
02335                                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'])    {
02336                                         curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
02337                                 }
02338                         }
02339                         $content = curl_exec($ch);
02340                         curl_close($ch);
02341 
02342                 } elseif ($includeHeader)       {
02343                         $parsedURL = parse_url($url);
02344                         if (!t3lib_div::inList('ftp,ftps,http,https,gopher,telnet', $parsedURL['scheme']))      {
02345                                 return false;
02346                         }
02347 
02348                         $fp = @fsockopen($parsedURL['host'], ($parsedURL['port'] > 0 ? $parsedURL['port'] : 80), $errno, $errstr, 2.0);
02349                         if (!$fp)       {
02350                                 return false;
02351                         }
02352 
02353                         $msg = 'GET ' . $parsedURL['path'] .
02354                                         ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
02355                                         ' HTTP/1.0' . "\r\n" . 'Host: ' .
02356                                         $parsedURL['host'] . "\r\n\r\n";
02357                         fputs($fp, $msg);
02358                         while (!feof($fp))      {
02359                                 $line = fgets($fp, 2048);
02360                                 $content.= $line;
02361                                 if ($includeHeader == 2 && !strlen(trim($line)))        {
02362                                         break;  // Stop at the first empty line (= end of header)
02363                                 }
02364                         }
02365                         fclose($fp);
02366 
02367                 } elseif (is_array($requestHeaders) && function_exists('stream_context_create'))        {
02368 
02369                         $ctx = stream_context_create(array(
02370                                                 'http' => array(
02371                                                         'header' => implode("\r\n", $requestHeaders)
02372                                                 )
02373                                         )
02374                                 );
02375 
02376                         if (function_exists('file_get_contents') && version_compare(phpversion(), '5.0', '>=')) {
02377                                 $content = @file_get_contents($url, false, $ctx);
02378                         }
02379                         elseif (false !== ($fd = @fopen($url, 'rb', false, $ctx)))      {
02380                                 $content = '';
02381                                 while (!feof($fd))      {
02382                                         $content .= fread($fd, 4096);
02383                                 }
02384                                 fclose($fd);
02385                         }
02386                 }
02387                 elseif (function_exists('file_get_contents'))   {
02388                         $content = @file_get_contents($url);
02389                 }
02390                 elseif (false !== ($fd = @fopen($url, 'rb')))   {
02391                         $content = '';
02392                         while (!feof($fd))      {
02393                                 $content .= fread($fd, 4096);
02394                         }
02395                         fclose($fd);
02396                 }
02397 
02398                 return $content;
02399         }
02400 
02409         function writeFile($file,$content)      {
02410                 if (!@is_file($file))   $changePermissions = true;
02411 
02412                 if ($fd = fopen($file,'wb'))    {
02413                         $res = fwrite($fd,$content);
02414                         fclose($fd);
02415 
02416                         if ($res===false)       return false;
02417 
02418                         if ($changePermissions) {       // Change the permissions only if the file has just been created
02419                                 t3lib_div::fixPermissions($file);
02420                         }
02421 
02422                         return true;
02423                 }
02424 
02425                 return false;
02426         }
02427 
02434         function fixPermissions($file)  {
02435                 if (@is_file($file) && TYPO3_OS!='WIN') {
02436                         @chmod($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));             // "@" is there because file is not necessarily OWNED by the user
02437                         if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
02438                                 @chgrp($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);                // "@" is there because file is not necessarily OWNED by the user
02439                         }
02440                 }
02441         }
02442 
02451         function writeFileToTypo3tempDir($filepath,$content)    {
02452 
02453                         // Parse filepath into directory and basename:
02454                 $fI = pathinfo($filepath);
02455                 $fI['dirname'].= '/';
02456 
02457                         // Check parts:
02458                 if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60)        {
02459                         if (defined('PATH_site'))       {
02460                                 $dirName = PATH_site.'typo3temp/';      // Setting main temporary directory name (standard)
02461                                 if (@is_dir($dirName))  {
02462                                         if (t3lib_div::isFirstPartOfStr($fI['dirname'],$dirName))       {
02463 
02464                                                         // Checking if the "subdir" is found:
02465                                                 $subdir = substr($fI['dirname'],strlen($dirName));
02466                                                 if ($subdir)    {
02467                                                         if (ereg('^[[:alnum:]_]+\/$',$subdir) || ereg('^[[:alnum:]_]+\/[[:alnum:]_]+\/$',$subdir))      {
02468                                                                 $dirName.= $subdir;
02469                                                                 if (!@is_dir($dirName)) {
02470                                                                         t3lib_div::mkdir_deep(PATH_site.'typo3temp/', $subdir);
02471                                                                 }
02472                                                         } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or  "[[:alnum:]_]/[[:alnum:]_]/"';
02473                                                 }
02474                                                         // Checking dir-name again (sub-dir might have been created):
02475                                                 if (@is_dir($dirName))  {
02476                                                         if ($filepath == $dirName.$fI['basename'])      {
02477                                                                 t3lib_div::writeFile($filepath, $content);
02478                                                                 if (!@is_file($filepath))       return 'File not written to disk! Write permission error in filesystem?';
02479                                                         } else return 'Calculated filelocation didn\'t match input $filepath!';
02480                                                 } else return '"'.$dirName.'" is not a directory!';
02481                                         } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
02482                                 } else return 'PATH_site + "typo3temp/" was not a directory!';
02483                         } else return 'PATH_site constant was NOT defined!';
02484                 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
02485         }
02486 
02494         function mkdir($theNewFolder)   {
02495                 $theNewFolder = preg_replace('|/$|','',$theNewFolder);
02496                 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
02497                         chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
02498 
02499                         if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
02500                                 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
02501                         }
02502                         return TRUE;
02503                 }
02504         }
02505 
02513         function mkdir_deep($destination,$deepDir)      {
02514                 $allParts = t3lib_div::trimExplode('/',$deepDir,1);
02515                 $root = '';
02516                 foreach($allParts as $part)     {
02517                         $root.= $part.'/';
02518                         if (!is_dir($destination.$root))        {
02519                                 t3lib_div::mkdir($destination.$root);
02520                                 if (!@is_dir($destination.$root))       {
02521                                         return 'Error: The directory "'.$destination.$root.'" could not be created...';
02522                                 }
02523                         }
02524                 }
02525         }
02526 
02535         function get_dirs($path)        {
02536                 if ($path)      {
02537                         $d = @dir($path);
02538                         if (is_object($d))      {
02539                                 while($entry=$d->read()) {
02540                                         if (@is_dir($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
02541                                             $filearray[]=$entry;
02542                                         }
02543                                 }
02544                                 $d->close();
02545                         } else return 'error';
02546                         return $filearray;
02547                 }
02548         }
02549 
02560         function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')        {
02561 
02562                         // Initialize variabels:
02563                 $filearray = array();
02564                 $sortarray = array();
02565                 $path = ereg_replace('\/$','',$path);
02566 
02567                         // Find files+directories:
02568                 if (@is_dir($path))     {
02569                         $extensionList = strtolower($extensionList);
02570                         $d = dir($path);
02571                         if (is_object($d))      {
02572                                 while($entry=$d->read()) {
02573                                         if (@is_file($path.'/'.$entry)) {
02574                                                 $fI = pathinfo($entry);
02575                                                 $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)
02576                                                 if (!$extensionList || t3lib_div::inList($extensionList,strtolower($fI['extension'])))  {
02577                                                     $filearray[$key]=($prependPath?$path.'/':'').$entry;
02578                                                         if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
02579                                                                 elseif ($order) {$sortarray[$key]=$entry;}
02580                                                 }
02581                                         }
02582                                 }
02583                                 $d->close();
02584                         } else return 'error opening path: "'.$path.'"';
02585                 }
02586 
02587                         // Sort them:
02588                 if ($order) {
02589                         asort($sortarray);
02590                         reset($sortarray);
02591                         $newArr=array();
02592                         while(list($k,$v)=each($sortarray))     {
02593                                 $newArr[$k]=$filearray[$k];
02594                         }
02595                         $filearray=$newArr;
02596                 }
02597 
02598                         // Return result
02599                 reset($filearray);
02600                 return $filearray;
02601         }
02602 
02614         function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)       {
02615                 if ($regDirs)   $fileArr[] = $path;
02616                 $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path,$extList,1,1));
02617 
02618                 $dirs = t3lib_div::get_dirs($path);
02619                 if (is_array($dirs) && $recursivityLevels>0)    {
02620                         foreach ($dirs as $subdirs)     {
02621                                 if ((string)$subdirs!='')       {
02622                                         $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
02623                                 }
02624                         }
02625                 }
02626                 return $fileArr;
02627         }
02628 
02637         function removePrefixPathFromList($fileArr,$prefixToRemove)     {
02638                 foreach($fileArr as $k => $absFileRef)  {
02639                         if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove))    {
02640                                 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
02641                         } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
02642                 }
02643                 return $fileArr;
02644         }
02645 
02653         function fixWindowsFilePath($theFile)   {
02654                 return str_replace('//','/', str_replace('\\','/', $theFile));
02655         }
02656 
02665         function resolveBackPath($pathStr)      {
02666                 $parts = explode('/',$pathStr);
02667                 $output=array();
02668                 $c = 0;
02669                 foreach($parts as $pV)  {
02670                         if ($pV=='..')  {
02671                                 if ($c) {
02672                                         array_pop($output);
02673                                         $c--;
02674                                 } else $output[]=$pV;
02675                         } else {
02676                                 $c++;
02677                                 $output[]=$pV;
02678                         }
02679                 }
02680                 return implode('/',$output);
02681         }
02682 
02693         function locationHeaderUrl($path)       {
02694                 $uI = parse_url($path);
02695                 if (substr($path,0,1)=='/')     { // relative to HOST
02696                         $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
02697                 } elseif (!$uI['scheme'])       { // No scheme either
02698                         $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
02699                 }
02700                 return $path;
02701         }
02702 
02703 
02704 
02705 
02706 
02707 
02708 
02709 
02710 
02711 
02712 
02713 
02714 
02715 
02716 
02717 
02718         /*************************
02719          *
02720          * DEBUG helper FUNCTIONS
02721          *
02722          *************************/
02723 
02733         function debug_ordvalue($string,$characters=100)        {
02734                 if(strlen($string) < $characters)       $characters = strlen($string);
02735                 for ($i=0; $i<$characters; $i++)        {
02736                         $valuestring.=' '.ord(substr($string,$i,1));
02737                 }
02738                 return trim($valuestring);
02739         }
02740 
02750         function view_array($array_in)  {
02751                 if (is_array($array_in))        {
02752                         $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
02753                         if (!count($array_in))  {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
02754                         while (list($key,$val)=each($array_in)) {
02755                                 $result.= '<tr><td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
02756                                 if (is_array($array_in[$key]))  {
02757                                         $result.=t3lib_div::view_array($array_in[$key]);
02758                                 } else
02759                                         $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
02760                                 $result.= '</td></tr>';
02761                         }
02762                         $result.= '</table>';
02763                 } else  {
02764                         $result  = false;
02765                 }
02766                 return $result;
02767         }
02768 
02778         function print_array($array_in) {
02779                 echo t3lib_div::view_array($array_in);
02780         }
02781 
02793         function debug($var="",$brOrHeader=0)   {
02794                 if ($brOrHeader && !t3lib_div::testInt($brOrHeader))    {
02795                         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>';
02796                 } elseif ($brOrHeader<0)        {
02797                         for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
02798                 }
02799 
02800                 if (is_array($var))     {
02801                         t3lib_div::print_array($var);
02802                 } elseif (is_object($var))      {
02803                         echo '<b>|Object:<pre>';
02804                         print_r($var);
02805                         echo '</pre>|</b>';
02806                 } elseif ((string)$var!='')     {
02807                         echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
02808                 } else {
02809                         echo '<b>| debug |</b>';
02810                 }
02811 
02812                 if ($brOrHeader && !t3lib_div::testInt($brOrHeader))    {
02813                         echo '</td></tr></table>';
02814                 } elseif ($brOrHeader>0)        {
02815                         for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
02816                 }
02817         }
02818 
02824         function debug_trail()  {
02825                 if (function_exists('debug_backtrace')) {
02826                         $trail = debug_backtrace();
02827                         $trail = array_reverse($trail);
02828                         array_pop($trail);
02829 
02830                         $path = array();
02831                         foreach($trail as $dat) {
02832                                 $path[] = $dat['class'].$dat['type'].$dat['function'];
02833                         }
02834 
02835                         return implode(' // ',$path);
02836                 } else return 'N/A';
02837         }
02838 
02846         function debugRows($rows,$header='')    {
02847                 if (is_array($rows))    {
02848                         reset($rows);
02849                         $firstEl = current($rows);
02850                         if (is_array($firstEl)) {
02851                                 $headerColumns = array_keys($firstEl);
02852                                 $tRows = array();
02853 
02854                                         // Header:
02855                                 $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>';
02856                                 $tCells = array();
02857                                 foreach($headerColumns as $key) {
02858                                         $tCells[] = '
02859                                                         <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
02860                                 }
02861                                 $tRows[] = '
02862                                                 <tr>'.implode('',$tCells).'
02863                                                 </tr>';
02864 
02865                                         // Rows:
02866                                 foreach($rows as $singleRow)    {
02867                                         $tCells = array();
02868                                         foreach($headerColumns as $key) {
02869                                                 $tCells[] = '
02870                                                         <td><font face="Verdana,Arial" size="1">'.htmlspecialchars($singleRow[$key]).'</font></td>';
02871                                         }
02872                                         $tRows[] = '
02873                                                 <tr>'.implode('',$tCells).'
02874                                                 </tr>';
02875                                 }
02876 
02877                                 $table = '
02878                                         <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
02879                                         </table>';
02880                                 echo $table;
02881                         } else debug('Empty array of rows',$header);
02882                 } else debug('No array of rows',$header);
02883         }
02884 
02885 
02886 
02887 
02888 
02889 
02890 
02891 
02892 
02893 
02894 
02895 
02896 
02897 
02898 
02899 
02900 
02901 
02902 
02903 
02904 
02905 
02906 
02907 
02908 
02909 
02910 
02911 
02912         /*************************
02913          *
02914          * SYSTEM INFORMATION
02915          *
02916          *************************/
02917 
02924         function getThisUrl()   {
02925                 $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'));            // Url of this script
02926                 $dir=t3lib_div::dirname($p['path']).'/';        // Strip file
02927                 $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
02928                 return $url;
02929         }
02930 
02940         function linkThisScript($getParams=array())     {
02941                 $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
02942                 $params = t3lib_div::_GET();
02943 
02944                 foreach($getParams as $k => $v) {
02945                         if (strcmp($v,''))      {
02946                                 $params[$k]=$v;
02947                         } else unset($params[$k]);
02948                 }
02949 
02950                 $pString = t3lib_div::implodeArrayForUrl('',$params);
02951 
02952                 return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
02953         }
02954 
02964         function linkThisUrl($url,$getParams=array())   {
02965                 $parts = parse_url($url);
02966                 $getP = array();
02967                 if ($parts['query'])    {
02968                         parse_str($parts['query'],$getP);
02969                 }
02970                 $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
02971                 $uP = explode('?',$url);
02972 
02973                 $params = t3lib_div::implodeArrayForUrl('',$getP);
02974                 $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
02975 
02976                 return $outurl;
02977         }
02978 
02987         function getIndpEnv($getEnvName)        {
02988                 /*
02989                         Conventions:
02990                         output from parse_url():
02991                         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
02992                             [scheme] => 'http'
02993                             [user] => 'username'
02994                             [pass] => 'password'
02995                             [host] => '192.168.1.4'
02996                                 [port] => '8080'
02997                             [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
02998                             [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
02999                             [fragment] => 'link1'
03000 
03001                                 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
03002                                                                         [path_dir] = '/typo3/32/temp/phpcheck/'
03003                                                                         [path_info] = '/arg1/arg2/arg3/'
03004                                                                         [path] = [path_script/path_dir][path_info]
03005 
03006 
03007                         Keys supported:
03008 
03009                         URI______:
03010                                 REQUEST_URI             =       [path]?[query]          = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
03011                                 HTTP_HOST               =       [host][:[port]]         = 192.168.1.4:8080
03012                                 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')!
03013                                 PATH_INFO               =       [path_info]                     = /arg1/arg2/arg3/
03014                                 QUERY_STRING    =       [query]                         = arg1,arg2,arg3&p1=parameter1&p2[key]=value
03015                                 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
03016                                                                                 (Notice: NO username/password + NO fragment)
03017 
03018                         CLIENT____:
03019                                 REMOTE_ADDR             =       (client IP)
03020                                 REMOTE_HOST             =       (client host)
03021                                 HTTP_USER_AGENT =       (client user agent)
03022                                 HTTP_ACCEPT_LANGUAGE    = (client accept language)
03023 
03024                         SERVER____:
03025                                 SCRIPT_FILENAME =       Absolute filename of script             (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
03026 
03027                         Special extras:
03028                                 TYPO3_HOST_ONLY =               [host]                  = 192.168.1.4
03029                                 TYPO3_PORT              =               [port]                  = 8080 (blank if 80, taken from host value)
03030                                 TYPO3_REQUEST_HOST =    [scheme]://[host][:[port]]
03031                                 TYPO3_REQUEST_URL =             [scheme]://[host][:[port]][path]?[query]        (sheme will by default be 'http' until we can detect if it's https -
03032                                 TYPO3_REQUEST_SCRIPT =  [scheme]://[host][:[port]][path_script]
03033                                 TYPO3_REQUEST_DIR =             [scheme]://[host][:[port]][path_dir]
03034                                 TYPO3_SITE_URL =                [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
03035                                 TYPO3_SITE_SCRIPT =     [script / Speaking URL] of the TYPO3 website
03036                                 TYPO3_DOCUMENT_ROOT     =       Absolute path of root of documents:     TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
03037 
03038                         Notice: [fragment] is apparently NEVER available to the script!
03039 
03040 
03041                         Testing suggestions:
03042                         - Output all the values.
03043                         - 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
03044                         - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
03045 
03046                 */
03047 
03048 #               if ($getEnvName=='HTTP_REFERER')        return '';
03049 
03050                 $retVal = '';
03051 
03052                 switch((string)$getEnvName)     {
03053                         case 'SCRIPT_NAME':
03054                                 $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']);
03055                         break;
03056                         case 'SCRIPT_FILENAME':
03057                                 $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'])));
03058                         break;
03059                         case 'REQUEST_URI':
03060                                         // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
03061                                 if (!$_SERVER['REQUEST_URI'])   {       // This is for ISS/CGI which does not have the REQUEST_URI available.
03062                                         $retVal = '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
03063                                                 ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
03064                                 } else $retVal = $_SERVER['REQUEST_URI'];
03065                         break;
03066                         case 'PATH_INFO':
03067                                         // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
03068                                         // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
03069                                         // 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)
03070 //                              if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1)  {
03071                                 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi')        {
03072                                         $retVal = $_SERVER['PATH_INFO'];
03073                                 }
03074                         break;
03075                                 // These are let through without modification
03076                         case 'REMOTE_ADDR':
03077                         case 'REMOTE_HOST':
03078                         case 'HTTP_REFERER':
03079                         case 'HTTP_HOST':
03080                         case 'HTTP_USER_AGENT':
03081                         case 'HTTP_ACCEPT_LANGUAGE':
03082                         case 'QUERY_STRING':
03083                                 $retVal = $_SERVER[$getEnvName];
03084                         break;
03085                         case 'TYPO3_DOCUMENT_ROOT':
03086                                 // 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.
03087                                 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
03088                                 $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
03089                                 $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
03090                                 $SFN_A = explode('/',strrev($SFN));
03091                                 $acc = array();
03092                                 while(list($kk,$vv)=each($SN_A))        {
03093                                         if (!strcmp($SFN_A[$kk],$vv))   {
03094                                                 $acc[] = $vv;
03095                                         } else break;
03096                                 }
03097                                 $commonEnd=strrev(implode('/',$acc));
03098                                 if (strcmp($commonEnd,''))      { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
03099                                 $retVal = $DR;
03100                         break;
03101                         case 'TYPO3_HOST_ONLY':
03102                                 $p = explode(':',$_SERVER['HTTP_HOST']);
03103                                 $retVal = $p[0];
03104                         break;
03105                         case 'TYPO3_PORT':
03106                                 $p = explode(':',$_SERVER['HTTP_HOST']);
03107                                 $retVal = $p[1];
03108                         break;
03109                         case 'TYPO3_REQUEST_HOST':
03110                                 $retVal = (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
03111                                         $_SERVER['HTTP_HOST'];
03112                         break;
03113                         case 'TYPO3_REQUEST_URL':
03114                                 $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
03115                         break;
03116                         case 'TYPO3_REQUEST_SCRIPT':
03117                                 $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
03118                         break;
03119                         case 'TYPO3_REQUEST_DIR':
03120                                 $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
03121                         break;
03122                         case 'TYPO3_SITE_URL':
03123                                 if (defined('PATH_thisScript') && defined('PATH_site')) {
03124                                         $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
03125                                         $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
03126                                         $siteUrl = substr($url,0,-strlen($lPath));
03127                                         if (substr($siteUrl,-1)!='/')   $siteUrl.='/';
03128                                         $retVal = $siteUrl;
03129                                 }
03130                         break;
03131                         case 'TYPO3_SITE_SCRIPT':
03132                                 $retVal = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
03133                         break;
03134                         case 'TYPO3_SSL':
03135                                 $retVal = $_SERVER['SSL_SESSION_ID'] || !strcmp($_SERVER['HTTPS'],'on') ? TRUE : FALSE;
03136                         break;
03137                         case '_ARRAY':
03138                                 $out = array();
03139                                         // Here, list ALL possible keys to this function for debug display.
03140                                 $envTestVars = t3lib_div::trimExplode(',','
03141                                         HTTP_HOST,
03142                                         TYPO3_HOST_ONLY,
03143                                         TYPO3_PORT,
03144                                         PATH_INFO,
03145                                         QUERY_STRING,
03146                                         REQUEST_URI,
03147                                         HTTP_REFERER,
03148                                         TYPO3_REQUEST_HOST,
03149                                         TYPO3_REQUEST_URL,
03150                                         TYPO3_REQUEST_SCRIPT,
03151                                         TYPO3_REQUEST_DIR,
03152                                         TYPO3_SITE_URL,
03153                                         TYPO3_SITE_SCRIPT,
03154                                         TYPO3_SSL,
03155                                         SCRIPT_NAME,
03156                                         TYPO3_DOCUMENT_ROOT,
03157                                         SCRIPT_FILENAME,
03158                                         REMOTE_ADDR,
03159                                         REMOTE_HOST,
03160                                         HTTP_USER_AGENT,
03161                                         HTTP_ACCEPT_LANGUAGE',1);
03162                                 reset($envTestVars);
03163                                 while(list(,$v)=each($envTestVars))     {
03164                                         $out[$v]=t3lib_div::getIndpEnv($v);
03165                                 }
03166                                 reset($out);
03167                                 $retVal = $out;
03168                         break;
03169                 }
03170                 return $retVal;
03171         }
03172 
03180         function milliseconds() {
03181                 $p=explode(' ',microtime());
03182                 return round(($p[0]+$p[1])*1000);
03183         }
03184 
03192         function clientInfo($useragent='')      {
03193                 if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
03194 
03195                 $bInfo=array();
03196                         // Which browser?
03197                 if (strstr($useragent,'Konqueror'))     {
03198                         $bInfo['BROWSER']= 'konqu';
03199                 } elseif (strstr($useragent,'Opera'))   {
03200                         $bInfo['BROWSER']= 'opera';
03201                 } elseif (strstr($useragent,'MSIE 4') || strstr($useragent,'MSIE 5') || strstr($useragent,'MSIE 6'))    {
03202                         $bInfo['BROWSER']= 'msie';
03203                 } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5'))     {
03204                         $bInfo['BROWSER']='net';
03205                 }
03206                 if ($bInfo['BROWSER'])  {
03207                                 // Browser version
03208                         switch($bInfo['BROWSER'])       {
03209                                 case 'net':
03210                                         $bInfo['VERSION']= doubleval(substr($useragent,8));
03211                                         if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
03212                                         if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
03213                                 break;
03214                                 case 'msie':
03215                                         $tmp = strstr($useragent,'MSIE');
03216                                         $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
03217                                 break;
03218                                 case 'opera':
03219                                         $tmp = strstr($useragent,'Opera');
03220                                         $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
03221                                 break;
03222                                 case 'konqu':
03223                                         $tmp = strstr($useragent,'Konqueror/');
03224                                         $bInfo['VERSION'] = doubleval(substr($tmp,10));
03225                                 break;
03226                         }
03227                                 // Client system
03228                         if (strstr($useragent,'Win'))   {
03229                                 $bInfo['SYSTEM'] = 'win';
03230                         } elseif (strstr($useragent,'Mac'))     {
03231                                 $bInfo['SYSTEM'] = 'mac';
03232                         } elseif (strstr($useragent,'Linux') || strstr($useragent,'X11') || strstr($useragent,'SGI') || strstr($useragent,' SunOS ') || strstr($useragent,' HP-UX '))   {
03233                                 $bInfo['SYSTEM'] = 'unix';
03234                         }
03235                 }
03236                         // Is true if the browser supports css to format forms, especially the width
03237                 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
03238 
03239                 return $bInfo;
03240         }
03241 
03249         function getHostname($requestHost=TRUE) {
03250                 $host = '';
03251                 if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode))      {
03252                         $host = $_SERVER['HTTP_HOST'];
03253                 }
03254                 if (!$host)     {
03255                                 // will fail for PHP 4.1 and 4.2
03256                         $host = @php_uname('n');
03257                                 // 'n' is ignored in broken installations
03258                         if (strpos($host, ' ')) $host = '';
03259                 }
03260                         // we have not found a FQDN yet
03261                 if ($host && strpos('.',$host) === FALSE)       {
03262                         $ip = gethostbyname($host);
03263                                 // we got an IP address
03264                         if ($ip != $host)       {
03265                                 $fqdn = gethostbyaddr($ip);
03266                                 if ($ip != $fqdn)       $host = $fqdn;
03267                         }
03268                 }
03269                 if (!$host)     $host = 'localhost.localdomain';
03270 
03271                 return $host;
03272         }
03273 
03274 
03275 
03276 
03277 
03278 
03279 
03280 
03281 
03282 
03283 
03284 
03285 
03286 
03287 
03288 
03289 
03290 
03291 
03292 
03293 
03294 
03295         /*************************
03296          *
03297          * TYPO3 SPECIFIC FUNCTIONS
03298          *
03299          *************************/
03300 
03310         function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)    {
03311                 if (!strcmp($filename,''))              return '';
03312 
03313                 if ($relToTYPO3_mainDir)        {
03314                         if (!defined('PATH_typo3'))     return '';
03315                         $relPathPrefix = PATH_typo3;
03316                 } else {
03317                         $relPathPrefix = PATH_site;
03318                 }
03319                 if (substr($filename,0,4)=='EXT:')      {       // extension
03320                         list($extKey,$local) = explode('/',substr($filename,4),2);
03321                         $filename='';
03322                         if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
03323                                 $filename = t3lib_extMgm::extPath($extKey).$local;
03324                         }
03325                 } elseif (!t3lib_div::isAbsPath($filename))     {       // relative. Prepended with $relPathPrefix
03326                         $filename=$relPathPrefix.$filename;
03327                 } elseif ($onlyRelative && !t3lib_div::isFirstPartOfStr($filename,$relPathPrefix)) {    // absolute, but set to blank if not allowed
03328                         $filename='';
03329                 }
03330                 if (strcmp($filename,'') && t3lib_div::validPathStr($filename)) {       // checks backpath.
03331                         return $filename;
03332                 }
03333         }
03334 
03346         function validPathStr($theFile) {
03347                 if (!strstr($theFile,'//') && !strstr($theFile,'\\') && !preg_match('#(?:^\.\.|/\.\./)#',$theFile))     return true;
03348         }
03349 
03357         function isAbsPath($path)       {
03358                 return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' :  substr($path,0,1)=='/';
03359         }
03360 
03368         function isAllowedAbsPath($path)        {
03369                 if (t3lib_div::isAbsPath($path) &&
03370                         t3lib_div::validPathStr($path) &&
03371                                 (       t3lib_div::isFirstPartOfStr($path,PATH_site)
03372                                         ||
03373                                         ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
03374                                 )
03375                         )       return true;
03376         }
03377 
03385         function verifyFilenameAgainstDenyPattern($filename)    {
03386                 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],''))    {
03387                         $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
03388                         if ($result)    return false;   // so if a matching filename is found, return false;
03389                 }
03390                 return true;
03391         }
03392 
03403         function upload_copy_move($source,$destination) {
03404                 if (is_uploaded_file($source))  {
03405                         $uploaded = TRUE;
03406                         // 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:
03407                         $uploadedResult = move_uploaded_file($source, $destination);
03408                 } else {
03409                         $uploaded = FALSE;
03410                         @copy($source,$destination);
03411                 }
03412 
03413                 t3lib_div::fixPermissions($destination);        // Change the permissions of the file
03414 
03415                         // 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
03416                 return $uploaded ? $uploadedResult : FALSE;
03417         }
03418 
03429         function upload_to_tempfile($uploadedFileName)  {
03430                 if (is_uploaded_file($uploadedFileName))        {
03431                         $tempFile = t3lib_div::tempnam('upload_temp_');
03432                         move_uploaded_file($uploadedFileName, $tempFile);
03433                         return @is_file($tempFile) ? $tempFile : '';
03434                 }
03435         }
03436 
03447         function unlink_tempfile($uploadedTempFileName) {
03448                 if ($uploadedTempFileName && t3lib_div::validPathStr($uploadedTempFileName) && t3lib_div::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName))    {
03449                         if (unlink($uploadedTempFileName))      return TRUE;
03450                 }
03451         }
03452 
03463         function tempnam($filePrefix)   {
03464                 return tempnam(PATH_site.'typo3temp/',$filePrefix);
03465         }
03466 
03477         function stdAuthCode($uid_or_record,$fields='',$codeLength=8)   {
03478 
03479                 if (is_array($uid_or_record))   {
03480                         $recCopy_temp=array();
03481                         if ($fields)    {
03482                                 $fieldArr = t3lib_div::trimExplode(',',$fields,1);
03483                                 reset($fieldArr);
03484                                 while(list($k,$v)=each($fieldArr))      {
03485                                         $recCopy_temp[$k]=$uid_or_record[$v];
03486                                 }
03487                         } else {
03488                                 $recCopy_temp=$uid_or_record;
03489                         }
03490                         $preKey = implode('|',$recCopy_temp);
03491                 } else {
03492                         $preKey = $uid_or_record;
03493                 }
03494 
03495                 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
03496                 $authCode = substr(md5($authCode),0,$codeLength);
03497                 return $authCode;
03498         }
03499 
03508         function cHashParams($addQueryParams) {
03509                 $params = explode('&',substr($addQueryParams,1));       // Splitting parameters up
03510 
03511                         // Make array:
03512                 $pA = array();
03513                 foreach($params as $theP)       {
03514                         $pKV = explode('=', $theP);     // Splitting single param by '=' sign
03515                         if (!t3lib_div::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0]))        {
03516                                 $pA[rawurldecode($pKV[0])] = (string)rawurldecode($pKV[1]);
03517                         }
03518                 }
03519                 $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
03520                 ksort($pA);
03521 
03522                 return $pA;
03523         }
03524 
03531         function hideIfNotTranslated($l18n_cfg_fieldValue)      {
03532                 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault'])     {
03533                         return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
03534                 } else {
03535                         return $l18n_cfg_fieldValue&2 ? TRUE : FALSE;
03536                 }
03537         }
03538 
03546         function readLLfile($fileRef,$langKey)  {
03547 
03548                 $file = t3lib_div::getFileAbsFileName($fileRef);
03549                 if ($file)      {
03550                         $baseFile = ereg_replace('\.(php|xml)$', '', $file);
03551 
03552                         if (@is_file($baseFile.'.xml')) {
03553                                 $LOCAL_LANG = t3lib_div::readLLXMLfile($baseFile.'.xml', $langKey);
03554                         } elseif (@is_file($baseFile.'.php'))   {
03555                                 include($baseFile.'.php');
03556                         } else die('Filereference, "'.$file.'", not found!');
03557                 }
03558 
03559                 return is_array($LOCAL_LANG)?$LOCAL_LANG:array();
03560         }
03561 
03570         function readLLXMLfile($fileRef,$langKey)       {
03571 
03572                 if (is_object($GLOBALS['LANG']))        {
03573                         $csConvObj = &$GLOBALS['LANG']->csConvObj;
03574                 } elseif (is_object($GLOBALS['TSFE']))  {
03575                         $csConvObj = &$GLOBALS['TSFE']->csConvObj;
03576                 } else $csConvObj = NULL;
03577 
03578                 if (@is_file($fileRef) && $langKey && is_object($csConvObj))    {
03579 
03580                                 // Set charset:
03581                         $origCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
03582 
03583                                 // Cache file name:
03584                         $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.2';
03585                         $cacheFileName = PATH_site.'typo3temp/llxml/'.
03586                                                         #str_replace('_','',ereg_replace('^.*\/','',dirname($fileRef))).
03587                                                         #'_'.basename($fileRef).
03588                                                         substr(basename($fileRef),10,15).
03589                                                         '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
03590 
03591                                 // Check if cache file exists...
03592                         if (!@is_file($cacheFileName))  {       // ... if it doesn't, create content and write it:
03593 
03594                                         // Read XML, parse it.
03595                                 $xmlString = t3lib_div::getUrl($fileRef);
03596                                 $xmlContent = t3lib_div::xml2array($xmlString);
03597                                 if (!is_array($xmlContent))     {
03598                                         die($fileRef.' was not XML!: '.$xmlContent);
03599                                 }
03600 
03601                                         // Set default LOCAL_LANG array content:
03602                                 $LOCAL_LANG = array();
03603                                 $LOCAL_LANG['default'] = $xmlContent['data']['default'];
03604 
03605                                         // 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)
03606                                         // This conversion is unneccessary for 99,99% of all default labels since they are in english, therefore ASCII.
03607                                         // 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.
03608                                         // Since the output from this function is probably always cached it is considered insignificant to do this conversion.
03609                                         // - kasper
03610                                 if (is_array($LOCAL_LANG['default']))   {
03611                                         foreach($LOCAL_LANG['default'] as $labelKey => $labelValue)     {
03612                                                 $LOCAL_LANG['default'][$labelKey] = $csConvObj->utf8_decode($labelValue,'iso-8859-1');
03613                                         }
03614                                 }
03615 
03616                                         // Specific language, convert from utf-8 to backend language charset:
03617                                         // 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.
03618                                 if ($langKey!='default')        {
03619 
03620                                                 // 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:
03621                                         if (!isset($xmlContent['data'][$langKey]))      {
03622                                                 $LOCAL_LANG[$langKey] = t3lib_div::llXmlAutoFileName($fileRef, $langKey);
03623                                         } else {
03624                                                 $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
03625                                         }
03626 
03627                                                 // Checking if charset should be converted.
03628                                         if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8')   {
03629                                                 foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue)      {
03630                                                         $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
03631                                                 }
03632                                         }
03633                                 }
03634 
03635                                         // Cache the content now:
03636                                 $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>$LOCAL_LANG);
03637                                 $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
03638                                 if ($res)       die('ERROR: '.$res);
03639                         } else {
03640                                         // Get content from cache:
03641                                 $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
03642                                 $LOCAL_LANG = $serContent['LOCAL_LANG'];
03643                         }
03644 
03645                                 // Checking for EXTERNAL file for non-default language:
03646                         if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey]))   {
03647 
03648                                         // Look for localized file:
03649                                 $localized_file = t3lib_div::getFileAbsFileName($LOCAL_LANG[$langKey]);
03650                                 if ($localized_file && @is_file($localized_file))       {
03651 
03652                                                 // Cache file name:
03653                                         $hashSource = substr($localized_file,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($localized_file));
03654                                         $cacheFileName = PATH_site.'typo3temp/llxml/ext_'.
03655                                                                         substr(basename($localized_file),10,15).
03656                                                                         '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
03657 
03658                                                 // Check if cache file exists...
03659                                         if (!@is_file($cacheFileName))  {       // ... if it doesn't, create content and write it:
03660 
03661                                                         // Read and parse XML content:
03662                                                 $local_xmlString = t3lib_div::getUrl($localized_file);
03663                                                 $local_xmlContent = t3lib_div::xml2array($local_xmlString);
03664                                                 $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
03665 
03666                                                         // Checking if charset should be converted.
03667                                                 if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8')   {
03668                                                         foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue)      {
03669                                                                 $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
03670                                                         }
03671                                                 }
03672 
03673                                                         // Cache the content now:
03674                                                 $serContent = array('extlang'=>$langKey, 'origFile'=>$LOCAL_LANG[$langKey], 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
03675                                                 $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
03676                                                 if ($res)       die('ERROR: '.$res);
03677                                         } else {
03678                                                         // Get content from cache:
03679                                                 $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
03680                                                 $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
03681                                         }
03682                                 } else {
03683                                         $LOCAL_LANG[$langKey] = array();
03684                                 }
03685                         }
03686 
03687                         return $LOCAL_LANG;
03688                 }
03689         }
03690 
03698         function llXmlAutoFileName($fileRef,$language)  {
03699 
03700                         // Analyse file reference:
03701                 $location = 'typo3conf/l10n/'.$language.'/';    // Default location of translations
03702                 if (t3lib_div::isFirstPartOfStr($fileRef,PATH_site.TYPO3_mainDir.'sysext/'))    {       // Is system:
03703                         $validatedPrefix = PATH_site.TYPO3_mainDir.'sysext/';
03704                         #$location = 'EXT:csh_'.$language.'/';  // For system extensions translations are found in "csh_*" extensions (language packs)
03705                 } elseif (t3lib_div::isFirstPartOfStr($fileRef,PATH_site.TYPO3_mainDir.'ext/')) {       // Is global:
03706                         $validatedPrefix = PATH_site.TYPO3_mainDir.'ext/';
03707                 } elseif (t3lib_div::isFirstPartOfStr($fileRef,PATH_site.'typo3conf/ext/'))     {       // Is local:
03708                         $validatedPrefix = PATH_site.'typo3conf/ext/';
03709                 } else {
03710                         $validatedPrefix = '';
03711                 }
03712 
03713                 if ($validatedPrefix)   {
03714 
03715                                 // Divide file reference into extension key, directory (if any) and base name:
03716                         list($file_extKey,$file_extPath) = explode('/',substr($fileRef,strlen($validatedPrefix)),2);
03717                         $temp = t3lib_div::revExplode('/',$file_extPath,2);
03718                         if (count($temp)==1)    array_unshift($temp,'');        // Add empty first-entry if not there.
03719                         list($file_extPath,$file_fileName) = $temp;
03720 
03721                                 // The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
03722                         return $location.
03723                                 $file_extKey.'/'.
03724                                 ($file_extPath?$file_extPath.'/':'').
03725                                 $language.'.'.$file_fileName;
03726                 } else return NULL;
03727         }
03728 
03729 
03746         function loadTCA($table)        {
03747                 global $TCA,$LANG_GENERAL_LABELS;
03748                 if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile'])     {
03749                         if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:'))    {
03750                                 include(PATH_t3lib.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
03751                         } elseif (t3lib_div::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file($TCA[$table]['ctrl']['dynamicConfigFile']))       {       // Absolute path...
03752                                 include($TCA[$table]['ctrl']['dynamicConfigFile']);
03753                         } else include(PATH_typo3conf.$TCA[$table]['ctrl']['dynamicConfigFile']);
03754                 }
03755         }
03756 
03766         function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')    {
03767                 if (!is_array ($dataStructArray)) return 'Data structure must be an array';
03768 
03769                 if (is_array($dataStructArray['sheets']))       {
03770                         $singleSheet = FALSE;
03771                         if (!isset($dataStructArray['sheets'][$sheet])) {
03772                                 $sheet='sDEF';
03773                         }
03774                         $dataStruct =  $dataStructArray['sheets'][$sheet];
03775 
03776                                 // If not an array, but still set, then regard it as a relative reference to a file:
03777                         if ($dataStruct && !is_array($dataStruct))      {
03778                                 $file = t3lib_div::getFileAbsFileName($dataStruct);
03779                                 if ($file && @is_file($file))   {
03780                                         $dataStruct = t3lib_div::xml2array(t3lib_div::getUrl($file));
03781                                 }
03782                         }
03783                 } else {
03784                         $singleSheet = TRUE;
03785                         $dataStruct = $dataStructArray;
03786                         if (isset($dataStruct['meta'])) unset($dataStruct['meta']);     // Meta data should not appear there.
03787                         $sheet = 'sDEF';        // Default sheet
03788                 }
03789                 return array($dataStruct,$sheet,$singleSheet);
03790         }
03791 
03799         function resolveAllSheetsInDS($dataStructArray) {
03800                 if (is_array($dataStructArray['sheets']))       {
03801                         $out=array('sheets'=>array());
03802                         foreach($dataStructArray['sheets'] as $sheetId => $sDat)        {
03803                                 list($ds,$aS) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheetId);
03804                                 if ($sheetId==$aS)      {
03805                                         $out['sheets'][$aS]=$ds;
03806                                 }
03807                         }
03808                 } else {
03809                         list($ds) = t3lib_div::resolveSheetDefInDS($dataStructArray);
03810                         $out = array('sheets' => array('sDEF' => $ds));
03811                 }
03812                 return $out;
03813         }
03814 
03828         function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)      {
03829                 global $TYPO3_CONF_VARS;
03830 
03831                         // Check persistent object and if found, call directly and exit.
03832                 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName]))        {
03833                         return call_user_func(
03834                                                 array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
03835                                                         $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
03836                                                 $params,
03837                                                 $ref
03838                                         );
03839                 }
03840 
03841                         // Check file-reference prefix; if found, require_once() the file (should be library of code)
03842                 if (strstr($funcName,':'))      {
03843                         list($file,$funcRef) = t3lib_div::revExplode(':',$funcName,2);
03844                         $requireFile = t3lib_div::getFileAbsFileName($file);
03845                         if ($requireFile) require_once($requireFile);
03846                 } else {
03847                         $funcRef = $funcName;
03848                 }
03849 
03850                         // Check for persistent object token, "&"
03851                 if (substr($funcRef,0,1)=='&')  {
03852                         $funcRef = substr($funcRef,1);
03853                         $storePersistentObject = TRUE;
03854                 } else {
03855                         $storePersistentObject = FALSE;
03856                 }
03857 
03858                         // Check prefix is valid:
03859                 if ($checkPrefix &&
03860                         !t3lib_div::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
03861                         !t3lib_div::isFirstPartOfStr(trim($funcRef),'tx_')
03862                         )       {
03863                         if (!$silent)   debug("Function/Class '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
03864                         return FALSE;
03865                 }
03866 
03867                         // Call function or method:
03868                 $parts = explode('->',$funcRef);
03869                 if (count($parts)==2)   {       // Class
03870 
03871                                 // Check if class/method exists:
03872                         if (class_exists($parts[0]))    {
03873 
03874                                         // Get/Create object of class:
03875                                 if ($storePersistentObject)     {       // Get reference to current instance of class:
03876                                         if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]]))    {
03877                                                 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = &t3lib_div::makeInstance($parts[0]);
03878                                         }
03879                                         $classObj = &$GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
03880                                 } else {        // Create new object:
03881                                         $classObj = &t3lib_div::makeInstance($parts[0]);
03882                                 }
03883 
03884                                 if (method_exists($classObj, $parts[1]))        {
03885 
03886                                                 // If persistent object should be created, set reference:
03887                                         if ($storePersistentObject)     {
03888                                                 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
03889                                                         'method' => $parts[1],
03890                                                         'obj' => &$classObj
03891                                                 );
03892                                         }
03893                                                 // Call method:
03894                                         $content = call_user_func(
03895                                                 array(&$classObj, $parts[1]),
03896                                                 $params,
03897                                                 $ref
03898                                         );
03899                                 } else {
03900                                         if (!$silent)   debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
03901                                 }
03902                         } else {
03903                                 if (!$silent)   debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
03904                         }
03905                 } else {        // Function
03906                         if (function_exists($funcRef))  {
03907                                 $content = call_user_func($funcRef, $params, $ref);
03908                         } else {
03909                                 if (!$silent)   debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
03910                         }
03911                 }
03912                 return $content;
03913         }
03914 
03926         function &getUserObj($classRef,$checkPrefix='user_',$silent=0)  {
03927                 global $TYPO3_CONF_VARS;
03928                         // Check persistent object and if found, call directly and exit.
03929                 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef]))     {
03930                         return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
03931                 } else {
03932 
03933                                 // Check file-reference prefix; if found, require_once() the file (should be library of code)
03934                         if (strstr($classRef,':'))      {
03935                                 list($file,$class) = t3lib_div::revExplode(':',$classRef,2);
03936                                 $requireFile = t3lib_div::getFileAbsFileName($file);
03937                                 if ($requireFile)       require_once($requireFile);
03938                         } else {
03939                                 $class = $classRef;
03940                         }
03941 
03942                                 // Check for persistent object token, "&"
03943                         if (substr($class,0,1)=='&')    {
03944                                 $class = substr($class,1);
03945                                 $storePersistentObject = TRUE;
03946                         } else {
03947                                 $storePersistentObject = FALSE;
03948                         }
03949 
03950                                 // Check prefix is valid:
03951                         if ($checkPrefix &&
03952                                 !t3lib_div::isFirstPartOfStr(trim($class),$checkPrefix) &&
03953                                 !t3lib_div::isFirstPartOfStr(trim($class),'tx_')
03954                                 )       {
03955                                 if (!$silent)   debug("Class '".$class."' was not prepended with '".$checkPrefix."'",1);
03956                                 return FALSE;
03957                         }
03958 
03959                                 // Check if class exists:
03960                         if (class_exists($class))       {
03961                                 $classObj = &t3lib_div::makeInstance($class);
03962 
03963                                         // If persistent object should be created, set reference:
03964                                 if ($storePersistentObject)     {
03965                                         $GLOBALS['T3_VAR']['getUserObj'][$classRef] = &$classObj;
03966                                 }
03967 
03968                                 return $classObj;
03969                         } else {
03970                                 if (!$silent)   debug("<strong>ERROR:</strong> No class named: ".$class,1);
03971                         }
03972                 }
03973         }
03974 
03984         function &makeInstance($className)      {
03985                 return class_exists('ux_'.$className) ? t3lib_div::makeInstance('ux_'.$className) : new $className;
03986         }
03987 
03996         function makeInstanceClassName($className)      {
03997                 return class_exists('ux_'.$className) ? t3lib_div::makeInstanceClassName('ux_'.$className) : $className;
03998         }
03999 
04010         function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())    {
04011                 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
04012 
04013                 $error = FALSE;
04014 
04015                 if (!is_array($excludeServiceKeys) ) {
04016                         $excludeServiceKeys = t3lib_div::trimExplode(',', $excludeServiceKeys, 1);
04017                 }
04018                 while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys))   {
04019 
04020                                 // Check persistent object and if found, call directly and exit.
04021                         if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]))   {
04022                                         // reset service and return object
04023                                 $T3_VAR['makeInstanceService'][$info['className']]->reset();
04024                                 return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
04025 
04026                                 // include file and create object
04027                         } else {
04028                                 $requireFile = t3lib_div::getFileAbsFileName($info['classFile']);
04029                                 if (@is_file($requireFile)) {
04030                                         require_once ($requireFile);
04031                                         $obj = t3lib_div::makeInstance($info['className']);
04032                                         if (is_object($obj)) {
04033                                                 if(!@is_callable(array($obj,'init')))   {
04034                                                                 // use silent logging??? I don't think so.
04035                                                         die ('Broken service:'.t3lib_div::view_array($info));
04036                                                 }
04037                                                 $obj->info = $info;
04038                                                 if ($obj->init()) { // service available?
04039 
04040                                                                 // create persistent object
04041                                                         $T3_VAR['makeInstanceService'][$info['className']] = &$obj;
04042 
04043                                                                 // needed to delete temp files
04044                                                         register_shutdown_function(array(&$obj, '__destruct'));
04045 
04046                                                         return $obj; // object is passed as reference by function definition
04047                                                 }
04048                                                 $error = $obj->getLastErrorArray();
04049                                                 unset($obj);
04050                                         }
04051                                 }
04052                         }
04053                                 // deactivate the service
04054                         t3lib_extMgm::deactivateService($info['serviceType'],$info['serviceKey']);
04055                 }
04056                 return $error;
04057         }
04058 
04074         function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='',$dontEncodeHeader=false)     {
04075                 if (!$charset)  {
04076                         $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'ISO-8859-1';
04077                 }
04078 
04079                 if (!$dontEncodeHeader) {
04080                                 // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
04081                         $newHeaders=array();
04082                         foreach (explode(chr(10),$headers) as $line)    {       // Split the header in lines and convert each line separately
04083                                 $parts = explode(': ',$line,2); // Field tags must not be encoded
04084                                 if (count($parts)==2)   {
04085                                         $parts[1] = t3lib_div::encodeHeader($parts[1],$enc,$charset);
04086                                         $newHeaders[] = implode(': ',$parts);
04087                                 } else {
04088                                         $newHeaders[] = $line;  // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
04089                                 }
04090                         }
04091                         $headers = implode(chr(10),$newHeaders);
04092                         unset($newHeaders);
04093 
04094                         $email = t3lib_div::encodeHeader($email,$enc,$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>")
04095                         $subject = t3lib_div::encodeHeader($subject,$enc,$charset);
04096                 }
04097 
04098                 switch ((string)$enc)   {
04099                         case 'base64':
04100                                 $headers=trim($headers).chr(10).
04101                                 'Mime-Version: 1.0'.chr(10).
04102                                 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
04103                                 'Content-Transfer-Encoding: base64';
04104 
04105                                 $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.
04106                         break;
04107                         case '8bit':
04108                                 $headers=trim($headers).chr(10).
04109                                 'Mime-Version: 1.0'.chr(10).
04110                                 'Content-Type: text/plain; charset='.$charset.chr(10).
04111                                 'Content-Transfer-Encoding: 8bit';
04112                         break;
04113                         case 'quoted-printable':
04114                         default:
04115                                 $headers=trim($headers).chr(10).
04116                                 'Mime-Version: 1.0'.chr(10).
04117                                 'Content-Type: text/plain; charset='.$charset.chr(10).
04118                                 'Content-Transfer-Encoding: quoted-printable';
04119 
04120                                 $message=t3lib_div::quoted_printable($message);
04121                         break;
04122                 }
04123 
04124                 $linebreak = chr(10);                   // Default line break for Unix systems.
04125                 if (TYPO3_OS=='WIN')    {
04126                         $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.
04127                 }
04128 
04129                 $headers=trim(implode($linebreak,t3lib_div::trimExplode(chr(10),$headers,1)));  // Make sure no empty lines are there.
04130 
04131                 mail($email,$subject,$message,$headers);
04132         }
04133 
04144         function quoted_printable($string,$maxlen=76)   {
04145                         // Make sure the string contains only Unix linebreaks
04146                 $string = str_replace(chr(13).chr(10), chr(10), $string);       // Replace Windows breaks (\r\n)
04147                 $string = str_replace(chr(13), chr(10), $string);               // Replace Mac breaks (\r)
04148 
04149                 $linebreak = chr(10);                   // Default line break for Unix systems.
04150                 if (TYPO3_OS=='WIN')    {
04151                         $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.
04152                 }
04153 
04154                 $newString = '';
04155                 $theLines = explode(chr(10),$string);   // Split lines
04156                 foreach ($theLines as $val)     {
04157                         $newVal = '';
04158                         $theValLen = strlen($val);
04159                         $len = 0;
04160                         for ($index=0; $index < $theValLen; $index++)   {       // Walk through each character of this line
04161                                 $char = substr($val,$index,1);
04162                                 $ordVal = ord($char);
04163                                 if ($len>($maxlen-4) || ($len>(($maxlen-10)-4)&&$ordVal==32))   {
04164                                         $newVal.='='.$linebreak;        // Add a line break
04165                                         $len=0;                 // Reset the length counter
04166                                 }
04167                                 if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
04168                                         $newVal.=$char;         // This character is ok, add it to the message
04169                                         $len++;
04170                                 } else {
04171                                         $newVal.=sprintf('=%02X',$ordVal);      // Special character, needs to be encoded
04172                                         $len+=3;
04173                                 }
04174                         }
04175                         $newVal = preg_replace('/'.chr(32).'$/','=20',$newVal);         // Replaces a possible SPACE-character at the end of a line
04176                         $newVal = preg_replace('/'.chr(9).'$/','=09',$newVal);          // Replaces a possible TAB-character at the end of a line
04177                         $newString.=$newVal.$linebreak;
04178                 }
04179                 return preg_replace('/'.$linebreak.'$/','',$newString);         // Remove last newline
04180         }
04181 
04191         function encodeHeader($line,$enc='',$charset='ISO-8859-1')      {
04192                         // Avoid problems if "###" is found in $line (would conflict with the placeholder which is used below)
04193                 if (strstr($line,'###'))        return $line;
04194 
04195                         // Check if any non-ASCII characters are found - otherwise encoding is not needed
04196                 if (!preg_match('/[^'.chr(32).'-'.chr(127).']/',$line)) return $line;
04197 
04198                         // Wrap email addresses in a special marker
04199                 $line = preg_replace('/([^ ]+@[^ ]+)/', '###$1###', $line);
04200 
04201                 $matches = preg_split('/(.?###.+###.?|\(|\))/', $line, -1, PREG_SPLIT_NO_EMPTY);
04202                 foreach ($matches as $part)     {
04203                         $oldPart = $part;
04204                         switch ((string)$enc)   {
04205                                 case 'base64':
04206                                         $part = '=?'.$charset.'?B?'.base64_encode($part).'?=';
04207                                 break;
04208                                 case 'quoted-printable':
04209                                 default:
04210                                         $qpValue = t3lib_div::quoted_printable($part,1000);
04211                                         if ($part!=$qpValue)    {
04212                                                 $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.
04213                                                 $part = '=?'.$charset.'?Q?'.$qpValue.'?=';
04214                                         }
04215                         }
04216                         $line = str_replace($oldPart, $part, $line);
04217                 }
04218                 $line = preg_replace('/###(.+?)###/', '$1', $line);     // Remove the wrappers
04219 
04220                 return $line;
04221         }
04222 
04234         function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')      {
04235                         // Substitute URLs with shorter links:
04236                 $urlSplit=explode('http://',$message);
04237                 reset($urlSplit);
04238                 while(list($c,$v)=each($urlSplit))      {
04239                         if ($c) {
04240                                 $newParts = preg_split('/\s|[<>"{}|\\\^`()\']/', $v, 2);
04241                                 $newURL='http://'.$newParts[0];
04242                                         switch((string)$urlmode)        {
04243                                                 case 'all':
04244                                                         $newURL=t3lib_div::makeRedirectUrl($newURL,0,$index_script_url);
04245                                                 break;
04246                                                 case '76':
04247                                                         $newURL=t3lib_div::makeRedirectUrl($newURL,76,$index_script_url);
04248                                                 break;
04249                                         }
04250                                 $urlSplit[$c]=$newURL.substr($v,strlen($newParts[0]));
04251                         }
04252                 }
04253 
04254                 $message=implode('',$urlSplit);
04255                 return $message;
04256         }
04257 
04268         function makeRedirectUrl($inUrl,$l=0,$index_script_url='')      {
04269                 if (strlen($inUrl)>$l)  {
04270                         $md5 = substr(md5($inUrl),0,20);
04271                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params'));
04272                         if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res))  {
04273                                 $insertFields = array(
04274                                         'md5hash' => $md5,
04275                                         'tstamp' => time(),
04276                                         'type' => 2,
04277                                         'params' => $inUrl
04278                                 );
04279 
04280                                 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
04281                         }
04282                         $inUrl=($index_script_url ? $index_script_url : t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php').
04283                                 '?RDCT='.$md5;
04284                 }
04285                 return $inUrl;
04286         }
04287 
04295         function freetypeDpiComp($font_size)    {
04296                 $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
04297                 if ($dpi!=72)   $font_size = $font_size/$dpi*72;
04298                 return $font_size;
04299         }
04300 
04307         function initSysLog()   {
04308                 global $TYPO3_CONF_VARS;
04309 
04310                         // for CLI logging name is <fqdn-hostname>:<TYPO3-path>
04311                 if (defined('TYPO3_cliMode') && TYPO3_cliMode)  {
04312                         $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = t3lib_div::getHostname($requestHost=FALSE).':'.PATH_site;
04313                 }
04314                         // for Web logging name is <protocol>://<request-hostame>/<site-path>
04315                 else {
04316                         $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = t3lib_div::getIndpEnv('TYPO3_SITE_URL');
04317                 }
04318 
04319                         // init custom logging
04320                 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
04321                         $params = array('initLog'=>TRUE);
04322                         $fakeThis = FALSE;
04323                         foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod)       {
04324                                 t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
04325                         }
04326                 }
04327 
04328                         // init TYPO3 logging
04329                 foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log)   {
04330                         list($type,$destination) = explode(',',$log,3);
04331 
04332                         if ($type == 'syslog')  {
04333                                 define_syslog_variables();
04334                                 if (TYPO3_OS == 'WIN')  {
04335                                         $facility = LOG_USER;
04336                                 } else {
04337                                         $facility = constant('LOG_'.strtoupper($destination));
04338                                 }
04339                                 openlog($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'], LOG_ODELAY, $facility);
04340                         }
04341                 }
04342 
04343                 $TYPO3_CONF_VARS['SYS']['systemLogLevel'] = t3lib_div::intInRange($TYPO3_CONF_VARS['SYS']['systemLogLevel'],0,4);
04344                 $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
04345         }
04346 
04357         function sysLog($msg, $extKey, $severity=0) {
04358                 global $TYPO3_CONF_VARS;
04359 
04360                 $severity = t3lib_div::intInRange($severity,0,4);
04361 
04362                         // is message worth logging?
04363                 if (intval($TYPO3_CONF_VARS['SYS']['systemLogLevel']) > $severity)      return;
04364 
04365                         // initialize logging
04366                 if (!$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'])      {
04367                         t3lib_div::initSysLog();
04368                 }
04369 
04370                         // do custom logging
04371                 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
04372                         $params = array('msg'=>$msg, 'extKey'=>$extKey);
04373                         if (function_exists('debug_backtrace')) {
04374                                 $params['backTrace'] = debug_backtrace();
04375                         }
04376                         $fakeThis = FALSE;
04377                         foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod)       {
04378                                 t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
04379                         }
04380                 }
04381 
04382                         // TYPO3 logging enabled?
04383                 if (!$TYPO3_CONF_VARS['SYS']['systemLog'])      return;
04384 
04385                         // use all configured logging options
04386                 foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log)   {
04387                         list($type,$destination,$level) = explode(',',$log,4);
04388 
04389                                 // is message worth logging for this log type?
04390                         if (intval($level) > $severity) continue;
04391 
04392                         $msgLine = ' - '.$extKey.': '.$msg;
04393 
04394                                 // write message to a file
04395                         if ($type == 'file')    {
04396                                 $file = fopen($destination, 'a');
04397                                 if ($file)     {
04398                                         flock($file, LOCK_EX);  // try locking, but ignore if not available (eg. on NFS and FAT)
04399                                         fwrite($file, date('d/m/Y i:H').$msgLine.chr(10));
04400                                         flock($file, LOCK_UN);    // release the lock
04401                                         fclose($file);
04402                                 }
04403                         }
04404                                 // send message per mail
04405                         elseif ($type == 'mail')        {
04406                                 list($to,$from) = explode('/',$destination);
04407                                 mail($to, 'Warning - error in TYPO3 installation',
04408                                         'Host: '.$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost']."\n".
04409                                         'Extension: '.$extKey."\n".
04410                                         'Severity: '.$severity."\n".
04411                                         "\n".$msg,
04412                                         ($from ? 'From: '.$from : '')
04413                                 );
04414                         }
04415                                 // use the PHP error log
04416                         elseif ($type == 'error_log')   {
04417                                 error_log($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'].$msgLine, 0);
04418                         }
04419                                 // use the system log
04420                         elseif ($type == 'syslog')      {
04421                                 $priority = array(LOG_INFO,LOG_NOTICE,LOG_WARNING,LOG_ERR,LOG_CRIT);
04422                                 syslog($priority[(int)$severity], $msgLine);
04423                         }
04424                 }
04425         }
04426 
04440         function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)     {
04441                 global $TYPO3_CONF_VARS;
04442 
04443                 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog']))    {
04444                         $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
04445                         $fakeThis = FALSE;
04446                         foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod)   {
04447                                 t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
04448                         }
04449                 }
04450         }
04451 
04461         function arrayToLogString($arr, $valueList=array(), $valueLength=20) {
04462                 $str = '';
04463                 if (is_array($arr))     {
04464                         if (!is_array($valueList))      {
04465                                 $valueList = t3lib_div::trimExplode(',', $valueList, 1);
04466                         }
04467                         $valListCnt = count($valueList);
04468                         foreach ($arr as $key => $value)        {
04469                                 if (!$valListCnt || in_array($key, $valueList)) {
04470                                         $str .= (string)$key.trim(': '.t3lib_div::fixed_lgd(str_replace("\n",'|',(string)$value), $valueLength)).'; ';
04471                                 }
04472                         }
04473                 }
04474                 return $str;
04475         }
04476 
04485         function imageMagickCommand($command, $parameters, $path='')    {
04486                 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
04487                 $isExt = (TYPO3_OS=='WIN' ? '.exe' : '');
04488                 $switchCompositeParameters=false;
04489 
04490                 if(!$path)      { $path = $gfxConf['im_path']; }
04491 
04492                 $im_version = strtolower($gfxConf['im_version_5']);
04493                 $combineScript = $gfxConf['im_combine_filename'] ? trim($gfxConf['im_combine_filename']) : 'combine';
04494 
04495                 if($command==='combine')        {       // This is only used internally, has no effect outside
04496                         $command = 'composite';
04497                 }
04498 
04499                         // Compile the path & command
04500                 if($im_version==='gm')  {
04501                         $switchCompositeParameters=true;
04502                         $path .= 'gm'.$isExt.' '.$command;
04503                 } else  {
04504                         if($im_version==='im6') { $switchCompositeParameters=true; }
04505                         $path .= (($command=='composite') ? $combineScript : $command).$isExt;
04506                 }
04507 
04508                 $cmdLine = $path.' '.$parameters;
04509 
04510                 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
04511                         $paramsArr = t3lib_div::unQuoteFilenames($parameters);
04512 
04513                         if(count($paramsArr)>5) {       // The mask image has been specified => swap the parameters
04514                                 $tmp = $paramsArr[count($paramsArr)-3];
04515                                 $paramsArr[count($paramsArr)-3] = $paramsArr[count($paramsArr)-4];
04516                                 $paramsArr[count($paramsArr)-4] = $tmp;
04517                         }
04518 
04519                         $cmdLine = $path.' '.implode(' ', $paramsArr);
04520                 }
04521 
04522                 return $cmdLine;
04523         }
04524 
04532         function unQuoteFilenames($parameters,$unQuote=FALSE)   {
04533                 $paramsArr = explode(' ', trim($parameters));
04534 
04535                 $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.
04536                 foreach($paramsArr as $k=>$v)   {
04537                         if($quoteActive > -1)   {
04538                                 $paramsArr[$quoteActive] .= ' '.$v;
04539                                 unset($paramsArr[$k]);
04540                                 if(ereg('"$', $v))      { $quoteActive = -1; }
04541 
04542                         } elseif(!trim($v))     {
04543                                 unset($paramsArr[$k]);  // Remove empty elements
04544 
04545                         } elseif(ereg('^"', $v))        {
04546                                 $quoteActive = $k;
04547                         }
04548                 }
04549 
04550                 if($unQuote) {
04551                         foreach($paramsArr as $key=>$val) {
04552                                 $paramsArr[$key]=preg_replace('/(^"|"$)/','',$val);
04553                         }
04554                 }
04555                 return $paramsArr;
04556         }
04557 
04558 
04566         function quoteJSvalue($value, $inScriptTags = false)    {
04567                 $value = addcslashes($value, '\''.chr(10).chr(13));
04568                 if (!$inScriptTags)     {
04569                         $value = htmlspecialchars($value);
04570                 }
04571                 return '\''.$value.'\'';
04572         }
04573 
04574 
04575 }
04576 
04577 ?>