Documentation TYPO3 par Ameos

class.t3lib_div.php

00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 1999-2005 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 ***************************************************************/
00211 class t3lib_div {
00212 
00213 
00214 
00215 
00216 
00217         /*************************
00218          *
00219          * GET/POST Variables
00220          *
00221          * Background:
00222          * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
00223          * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
00224          * But the clean solution is that quotes are never escaped and that is what the functions below offers.
00225          * Eventually TYPO3 should provide this in the global space as well.
00226          * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
00227          *
00228          *************************/
00229 
00241         function _GP($var)      {
00242                 if(empty($var)) return;
00243                 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00244                 if (isset($value))      {
00245                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00246                 }
00247                 return $value;
00248         }
00249 
00259         function _GET($var=NULL)        {
00260                 $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
00261                 if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
00262                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00263                 }
00264                 return $value;
00265         }
00266 
00276         function _POST($var=NULL)       {
00277                 $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
00278                 if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
00279                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00280                 }
00281                 return $value;
00282         }
00283 
00292         function _GETset($inputGet,$key='')     {
00293                         // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
00294                 if (strcmp($key,''))    {
00295                         if (is_array($inputGet))        { t3lib_div::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); }
00296                         $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
00297                 } elseif (is_array($inputGet)){
00298                         t3lib_div::addSlashesOnArray($inputGet);
00299                         $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
00300                 }
00301         }
00302 
00315         function GPvar($var,$strip=0)   {
00316                 if(empty($var)) return;
00317                 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00318                 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.
00319                 if ($strip && isset($value) && is_array($value)) { t3lib_div::stripSlashesOnArray($value); }
00320                 return $value;
00321         }
00322 
00332         function GParrayMerged($var)    {
00333                 $postA = is_array($_POST[$var]) ? $_POST[$var] : array();
00334                 $getA = is_array($_GET[$var]) ? $_GET[$var] : array();
00335                 $mergedA = t3lib_div::array_merge_recursive_overrule($getA,$postA);
00336                 t3lib_div::stripSlashesOnArray($mergedA);
00337                 return $mergedA;
00338         }
00339 
00340 
00341 
00342 
00343 
00344 
00345 
00346 
00347 
00348 
00349         /*************************
00350          *
00351          * IMAGE FUNCTIONS
00352          *
00353          *************************/
00354 
00355 
00376         function gif_compress($theFile, $type)  {
00377                 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
00378                 $returnCode='';
00379                 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif')      {       // GIF...
00380                         if (($type=='IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw'])       {       // IM
00381                                 $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
00382                                 exec($cmd);
00383 
00384                                 $returnCode='IM';
00385                         } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png'])       {       // GD
00386                                 $tempImage = imageCreateFromGif($theFile);
00387                                 imageGif($tempImage, $theFile);
00388                                 imageDestroy($tempImage);
00389                                 $returnCode='GD';
00390                         }
00391                 }
00392                 return $returnCode;
00393         }
00394 
00404         function png_to_gif_by_imagemagick($theFile)    {
00405                 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
00406                         && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
00407                         && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
00408                         && strtolower(substr($theFile,-4,4))=='.png'
00409                         && @is_file($theFile))  {       // IM
00410                                 $newFile = substr($theFile,0,-4).'.gif';
00411                                 $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $gfxConf['im_path_lzw']);
00412                                 exec($cmd);
00413                                 $theFile = $newFile;
00414                                         // 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!!
00415                 }
00416                 return $theFile;
00417         }
00418 
00429         function read_png_gif($theFile,$output_png=0)   {
00430                 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile))     {
00431                         $ext = strtolower(substr($theFile,-4,4));
00432                         if (
00433                                         ((string)$ext=='.png' && $output_png)   ||
00434                                         ((string)$ext=='.gif' && !$output_png)
00435                                 )       {
00436                                 return $theFile;
00437                         } else {
00438                                 $newFile = PATH_site.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?'.png':'.gif');
00439                                 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'].'convert "'.$theFile.'" "'.$newFile.'"');
00440                                 if (@is_file($newFile)) return $newFile;
00441                         }
00442                 }
00443         }
00444 
00445 
00446 
00447 
00448 
00449 
00450 
00451 
00452 
00453 
00454 
00455 
00456 
00457 
00458 
00459         /*************************
00460          *
00461          * STRING FUNCTIONS
00462          *
00463          *************************/
00464 
00478         function fixed_lgd($string,$origChars,$preStr='...')    {
00479                 $chars = abs($origChars);
00480                 if ($chars >= 4)        {
00481                         if(strlen($string)>$chars)  {
00482                                 return $origChars < 0 ?
00483                                         $preStr.trim(substr($string, -($chars-3))) :
00484                                         trim(substr($string, 0, $chars-3)).$preStr;
00485                         }
00486                 }
00487                 return $string;
00488         }
00489 
00503         function fixed_lgd_pre($string,$chars)  {
00504                 return strrev(t3lib_div::fixed_lgd(strrev($string),$chars));
00505         }
00506 
00517         function fixed_lgd_cs($string,$chars)   {
00518                 if (is_object($GLOBALS['LANG']))        {
00519                         return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet,$string,$chars,'...');
00520                 } else {
00521                         return t3lib_div::fixed_lgd($string, $chars);
00522                 }
00523         }
00524 
00534         function breakTextForEmail($str,$implChar="\n",$charWidth=76)   {
00535                 $lines = explode(chr(10),$str);
00536                 $outArr=array();
00537                 while(list(,$lStr)=each($lines))        {
00538                         $outArr = array_merge($outArr,t3lib_div::breakLinesForEmail($lStr,$implChar,$charWidth));
00539                 }
00540                 return implode(chr(10),$outArr);
00541         }
00542 
00553         function breakLinesForEmail($str,$implChar="\n",$charWidth=76)  {
00554                 $lines=array();
00555                 $l=$charWidth;
00556                 $p=0;
00557                 while(strlen($str)>$p)  {
00558                         $substr=substr($str,$p,$l);
00559                         if (strlen($substr)==$l)        {
00560                                 $count = count(explode(' ',trim(strrev($substr))));
00561                                 if ($count>1)   {       // OK...
00562                                         $parts = explode(' ',strrev($substr),2);
00563                                         $theLine = strrev($parts[1]);
00564                                 } else {
00565                                         $afterParts = explode(' ',substr($str,$l+$p),2);
00566                                         $theLine = $substr.$afterParts[0];
00567                                 }
00568                                 if (!strlen($theLine))  {break; }       // Error, because this would keep us in an endless loop.
00569                         } else {
00570                                 $theLine=$substr;
00571                         }
00572 
00573                         $lines[]=trim($theLine);
00574                         $p+=strlen($theLine);
00575                         if (!trim(substr($str,$p,$l)))  break;  // added...
00576                 }
00577                 return implode($implChar,$lines);
00578         }
00579 
00588         function cmpIP($baseIP, $list)  {
00589                 $IPpartsReq = explode('.',$baseIP);
00590                 if (count($IPpartsReq)==4)      {
00591                         $values = t3lib_div::trimExplode(',',$list,1);
00592 
00593                         foreach($values as $test)       {
00594                                 list($test,$mask) = explode('/',$test);
00595 
00596                                 if(intval($mask)) {
00597                                                 // "192.168.3.0/24"
00598                                         $lnet = ip2long($test);
00599                                         $lip = ip2long($baseIP);
00600                                         $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
00601                                         $firstpart = substr($binnet,0,$mask);
00602                                         $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
00603                                         $firstip = substr($binip,0,$mask);
00604                                         $yes = (strcmp($firstpart,$firstip)==0);
00605                                 } else {
00606                                                 // "192.168.*.*"
00607                                         $IPparts = explode('.',$test);
00608                                         $yes = 1;
00609                                         reset($IPparts);
00610                                         while(list($index,$val)=each($IPparts)) {
00611                                                 $val = trim($val);
00612                                                 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val))       {
00613                                                         $yes=0;
00614                                                 }
00615                                         }
00616                                 }
00617                                 if ($yes) return true;
00618                         }
00619                 }
00620                 return false;
00621         }
00622 
00630         function cmpFQDN($baseIP, $list)        {
00631                 if (count(explode('.',$baseIP))==4)     {
00632                         $resolvedHostName = explode('.', gethostbyaddr($baseIP));
00633                         $values = t3lib_div::trimExplode(',',$list,1);
00634 
00635                         foreach($values as $test)       {
00636                                 $hostNameParts = explode('.',$test);
00637                                 $yes = 1;
00638 
00639                                 foreach($hostNameParts as $index => $val)       {
00640                                         $val = trim($val);
00641                                         if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
00642                                                 $yes=0;
00643                                         }
00644                                 }
00645                                 if ($yes) return true;
00646                         }
00647                 }
00648                 return false;
00649         }
00650 
00660         function inList($list,$item)    {
00661                 return strstr(','.$list.',', ','.$item.',') ? true : false;
00662         }
00663 
00672         function rmFromList($element,$list)     {
00673                 $items = explode(',',$list);
00674                 while(list($k,$v)=each($items)) {
00675                         if ($v==$element)       {unset($items[$k]);}
00676                 }
00677                 return implode(',',$items);
00678         }
00679 
00688         function expandList($list)      {
00689                 $items = explode(',',$list);
00690                 $list = array();
00691                 while(list(,$item)=each($items))        {
00692                         $range = explode('-',$item);
00693                         if (isset($range[1]))   {
00694                                 $runAwayBrake = 1000;
00695                                 for ($n=$range[0]; $n<=$range[1]; $n++) {
00696                                         $list[] = $n;
00697 
00698                                         $runAwayBrake--;
00699                                         if ($runAwayBrake<=0)   break;
00700                                 }
00701                         } else {
00702                                 $list[] = $item;
00703                         }
00704                 }
00705 
00706                 return implode(',',$list);
00707         }
00708 
00719         function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)  {
00720                 // Returns $theInt as an integer in the integerspace from $min to $max
00721                 $theInt = intval($theInt);
00722                 if ($zeroValue && !$theInt)     {$theInt=$zeroValue;}   // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
00723                 if ($theInt<$min){$theInt=$min;}
00724                 if ($theInt>$max){$theInt=$max;}
00725                 return $theInt;
00726         }
00727 
00735         function intval_positive($theInt)       {
00736                 $theInt = intval($theInt);
00737                 if ($theInt<0){$theInt=0;}
00738                 return $theInt;
00739         }
00740 
00748         function int_from_ver($verNumberStr)    {
00749                 $verParts = explode('.',$verNumberStr);
00750                 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));
00751         }
00752 
00760         function md5int($str)   {
00761                 return hexdec(substr(md5($str),0,7));
00762         }
00763 
00773         function shortMD5($input, $len=10)      {
00774                 return substr(md5($input),0,$len);
00775         }
00776 
00786         function uniqueList($in_list, $secondParameter=NULL)    {
00787                 if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
00788                 if (isset($secondParameter))    die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
00789 
00790                 return implode(',',array_unique(t3lib_div::trimExplode(',',$in_list,1)));
00791         }
00792 
00800         function split_fileref($fileref)        {
00801                 if (    ereg('(.*/)(.*)$',$fileref,$reg)        )       {
00802                         $info['path'] = $reg[1];
00803                         $info['file'] = $reg[2];
00804                 } else {
00805                         $info['path'] = '';
00806                         $info['file'] = $fileref;
00807                 }
00808                 $reg='';
00809                 if (    ereg('(.*)\.([^\.]*$)',$info['file'],$reg)      )       {
00810                         $info['filebody'] = $reg[1];
00811                         $info['fileext'] = strtolower($reg[2]);
00812                         $info['realFileext'] = $reg[2];
00813                 } else {
00814                         $info['filebody'] = $info['file'];
00815                         $info['fileext'] = '';
00816                 }
00817                 reset($info);
00818                 return $info;
00819         }
00820 
00837         function dirname($path) {
00838                 $p=t3lib_div::revExplode('/',$path,2);
00839                 return count($p)==2?$p[0]:'';
00840         }
00841 
00853         function modifyHTMLColor($color,$R,$G,$B)       {
00854                 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
00855                 $nR = t3lib_div::intInRange(hexdec(substr($color,1,2))+$R,0,255);
00856                 $nG = t3lib_div::intInRange(hexdec(substr($color,3,2))+$G,0,255);
00857                 $nB = t3lib_div::intInRange(hexdec(substr($color,5,2))+$B,0,255);
00858                 return '#'.
00859                         substr('0'.dechex($nR),-2).
00860                         substr('0'.dechex($nG),-2).
00861                         substr('0'.dechex($nB),-2);
00862         }
00863 
00873         function modifyHTMLColorAll($color,$all)        {
00874                 return t3lib_div::modifyHTMLColor($color,$all,$all,$all);
00875         }
00876 
00884         function rm_endcomma($string)   {
00885                 return ereg_replace(',$','',$string);
00886         }
00887 
00897         function danish_strtoupper($string)     {
00898                 $value = strtoupper($string);
00899                 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
00900         }
00901 
00912         function convUmlauts($str)      {
00913                 $pat  = array ( '/ä/',  '/Ä/',  '/ö/',  '/Ö/',  '/ü/',  '/Ü/',  '/ß/',  '/å/',  '/Å/',  '/ø/',  '/Ø/',  '/æ/',  '/Æ/'   );
00914                 $repl = array ( 'ae',   'Ae',   'oe',   'Oe',   'ue',   'Ue',   'ss',   'aa',   'AA',   'oe',   'OE',   'ae',   'AE'    );
00915                 return preg_replace($pat,$repl,$str);
00916         }
00917 
00925         function testInt($var)  {
00926                 return !strcmp($var,intval($var));
00927         }
00928 
00937         function isFirstPartOfStr($str,$partStr)        {
00938                 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
00939                 $psLen = strlen($partStr);
00940                 if ($psLen)     {
00941                         return substr($str,0,$psLen)==(string)$partStr;
00942                 } else return false;
00943         }
00944 
00953         function formatSize($sizeInBytes,$labels='')    {
00954 
00955                         // Set labels:
00956                 if (strlen($labels) == 0) {
00957                     $labels = ' | K| M| G';
00958                 } else {
00959                     $labels = str_replace('"','',$labels);
00960                 }
00961                 $labelArr = explode('|',$labels);
00962 
00963                         // Find size:
00964                 if ($sizeInBytes>900)   {
00965                         if ($sizeInBytes>900000000)     {       // GB
00966                                 $val = $sizeInBytes/(1024*1024*1024);
00967                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
00968                         }
00969                         elseif ($sizeInBytes>900000)    {       // MB
00970                                 $val = $sizeInBytes/(1024*1024);
00971                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
00972                         } else {        // KB
00973                                 $val = $sizeInBytes/(1024);
00974                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
00975                         }
00976                 } else {        // Bytes
00977                         return $sizeInBytes.$labelArr[0];
00978                 }
00979         }
00980 
00988         function convertMicrotime($microtime)   {
00989                 $parts = explode(' ',$microtime);
00990                 return round(($parts[0]+$parts[1])*1000);
00991         }
00992 
01002         function splitCalc($string,$operators)  {
01003                 $res = Array();
01004                 $sign='+';
01005                 while($string)  {
01006                         $valueLen=strcspn($string,$operators);
01007                         $value=substr($string,0,$valueLen);
01008                         $res[] = Array($sign,trim($value));
01009                         $sign=substr($string,$valueLen,1);
01010                         $string=substr($string,$valueLen+1);
01011                 }
01012                 reset($res);
01013                 return $res;
01014         }
01015 
01024         function calcPriority($string)  {
01025                 $string=ereg_replace('[[:space:]]*','',$string);        // removing all whitespace
01026                 $string='+'.$string;    // Ensuring an operator for the first entrance
01027                 $qm='\*\/\+-^%';
01028                 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
01029                         // split the expression here:
01030                 preg_match_all('/'.$regex.'/',$string,$reg);
01031 
01032                 reset($reg[2]);
01033                 $number=0;
01034                 $Msign='+';
01035                 $err='';
01036                 $buffer=doubleval(current($reg[2]));
01037                 next($reg[2]);  // Advance pointer
01038                 while(list($k,$v)=each($reg[2]))        {
01039                         $v=doubleval($v);
01040                         $sign = $reg[1][$k];
01041                         if ($sign=='+' || $sign=='-')   {
01042                                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01043                                 $Msign = $sign;
01044                                 $buffer=$v;
01045                         } else {
01046                                 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
01047                                 if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';}
01048                                 if ($sign=='*') {$buffer*=$v;}
01049                                 if ($sign=='^') {$buffer=pow($buffer,$v);}
01050                         }
01051                 }
01052                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01053                 return $err ? 'ERROR: '.$err : $number;
01054         }
01055 
01064         function calcParenthesis($string)       {
01065                 $securC=100;
01066                 do {
01067                         $valueLenO=strcspn($string,'(');
01068                         $valueLenC=strcspn($string,')');
01069                         if ($valueLenC==strlen($string) || $valueLenC < $valueLenO)     {
01070                                 $value = t3lib_div::calcPriority(substr($string,0,$valueLenC));
01071                                 $string = $value.substr($string,$valueLenC+1);
01072                                 return $string;
01073                         } else {
01074                                 $string = substr($string,0,$valueLenO).t3lib_div::calcParenthesis(substr($string,$valueLenO+1));
01075                         }
01076                                 // Security:
01077                         $securC--;
01078                         if ($securC<=0) break;
01079                 } while($valueLenO<strlen($string));
01080                 return $string;
01081         }
01082 
01090         function htmlspecialchars_decode($value)        {
01091                 $value = str_replace('&gt;','>',$value);
01092                 $value = str_replace('&lt;','<',$value);
01093                 $value = str_replace('&quot;','"',$value);
01094                 $value = str_replace('&amp;','&',$value);
01095                 return $value;
01096         }
01097 
01105         function deHSCentities($str)    {
01106                 return ereg_replace('&amp;([#[:alnum:]]*;)','&\1',$str);
01107         }
01108 
01118         function slashJS($string,$extended=0,$char="'") {
01119                 if ($extended)  {$string = str_replace ("\\", "\\\\", $string);}
01120                 return str_replace ($char, "\\".$char, $string);
01121         }
01122 
01131         function rawUrlEncodeJS($str)   {
01132                 return str_replace('%20',' ',rawurlencode($str));
01133         }
01134 
01143         function rawUrlEncodeFP($str)   {
01144                 return str_replace('%2F','/',rawurlencode($str));
01145         }
01146 
01154         function validEmail($email)     {
01155                 $email = trim ($email);
01156                 if (strstr($email,' '))  return FALSE;
01157                 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE : FALSE;
01158         }
01159 
01169         function formatForTextarea($content)    {
01170                 return chr(10).htmlspecialchars($content);
01171         }
01172 
01173 
01174 
01175 
01176 
01177 
01178 
01179 
01180 
01181 
01182 
01183 
01184         /*************************
01185          *
01186          * ARRAY FUNCTIONS
01187          *
01188          *************************/
01189 
01200         function inArray($in_array,$item)       {
01201                 if (is_array($in_array))        {
01202                         while (list(,$val)=each($in_array))     {
01203                                 if (!is_array($val) && !strcmp($val,$item)) return true;
01204                         }
01205                 }
01206         }
01207 
01217         function intExplode($delim, $string)    {
01218                 $temp = explode($delim,$string);
01219                 while(list($key,$val)=each($temp))      {
01220                         $temp[$key]=intval($val);
01221                 }
01222                 reset($temp);
01223                 return $temp;
01224         }
01225 
01236         function revExplode($delim, $string, $count=0)  {
01237                 $temp = explode($delim,strrev($string),$count);
01238                 while(list($key,$val)=each($temp))      {
01239                         $temp[$key]=strrev($val);
01240                 }
01241                 $temp=array_reverse($temp);
01242                 reset($temp);
01243                 return $temp;
01244         }
01245 
01256         function trimExplode($delim, $string, $onlyNonEmptyValues=0)    {
01257                 $temp = explode($delim,$string);
01258                 $newtemp=array();
01259                 while(list($key,$val)=each($temp))      {
01260                         if (!$onlyNonEmptyValues || strcmp('',trim($val)))      {
01261                                 $newtemp[]=trim($val);
01262                         }
01263                 }
01264                 reset($newtemp);
01265                 return $newtemp;
01266         }
01267 
01278         function uniqueArray($valueArray)       {
01279                 return array_unique($valueArray);
01280         }
01281 
01290         function removeArrayEntryByValue($array,$cmpValue)      {
01291                 if (is_array($array))   {
01292                         reset($array);
01293                         while(list($k,$v)=each($array)) {
01294                                 if (is_array($v))       {
01295                                         $array[$k] = t3lib_div::removeArrayEntryByValue($v,$cmpValue);
01296                                 } else {
01297                                         if (!strcmp($v,$cmpValue))      {
01298                                                 unset($array[$k]);
01299                                         }
01300                                 }
01301                         }
01302                 }
01303                 reset($array);
01304                 return $array;
01305         }
01306 
01319         function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)      {
01320                 if (is_array($theArray))        {
01321                         foreach($theArray as $Akey => $AVal)    {
01322                                 $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
01323                                 if (is_array($AVal))    {
01324                                         $str = t3lib_div::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
01325                                 } else {
01326                                         if (!$skipBlank || strcmp($AVal,''))    {
01327                                                 $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
01328                                                         '='.rawurlencode($AVal);
01329                                         }
01330                                 }
01331                         }
01332                 }
01333                 return $str;
01334         }
01335 
01344         function explodeUrl2Array($string,$multidim=FALSE)      {
01345                 if ($multidim)  {
01346                         parse_str($string,$tempGetVars);
01347                         return $tempGetVars;
01348                 } else {
01349                         $output = array();
01350                         $p = explode('&',$string);
01351                         foreach($p as $v)       {
01352                                 if (strlen($v)) {
01353                                         list($pK,$pV) = explode('=',$v,2);
01354                                         $output[rawurldecode($pK)] = rawurldecode($pV);
01355                                 }
01356                         }
01357                         return $output;
01358                 }
01359         }
01360 
01371         function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)        {
01372                 $keys = t3lib_div::trimExplode(',',$varList,1);
01373                 $outArr=array();
01374                 foreach($keys as $v)    {
01375                         if (isset($getArray[$v]))       {
01376                                 $outArr[$v]=$getArray[$v];
01377                         } elseif ($GPvarAlt) {
01378                                 $outArr[$v]=t3lib_div::_GP($v);
01379                         }
01380                 }
01381                 return $outArr;
01382         }
01383 
01394         function addSlashesOnArray(&$theArray)  {
01395                 if (is_array($theArray))        {
01396                         reset($theArray);
01397                         while(list($Akey,$AVal)=each($theArray))        {
01398                                 if (is_array($AVal))    {
01399                                         t3lib_div::addSlashesOnArray($theArray[$Akey]);
01400                                 } else {
01401                                         $theArray[$Akey] = addslashes($AVal);
01402                                 }
01403                         }
01404                         reset($theArray);
01405                 }
01406         }
01407 
01418         function stripSlashesOnArray(&$theArray)        {
01419                 if (is_array($theArray))        {
01420                         reset($theArray);
01421                         while(list($Akey,$AVal)=each($theArray))        {
01422                                 if (is_array($AVal))    {
01423                                         t3lib_div::stripSlashesOnArray($theArray[$Akey]);
01424                                 } else {
01425                                         $theArray[$Akey] = stripslashes($AVal);
01426                                 }
01427                         }
01428                         reset($theArray);
01429                 }
01430         }
01431 
01440         function slashArray($arr,$cmd)  {
01441                 if ($cmd=='strip')      t3lib_div::stripSlashesOnArray($arr);
01442                 if ($cmd=='add')        t3lib_div::addSlashesOnArray($arr);
01443                 return $arr;
01444         }
01445 
01457         function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) {
01458                 reset($arr1);
01459                 while(list($key,$val) = each($arr1)) {
01460                         if(is_array($arr0[$key])) {
01461                                 if (is_array($arr1[$key]))      {
01462                                         $arr0[$key] = t3lib_div::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys);
01463                                 }
01464                         } else {
01465                                 if ($notAddKeys) {
01466                                         if (isset($arr0[$key])) {
01467                                                 if ($includeEmtpyValues OR $val) {
01468                                                         $arr0[$key] = $val;
01469                                                 }
01470                                         }
01471                                 } else {
01472                                         if ($includeEmtpyValues OR $val) {
01473                                                 $arr0[$key] = $val;
01474                                         }
01475                                 }
01476                         }
01477                 }
01478                 reset($arr0);
01479                 return $arr0;
01480         }
01481 
01490         function array_merge($arr1,$arr2)       {
01491                 return $arr2+$arr1;
01492         }
01493 
01503         function csvValues($row,$delim=',',$quote='"')  {
01504                 reset($row);
01505                 $out=array();
01506                 while(list(,$value)=each($row)) {
01507                         list($valPart) = explode(chr(10),$value);
01508                         $valPart = trim($valPart);
01509                         $out[]=str_replace($quote,$quote.$quote,$valPart);
01510                 }
01511                 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
01512                 return $str;
01513         }
01514 
01515 
01516 
01517 
01518 
01519 
01520 
01521 
01522 
01523 
01524 
01525 
01526 
01527 
01528 
01529 
01530         /*************************
01531          *
01532          * HTML/XML PROCESSING
01533          *
01534          *************************/
01535 
01545         function get_tag_attributes($tag)       {
01546                 $components = t3lib_div::split_tag_attributes($tag);
01547                 $name = '';      // attribute name is stored here
01548                 $valuemode = '';
01549                 if (is_array($components))      {
01550                         while (list($key,$val) = each ($components))    {
01551                                 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
01552                                         if ($valuemode) {
01553                                                 if ($name)      {
01554                                                         $attributes[$name] = $val;
01555                                                         $name = '';
01556                                                 }
01557                                         } else {
01558                                                 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val)))    {
01559                                                         $attributes[$key] = '';
01560                                                         $name = $key;
01561                                                 }
01562                                         }
01563                                         $valuemode = '';
01564                                 } else {
01565                                         $valuemode = 'on';
01566                                 }
01567                         }
01568                         if (is_array($attributes))      reset($attributes);
01569                         return $attributes;
01570                 }
01571         }
01572 
01582         function split_tag_attributes($tag)     {
01583                 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
01584                         // Removes any > in the end of the string
01585                 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
01586 
01587                 while (strcmp($tag_tmp,''))     {       // Compared with empty string instead , 030102
01588                         $firstChar=substr($tag_tmp,0,1);
01589                         if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
01590                                 $reg=explode($firstChar,$tag_tmp,3);
01591                                 $value[]=$reg[1];
01592                                 $tag_tmp=trim($reg[2]);
01593                         } elseif (!strcmp($firstChar,'=')) {
01594                                 $value[] = '=';
01595                                 $tag_tmp = trim(substr($tag_tmp,1));            // Removes = chars.
01596                         } else {
01597                                         // There are '' around the value. We look for the next ' ' or '>'
01598                                 $reg = split('[[:space:]=]',$tag_tmp,2);
01599                                 $value[] = trim($reg[0]);
01600                                 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
01601                         }
01602                 }
01603                 if (is_array($value))   reset($value);
01604                 return $value;
01605         }
01606 
01616         function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)   {
01617                 if (is_array($arr))     {
01618                         if ($xhtmlSafe) {
01619                                 $newArr=array();
01620                                 foreach($arr as $p => $v)       {
01621                                         if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
01622                                 }
01623                                 $arr = $newArr;
01624                         }
01625                         $list = array();
01626                         foreach($arr as $p => $v)       {
01627                                 if (strcmp($v,'') || $dontOmitBlankAttribs)     {$list[]=$p.'="'.$v.'"';}
01628                         }
01629                         return implode(' ',$list);
01630                 }
01631         }
01632 
01643         function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)       {
01644                 return t3lib_div::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
01645         }
01646 
01658         function wrapJS($string, $linebreak=TRUE) {
01659                 if(trim($string)) {
01660                                 // <script wrapped in nl?
01661                         $cr = $linebreak? "\n" : '';
01662 
01663                                 // remove nl from the beginning
01664                         $string = preg_replace ('/^\n+/', '', $string);
01665                                 // re-ident to one tab using the first line as reference
01666                         if(preg_match('/^(\t+)/',$string,$match)) {
01667                                 $string = str_replace($match[1],"\t", $string);
01668                         }
01669                         $string = $cr.'<script type="text/javascript">
01670 /*<![CDATA[*/
01671 '.$string.'
01672 /*]]>*/
01673 </script>'.$cr;
01674                 }
01675                 return trim($string);
01676         }
01677 
01678 
01688         function xml2tree($string,$depth=999) {
01689                 $parser = xml_parser_create();
01690                 $vals = array();
01691                 $index = array();
01692 
01693                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
01694                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
01695                 xml_parse_into_struct($parser, $string, $vals, $index);
01696 
01697                 if (xml_get_error_code($parser))        return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
01698                 xml_parser_free($parser);
01699 
01700                 $stack = array( array() );
01701                 $stacktop = 0;
01702                 $startPoint=0;
01703 
01704                 unset($tagi);
01705                 foreach($vals as $key => $val) {
01706                         $type = $val['type'];
01707 
01708                                 // open tag:
01709                         if ($type=='open' || $type=='complete') {
01710                                 $stack[$stacktop++] = $tagi;
01711 
01712                                 if ($depth==$stacktop)  {
01713                                         $startPoint=$key;
01714                                 }
01715 
01716                                 $tagi = array('tag' => $val['tag']);
01717 
01718                                 if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
01719                                 if(isset($val['value']))        $tagi['values'][] = $val['value'];
01720                         }
01721                                 // finish tag:
01722                         if ($type=='complete' || $type=='close')        {
01723                                 $oldtagi = $tagi;
01724                                 $tagi = $stack[--$stacktop];
01725                                 $oldtag = $oldtagi['tag'];
01726                                 unset($oldtagi['tag']);
01727 
01728                                 if ($depth==($stacktop+1))      {
01729                                         if ($key-$startPoint > 0)       {
01730                                                 $partArray = array_slice(
01731                                                         $vals,
01732                                                         $startPoint+1,
01733                                                         $key-$startPoint-1
01734                                                 );
01735                                                 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
01736                                                 $oldtagi['XMLvalue']=t3lib_div::xmlRecompileFromStructValArray($partArray);
01737                                         } else {
01738                                                 $oldtagi['XMLvalue']=$oldtagi['values'][0];
01739                                         }
01740                                 }
01741 
01742                                 $tagi['ch'][$oldtag][] = $oldtagi;
01743                                 unset($oldtagi);
01744                         }
01745                                 // cdata
01746                         if($type=='cdata') {
01747                                 $tagi['values'][] = $val['value'];
01748                         }
01749                 }
01750                 return $tagi['ch'];
01751         }
01752 
01774         function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array())    {
01775                         // 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
01776                 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
01777                                                 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
01778                                                 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
01779                                                 chr(30).chr(31);
01780                         // Set indenting mode:
01781                 $indentChar = $spaceInd ? ' ' : chr(9);
01782                 $indentN = $spaceInd>0 ? $spaceInd : 1;
01783 
01784                         // Init output variable:
01785                 $output='';
01786 
01787                         // Traverse the input array
01788                 if (is_array($array))   {
01789                         foreach($array as $k=>$v)       {
01790                                 $attr = '';
01791                                 $tagName = $k;
01792 
01793                                         // Construct the tag name.
01794                                 if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) {            // Use tag based on grand-parent + parent tag name
01795                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
01796                                         $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
01797                                 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) {            // Use tag based on parent tag name + current tag
01798                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
01799                                         $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
01800                                 } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) {                // Use tag based on parent tag name:
01801                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
01802                                         $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
01803                                 } elseif (!strcmp(intval($tagName),$tagName))   {       // If integer...;
01804                                         if ($options['useNindex']) {    // If numeric key, prefix "n"
01805                                                 $tagName = 'n'.$tagName;
01806                                         } else {        // Use special tag for num. keys:
01807                                                 $attr.=' index="'.$tagName.'"';
01808                                                 $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
01809                                         }
01810                                 } elseif($options['useIndexTagForAssoc']) {             // Use tag for all associative keys:
01811                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
01812                                         $tagName = $options['useIndexTagForAssoc'];
01813                                 }
01814 
01815                                         // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
01816                                 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
01817 
01818                                         // If the value is an array then we will call this function recursively:
01819                                 if (is_array($v))       {
01820 
01821                                                 // Sub elements:
01822                                         if ($options['alt_options'][$stackData['path'].'/'.$tagName])   {
01823                                                 $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
01824                                                 $clearStackPath = $subOptions['clearStackPath'];
01825                                         } else {
01826                                                 $subOptions = $options;
01827                                                 $clearStackPath = FALSE;
01828                                         }
01829 
01830                                         $content = chr(10).
01831                                                                 t3lib_div::array2xml(
01832                                                                         $v,
01833                                                                         $NSprefix,
01834                                                                         $level+1,
01835                                                                         '',
01836                                                                         $spaceInd,
01837                                                                         $subOptions,
01838                                                                         array(
01839                                                                                 'parentTagName' => $tagName,
01840                                                                                 'grandParentTagName' => $stackData['parentTagName'],
01841                                                                                 'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
01842                                                                         )
01843                                                                 ).
01844                                                                 str_pad('',($level+1)*$indentN,$indentChar);
01845                                         $attr.=' type="array"';
01846                                 } else {        // Just a value:
01847 
01848                                                 // Look for binary chars:
01849                                         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!
01850                                                         // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
01851                                                 $content = chr(10).chunk_split(base64_encode($v));
01852                                                 $attr.=' base64="1"';
01853                                         } else {
01854                                                         // Otherwise, just htmlspecialchar the stuff:
01855                                                 $content = htmlspecialchars($v);
01856                                                 $dType = gettype($v);
01857                                                 if ($dType!='string' && !$options['disableTypeAttrib']) { $attr.=' type="'.$dType.'"'; }
01858                                         }
01859                                 }
01860 
01861                                         // Add the element to the output string:
01862                                 $output.=str_pad('',($level+1)*$indentN,$indentChar).'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.chr(10);
01863                         }
01864                 }
01865 
01866                         // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
01867                 if (!$level)    {
01868                         $output =
01869                                 '<'.$docTag.'>'.chr(10).
01870                                 $output.
01871                                 '</'.$docTag.'>';
01872                 }
01873 
01874                 return $output;
01875         }
01876 
01888         function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
01889                 global $TYPO3_CONF_VARS;
01890 
01891                         // Create parser:
01892                 $parser = xml_parser_create();
01893                 $vals = array();
01894                 $index = array();
01895 
01896                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
01897                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
01898 
01899                         // PHP5 fix of charset awareness:
01900                         // 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.
01901                         // 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.
01902                         // 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.
01903                 if ((double)phpversion()>=5)    {
01904                         unset($ereg_result);
01905                         ereg('^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"',substr($string,0,200),$ereg_result);
01906                         $theCharset = $ereg_result[1] ? $ereg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
01907                         xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);  // us-ascii / utf-8 / iso-8859-1
01908                 }
01909 
01910                         // Parse content:
01911                 xml_parse_into_struct($parser, $string, $vals, $index);
01912 
01913                         // If error, return error message:
01914                 if (xml_get_error_code($parser))        {
01915                         return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
01916                 }
01917                 xml_parser_free($parser);
01918 
01919                         // Init vars:
01920                 $stack = array(array());
01921                 $stacktop = 0;
01922                 $current=array();
01923                 $tagName = '';
01924                 $documentTag = '';
01925 
01926                         // Traverse the parsed XML structure:
01927                 foreach($vals as $key => $val) {
01928 
01929                                 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
01930                         $tagName = $val['tag'];
01931                         if (!$documentTag)      $documentTag = $tagName;
01932 
01933                                 // Test for name space:
01934                         $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
01935 
01936                                 // Test for numeric tag, encoded on the form "nXXX":
01937                         $testNtag = substr($tagName,1); // Closing tag.
01938                         $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
01939 
01940                                 // Test for alternative index value:
01941                         if (strlen($val['attributes']['index']))        { $tagName = $val['attributes']['index']; }
01942 
01943                                 // Setting tag-values, manage stack:
01944                         switch($val['type'])    {
01945                                 case 'open':            // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
01946                                         $current[$tagName] = array();   // Setting blank place holder
01947                                         $stack[$stacktop++] = $current;
01948                                         $current = array();
01949                                 break;
01950                                 case 'close':   // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
01951                                         $oldCurrent = $current;
01952                                         $current = $stack[--$stacktop];
01953                                         end($current);  // Going to the end of array to get placeholder key, key($current), and fill in array next:
01954                                         $current[key($current)] = $oldCurrent;
01955                                         unset($oldCurrent);
01956                                 break;
01957                                 case 'complete':        // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
01958                                         if ($val['attributes']['base64'])       {
01959                                                 $current[$tagName] = base64_decode($val['value']);
01960                                         } else {
01961                                                 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
01962 
01963                                                         // Cast type:
01964                                                 switch((string)$val['attributes']['type'])      {
01965                                                         case 'integer':
01966                                                                 $current[$tagName] = (integer)$current[$tagName];
01967                                                         break;
01968                                                         case 'double':
01969                                                                 $current[$tagName] = (double)$current[$tagName];
01970                                                         break;
01971                                                         case 'boolean':
01972                                                                 $current[$tagName] = (bool)$current[$tagName];
01973                                                         break;
01974                                                         case 'array':
01975                                                                 $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...
01976                                                         break;
01977                                                 }
01978                                         }
01979                                 break;
01980                         }
01981                 }
01982 
01983                 if ($reportDocTag)      {
01984                         $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
01985                 }
01986 
01987                         // Finally return the content of the document tag.
01988                 return $current[$tagName];
01989         }
01990 
01998         function xmlRecompileFromStructValArray($vals)  {
01999                 $XMLcontent='';
02000 
02001                 foreach($vals as $val) {
02002                         $type = $val['type'];
02003 
02004                                 // open tag:
02005                         if ($type=='open' || $type=='complete') {
02006                                 $XMLcontent.='<'.$val['tag'];
02007                                 if(isset($val['attributes']))  {
02008                                         foreach($val['attributes'] as $k => $v) {
02009                                                 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
02010                                         }
02011                                 }
02012                                 if ($type=='complete')  {
02013                                         if(isset($val['value']))        {
02014                                                 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
02015                                         } else $XMLcontent.='/>';
02016                                 } else $XMLcontent.='>';
02017 
02018                                 if ($type=='open' && isset($val['value']))      {
02019                                         $XMLcontent.=htmlspecialchars($val['value']);
02020                                 }
02021                         }
02022                                 // finish tag:
02023                         if ($type=='close')     {
02024                                 $XMLcontent.='</'.$val['tag'].'>';
02025                         }
02026                                 // cdata
02027                         if($type=='cdata') {
02028                                 $XMLcontent.=htmlspecialchars($val['value']);
02029                         }
02030                 }
02031 
02032                 return $XMLcontent;
02033         }
02034 
02042         function xmlGetHeaderAttribs($xmlData)  {
02043                 $xmlHeader = substr(trim($xmlData),0,200);
02044                 $reg=array();
02045                 if (eregi('^<\?xml([^>]*)\?\>',$xmlHeader,$reg))        {
02046                         return t3lib_div::get_tag_attributes($reg[1]);
02047                 }
02048         }
02049 
02050 
02051 
02052 
02053 
02054 
02055 
02056 
02057 
02058 
02059 
02060         /*************************
02061          *
02062          * FILES FUNCTIONS
02063          *
02064          *************************/
02065 
02074         function getURL($url)   {
02075                 $content = '';
02076 
02077                         // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
02078                 if((substr($url,0,7)=='http://') && ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse']=='1'))       {
02079                         //external URL without error checking.
02080                         $ch = curl_init();
02081                         curl_setopt ($ch,CURLOPT_URL, $url);
02082                         curl_setopt ($ch,CURLOPT_HEADER, 0);
02083                         curl_setopt ($ch,CURLOPT_RETURNTRANSFER, 1);
02084 
02085                         if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
02086                                 curl_setopt ($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
02087 
02088                                 // I don't know if it will be needed
02089                                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
02090                                         curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'] );
02091                                 }
02092                                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
02093                                         curl_setopt ($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'] );
02094                                 }
02095                         }
02096                         $content=curl_exec ($ch);
02097                         curl_close ($ch);
02098                         return $content;
02099                 } elseif($fd = fopen($url,'rb'))    {
02100                         while (!feof($fd))      {
02101                                 $content.=fread($fd, 5000);
02102                         }
02103                         fclose($fd);
02104                         return $content;
02105                 }
02106         }
02107 
02116         function writeFile($file,$content)      {
02117                 if($fd = fopen($file,'wb'))     {
02118                         fwrite( $fd, $content);
02119                         fclose( $fd );
02120 
02121                         t3lib_div::fixPermissions($file);       // Change the permissions of the file
02122 
02123                         return true;
02124                 }
02125         }
02126 
02133         function fixPermissions($file)  {
02134                 if (@is_file($file) && TYPO3_OS!='WIN') {
02135                         @chmod($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));             // "@" is there because file is not necessarily OWNED by the user
02136                         if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
02137                                 @chgrp($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);                // "@" is there because file is not necessarily OWNED by the user
02138                         }
02139                 }
02140         }
02141 
02150         function writeFileToTypo3tempDir($filepath,$content)    {
02151 
02152                         // Parse filepath into directory and basename:
02153                 $fI = pathinfo($filepath);
02154                 $fI['dirname'].= '/';
02155 
02156                         // Check parts:
02157                 if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60)        {
02158                         if (defined('PATH_site'))       {
02159                                 $dirName = PATH_site.'typo3temp/';      // Setting main temporary directory name (standard)
02160                                 if (@is_dir($dirName))  {
02161                                         if (t3lib_div::isFirstPartOfStr($fI['dirname'],$dirName))       {
02162 
02163                                                         // Checking if the "subdir" is found:
02164                                                 $subdir = substr($fI['dirname'],strlen($dirName));
02165                                                 if ($subdir)    {
02166                                                         if (ereg('^[[:alnum:]_]+\/$',$subdir))  {
02167                                                                 $dirName.= $subdir;
02168                                                                 if (!@is_dir($dirName)) {
02169                                                                         t3lib_div::mkdir($dirName);
02170                                                                 }
02171                                                         } else return 'Subdir, "'.$subdir.'", was NOT on the form "[a-z]/"';
02172                                                 }
02173                                                         // Checking dir-name again (sub-dir might have been created):
02174                                                 if (@is_dir($dirName))  {
02175                                                         if ($filepath == $dirName.$fI['basename'])      {
02176                                                                 t3lib_div::writeFile($filepath, $content);
02177                                                                 if (!@is_file($filepath))       return 'File not written to disk! Write permission error in filesystem?';
02178                                                         } else return 'Calculated filelocation didn\'t match input $filepath!';
02179                                                 } else return '"'.$dirName.'" is not a directory!';
02180                                         } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
02181                                 } else return 'PATH_site + "typo3temp/" was not a directory!';
02182                         } else return 'PATH_site constant was NOT defined!';
02183                 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
02184         }
02185 
02193         function mkdir($theNewFolder)   {
02194                 $theNewFolder = ereg_replace('\/$','',$theNewFolder);
02195                 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
02196                         chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
02197 
02198                         if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
02199                                 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
02200                         }
02201                         return TRUE;
02202                 }
02203         }
02204 
02213         function get_dirs($path)        {
02214                 if ($path)      {
02215                         $d = @dir($path);
02216                         if (is_object($d))      {
02217                                 while($entry=$d->read()) {
02218                                         if (@is_dir($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
02219                                             $filearray[]=$entry;
02220                                         }
02221                                 }
02222                                 $d->close();
02223                         } else return 'error';
02224                         return $filearray;
02225                 }
02226         }
02227 
02238         function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')        {
02239 
02240                         // Initialize variabels:
02241                 $filearray = array();
02242                 $sortarray = array();
02243                 $path = ereg_replace('\/$','',$path);
02244 
02245                         // Find files+directories:
02246                 if (@is_dir($path))     {
02247                         $extensionList = strtolower($extensionList);
02248                         $d = dir($path);
02249                         if (is_object($d))      {
02250                                 while($entry=$d->read()) {
02251                                         if (@is_file($path.'/'.$entry)) {
02252                                                 $fI = pathinfo($entry);
02253                                                 $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)
02254                                                 if (!$extensionList || t3lib_div::inList($extensionList,strtolower($fI['extension'])))  {
02255                                                     $filearray[$key]=($prependPath?$path.'/':'').$entry;
02256                                                         if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
02257                                                                 elseif ($order) {$sortarray[$key]=$entry;}
02258                                                 }
02259                                         }
02260                                 }
02261                                 $d->close();
02262                         } else return 'error opening path: "'.$path.'"';
02263                 }
02264 
02265                         // Sort them:
02266                 if ($order) {
02267                         asort($sortarray);
02268                         reset($sortarray);
02269                         $newArr=array();
02270                         while(list($k,$v)=each($sortarray))     {
02271                                 $newArr[$k]=$filearray[$k];
02272                         }
02273                         $filearray=$newArr;
02274                 }
02275 
02276                         // Return result
02277                 reset($filearray);
02278                 return $filearray;
02279         }
02280 
02292         function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)       {
02293                 if ($regDirs)   $fileArr[] = $path;
02294                 $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path,$extList,1,1));
02295 
02296                 $dirs = t3lib_div::get_dirs($path);
02297                 if (is_array($dirs) && $recursivityLevels>0)    {
02298                         foreach ($dirs as $subdirs)     {
02299                                 if ((string)$subdirs!='')       {
02300                                         $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
02301                                 }
02302                         }
02303                 }
02304                 return $fileArr;
02305         }
02306 
02315         function removePrefixPathFromList($fileArr,$prefixToRemove)     {
02316                 foreach($fileArr as $k => $absFileRef)  {
02317                         if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove))    {
02318                                 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
02319                         } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
02320                 }
02321                 return $fileArr;
02322         }
02323 
02331         function fixWindowsFilePath($theFile)   {
02332                 return str_replace('//','/', str_replace('\\','/', $theFile));
02333         }
02334 
02343         function resolveBackPath($pathStr)      {
02344                 $parts = explode('/',$pathStr);
02345                 $output=array();
02346                 foreach($parts as $pV)  {
02347                         if ($pV=='..')  {
02348                                 if ($c) {
02349                                         array_pop($output);
02350                                         $c--;
02351                                 } else $output[]=$pV;
02352                         } else {
02353                                 $c++;
02354                                 $output[]=$pV;
02355                         }
02356                 }
02357                 return implode('/',$output);
02358         }
02359 
02370         function locationHeaderUrl($path)       {
02371                 $uI = parse_url($path);
02372                 if (substr($path,0,1)=='/')     { // relative to HOST
02373                         $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
02374                 } elseif (!$uI['scheme'])       { // No scheme either
02375                         $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
02376                 }
02377                 return $path;
02378         }
02379 
02380 
02381 
02382 
02383 
02384 
02385 
02386 
02387 
02388 
02389 
02390 
02391 
02392 
02393 
02394 
02395         /*************************
02396          *
02397          * DEBUG helper FUNCTIONS
02398          *
02399          *************************/
02400 
02410         function debug_ordvalue($string,$characters=100)        {
02411                 if(strlen($string) < $characters)       $characters = strlen($string);
02412                 for ($i=0; $i<$characters; $i++)        {
02413                         $valuestring.=' '.ord(substr($string,$i,1));
02414                 }
02415                 return trim($valuestring);
02416         }
02417 
02427         function view_array($array_in)  {
02428                 if (is_array($array_in))        {
02429                         $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
02430                         if (!count($array_in))  {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
02431                         while (list($key,$val)=each($array_in)) {
02432                                 $result.= '<tr><td><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
02433                                 if (is_array($array_in[$key]))  {
02434                                         $result.=t3lib_div::view_array($array_in[$key]);
02435                                 } else
02436                                         $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
02437                                 $result.= '</td></tr>';
02438                         }
02439                         $result.= '</table>';
02440                 } else  {
02441                         $result  = false;
02442                 }
02443                 return $result;
02444         }
02445 
02455         function print_array($array_in) {
02456                 echo t3lib_div::view_array($array_in);
02457         }
02458 
02470         function debug($var="",$brOrHeader=0)   {
02471                 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
02472                         echo '<table 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><td>';
02473                 } elseif ($brOrHeader<0) {
02474                         for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
02475                 }
02476 
02477                 if (is_array($var))     {
02478                         t3lib_div::print_array($var);
02479                 } elseif (is_object($var))      {
02480                         echo '<b>|Object:<pre>';
02481                         print_r($var);
02482                         echo '</pre>|</b>';
02483                 } elseif ((string)$var!='') {
02484                         echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
02485                 } else {
02486                         echo '<b>| debug |</b>';
02487                 }
02488 
02489                 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
02490                         echo '</td></tr></table>';
02491                 } elseif ($brOrHeader>0) {
02492                         for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
02493                 }
02494         }
02495 
02496 
02497 
02498 
02499 
02500 
02501 
02502 
02503 
02504 
02505 
02506 
02507 
02508 
02509 
02510 
02511 
02512 
02513 
02514 
02515 
02516 
02517 
02518 
02519 
02520 
02521 
02522 
02523 
02524 
02525 
02526 
02527         /*************************
02528          *
02529          * SYSTEM INFORMATION
02530          *
02531          *************************/
02532 
02539         function getThisUrl()   {
02540                 $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'));            // Url of this script
02541                 $dir=t3lib_div::dirname($p['path']).'/';        // Strip file
02542                 $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
02543                 return $url;
02544         }
02545 
02555         function linkThisScript($getParams=array())     {
02556                 $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
02557                 $params = t3lib_div::_GET();
02558 
02559                 foreach($getParams as $k => $v) {
02560                         if (strcmp($v,''))      {
02561                                 $params[$k]=$v;
02562                         } else unset($params[$k]);
02563                 }
02564 
02565                 $pString = t3lib_div::implodeArrayForUrl('',$params);
02566 
02567                 return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
02568         }
02569 
02579         function linkThisUrl($url,$getParams=array())   {
02580                 $parts = parse_url($url);
02581                 if ($parts['query'])    {
02582                         parse_str($parts['query'],$getP);
02583                 } else {
02584                         $getP = array();
02585                 }
02586 
02587                 $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
02588                 $uP = explode('?',$url);
02589 
02590                 $params = t3lib_div::implodeArrayForUrl('',$getP);
02591                 $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
02592 
02593                 return $outurl;
02594         }
02595 
02604         function getIndpEnv($getEnvName)        {
02605                 /*
02606                         Conventions:
02607                         output from parse_url():
02608                         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
02609                             [scheme] => 'http'
02610                             [user] => 'username'
02611                             [pass] => 'password'
02612                             [host] => '192.168.1.4'
02613                                 [port] => '8080'
02614                             [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
02615                             [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
02616                             [fragment] => 'link1'
02617 
02618                                 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
02619                                                                         [path_dir] = '/typo3/32/temp/phpcheck/'
02620                                                                         [path_info] = '/arg1/arg2/arg3/'
02621                                                                         [path] = [path_script/path_dir][path_info]
02622 
02623 
02624                         Keys supported:
02625 
02626                         URI______:
02627                                 REQUEST_URI             =       [path]?[query]          = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
02628                                 HTTP_HOST               =       [host][:[port]]         = 192.168.1.4:8080
02629                                 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')!
02630                                 PATH_INFO               =       [path_info]                     = /arg1/arg2/arg3/
02631                                 QUERY_STRING    =       [query]                         = arg1,arg2,arg3&p1=parameter1&p2[key]=value
02632                                 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
02633                                                                                 (Notice: NO username/password + NO fragment)
02634 
02635                         CLIENT____:
02636                                 REMOTE_ADDR             =       (client IP)
02637                                 REMOTE_HOST             =       (client host)
02638                                 HTTP_USER_AGENT =       (client user agent)
02639                                 HTTP_ACCEPT_LANGUAGE    = (client accept language)
02640 
02641                         SERVER____:
02642                                 SCRIPT_FILENAME =       Absolute filename of script             (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
02643 
02644                         Special extras:
02645                                 TYPO3_HOST_ONLY =               [host]                  = 192.168.1.4
02646                                 TYPO3_PORT              =               [port]                  = 8080 (blank if 80, taken from host value)
02647                                 TYPO3_REQUEST_HOST =    [scheme]://[host][:[port]]
02648                                 TYPO3_REQUEST_URL =             [scheme]://[host][:[port]][path]?[query]        (sheme will by default be 'http' until we can detect if it's https -
02649                                 TYPO3_REQUEST_SCRIPT =  [scheme]://[host][:[port]][path_script]
02650                                 TYPO3_REQUEST_DIR =             [scheme]://[host][:[port]][path_dir]
02651                                 TYPO3_SITE_URL =                [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
02652                                 TYPO3_SITE_SCRIPT =     [script / Speaking URL] of the TYPO3 website
02653                                 TYPO3_DOCUMENT_ROOT     =       Absolute path of root of documents:     TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
02654 
02655                         Notice: [fragment] is apparently NEVER available to the script!
02656 
02657 
02658                         Testing suggestions:
02659                         - Output all the values.
02660                         - 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
02661                         - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
02662 
02663                 */
02664 
02665 #               if ($getEnvName=='HTTP_REFERER')        return '';
02666                 switch((string)$getEnvName)     {
02667                         case 'SCRIPT_NAME':
02668                                 return (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']);
02669                         break;
02670                         case 'SCRIPT_FILENAME':
02671                                 return 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'])));
02672                         break;
02673                         case 'REQUEST_URI':
02674                                         // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
02675                                 if (!$_SERVER['REQUEST_URI'])   {       // This is for ISS/CGI which does not have the REQUEST_URI available.
02676                                         return '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
02677                                                 ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
02678                                 } else return $_SERVER['REQUEST_URI'];
02679                         break;
02680                         case 'PATH_INFO':
02681                                         // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
02682                                         // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
02683                                         // 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)
02684 //                              if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1)  {
02685                                 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi')        {
02686                                         return $_SERVER['PATH_INFO'];
02687                                 } else return '';
02688                         break;
02689                                 // These are let through without modification
02690                         case 'REMOTE_ADDR':
02691                         case 'REMOTE_HOST':
02692                         case 'HTTP_REFERER':
02693                         case 'HTTP_HOST':
02694                         case 'HTTP_USER_AGENT':
02695                         case 'HTTP_ACCEPT_LANGUAGE':
02696                         case 'QUERY_STRING':
02697                                 return $_SERVER[$getEnvName];
02698                         break;
02699                         case 'TYPO3_DOCUMENT_ROOT':
02700                                 // 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.
02701                                 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
02702                                 $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
02703                                 $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
02704                                 $SFN_A = explode('/',strrev($SFN));
02705                                 $acc = array();
02706                                 while(list($kk,$vv)=each($SN_A))        {
02707                                         if (!strcmp($SFN_A[$kk],$vv))   {
02708                                                 $acc[] = $vv;
02709                                         } else break;
02710                                 }
02711                                 $commonEnd=strrev(implode('/',$acc));
02712                                 if (strcmp($commonEnd,''))      { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
02713                                 return $DR;
02714                         break;
02715                         case 'TYPO3_HOST_ONLY':
02716                                 $p = explode(':',$_SERVER['HTTP_HOST']);
02717                                 return $p[0];
02718                         break;
02719                         case 'TYPO3_PORT':
02720                                 $p = explode(':',$_SERVER['HTTP_HOST']);
02721                                 return $p[1];
02722                         break;
02723                         case 'TYPO3_REQUEST_HOST':
02724                                 return (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
02725                                         $_SERVER['HTTP_HOST'];
02726                         break;
02727                         case 'TYPO3_REQUEST_URL':
02728                                 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
02729                         break;
02730                         case 'TYPO3_REQUEST_SCRIPT':
02731                                 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
02732                         break;
02733                         case 'TYPO3_REQUEST_DIR':
02734                                 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
02735                         break;
02736                         case 'TYPO3_SITE_URL':
02737                                 if (defined('PATH_thisScript') && defined('PATH_site')) {
02738                                         $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
02739                                         $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
02740                                         $siteUrl = substr($url,0,-strlen($lPath));
02741                                         if (substr($siteUrl,-1)!='/')   $siteUrl.='/';
02742                                         return $siteUrl;
02743                                 } else return '';
02744                         break;
02745                         case 'TYPO3_SITE_SCRIPT':
02746                                 return substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
02747                         break;
02748                         case 'TYPO3_SSL':
02749                                 return $_SERVER['SSL_SESSION_ID'] || !strcmp($_SERVER['HTTPS'],'on') ? TRUE : FALSE;
02750                         break;
02751                         case '_ARRAY':
02752                                 $out = array();
02753                                         // Here, list ALL possible keys to this function for debug display.
02754                                 $envTestVars = t3lib_div::trimExplode(',','
02755                                         HTTP_HOST,
02756                                         TYPO3_HOST_ONLY,
02757                                         TYPO3_PORT,
02758                                         PATH_INFO,
02759                                         QUERY_STRING,
02760                                         REQUEST_URI,
02761                                         HTTP_REFERER,
02762                                         TYPO3_REQUEST_HOST,
02763                                         TYPO3_REQUEST_URL,
02764                                         TYPO3_REQUEST_SCRIPT,
02765                                         TYPO3_REQUEST_DIR,
02766                                         TYPO3_SITE_URL,
02767                                         TYPO3_SITE_SCRIPT,
02768                                         TYPO3_SSL,
02769                                         SCRIPT_NAME,
02770                                         TYPO3_DOCUMENT_ROOT,
02771                                         SCRIPT_FILENAME,
02772                                         REMOTE_ADDR,
02773                                         REMOTE_HOST,
02774                                         HTTP_USER_AGENT,
02775                                         HTTP_ACCEPT_LANGUAGE',1);
02776                                 reset($envTestVars);
02777                                 while(list(,$v)=each($envTestVars))     {
02778                                         $out[$v]=t3lib_div::getIndpEnv($v);
02779                                 }
02780                                 reset($out);
02781                                 return $out;
02782                         break;
02783                 }
02784         }
02785 
02793         function milliseconds() {
02794                 $p=explode(' ',microtime());
02795                 return round(($p[0]+$p[1])*1000);
02796         }
02797 
02805         function clientInfo($useragent='')      {
02806                 if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
02807 
02808                 $bInfo=array();
02809                         // Which browser?
02810                 if (strstr($useragent,'Konqueror'))     {
02811                         $bInfo['BROWSER']= 'konqu';
02812                 } elseif (strstr($useragent,'Opera'))   {
02813                         $bInfo['BROWSER']= 'opera';
02814                 } elseif (strstr($useragent,'MSIE 4') || strstr($useragent,'MSIE 5') || strstr($useragent,'MSIE 6'))    {
02815                         $bInfo['BROWSER']= 'msie';
02816                 } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5'))     {
02817                         $bInfo['BROWSER']='net';
02818                 }
02819                 if ($bInfo['BROWSER'])  {
02820                                 // Browser version
02821                         switch($bInfo['BROWSER'])       {
02822                                 case 'net':
02823                                         $bInfo['VERSION']= doubleval(substr($useragent,8));
02824                                         if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
02825                                         if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
02826                                 break;
02827                                 case 'msie':
02828                                         $tmp = strstr($useragent,'MSIE');
02829                                         $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
02830                                 break;
02831                                 case 'opera':
02832                                         $tmp = strstr($useragent,'Opera');
02833                                         $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
02834                                 break;
02835                                 case 'konqu':
02836                                         $tmp = strstr($useragent,'Konqueror/');
02837                                         $bInfo['VERSION'] = doubleval(substr($tmp,10));
02838                                 break;
02839                         }
02840                                 // Client system
02841                         if (strstr($useragent,'Win'))   {
02842                                 $bInfo['SYSTEM'] = 'win';
02843                         } elseif (strstr($useragent,'Mac'))     {
02844                                 $bInfo['SYSTEM'] = 'mac';
02845                         } elseif (strstr($useragent,'Linux') || strstr($useragent,'X11') || strstr($useragent,'SGI') || strstr($useragent,' SunOS ') || strstr($useragent,' HP-UX '))   {
02846                                 $bInfo['SYSTEM'] = 'unix';
02847                         }
02848                 }
02849                         // Is true if the browser supports css to format forms, especially the width
02850                 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
02851 
02852                 return $bInfo;
02853         }
02854 
02855 
02856 
02857 
02858 
02859 
02860 
02861 
02862 
02863 
02864 
02865 
02866 
02867 
02868 
02869 
02870 
02871 
02872 
02873 
02874 
02875 
02876 
02877         /*************************
02878          *
02879          * TYPO3 SPECIFIC FUNCTIONS
02880          *
02881          *************************/
02882 
02892         function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)    {
02893                 if (!strcmp($filename,''))              return '';
02894 
02895                 if ($relToTYPO3_mainDir)        {
02896                         if (!defined('PATH_typo3'))     return '';
02897                         $relPathPrefix = PATH_typo3;
02898                 } else {
02899                         $relPathPrefix = PATH_site;
02900                 }
02901                 if (substr($filename,0,4)=='EXT:')      {       // extension
02902                         list($extKey,$local) = explode('/',substr($filename,4),2);
02903                         $filename='';
02904                         if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
02905                                 $filename = t3lib_extMgm::extPath($extKey).$local;
02906                         }
02907                 } elseif (!t3lib_div::isAbsPath($filename))     {       // relative. Prepended with $relPathPrefix
02908                         $filename=$relPathPrefix.$filename;
02909                 } elseif ($onlyRelative && !t3lib_div::isFirstPartOfStr($filename,$relPathPrefix)) {    // absolute, but set to blank if not allowed
02910                         $filename='';
02911                 }
02912                 if (strcmp($filename,'') && t3lib_div::validPathStr($filename)) {       // checks backpath.
02913                         return $filename;
02914                 }
02915         }
02916 
02928         function validPathStr($theFile) {
02929                 if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
02930         }
02931 
02939         function isAbsPath($path)       {
02940                 return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' :  substr($path,0,1)=='/';
02941         }
02942 
02950         function isAllowedAbsPath($path)        {
02951                 if (t3lib_div::isAbsPath($path) &&
02952                         t3lib_div::validPathStr($path) &&
02953                                 (       t3lib_div::isFirstPartOfStr($path,PATH_site)
02954                                         ||
02955                                         ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
02956                                 )
02957                         )       return true;
02958         }
02959 
02967         function verifyFilenameAgainstDenyPattern($filename)    {
02968                 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],''))    {
02969                         $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
02970                         if ($result)    return false;   // so if a matching filename is found, return false;
02971                 }
02972                 return true;
02973         }
02974 
02985         function upload_copy_move($source,$destination) {
02986                 if (is_uploaded_file($source))  {
02987                         $uploaded = TRUE;
02988                         // 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:
02989                         $uploadedResult = move_uploaded_file($source, $destination);
02990                 } else {
02991                         $uploaded = FALSE;
02992                         @copy($source,$destination);
02993                 }
02994 
02995                 t3lib_div::fixPermissions($destination);        // Change the permissions of the file
02996 
02997                         // 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
02998                 return $uploaded ? $uploadedResult : FALSE;
02999         }
03000 
03011         function upload_to_tempfile($uploadedFileName)  {
03012                 if (is_uploaded_file($uploadedFileName))        {
03013                         $tempFile = t3lib_div::tempnam('upload_temp_');
03014                         move_uploaded_file($uploadedFileName, $tempFile);
03015                         return @is_file($tempFile) ? $tempFile : '';
03016                 }
03017         }
03018 
03029         function unlink_tempfile($uploadedTempFileName) {
03030                 if ($uploadedTempFileName && t3lib_div::validPathStr($uploadedTempFileName) && t3lib_div::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName))    {
03031                         if (unlink($uploadedTempFileName))      return TRUE;
03032                 }
03033         }
03034 
03045         function tempnam($filePrefix)   {
03046                 return tempnam(PATH_site.'typo3temp/',$filePrefix);
03047         }
03048 
03058         function stdAuthCode($uid_or_record,$fields='') {
03059                 if (is_array($uid_or_record))   {
03060                         $recCopy_temp=array();
03061                         if ($fields)    {
03062                                 $fieldArr = t3lib_div::trimExplode(',',$fields,1);
03063                                 reset($fieldArr);
03064                                 while(list($k,$v)=each($fieldArr))      {
03065                                         $recCopy_temp[$k]=$recCopy[$v];
03066                                 }
03067                         } else {
03068                                 $recCopy_temp=$recCopy;
03069                         }
03070                         $preKey = implode('|',$recCopy_temp);
03071                 } else {
03072                         $preKey = $uid_or_record;
03073                 }
03074 
03075                 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
03076                 $authCode = substr(md5($authCode),0,8);
03077                 return $authCode;
03078         }
03079 
03088         function cHashParams($addQueryParams) {
03089                 $params = explode('&',substr($addQueryParams,1));       // Splitting parameters up
03090 
03091                         // Make array:
03092                 $pA = array();
03093                 foreach($params as $theP)       {
03094                         $pKV = explode('=', $theP);     // Splitting single param by '=' sign
03095                         if (!t3lib_div::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0]))        {
03096                                 $pA[$pKV[0]] = (string)rawurldecode($pKV[1]);
03097                         }
03098                 }
03099                 $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
03100                 ksort($pA);
03101 
03102                 return $pA;
03103         }
03104 
03111         function hideIfNotTranslated($l18n_cfg_fieldValue)      {
03112                 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault'])     {
03113                         return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
03114                 } else {
03115                         return $l18n_cfg_fieldValue&2 ? TRUE : FALSE;
03116                 }
03117         }
03118 
03126         function readLLfile($fileRef,$langKey)  {
03127                 $file = t3lib_div::getFileAbsFileName($fileRef);
03128                 if ($file)      {
03129                         $baseFile = ereg_replace('\.(php|xml)$', '', $file);
03130 
03131                         if (@is_file($baseFile.'.xml')) {
03132                                 $LOCAL_LANG = t3lib_div::readLLXMLfile($baseFile.'.xml', $langKey);
03133                         } elseif (@is_file($baseFile.'.php'))   {
03134                                 include($baseFile.'.php');
03135                         } else die('Filereference, "'.$file.'", not found!');
03136                 }
03137 
03138                 return is_array($LOCAL_LANG)?$LOCAL_LANG:array();
03139         }
03140 
03149         function readLLXMLfile($fileRef,$langKey)       {
03150 
03151                 if (is_object($GLOBALS['LANG']))        {
03152                         $csConvObj = &$GLOBALS['LANG']->csConvObj;
03153                 } elseif (is_object($GLOBALS['TSFE']))  {
03154                         $csConvObj = &$GLOBALS['TSFE']->csConvObj;
03155                 } else $csConvObj = NULL;
03156 
03157                 if (@is_file($fileRef) && $langKey && is_object($csConvObj))    {
03158 
03159                                 // Set charset:
03160                         $origCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
03161 
03162                                 // Cache file name:
03163                         $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef));
03164                         $cacheFileName = PATH_site.'typo3temp/llxml/'.
03165                                                         #str_replace('_','',ereg_replace('^.*\/','',dirname($fileRef))).
03166                                                         #'_'.basename($fileRef).
03167                                                         substr(basename($fileRef),10,15).
03168                                                         '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
03169 
03170                                 // Check if cache file exists...
03171                         if (!@is_file($cacheFileName))  {       // ... if it doesn't, create content and write it:
03172 
03173                                         // Read XML, parse it.
03174                                 $xmlString = t3lib_div::getUrl($fileRef);
03175                                 $xmlContent = t3lib_div::xml2array($xmlString);
03176 
03177                                         // Set default LOCAL_LANG array content:
03178                                 $LOCAL_LANG = array();
03179                                 $LOCAL_LANG['default'] = $xmlContent['data']['default'];
03180 
03181                                         // Specific language, convert from utf-8 to backend language charset:
03182                                         // 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.
03183                                 if ($langKey!='default')        {
03184                                         $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
03185 
03186                                                 // Checking if charset should be converted.
03187                                         if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8')   {
03188                                                 foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue)      {
03189                                                         $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
03190                                                 }
03191                                         }
03192                                 }
03193 
03194                                         // Cache the content now:
03195                                 $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>$LOCAL_LANG);
03196                                 $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
03197                                 if ($res)       die('ERROR: '.$res);
03198                         } else {
03199                                         // Get content from cache:
03200                                 $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
03201                                 $LOCAL_LANG = $serContent['LOCAL_LANG'];
03202                         }
03203 
03204                                 // Checking for EXTERNAL file for non-default language:
03205                         if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey]))   {
03206 
03207                                         // Look for localized file:
03208                                 $localized_file = t3lib_div::getFileAbsFileName($LOCAL_LANG[$langKey]);
03209                                 if ($localized_file && @is_file($localized_file))       {
03210 
03211                                                 // Cache file name:
03212                                         $hashSource = substr($localized_file,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($localized_file));
03213                                         $cacheFileName = PATH_site.'typo3temp/llxml/ext_'.
03214                                                                         substr(basename($localized_file),10,15).
03215                                                                         '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
03216 
03217                                                 // Check if cache file exists...
03218                                         if (!@is_file($cacheFileName))  {       // ... if it doesn't, create content and write it:
03219 
03220                                                         // Read and parse XML content:
03221                                                 $local_xmlString = t3lib_div::getUrl($localized_file);
03222                                                 $local_xmlContent = t3lib_div::xml2array($local_xmlString);
03223                                                 $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
03224 
03225                                                         // Checking if charset should be converted.
03226                                                 if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8')   {
03227                                                         foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue)      {
03228                                                                 $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
03229                                                         }
03230                                                 }
03231 
03232                                                         // Cache the content now:
03233                                                 $serContent = array('extlang'=>$langKey, 'origFile'=>$LOCAL_LANG[$langKey], 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
03234                                                 $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
03235                                                 if ($res)       die('ERROR: '.$res);
03236                                         } else {
03237                                                         // Get content from cache:
03238                                                 $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
03239                                                 $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
03240                                         }
03241                                 } else {
03242                                         $LOCAL_LANG[$langKey] = array();
03243                                 }
03244                         }
03245 
03246                         return $LOCAL_LANG;
03247                 }
03248         }
03249 
03262         function loadTCA($table)        {
03263                 global $TCA,$LANG_GENERAL_LABELS;
03264                 if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile'])     {
03265                         if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:'))    {
03266                                 include(PATH_t3lib.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
03267                         } elseif (t3lib_div::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file($TCA[$table]['ctrl']['dynamicConfigFile']))       {       // Absolute path...
03268                                 include($TCA[$table]['ctrl']['dynamicConfigFile']);
03269                         } else include(PATH_typo3conf.$TCA[$table]['ctrl']['dynamicConfigFile']);
03270                 }
03271         }
03272 
03282         function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')    {
03283                 if (is_array($dataStructArray['sheets']))       {
03284                         $singleSheet = FALSE;
03285                         if (!isset($dataStructArray['sheets'][$sheet])) {
03286                                 $sheet='sDEF';
03287                         }
03288                         $dataStruct =  $dataStructArray['sheets'][$sheet];
03289 
03290                                 // If not an array, but still set, then regard it as a relative reference to a file:
03291                         if ($dataStruct && !is_array($dataStruct))      {
03292                                 $file = t3lib_div::getFileAbsFileName($dataStruct);
03293                                 if ($file && @is_file($file))   {
03294                                         $dataStruct = t3lib_div::xml2array(t3lib_div::getUrl($file));
03295                                 }
03296                         }
03297                 } else {
03298                         $singleSheet = TRUE;
03299                         $dataStruct = $dataStructArray;
03300                         unset($dataStruct['meta']);     // Meta data should not appear there.
03301                         $sheet = 'sDEF';        // Default sheet
03302                 }
03303                 return array($dataStruct,$sheet,$singleSheet);
03304         }
03305 
03313         function resolveAllSheetsInDS($dataStructArray) {
03314                 if (is_array($dataStructArray['sheets']))       {
03315                         $out=array('sheets'=>array());
03316                         foreach($dataStructArray['sheets'] as $sheetId => $sDat)        {
03317                                 list($ds,$aS) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheetId);
03318                                 if ($sheetId==$aS)      {
03319                                         $out['sheets'][$aS]=$ds;
03320                                 }
03321                         }
03322                 } else {
03323                         list($ds) = t3lib_div::resolveSheetDefInDS($dataStructArray);
03324                         $out = array('sheets' => array('sDEF' => $ds));
03325                 }
03326                 return $out;
03327         }
03328 
03342         function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)      {
03343                 global $TYPO3_CONF_VARS;
03344 
03345                         // Check persistent object and if found, call directly and exit.
03346                 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName]))        {
03347                         return call_user_method(
03348                                                 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method'],
03349                                                 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
03350                                                 $params,
03351                                                 $ref
03352                                         );
03353                 }
03354 
03355                         // Check file-reference prefix; if found, require_once() the file (should be library of code)
03356                 if (strstr($funcName,':'))      {
03357                         list($file,$funcRef) = t3lib_div::revExplode(':',$funcName,2);
03358                         $requireFile = t3lib_div::getFileAbsFileName($file);
03359                         if ($requireFile) require_once($requireFile);
03360                 } else {
03361                         $funcRef = $funcName;
03362                 }
03363 
03364                         // Check for persistent object token, "&"
03365                 if (substr($funcRef,0,1)=='&')  {
03366                         $funcRef = substr($funcRef,1);
03367                         $storePersistentObject = TRUE;
03368                 } else {
03369                         $storePersistentObject = FALSE;
03370                 }
03371 
03372                         // Check prefix is valid:
03373                 if ($checkPrefix &&
03374                         !t3lib_div::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
03375                         !t3lib_div::isFirstPartOfStr(trim($funcRef),'tx_')
03376                         )       {
03377                         if (!$silent)   debug("Function/Class '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
03378                         return FALSE;
03379                 }
03380 
03381                         // Call function or method:
03382                 $parts = explode('->',$funcRef);
03383                 if (count($parts)==2)   {       // Class
03384 
03385                                 // Check if class/method exists:
03386                         if (class_exists($parts[0]))    {
03387 
03388                                         // Get/Create object of class:
03389                                 if ($storePersistentObject)     {       // Get reference to current instance of class:
03390                                         if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]]))    {
03391                                                 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = &t3lib_div::makeInstance($parts[0]);
03392                                         }
03393                                         $classObj = &$GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
03394                                 } else {        // Create new object:
03395                                         $classObj = &t3lib_div::makeInstance($parts[0]);
03396                                 }
03397 
03398                                 if (method_exists($classObj, $parts[1]))        {
03399 
03400                                                 // If persistent object should be created, set reference:
03401                                         if ($storePersistentObject)     {
03402                                                 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
03403                                                         'method' => $parts[1],
03404                                                         'obj' => &$classObj
03405                                                 );
03406                                         }
03407                                                 // Call method:
03408                                         $content = call_user_method(
03409                                                 $parts[1],
03410                                                 $classObj,
03411                                                 $params,
03412                                                 $ref
03413                                         );
03414                                 } else {
03415                                         if (!$silent)   debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
03416                                 }
03417                         } else {
03418                                 if (!$silent)   debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
03419                         }
03420                 } else {        // Function
03421                         if (function_exists($funcRef))  {
03422                                 $content = call_user_func($funcRef, $params, $ref);
03423                         } else {
03424                                 if (!$silent)   debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
03425                         }
03426                 }
03427                 return $content;
03428         }
03429 
03441         function &getUserObj($classRef,$checkPrefix='user_',$silent=0)  {
03442                 global $TYPO3_CONF_VARS;
03443                         // Check persistent object and if found, call directly and exit.
03444                 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef]))     {
03445                         return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
03446                 } else {
03447 
03448                                 // Check file-reference prefix; if found, require_once() the file (should be library of code)
03449                         if (strstr($classRef,':'))      {
03450                                 list($file,$class) = t3lib_div::revExplode(':',$classRef,2);
03451                                 $requireFile = t3lib_div::getFileAbsFileName($file);
03452                                 if ($requireFile)       require_once($requireFile);
03453                         } else {
03454                                 $class = $classRef;
03455                         }
03456 
03457                                 // Check for persistent object token, "&"
03458                         if (substr($class,0,1)=='&')    {
03459                                 $class = substr($class,1);
03460                                 $storePersistentObject = TRUE;
03461                         } else {
03462                                 $storePersistentObject = FALSE;
03463                         }
03464 
03465                                 // Check prefix is valid:
03466                         if ($checkPrefix &&
03467                                 !t3lib_div::isFirstPartOfStr(trim($class),$checkPrefix) &&
03468                                 !t3lib_div::isFirstPartOfStr(trim($class),'tx_')
03469                                 )       {
03470                                 if (!$silent)   debug("Class '".$class."' was not prepended with '".$checkPrefix."'",1);
03471                                 return FALSE;
03472                         }
03473 
03474                                 // Check if class exists:
03475                         if (class_exists($class))       {
03476                                 $classObj = &t3lib_div::makeInstance($class);
03477 
03478                                         // If persistent object should be created, set reference:
03479                                 if ($storePersistentObject)     {
03480                                         $GLOBALS['T3_VAR']['getUserObj'][$classRef] = &$classObj;
03481                                 }
03482 
03483                                 return $classObj;
03484                         } else {
03485                                 if (!$silent)   debug("<strong>ERROR:</strong> No class named: ".$class,1);
03486                         }
03487                 }
03488         }
03489 
03499         function &makeInstance($className)      {
03500                 return class_exists('ux_'.$className) ? t3lib_div::makeInstance('ux_'.$className) : new $className;
03501         }
03502 
03511         function makeInstanceClassName($className)      {
03512                 return class_exists('ux_'.$className) ? t3lib_div::makeInstanceClassName('ux_'.$className) : $className;
03513         }
03514 
03525         function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())    {
03526                 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
03527 
03528                 $error = FALSE;
03529 
03530                 if (!is_array($excludeServiceKeys) ) {
03531                         $excludeServiceKeys = t3lib_div::trimExplode(',', $excludeServiceKeys, 1);
03532                 }
03533                 while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys))   {
03534 
03535                                 // Check persistent object and if found, call directly and exit.
03536                         if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]))   {
03537                                         // reset service and return object
03538                                 $T3_VAR['makeInstanceService'][$info['className']]->reset();
03539                                 return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
03540 
03541                                 // include file and create object
03542                         } else {
03543                                 $requireFile = t3lib_div::getFileAbsFileName($info['classFile']);
03544                                 if (@is_file($requireFile)) {
03545                                         require_once ($requireFile);
03546                                         $obj = t3lib_div::makeInstance($info['className']);
03547                                         if (is_object($obj)) {
03548                                                 if(!@is_callable(array($obj,'init')))   {
03549                                                                 // use silent logging??? I don't think so.
03550                                                         die ('Broken service:'.t3lib_div::view_array($info));
03551                                                 }
03552                                                 $obj->info = $info;
03553                                                 if ($obj->init()) { // service available?
03554 
03555                                                                 // create persistent object
03556                                                         $T3_VAR['makeInstanceService'][$info['className']] = &$obj;
03557 
03558                                                                 // needed to delete temp files
03559                                                         register_shutdown_function(array(&$obj, '__destruct'));
03560 
03561                                                         return $obj; // object is passed as reference by function definition
03562                                                 }
03563                                                 $error = $obj->getLastErrorArray();
03564                                                 unset($obj);
03565                                         }
03566                                 }
03567                         }
03568                                 // deactivate the service
03569                         t3lib_extMgm::deactivateService($info['serviceType'],$info['serviceKey']);
03570                 }
03571                 return $error;
03572         }
03573 
03589         function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0)      {
03590                 switch((string)$enc)    {
03591                         case 'base64':
03592                                 $headers=trim($headers).chr(10).
03593                                 'Mime-Version: 1.0'.chr(10).
03594                                 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
03595                                 'Content-Transfer-Encoding: base64';
03596 
03597                                 $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.
03598 
03599                                 if (!$dontEncodeSubject)        $subject='=?'.$charset.'?B?'.base64_encode($subject).'?=';
03600                         break;
03601                         case 'quoted-printable':
03602                                 $headers=trim($headers).chr(10).
03603                                 'Mime-Version: 1.0'.chr(10).
03604                                 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
03605                                 'Content-Transfer-Encoding: quoted-printable';
03606 
03607                                 $message=t3lib_div::quoted_printable($message);
03608 
03609                                 if (!$dontEncodeSubject)        $subject='=?'.$charset.'?Q?'.trim(t3lib_div::quoted_printable(ereg_replace('[[:space:]]','_',$subject),1000)).'?=';
03610                         break;
03611                         case '8bit':
03612                                 $headers=trim($headers).chr(10).
03613                                 'Mime-Version: 1.0'.chr(10).
03614                                 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
03615                                 'Content-Transfer-Encoding: 8bit';
03616                         break;
03617                 }
03618                 $headers=trim(implode(chr(10),t3lib_div::trimExplode(chr(10),$headers,1)));     // make sure no empty lines are there.
03619 
03620                 mail($email,$subject,$message,$headers);
03621         }
03622 
03634         function quoted_printable($string,$maxlen=76)   {
03635                         // Make sure the string contains only Unix linebreaks
03636                 $string = str_replace(chr(13).chr(10), chr(10), $string);       // Replace Windows breaks (\r\n)
03637                 $string = str_replace(chr(13), chr(10), $string);               // Replace Mac breaks (\r)
03638 
03639                 $newString = '';
03640                 $theLines = explode(chr(10),$string);   // Split lines
03641                 foreach($theLines as $val)      {
03642                         $newVal = '';
03643                         $theValLen = strlen($val);
03644                         $len = 0;
03645                         for ($index=0; $index < $theValLen; $index++)   {       // Walk through each character of this line
03646                                 $char = substr($val,$index,1);
03647                                 $ordVal = ord($char);
03648                                 if ($len>($maxlen-4) || ($len>(($maxlen-10)-4)&&$ordVal==32))   {
03649                                         $newVal.='='.chr(13).chr(10);   // Add a line break
03650                                         $len=0;                 // Reset the length counter
03651                                 }
03652                                 if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
03653                                         $newVal.=$char;         // This character is ok, add it to the message
03654                                         $len++;
03655                                 } else {
03656                                         $newVal.=sprintf('=%02X',$ordVal);      // Special character, needs to be encoded
03657                                         $len+=3;
03658                                 }
03659                         }
03660                         $newVal = ereg_replace(chr(32).'$','=20',$newVal);              // Replaces a possible SPACE-character at the end of a line
03661                         $newVal = ereg_replace(chr(9).'$','=09',$newVal);               // Replaces a possible TAB-character at the end of a line
03662                         $newString.=$newVal.chr(13).chr(10);
03663                 }
03664                 return ereg_replace(chr(13).chr(10).'$','',$newString);
03665         }
03666 
03678         function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')      {
03679                         // Substitute URLs with shorter links:
03680                 $urlSplit=explode('http://',$message);
03681                 reset($urlSplit);
03682                 while(list($c,$v)=each($urlSplit))      {
03683                         if ($c) {
03684                                 $newParts = split('[[:space:]]|\)|\(',$v,2);
03685                                 $newURL='http://'.$newParts[0];
03686                                         switch((string)$urlmode)        {
03687                                                 case 'all':
03688                                                         $newURL=t3lib_div::makeRedirectUrl($newURL,0,$index_script_url);
03689                                                 break;
03690                                                 case '76':
03691                                                         $newURL=t3lib_div::makeRedirectUrl($newURL,76,$index_script_url);
03692                                                 break;
03693                                         }
03694                                 $urlSplit[$c]=$newURL.substr($v,strlen($newParts[0]));
03695                         }
03696                 }
03697 
03698                 $message=implode('',$urlSplit);
03699                 return $message;
03700         }
03701 
03712         function makeRedirectUrl($inUrl,$l=0,$index_script_url='')      {
03713                 if (strlen($inUrl)>$l)  {
03714                         $md5 = substr(md5($inUrl),0,20);
03715                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params'));
03716                         if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res))  {
03717                                 $insertFields = array(
03718                                         'md5hash' => $md5,
03719                                         'tstamp' => time(),
03720                                         'type' => 2,
03721                                         'params' => $inUrl
03722                                 );
03723 
03724                                 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
03725                         }
03726                         $inUrl=($index_script_url ? $index_script_url : t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR')).
03727                                 '?RDCT='.$md5;
03728                 }
03729                 return $inUrl;
03730         }
03731 
03739         function freetypeDpiComp($font_size)    {
03740                 $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
03741                 if ($dpi!=72)   $font_size = $font_size/$dpi*72;
03742                 return $font_size;
03743         }
03744 
03758         function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)     {
03759                 global $TYPO3_CONF_VARS;
03760 
03761                 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog']))    {
03762                         $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
03763                         $fakeThis = FALSE;
03764                         foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod)   {
03765                                 t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
03766                         }
03767                 }
03768         }
03769 
03779         function arrayToLogString($arr, $valueList=array(), $valueLength=20) {
03780                 $str = '';
03781                 if(is_array($arr)) {
03782                         if (!is_array($valueList)) {
03783                                 $valueList = explode(',', $valueList);
03784                         }
03785                         foreach($arr as $key => $value) {
03786                                 if (!count($valueList) OR (count($valueList) AND in_array($key, $valueList))) {
03787                                         $str .= (string)$key.trim(': '.t3lib_div::fixed_lgd(str_replace("\n",'|',(string)$value), $valueLength)).'; ';
03788                                 }
03789                         }
03790                 }
03791                 return $str;
03792         }
03793 
03802         function imageMagickCommand($command, $parameters, $path='')    {
03803                 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
03804                 $isExt = (TYPO3_OS=='WIN' ? '.exe' : '');
03805                 $switchCompositeParameters=false;
03806 
03807                 if(!$path)      { $path = $gfxConf['im_path']; }
03808 
03809                 $im_version = strtolower($gfxConf['im_version_5']);
03810                 $combineScript = $gfxConf['im_combine_filename'] ? trim($gfxConf['im_combine_filename']) : 'combine';
03811 
03812                 if($command==='combine')        {       // This is only used internally, has no effect outside
03813                         $command = 'composite';
03814 }
03815 
03816                         // Compile the path & command
03817                 if($im_version==='gm')  {
03818                         $switchCompositeParameters=true;
03819                         $path .= 'gm'.$isExt.' '.$command;
03820                 } else  {
03821                         if($im_version==='im6') { $switchCompositeParameters=true; }
03822                         $path .= (($command=='composite') ? $combineScript : $command).$isExt;
03823                 }
03824 
03825                 $cmdLine = $path.' '.$parameters;
03826 
03827                 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
03828                         $paramsArr = t3lib_div::unQuoteFilenames($parameters);
03829 
03830                         if(count($paramsArr)==6)        {       // The mask image has been specified => swap the parameters
03831                                 $tmp = $paramsArr[3];
03832                                 $paramsArr[3] = $paramsArr[2];
03833                                 $paramsArr[2] = $tmp;
03834                         }
03835 
03836                         $cmdLine = $path.' '.implode(' ', $paramsArr);
03837                 }
03838 
03839                 return $cmdLine;
03840         }
03841 
03848         function unQuoteFilenames($parameters)  {
03849                 $paramsArr = explode(' ', trim($parameters));
03850 
03851                 $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.
03852                 foreach($paramsArr as $k=>$v)   {
03853                         if($quoteActive > -1)   {
03854                                 $paramsArr[$quoteActive] .= ' '.$v;
03855                                 unset($paramsArr[$k]);
03856                                 if(ereg('"$', $v))      { $quoteActive = -1; }
03857 
03858                         } elseif(!trim($v))     {
03859                                 unset($paramsArr[$k]);  // Remove empty elements
03860 
03861                         } elseif(ereg('^"', $v))        {
03862                                 $quoteActive = $k;
03863                         }
03864                 }
03865 
03866                 return $paramsArr;
03867         }
03868 }
03869 
03870 ?>


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