Documentation TYPO3 par Ameos

class.t3lib_div.php

00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 1999-2004 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 ***************************************************************/
00209 class t3lib_div {
00210 
00211 
00212 
00213 
00214 
00215         /*************************
00216          *
00217          * GET/POST Variables
00218          *
00219          * Background:
00220          * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
00221          * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
00222          * But the clean solution is that quotes are never escaped and that is what the functions below offers.
00223          * Eventually TYPO3 should provide this in the global space as well.
00224          * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
00225          *
00226          *************************/
00227 
00239         function _GP($var)      {
00240                 if(empty($var)) return;
00241                 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00242                 if (isset($value))      {
00243                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00244                 }
00245                 return $value;
00246         }
00247 
00257         function _GET($var=NULL)        {
00258                 $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
00259                 if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
00260                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00261                 }
00262                 return $value;
00263         }
00264 
00274         function _POST($var=NULL)       {
00275                 $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
00276                 if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
00277                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00278                 }
00279                 return $value;
00280         }
00281 
00290         function _GETset($inputGet,$key='')     {
00291                         // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
00292                 if (strcmp($key,''))    {
00293                         if (is_array($inputGet))        { t3lib_div::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); }
00294                         $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
00295                 } elseif (is_array($inputGet)){
00296                         t3lib_div::addSlashesOnArray($inputGet);
00297                         $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
00298                 }
00299         }
00300 
00313         function GPvar($var,$strip=0)   {
00314                 if(empty($var)) return;
00315                 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00316                 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.
00317                 if ($strip && isset($value) && is_array($value)) { t3lib_div::stripSlashesOnArray($value); }
00318                 return $value;
00319         }
00320 
00330         function GParrayMerged($var)    {
00331                 $postA = is_array($_POST[$var]) ? $_POST[$var] : array();
00332                 $getA = is_array($_GET[$var]) ? $_GET[$var] : array();
00333                 $mergedA = t3lib_div::array_merge_recursive_overrule($getA,$postA);
00334                 t3lib_div::stripSlashesOnArray($mergedA);
00335                 return $mergedA;
00336         }
00337 
00338 
00339 
00340 
00341 
00342 
00343 
00344 
00345 
00346 
00347         /*************************
00348          *
00349          * IMAGE FUNCTIONS
00350          *
00351          *************************/
00352 
00353 
00374         function gif_compress($theFile, $type)  {
00375                 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
00376                 $returnCode='';
00377                 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif')      {       // GIF...
00378                         if (($type=='IM' || !$type) && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'])   {       // IM
00379                                 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'].'convert "'.$theFile.'" "'.$theFile.'"');
00380                                 $returnCode='IM';
00381                         } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png'])       {       // GD
00382                                 $tempImage = imageCreateFromGif($theFile);
00383                                 imageGif($tempImage, $theFile);
00384                                 imageDestroy($tempImage);
00385                                 $returnCode='GD';
00386                         }
00387                 }
00388                 return $returnCode;
00389         }
00390 
00400         function png_to_gif_by_imagemagick($theFile)    {
00401                 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
00402                         && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
00403                         && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
00404                         && strtolower(substr($theFile,-4,4))=='.png'
00405                         && @is_file($theFile))  {       // IM
00406                                 $newFile = substr($theFile,0,-4).'.gif';
00407                                 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'].'convert "'.$theFile.'" "'.$newFile.'"');
00408                                 $theFile = $newFile;
00409                                         // 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!!
00410                 }
00411                 return $theFile;
00412         }
00413 
00424         function read_png_gif($theFile,$output_png=0)   {
00425                 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile))     {
00426                         $ext = strtolower(substr($theFile,-4,4));
00427                         if (
00428                                         ((string)$ext=='.png' && $output_png)   ||
00429                                         ((string)$ext=='.gif' && !$output_png)
00430                                 )       {
00431                                 return $theFile;
00432                         } else {
00433                                 $newFile = PATH_site.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?'.png':'.gif');
00434                                 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'].'convert "'.$theFile.'" "'.$newFile.'"');
00435                                 if (@is_file($newFile)) return $newFile;
00436                         }
00437                 }
00438         }
00439 
00440 
00441 
00442 
00443 
00444 
00445 
00446 
00447 
00448 
00449 
00450 
00451 
00452 
00453 
00454         /*************************
00455          *
00456          * STRING FUNCTIONS
00457          *
00458          *************************/
00459 
00473         function fixed_lgd($string,$origChars,$preStr='...')    {
00474                 $chars = abs($origChars);
00475                 if ($chars >= 4)        {
00476                         if(strlen($string)>$chars)  {
00477                                 return $origChars < 0 ?
00478                                         $preStr.trim(substr($string, -($chars-3))) :
00479                                         trim(substr($string, 0, $chars-3)).$preStr;
00480                         }
00481                 }
00482                 return $string;
00483         }
00484 
00498         function fixed_lgd_pre($string,$chars)  {
00499                 return strrev(t3lib_div::fixed_lgd(strrev($string),$chars));
00500         }
00501 
00512         function fixed_lgd_cs($string,$chars)   {
00513                 if (is_object($GLOBALS['LANG']))        {
00514                         return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet,$string,$chars,'...');
00515                 } else {
00516                         return t3lib_div::fixed_lgd($string, $chars);
00517                 }
00518         }
00519 
00529         function breakTextForEmail($str,$implChar="\n",$charWidth=76)   {
00530                 $lines = explode(chr(10),$str);
00531                 $outArr=array();
00532                 while(list(,$lStr)=each($lines))        {
00533                         $outArr = array_merge($outArr,t3lib_div::breakLinesForEmail($lStr,$implChar,$charWidth));
00534                 }
00535                 return implode(chr(10),$outArr);
00536         }
00537 
00548         function breakLinesForEmail($str,$implChar="\n",$charWidth=76)  {
00549                 $lines=array();
00550                 $l=$charWidth;
00551                 $p=0;
00552                 while(strlen($str)>$p)  {
00553                         $substr=substr($str,$p,$l);
00554                         if (strlen($substr)==$l)        {
00555                                 $count = count(explode(' ',trim(strrev($substr))));
00556                                 if ($count>1)   {       // OK...
00557                                         $parts = explode(' ',strrev($substr),2);
00558                                         $theLine = strrev($parts[1]);
00559                                 } else {
00560                                         $afterParts = explode(' ',substr($str,$l+$p),2);
00561                                         $theLine = $substr.$afterParts[0];
00562                                 }
00563                                 if (!strlen($theLine))  {break; }       // Error, because this would keep us in an endless loop.
00564                         } else {
00565                                 $theLine=$substr;
00566                         }
00567 
00568                         $lines[]=trim($theLine);
00569                         $p+=strlen($theLine);
00570                         if (!trim(substr($str,$p,$l)))  break;  // added...
00571                 }
00572                 return implode($implChar,$lines);
00573         }
00574 
00583         function cmpIP($baseIP, $list)  {
00584                 $IPpartsReq = explode('.',$baseIP);
00585                 if (count($IPpartsReq)==4)      {
00586                         $values = t3lib_div::trimExplode(',',$list,1);
00587 
00588                         foreach($values as $test)       {
00589                                 list($test,$mask) = explode('/',$test);
00590 
00591                                 if(intval($mask)) {
00592                                                 // "192.168.3.0/24"
00593                                         $lnet = ip2long($test);
00594                                         $lip = ip2long($baseIP);
00595                                         $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
00596                                         $firstpart = substr($binnet,0,$mask);
00597                                         $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
00598                                         $firstip = substr($binip,0,$mask);
00599                                         $yes = (strcmp($firstpart,$firstip)==0);
00600                                 } else {
00601                                                 // "192.168.*.*"
00602                                         $IPparts = explode('.',$test);
00603                                         $yes = 1;
00604                                         reset($IPparts);
00605                                         while(list($index,$val)=each($IPparts)) {
00606                                                 $val = trim($val);
00607                                                 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val))       {
00608                                                         $yes=0;
00609                                                 }
00610                                         }
00611                                 }
00612                                 if ($yes) return true;
00613                         }
00614                 }
00615                 return false;
00616         }
00617 
00625         function cmpFQDN($baseIP, $list)        {
00626                 if (count(explode('.',$baseIP))==4)     {
00627                         $resolvedHostName = explode('.', gethostbyaddr($baseIP));
00628                         $values = t3lib_div::trimExplode(',',$list,1);
00629 
00630                         foreach($values as $test)       {
00631                                 $hostNameParts = explode('.',$test);
00632                                 $yes = 1;
00633 
00634                                 foreach($hostNameParts as $index => $val)       {
00635                                         $val = trim($val);
00636                                         if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
00637                                                 $yes=0;
00638                                         }
00639                                 }
00640                                 if ($yes) return true;
00641                         }
00642                 }
00643                 return false;
00644         }
00645 
00655         function inList($in_list,$item) {
00656                 return strstr(','.$in_list.',', ','.$item.',');
00657         }
00658 
00667         function rmFromList($element,$list)     {
00668                 $items = explode(',',$list);
00669                 while(list($k,$v)=each($items)) {
00670                         if ($v==$element)       {unset($items[$k]);}
00671                 }
00672                 return implode(',',$items);
00673         }
00674 
00685         function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)  {
00686                 // Returns $theInt as an integer in the integerspace from $min to $max
00687                 $theInt = intval($theInt);
00688                 if ($zeroValue && !$theInt)     {$theInt=$zeroValue;}   // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
00689                 if ($theInt<$min){$theInt=$min;}
00690                 if ($theInt>$max){$theInt=$max;}
00691                 return $theInt;
00692         }
00693 
00701         function intval_positive($theInt)       {
00702                 $theInt = intval($theInt);
00703                 if ($theInt<0){$theInt=0;}
00704                 return $theInt;
00705         }
00706 
00714         function int_from_ver($verNumberStr)    {
00715                 $verParts = explode('.',$verNumberStr);
00716                 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));
00717         }
00718 
00726         function md5int($str)   {
00727                 return hexdec(substr(md5($str),0,7));
00728         }
00729 
00739         function shortMD5($input, $len=10)      {
00740                 return substr(md5($input),0,$len);
00741         }
00742 
00752         function uniqueList($in_list, $secondParameter=NULL)    {
00753                 if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
00754                 if (isset($secondParameter))    die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
00755 
00756                 return implode(',',array_unique(t3lib_div::trimExplode(',',$in_list,1)));
00757         }
00758 
00766         function split_fileref($fileref)        {
00767                 if (    ereg('(.*/)(.*)$',$fileref,$reg)        )       {
00768                         $info['path'] = $reg[1];
00769                         $info['file'] = $reg[2];
00770                 } else {
00771                         $info['path'] = '';
00772                         $info['file'] = $fileref;
00773                 }
00774                 $reg='';
00775                 if (    ereg('(.*)\.([^\.]*$)',$info['file'],$reg)      )       {
00776                         $info['filebody'] = $reg[1];
00777                         $info['fileext'] = strtolower($reg[2]);
00778                         $info['realFileext'] = $reg[2];
00779                 } else {
00780                         $info['filebody'] = $info['file'];
00781                         $info['fileext'] = '';
00782                 }
00783                 reset($info);
00784                 return $info;
00785         }
00786 
00803         function dirname($path) {
00804                 $p=t3lib_div::revExplode('/',$path,2);
00805                 return count($p)==2?$p[0]:'';
00806         }
00807 
00819         function modifyHTMLColor($color,$R,$G,$B)       {
00820                 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
00821                 $nR = t3lib_div::intInRange(hexdec(substr($color,1,2))+$R,0,255);
00822                 $nG = t3lib_div::intInRange(hexdec(substr($color,3,2))+$G,0,255);
00823                 $nB = t3lib_div::intInRange(hexdec(substr($color,5,2))+$B,0,255);
00824                 return '#'.
00825                         substr('0'.dechex($nR),-2).
00826                         substr('0'.dechex($nG),-2).
00827                         substr('0'.dechex($nB),-2);
00828         }
00829 
00839         function modifyHTMLColorAll($color,$all)        {
00840                 return t3lib_div::modifyHTMLColor($color,$all,$all,$all);
00841         }
00842 
00850         function rm_endcomma($string)   {
00851                 return ereg_replace(',$','',$string);
00852         }
00853 
00863         function danish_strtoupper($string)     {
00864                 $value = strtoupper($string);
00865                 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
00866         }
00867 
00878         function convUmlauts($str)      {
00879                 $pat  = array ( '/ä/',  '/Ä/',  '/ö/',  '/Ö/',  '/ü/',  '/Ü/',  '/ß/',  '/å/',  '/Å/',  '/ø/',  '/Ø/',  '/æ/',  '/Æ/'   );
00880                 $repl = array ( 'ae',   'Ae',   'oe',   'Oe',   'ue',   'Ue',   'ss',   'aa',   'AA',   'oe',   'OE',   'ae',   'AE'    );
00881                 return preg_replace($pat,$repl,$str);
00882         }
00883 
00891         function testInt($var)  {
00892                 return !strcmp($var,intval($var));
00893         }
00894 
00903         function isFirstPartOfStr($str,$partStr)        {
00904                 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
00905                 $psLen = strlen($partStr);
00906                 if ($psLen)     {
00907                         return substr($str,0,$psLen)==(string)$partStr;
00908                 } else return false;
00909         }
00910 
00919         function formatSize($sizeInBytes,$labels='')    {
00920 
00921                         // Set labels:
00922                 if (strlen($labels) == 0) {
00923                     $labels = ' | K| M| G';
00924                 } else {
00925                     $labels = str_replace('"','',$labels);
00926                 }
00927                 $labelArr = explode('|',$labels);
00928 
00929                         // Find size:
00930                 if ($sizeInBytes>900)   {
00931                         if ($sizeInBytes>900000000)     {       // GB
00932                                 $val = $sizeInBytes/(1024*1024*1024);
00933                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
00934                         }
00935                         elseif ($sizeInBytes>900000)    {       // MB
00936                                 $val = $sizeInBytes/(1024*1024);
00937                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
00938                         } else {        // KB
00939                                 $val = $sizeInBytes/(1024);
00940                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
00941                         }
00942                 } else {        // Bytes
00943                         return $sizeInBytes.$labelArr[0];
00944                 }
00945         }
00946 
00954         function convertMicrotime($microtime)   {
00955                 $parts = explode(' ',$microtime);
00956                 return round(($parts[0]+$parts[1])*1000);
00957         }
00958 
00968         function splitCalc($string,$operators)  {
00969                 $res = Array();
00970                 $sign='+';
00971                 while($string)  {
00972                         $valueLen=strcspn($string,$operators);
00973                         $value=substr($string,0,$valueLen);
00974                         $res[] = Array($sign,trim($value));
00975                         $sign=substr($string,$valueLen,1);
00976                         $string=substr($string,$valueLen+1);
00977                 }
00978                 reset($res);
00979                 return $res;
00980         }
00981 
00990         function calcPriority($string)  {
00991                 $string=ereg_replace('[[:space:]]*','',$string);        // removing all whitespace
00992                 $string='+'.$string;    // Ensuring an operator for the first entrance
00993                 $qm='\*\/\+-^%';
00994                 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
00995                         // split the expression here:
00996                 preg_match_all('/'.$regex.'/',$string,$reg);
00997 
00998                 reset($reg[2]);
00999                 $number=0;
01000                 $Msign='+';
01001                 $err='';
01002                 $buffer=doubleval(current($reg[2]));
01003                 next($reg[2]);  // Advance pointer
01004                 while(list($k,$v)=each($reg[2]))        {
01005                         $v=doubleval($v);
01006                         $sign = $reg[1][$k];
01007                         if ($sign=='+' || $sign=='-')   {
01008                                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01009                                 $Msign = $sign;
01010                                 $buffer=$v;
01011                         } else {
01012                                 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
01013                                 if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';}
01014                                 if ($sign=='*') {$buffer*=$v;}
01015                                 if ($sign=='^') {$buffer=pow($buffer,$v);}
01016                         }
01017                 }
01018                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01019                 return $err ? 'ERROR: '.$err : $number;
01020         }
01021 
01030         function calcParenthesis($string)       {
01031                 $securC=100;
01032                 do {
01033                         $valueLenO=strcspn($string,'(');
01034                         $valueLenC=strcspn($string,')');
01035                         if ($valueLenC==strlen($string) || $valueLenC < $valueLenO)     {
01036                                 $value = t3lib_div::calcPriority(substr($string,0,$valueLenC));
01037                                 $string = $value.substr($string,$valueLenC+1);
01038                                 return $string;
01039                         } else {
01040                                 $string = substr($string,0,$valueLenO).t3lib_div::calcParenthesis(substr($string,$valueLenO+1));
01041                         }
01042                                 // Security:
01043                         $securC--;
01044                         if ($securC<=0) break;
01045                 } while($valueLenO<strlen($string));
01046                 return $string;
01047         }
01048 
01056         function htmlspecialchars_decode($value)        {
01057                 $value = str_replace('&gt;','>',$value);
01058                 $value = str_replace('&lt;','<',$value);
01059                 $value = str_replace('&quot;','"',$value);
01060                 $value = str_replace('&amp;','&',$value);
01061                 return $value;
01062         }
01063 
01071         function deHSCentities($str)    {
01072                 return ereg_replace('&amp;([#[:alnum:]]*;)','&\1',$str);
01073         }
01074 
01084         function slashJS($string,$extended=0,$char="'") {
01085                 if ($extended)  {$string = str_replace ("\\", "\\\\", $string);}
01086                 return str_replace ($char, "\\".$char, $string);
01087         }
01088 
01097         function rawUrlEncodeJS($str)   {
01098                 return str_replace('%20',' ',rawurlencode($str));
01099         }
01100 
01109         function rawUrlEncodeFP($str)   {
01110                 return str_replace('%2F','/',rawurlencode($str));
01111         }
01112 
01120         function validEmail($email)     {
01121                 $email = trim ($email);
01122                 if (strstr($email,' '))  return FALSE;
01123                 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE : FALSE;
01124         }
01125 
01135         function formatForTextarea($content)    {
01136                 return chr(10).htmlspecialchars($content);
01137         }
01138 
01139 
01140 
01141 
01142 
01143 
01144 
01145 
01146 
01147 
01148 
01149 
01150         /*************************
01151          *
01152          * ARRAY FUNCTIONS
01153          *
01154          *************************/
01155 
01166         function inArray($in_array,$item)       {
01167                 if (is_array($in_array))        {
01168                         while (list(,$val)=each($in_array))     {
01169                                 if (!is_array($val) && !strcmp($val,$item)) return true;
01170                         }
01171                 }
01172         }
01173 
01183         function intExplode($delim, $string)    {
01184                 $temp = explode($delim,$string);
01185                 while(list($key,$val)=each($temp))      {
01186                         $temp[$key]=intval($val);
01187                 }
01188                 reset($temp);
01189                 return $temp;
01190         }
01191 
01202         function revExplode($delim, $string, $count=0)  {
01203                 $temp = explode($delim,strrev($string),$count);
01204                 while(list($key,$val)=each($temp))      {
01205                         $temp[$key]=strrev($val);
01206                 }
01207                 $temp=array_reverse($temp);
01208                 reset($temp);
01209                 return $temp;
01210         }
01211 
01222         function trimExplode($delim, $string, $onlyNonEmptyValues=0)    {
01223                 $temp = explode($delim,$string);
01224                 $newtemp=array();
01225                 while(list($key,$val)=each($temp))      {
01226                         if (!$onlyNonEmptyValues || strcmp('',trim($val)))      {
01227                                 $newtemp[]=trim($val);
01228                         }
01229                 }
01230                 reset($newtemp);
01231                 return $newtemp;
01232         }
01233 
01244         function uniqueArray($valueArray)       {
01245                 return array_unique($valueArray);
01246         }
01247 
01256         function removeArrayEntryByValue($array,$cmpValue)      {
01257                 if (is_array($array))   {
01258                         reset($array);
01259                         while(list($k,$v)=each($array)) {
01260                                 if (is_array($v))       {
01261                                         $array[$k] = t3lib_div::removeArrayEntryByValue($v,$cmpValue);
01262                                 } else {
01263                                         if (!strcmp($v,$cmpValue))      {
01264                                                 unset($array[$k]);
01265                                         }
01266                                 }
01267                         }
01268                 }
01269                 reset($array);
01270                 return $array;
01271         }
01272 
01284         function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)      {
01285                 if (is_array($theArray))        {
01286                         foreach($theArray as $Akey => $AVal)    {
01287                                 $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
01288                                 if (is_array($AVal))    {
01289                                         $str = t3lib_div::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
01290                                 } else {
01291                                         if (!$skipBlank || strcmp($AVal,''))    {
01292                                                 $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
01293                                                         '='.rawurlencode($AVal);        // strips slashes because _POST / _GET input is with slashes...
01294                                         }
01295                                 }
01296                         }
01297                 }
01298                 return $str;
01299         }
01300 
01311         function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)        {
01312                 $keys = t3lib_div::trimExplode(',',$varList,1);
01313                 $outArr=array();
01314                 foreach($keys as $v)    {
01315                         if (isset($getArray[$v]))       {
01316                                 $outArr[$v]=$getArray[$v];
01317                         } elseif ($GPvarAlt) {
01318                                 $outArr[$v]=t3lib_div::_GP($v);
01319                         }
01320                 }
01321                 return $outArr;
01322         }
01323 
01334         function addSlashesOnArray(&$theArray)  {
01335                 if (is_array($theArray))        {
01336                         reset($theArray);
01337                         while(list($Akey,$AVal)=each($theArray))        {
01338                                 if (is_array($AVal))    {
01339                                         t3lib_div::addSlashesOnArray($theArray[$Akey]);
01340                                 } else {
01341                                         $theArray[$Akey] = addslashes($AVal);
01342                                 }
01343                         }
01344                         reset($theArray);
01345                 }
01346         }
01347 
01358         function stripSlashesOnArray(&$theArray)        {
01359                 if (is_array($theArray))        {
01360                         reset($theArray);
01361                         while(list($Akey,$AVal)=each($theArray))        {
01362                                 if (is_array($AVal))    {
01363                                         t3lib_div::stripSlashesOnArray($theArray[$Akey]);
01364                                 } else {
01365                                         $theArray[$Akey] = stripslashes($AVal);
01366                                 }
01367                         }
01368                         reset($theArray);
01369                 }
01370         }
01371 
01380         function slashArray($arr,$cmd)  {
01381                 if ($cmd=='strip')      t3lib_div::stripSlashesOnArray($arr);
01382                 if ($cmd=='add')        t3lib_div::addSlashesOnArray($arr);
01383                 return $arr;
01384         }
01385 
01397         function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) {
01398                 reset($arr1);
01399                 while(list($key,$val) = each($arr1)) {
01400                         if(is_array($arr0[$key])) {
01401                                 if (is_array($arr1[$key]))      {
01402                                         $arr0[$key] = t3lib_div::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys);
01403                                 }
01404                         } else {
01405                                 if ($notAddKeys) {
01406                                         if (isset($arr0[$key])) {
01407                                                 if ($includeEmtpyValues OR $val) {
01408                                                         $arr0[$key] = $val;
01409                                                 }
01410                                         }
01411                                 } else {
01412                                         if ($includeEmtpyValues OR $val) {
01413                                                 $arr0[$key] = $val;
01414                                         }
01415                                 }
01416                         }
01417                 }
01418                 reset($arr0);
01419                 return $arr0;
01420         }
01421 
01430         function array_merge($arr1,$arr2)       {
01431                 return $arr2+$arr1;
01432         }
01433 
01443         function csvValues($row,$delim=',',$quote='"')  {
01444                 reset($row);
01445                 $out=array();
01446                 while(list(,$value)=each($row)) {
01447                         list($valPart) = explode(chr(10),$value);
01448                         $valPart = trim($valPart);
01449                         $out[]=str_replace($quote,$quote.$quote,$valPart);
01450                 }
01451                 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
01452                 return $str;
01453         }
01454 
01455 
01456 
01457 
01458 
01459 
01460 
01461 
01462 
01463 
01464 
01465 
01466 
01467 
01468 
01469 
01470         /*************************
01471          *
01472          * HTML/XML PROCESSING
01473          *
01474          *************************/
01475 
01485         function get_tag_attributes($tag)       {
01486                 $components = t3lib_div::split_tag_attributes($tag);
01487                 $name = '';      // attribute name is stored here
01488                 $valuemode = '';
01489                 if (is_array($components))      {
01490                         while (list($key,$val) = each ($components))    {
01491                                 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
01492                                         if ($valuemode) {
01493                                                 if ($name)      {
01494                                                         $attributes[$name] = $val;
01495                                                         $name = '';
01496                                                 }
01497                                         } else {
01498                                                 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val)))    {
01499                                                         $attributes[$key] = '';
01500                                                         $name = $key;
01501                                                 }
01502                                         }
01503                                         $valuemode = '';
01504                                 } else {
01505                                         $valuemode = 'on';
01506                                 }
01507                         }
01508                         if (is_array($attributes))      reset($attributes);
01509                         return $attributes;
01510                 }
01511         }
01512 
01522         function split_tag_attributes($tag)     {
01523                 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
01524                         // Removes any > in the end of the string
01525                 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
01526 
01527                 while (strcmp($tag_tmp,''))     {       // Compared with empty string instead , 030102
01528                         $firstChar=substr($tag_tmp,0,1);
01529                         if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
01530                                 $reg=explode($firstChar,$tag_tmp,3);
01531                                 $value[]=$reg[1];
01532                                 $tag_tmp=trim($reg[2]);
01533                         } elseif (!strcmp($firstChar,'=')) {
01534                                 $value[] = '=';
01535                                 $tag_tmp = trim(substr($tag_tmp,1));            // Removes = chars.
01536                         } else {
01537                                         // There are '' around the value. We look for the next ' ' or '>'
01538                                 $reg = split('[[:space:]=]',$tag_tmp,2);
01539                                 $value[] = trim($reg[0]);
01540                                 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
01541                         }
01542                 }
01543                 if (is_array($value))   reset($value);
01544                 return $value;
01545         }
01546 
01556         function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)   {
01557                 if (is_array($arr))     {
01558                         if ($xhtmlSafe) {
01559                                 $newArr=array();
01560                                 foreach($arr as $p => $v)       {
01561                                         if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
01562                                 }
01563                                 $arr = $newArr;
01564                         }
01565                         $list = array();
01566                         foreach($arr as $p => $v)       {
01567                                 if (strcmp($v,'') || $dontOmitBlankAttribs)     {$list[]=$p.'="'.$v.'"';}
01568                         }
01569                         return implode(' ',$list);
01570                 }
01571         }
01572 
01583         function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)       {
01584                 return t3lib_div::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
01585         }
01586 
01598         function wrapJS($string, $linebreak=TRUE) {
01599                 if(trim($string)) {
01600                                 // <script wrapped in nl?
01601                         $cr = $linebreak? "\n" : '';
01602 
01603                                 // remove nl from the beginning
01604                         $string = preg_replace ('/^\n+/', '', $string);
01605                                 // re-ident to one tab using the first line as reference
01606                         if(preg_match('/^(\t+)/',$string,$match)) {
01607                                 $string = str_replace($match[1],"\t", $string);
01608                         }
01609                         $string = $cr.'<script type="text/javascript">
01610 /*<![CDATA[*/
01611 '.$string.'
01612 /*]]>*/
01613 </script>'.$cr;
01614                 }
01615                 return trim($string);
01616         }
01617 
01618 
01628         function xml2tree($string,$depth=999) {
01629                 $parser = xml_parser_create();
01630                 $vals = array();
01631                 $index = array();
01632 
01633                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
01634                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
01635                 xml_parse_into_struct($parser, $string, $vals, $index);
01636 
01637                 if (xml_get_error_code($parser))        return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
01638                 xml_parser_free($parser);
01639 
01640                 $stack = array( array() );
01641                 $stacktop = 0;
01642                 $startPoint=0;
01643 
01644                 unset($tagi);
01645                 foreach($vals as $key => $val) {
01646                         $type = $val['type'];
01647 
01648                                 // open tag:
01649                         if ($type=='open' || $type=='complete') {
01650                                 $stack[$stacktop++] = $tagi;
01651 
01652                                 if ($depth==$stacktop)  {
01653                                         $startPoint=$key;
01654                                 }
01655 
01656                                 $tagi = array('tag' => $val['tag']);
01657 
01658                                 if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
01659                                 if(isset($val['value']))        $tagi['values'][] = $val['value'];
01660                         }
01661                                 // finish tag:
01662                         if ($type=='complete' || $type=='close')        {
01663                                 $oldtagi = $tagi;
01664                                 $tagi = $stack[--$stacktop];
01665                                 $oldtag = $oldtagi['tag'];
01666                                 unset($oldtagi['tag']);
01667 
01668                                 if ($depth==($stacktop+1))      {
01669                                         if ($key-$startPoint > 0)       {
01670                                                 $partArray = array_slice(
01671                                                         $vals,
01672                                                         $startPoint+1,
01673                                                         $key-$startPoint-1
01674                                                 );
01675                                                 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
01676                                                 $oldtagi['XMLvalue']=t3lib_div::xmlRecompileFromStructValArray($partArray);
01677                                         } else {
01678                                                 $oldtagi['XMLvalue']=$oldtagi['values'][0];
01679                                         }
01680                                 }
01681 
01682                                 $tagi['ch'][$oldtag][] = $oldtagi;
01683                                 unset($oldtagi);
01684                         }
01685                                 // cdata
01686                         if($type=='cdata') {
01687                                 $tagi['values'][] = $val['value'];
01688                         }
01689                 }
01690                 return $tagi['ch'];
01691         }
01692 
01714         function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$parentTagName='')     {
01715                         // 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
01716                 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
01717                                                 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
01718                                                 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
01719                                                 chr(30).chr(31);
01720                         // Set indenting mode:
01721                 $indentChar = $spaceInd ? ' ' : chr(9);
01722                 $indentN = $spaceInd>0 ? $spaceInd : 1;
01723 
01724                         // Init output variable:
01725                 $output='';
01726 
01727                         // Traverse the input array
01728                 if (is_array($array))   {
01729                         foreach($array as $k=>$v)       {
01730                                 $attr = '';
01731                                 $tagName = $k;
01732 
01733                                         // Construct the tag name.
01734                                 if (!strcmp(intval($tagName),$tagName)) {       // If integer...;
01735                                         if ($options['useNindex']) {    // If numeric key, prefix "n"
01736                                                 $tagName = 'n'.$tagName;
01737                                         } else {        // Use special tag for num. keys:
01738                                                 $attr.=' index="'.$tagName.'"';
01739                                                 $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
01740                                         }
01741                                 } elseif($options['useIndexTagForAssoc']) {             // Use tag for all associative keys:
01742                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
01743                                         $tagName = $options['useIndexTagForAssoc'];
01744                                 } elseif(isset($options['parentTagMap'][$parentTagName])) {             // Use tag based on parent tag name:
01745                                         $attr.=' index="'.htmlspecialchars($tagName).'"';
01746                                         $tagName = (string)$options['parentTagMap'][$parentTagName];
01747                                 }
01748 
01749                                         // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
01750                                 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
01751 
01752                                         // If the value is an array then we will call this function recursively:
01753                                 if (is_array($v))       {
01754                                         // Sub elements:
01755                                         $content = chr(10).t3lib_div::array2xml($v,$NSprefix,$level+1,'',$spaceInd,$options,$tagName).
01756                                                                 str_pad('',($level+1)*$indentN,$indentChar);
01757                                         $attr.=' type="array"';
01758                                 } else {        // Just a value:
01759 
01760                                                 // Look for binary chars:
01761                                         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!
01762                                                         // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
01763                                                 $content = chr(10).chunk_split(base64_encode($v));
01764                                                 $attr.=' base64="1"';
01765                                         } else {
01766                                                         // Otherwise, just htmlspecialchar the stuff:
01767                                                 $content = htmlspecialchars($v);
01768                                                 $dType = gettype($v);
01769                                                 if ($dType!='string')   { $attr.=' type="'.$dType.'"'; }
01770                                         }
01771                                 }
01772 
01773                                         // Add the element to the output string:
01774                                 $output.=str_pad('',($level+1)*$indentN,$indentChar).'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.chr(10);
01775                         }
01776                 }
01777 
01778                         // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
01779                 if (!$level)    {
01780                         $output =
01781                                 '<'.$docTag.'>'.chr(10).
01782                                 $output.
01783                                 '</'.$docTag.'>';
01784                 }
01785 
01786                 return $output;
01787         }
01788 
01799         function xml2array($string,$NSprefix='') {
01800                 global $TYPO3_CONF_VARS;
01801 
01802                         // Create parser:
01803                 $parser = xml_parser_create();
01804                 $vals = array();
01805                 $index = array();
01806 
01807                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
01808                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
01809 
01810                         // PHP5 fix of charset awareness:
01811                         // 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.
01812                         // 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.
01813                         // 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.
01814                 if ((double)phpversion()>=5)    {
01815                         unset($ereg_result);
01816                         ereg('^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"',substr($string,0,200),$ereg_result);
01817                         $theCharset = $ereg_result[1] ? $ereg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
01818                         xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);  // us-ascii / utf-8 / iso-8859-1
01819                 }
01820 
01821                         // Parse content:
01822                 xml_parse_into_struct($parser, $string, $vals, $index);
01823 
01824                         // If error, return error message:
01825                 if (xml_get_error_code($parser))        return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
01826                 xml_parser_free($parser);
01827 
01828                         // Init vars:
01829                 $stack = array(array());
01830                 $stacktop = 0;
01831                 $current=array();
01832                 $tagName='';
01833 
01834                         // Traverse the parsed XML structure:
01835                 foreach($vals as $key => $val) {
01836 
01837                                 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
01838                         $tagName = $val['tag'];
01839 
01840                                 // Test for name space:
01841                         $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
01842 
01843                                 // Test for numeric tag, encoded on the form "nXXX":
01844                         $testNtag = substr($tagName,1); // Closing tag.
01845                         $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
01846 
01847                                 // Test for alternative index value:
01848                         if (strlen($val['attributes']['index']))        { $tagName = $val['attributes']['index']; }
01849 
01850                                 // Setting tag-values, manage stack:
01851                         switch($val['type'])    {
01852                                 case 'open':            // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
01853                                         $current[$tagName] = array();   // Setting blank place holder
01854                                         $stack[$stacktop++] = $current;
01855                                         $current = array();
01856                                 break;
01857                                 case 'close':   // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
01858                                         $oldCurrent = $current;
01859                                         $current = $stack[--$stacktop];
01860                                         end($current);  // Going to the end of array to get placeholder key, key($current), and fill in array next:
01861                                         $current[key($current)] = $oldCurrent;
01862                                         unset($oldCurrent);
01863                                 break;
01864                                 case 'complete':        // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
01865                                         if ($val['attributes']['base64'])       {
01866                                                 $current[$tagName] = base64_decode($val['value']);
01867                                         } else {
01868                                                 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
01869 
01870                                                         // Cast type:
01871                                                 switch((string)$val['attributes']['type'])      {
01872                                                         case 'integer':
01873                                                                 $current[$tagName] = (integer)$current[$tagName];
01874                                                         break;
01875                                                         case 'double':
01876                                                                 $current[$tagName] = (double)$current[$tagName];
01877                                                         break;
01878                                                         case 'boolean':
01879                                                                 $current[$tagName] = (bool)$current[$tagName];
01880                                                         break;
01881                                                         case 'array':
01882                                                                 $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...
01883                                                         break;
01884                                                 }
01885                                         }
01886                                 break;
01887                         }
01888                 }
01889 
01890                         // Finally return the content of the document tag.
01891                 return $current[$tagName];
01892         }
01893 
01901         function xmlRecompileFromStructValArray($vals)  {
01902                 $XMLcontent='';
01903 
01904                 foreach($vals as $val) {
01905                         $type = $val['type'];
01906 
01907                                 // open tag:
01908                         if ($type=='open' || $type=='complete') {
01909                                 $XMLcontent.='<'.$val['tag'];
01910                                 if(isset($val['attributes']))  {
01911                                         foreach($val['attributes'] as $k => $v) {
01912                                                 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
01913                                         }
01914                                 }
01915                                 if ($type=='complete')  {
01916                                         if(isset($val['value']))        {
01917                                                 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
01918                                         } else $XMLcontent.='/>';
01919                                 } else $XMLcontent.='>';
01920 
01921                                 if ($type=='open' && isset($val['value']))      {
01922                                         $XMLcontent.=htmlspecialchars($val['value']);
01923                                 }
01924                         }
01925                                 // finish tag:
01926                         if ($type=='close')     {
01927                                 $XMLcontent.='</'.$val['tag'].'>';
01928                         }
01929                                 // cdata
01930                         if($type=='cdata') {
01931                                 $XMLcontent.=htmlspecialchars($val['value']);
01932                         }
01933                 }
01934 
01935                 return $XMLcontent;
01936         }
01937 
01945         function xmlGetHeaderAttribs($xmlData)  {
01946                 $xmlHeader = substr(trim($xmlData),0,200);
01947                 $reg=array();
01948                 if (eregi('^<\?xml([^>]*)\?\>',$xmlHeader,$reg))        {
01949                         return t3lib_div::get_tag_attributes($reg[1]);
01950                 }
01951         }
01952 
01953 
01954 
01955 
01956 
01957 
01958 
01959 
01960 
01961 
01962 
01963         /*************************
01964          *
01965          * FILES FUNCTIONS
01966          *
01967          *************************/
01968 
01977         function getURL($url)   {
01978                 $content = '';
01979 
01980                         // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
01981                 if((substr($url,0,7)=='http://') && ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse']=='1'))       {
01982                         //external URL without error checking.
01983                         $ch = curl_init();
01984                         curl_setopt ($ch,CURLOPT_URL, $url);
01985                         curl_setopt ($ch,CURLOPT_HEADER, 0);
01986                         curl_setopt ($ch,CURLOPT_RETURNTRANSFER, 1);
01987 
01988                         if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
01989                                 curl_setopt ($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
01990 
01991                                 // I don't know if it will be needed
01992                                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
01993                                         curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'] );
01994                                 }
01995                                 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
01996                                         curl_setopt ($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'] );
01997                                 }
01998                         }
01999                         $content=curl_exec ($ch);
02000                         curl_close ($ch);
02001                         return $content;
02002                 } elseif($fd = fopen($url,'rb'))    {
02003                         while (!feof($fd))      {
02004                                 $content.=fread($fd, 5000);
02005                         }
02006                         fclose($fd);
02007                         return $content;
02008                 }
02009         }
02010 
02019         function writeFile($file,$content)      {
02020                 if($fd = fopen($file,'wb'))     {
02021                         fwrite( $fd, $content);
02022                         fclose( $fd );
02023 
02024                                 // Setting file system mode & group ownership of file:
02025                         if (@is_file($file) && TYPO3_OS!='WIN') {
02026                                 @chmod($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));             // "@" is there because file is not necessarily OWNED by the user
02027                                 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
02028                                         @chgrp($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);                // "@" is there because file is not necessarily OWNED by the user
02029                                 }
02030                         }
02031 
02032                         return true;
02033                 }
02034         }
02035 
02044         function writeFileToTypo3tempDir($filepath,$content)    {
02045 
02046                         // Parse filepath into directory and basename:
02047                 $fI = pathinfo($filepath);
02048                 $fI['dirname'].= '/';
02049 
02050                         // Check parts:
02051                 if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60)        {
02052                         if (defined('PATH_site'))       {
02053                                 $dirName = PATH_site.'typo3temp/';      // Setting main temporary directory name (standard)
02054                                 if (@is_dir($dirName))  {
02055                                         if (t3lib_div::isFirstPartOfStr($fI['dirname'],$dirName))       {
02056 
02057                                                         // Checking if the "subdir" is found:
02058                                                 $subdir = substr($fI['dirname'],strlen($dirName));
02059                                                 if ($subdir)    {
02060                                                         if (ereg('^[[:alnum:]_]+\/$',$subdir))  {
02061                                                                 $dirName.= $subdir;
02062                                                                 if (!@is_dir($dirName)) {
02063                                                                         t3lib_div::mkdir($dirName);
02064                                                                 }
02065                                                         } else return 'Subdir, "'.$subdir.'", was NOT on the form "[a-z]/"';
02066                                                 }
02067                                                         // Checking dir-name again (sub-dir might have been created):
02068                                                 if (@is_dir($dirName))  {
02069                                                         if ($filepath == $dirName.$fI['basename'])      {
02070                                                                 t3lib_div::writeFile($filepath, $content);
02071                                                                 if (!@is_file($filepath))       return 'File not written to disk! Write permission error in filesystem?';
02072                                                         } else return 'Calculated filelocation didn\'t match input $filepath!';
02073                                                 } else return '"'.$dirName.'" is not a directory!';
02074                                         } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
02075                                 } else return 'PATH_site + "typo3temp/" was not a directory!';
02076                         } else return 'PATH_site constant was NOT defined!';
02077                 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
02078         }
02079 
02087         function mkdir($theNewFolder)   {
02088                 $theNewFolder = ereg_replace('\/$','',$theNewFolder);
02089                 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
02090                         chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
02091 
02092                         if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
02093                                 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
02094                         }
02095                         return TRUE;
02096                 }
02097         }
02098 
02107         function get_dirs($path)        {
02108                 if ($path)      {
02109                         $d = @dir($path);
02110                         if (is_object($d))      {
02111                                 while($entry=$d->read()) {
02112                                         if (@is_dir($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
02113                                             $filearray[]=$entry;
02114                                         }
02115                                 }
02116                                 $d->close();
02117                         } else return 'error';
02118                         return $filearray;
02119                 }
02120         }
02121 
02132         function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')        {
02133 
02134                         // Initialize variabels:
02135                 $filearray = array();
02136                 $sortarray = array();
02137                 $path = ereg_replace('\/$','',$path);
02138 
02139                         // Find files+directories:
02140                 if (@is_dir($path))     {
02141                         $extensionList = strtolower($extensionList);
02142                         $d = dir($path);
02143                         if (is_object($d))      {
02144                                 while($entry=$d->read()) {
02145                                         if (@is_file($path.'/'.$entry)) {
02146                                                 $fI = pathinfo($entry);
02147                                                 $key = md5($path.'/'.$entry);
02148                                                 if (!$extensionList || t3lib_div::inList($extensionList,strtolower($fI['extension'])))  {
02149                                                     $filearray[$key]=($prependPath?$path.'/':'').$entry;
02150                                                         if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
02151                                                                 elseif ($order) {$sortarray[$key]=$entry;}
02152                                                 }
02153                                         }
02154                                 }
02155                                 $d->close();
02156                         } else return 'error opening path: "'.$path.'"';
02157                 }
02158 
02159                         // Sort them:
02160                 if ($order) {
02161                         asort($sortarray);
02162                         reset($sortarray);
02163                         $newArr=array();
02164                         while(list($k,$v)=each($sortarray))     {
02165                                 $newArr[$k]=$filearray[$k];
02166                         }
02167                         $filearray=$newArr;
02168                 }
02169 
02170                         // Return result
02171                 reset($filearray);
02172                 return $filearray;
02173         }
02174 
02186         function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)       {
02187                 if ($regDirs)   $fileArr[] = $path;
02188                 $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path,$extList,1,1));
02189 
02190                 $dirs = t3lib_div::get_dirs($path);
02191                 if (is_array($dirs) && $recursivityLevels>0)    {
02192                         foreach ($dirs as $subdirs)     {
02193                                 if ((string)$subdirs!='')       {
02194                                         $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
02195                                 }
02196                         }
02197                 }
02198                 return $fileArr;
02199         }
02200 
02209         function removePrefixPathFromList($fileArr,$prefixToRemove)     {
02210                 foreach($fileArr as $k => $absFileRef)  {
02211                         if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove))    {
02212                                 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
02213                         } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
02214                 }
02215                 return $fileArr;
02216         }
02217 
02225         function fixWindowsFilePath($theFile)   {
02226                 return str_replace('//','/', str_replace('\\','/', $theFile));
02227         }
02228 
02237         function resolveBackPath($pathStr)      {
02238                 $parts = explode('/',$pathStr);
02239                 $output=array();
02240                 foreach($parts as $pV)  {
02241                         if ($pV=='..')  {
02242                                 if ($c) {
02243                                         array_pop($output);
02244                                         $c--;
02245                                 } else $output[]=$pV;
02246                         } else {
02247                                 $c++;
02248                                 $output[]=$pV;
02249                         }
02250                 }
02251                 return implode('/',$output);
02252         }
02253 
02264         function locationHeaderUrl($path)       {
02265                 $uI = parse_url($path);
02266                 if (substr($path,0,1)=='/')     { // relative to HOST
02267                         $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
02268                 } elseif (!$uI['scheme'])       { // No scheme either
02269                         $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
02270                 }
02271                 return $path;
02272         }
02273 
02274 
02275 
02276 
02277 
02278 
02279 
02280 
02281 
02282 
02283 
02284 
02285 
02286 
02287 
02288 
02289         /*************************
02290          *
02291          * DEBUG helper FUNCTIONS
02292          *
02293          *************************/
02294 
02304         function debug_ordvalue($string,$characters=100)        {
02305                 if(strlen($string) < $characters)       $characters = strlen($string);
02306                 for ($i=0; $i<$characters; $i++)        {
02307                         $valuestring.=' '.ord(substr($string,$i,1));
02308                 }
02309                 return trim($valuestring);
02310         }
02311 
02321         function view_array($array_in)  {
02322                 if (is_array($array_in))        {
02323                         $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
02324                         if (!count($array_in))  {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
02325                         while (list($key,$val)=each($array_in)) {
02326                                 $result.= '<tr><td><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
02327                                 if (is_array($array_in[$key]))  {
02328                                         $result.=t3lib_div::view_array($array_in[$key]);
02329                                 } else
02330                                         $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
02331                                 $result.= '</td></tr>';
02332                         }
02333                         $result.= '</table>';
02334                 } else  {
02335                         $result  = false;
02336                 }
02337                 return $result;
02338         }
02339 
02349         function print_array($array_in) {
02350                 echo t3lib_div::view_array($array_in);
02351         }
02352 
02364         function debug($var="",$brOrHeader=0)   {
02365                 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
02366                         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>';
02367                 } elseif ($brOrHeader<0) {
02368                         for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
02369                 }
02370 
02371                 if (is_array($var))     {
02372                         t3lib_div::print_array($var);
02373                 } elseif (is_object($var))      {
02374                         echo '<b>|Object:<pre>';
02375                         print_r($var);
02376                         echo '</pre>|</b>';
02377                 } elseif ((string)$var!='') {
02378                         echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
02379                 } else {
02380                         echo '<b>| debug |</b>';
02381                 }
02382 
02383                 if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
02384                         echo '</td></tr></table>';
02385                 } elseif ($brOrHeader>0) {
02386                         for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
02387                 }
02388         }
02389 
02390 
02391 
02392 
02393 
02394 
02395 
02396 
02397 
02398 
02399 
02400 
02401 
02402 
02403 
02404 
02405 
02406 
02407 
02408 
02409 
02410 
02411 
02412 
02413 
02414 
02415 
02416 
02417 
02418 
02419 
02420 
02421         /*************************
02422          *
02423          * SYSTEM INFORMATION
02424          *
02425          *************************/
02426 
02433         function getThisUrl()   {
02434                 $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'));            // Url of this script
02435                 $dir=t3lib_div::dirname($p['path']).'/';        // Strip file
02436                 $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
02437                 return $url;
02438         }
02439 
02449         function linkThisScript($getParams=array())     {
02450                 $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
02451                 $params = t3lib_div::_GET();
02452 
02453                 foreach($getParams as $k => $v) {
02454                         if (strcmp($v,''))      {
02455                                 $params[$k]=$v;
02456                         } else unset($params[$k]);
02457                 }
02458 
02459                 $pString = t3lib_div::implodeArrayForUrl('',$params);
02460 
02461                 return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
02462         }
02463 
02473         function linkThisUrl($url,$getParams=array())   {
02474                 $parts = parse_url($url);
02475                 if ($parts['query'])    {
02476                         parse_str($parts['query'],$getP);
02477                 } else {
02478                         $getP = array();
02479                 }
02480 
02481                 $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
02482                 $uP = explode('?',$url);
02483 
02484                 $params = t3lib_div::implodeArrayForUrl('',$getP);
02485                 $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
02486 
02487                 return $outurl;
02488         }
02489 
02498         function getIndpEnv($getEnvName)        {
02499                 /*
02500                         Conventions:
02501                         output from parse_url():
02502                         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
02503                             [scheme] => 'http'
02504                             [user] => 'username'
02505                             [pass] => 'password'
02506                             [host] => '192.168.1.4'
02507                                 [port] => '8080'
02508                             [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
02509                             [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
02510                             [fragment] => 'link1'
02511 
02512                                 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
02513                                                                         [path_dir] = '/typo3/32/temp/phpcheck/'
02514                                                                         [path_info] = '/arg1/arg2/arg3/'
02515                                                                         [path] = [path_script/path_dir][path_info]
02516 
02517 
02518                         Keys supported:
02519 
02520                         URI______:
02521                                 REQUEST_URI             =       [path]?[query]          = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
02522                                 HTTP_HOST               =       [host][:[port]]         = 192.168.1.4:8080
02523                                 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')!
02524                                 PATH_INFO               =       [path_info]                     = /arg1/arg2/arg3/
02525                                 QUERY_STRING    =       [query]                         = arg1,arg2,arg3&p1=parameter1&p2[key]=value
02526                                 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
02527                                                                                 (Notice: NO username/password + NO fragment)
02528 
02529                         CLIENT____:
02530                                 REMOTE_ADDR             =       (client IP)
02531                                 REMOTE_HOST             =       (client host)
02532                                 HTTP_USER_AGENT =       (client user agent)
02533                                 HTTP_ACCEPT_LANGUAGE    = (client accept language)
02534 
02535                         SERVER____:
02536                                 SCRIPT_FILENAME =       Absolute filename of script             (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
02537 
02538                         Special extras:
02539                                 TYPO3_HOST_ONLY =               [host]                  = 192.168.1.4
02540                                 TYPO3_PORT              =               [port]                  = 8080 (blank if 80, taken from host value)
02541                                 TYPO3_REQUEST_HOST =    [scheme]://[host][:[port]]
02542                                 TYPO3_REQUEST_URL =             [scheme]://[host][:[port]][path]?[query]        (sheme will by default be 'http' until we can detect if it's https -
02543                                 TYPO3_REQUEST_SCRIPT =  [scheme]://[host][:[port]][path_script]
02544                                 TYPO3_REQUEST_DIR =             [scheme]://[host][:[port]][path_dir]
02545                                 TYPO3_SITE_URL =                [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
02546                                 TYPO3_SITE_SCRIPT =     [script / Speaking URL] of the TYPO3 website
02547                                 TYPO3_DOCUMENT_ROOT     =       Absolute path of root of documents:     TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
02548 
02549                         Notice: [fragment] is apparently NEVER available to the script!
02550 
02551 
02552                         Testing suggestions:
02553                         - Output all the values.
02554                         - 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
02555                         - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
02556 
02557                 */
02558 
02559 #               if ($getEnvName=='HTTP_REFERER')        return '';
02560                 switch((string)$getEnvName)     {
02561                         case 'SCRIPT_NAME':
02562                                 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']);
02563                         break;
02564                         case 'SCRIPT_FILENAME':
02565                                 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'])));
02566                         break;
02567                         case 'REQUEST_URI':
02568                                 // Typical application of REQUEST_URI is return urls, forms submitting to itselt etc. Eg:       returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
02569                                 if (!$_SERVER['REQUEST_URI'])   {       // This is for ISS/CGI which does not have the REQUEST_URI available.
02570                                         return '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
02571                                                 ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
02572                                 } else return $_SERVER['REQUEST_URI'];
02573                         break;
02574                         case 'PATH_INFO':
02575                                         // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
02576                                         // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
02577                                         // 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)
02578 //                              if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1)  {
02579                                 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi')        {
02580                                         return $_SERVER['PATH_INFO'];
02581                                 } else return '';
02582                         break;
02583                                 // These are let through without modification
02584                         case 'REMOTE_ADDR':
02585                         case 'REMOTE_HOST':
02586                         case 'HTTP_REFERER':
02587                         case 'HTTP_HOST':
02588                         case 'HTTP_USER_AGENT':
02589                         case 'HTTP_ACCEPT_LANGUAGE':
02590                         case 'QUERY_STRING':
02591                                 return $_SERVER[$getEnvName];
02592                         break;
02593                         case 'TYPO3_DOCUMENT_ROOT':
02594                                 // 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.
02595                                 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
02596                                 $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
02597                                 $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
02598                                 $SFN_A = explode('/',strrev($SFN));
02599                                 $acc = array();
02600                                 while(list($kk,$vv)=each($SN_A))        {
02601                                         if (!strcmp($SFN_A[$kk],$vv))   {
02602                                                 $acc[] = $vv;
02603                                         } else break;
02604                                 }
02605                                 $commonEnd=strrev(implode('/',$acc));
02606                                 if (strcmp($commonEnd,''))              $DR = substr($SFN,0,-(strlen($commonEnd)+1));
02607                                 return $DR;
02608                         break;
02609                         case 'TYPO3_HOST_ONLY':
02610                                 $p = explode(':',$_SERVER['HTTP_HOST']);
02611                                 return $p[0];
02612                         break;
02613                         case 'TYPO3_PORT':
02614                                 $p = explode(':',$_SERVER['HTTP_HOST']);
02615                                 return $p[1];
02616                         break;
02617                         case 'TYPO3_REQUEST_HOST':
02618                                 return (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
02619                                         $_SERVER['HTTP_HOST'];
02620                         break;
02621                         case 'TYPO3_REQUEST_URL':
02622                                 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
02623                         break;
02624                         case 'TYPO3_REQUEST_SCRIPT':
02625                                 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
02626                         break;
02627                         case 'TYPO3_REQUEST_DIR':
02628                                 return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
02629                         break;
02630                         case 'TYPO3_SITE_URL':
02631                                 if (defined('PATH_thisScript') && defined('PATH_site')) {
02632                                         $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
02633                                         $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
02634                                         $siteUrl = substr($url,0,-strlen($lPath));
02635                                         if (substr($siteUrl,-1)!='/')   $siteUrl.='/';
02636                                         return $siteUrl;
02637                                 } else return '';
02638                         break;
02639                         case 'TYPO3_SITE_SCRIPT':
02640                                 return substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
02641                         break;
02642                         case 'TYPO3_SSL':
02643                                 return $_SERVER['SSL_SESSION_ID'] || !strcmp($_SERVER['HTTPS'],'on') ? TRUE : FALSE;
02644                         break;
02645                         case '_ARRAY':
02646                                 $out = array();
02647                                         // Here, list ALL possible keys to this function for debug display.
02648                                 $envTestVars = t3lib_div::trimExplode(',','
02649                                         HTTP_HOST,
02650                                         TYPO3_HOST_ONLY,
02651                                         TYPO3_PORT,
02652                                         PATH_INFO,
02653                                         QUERY_STRING,
02654                                         REQUEST_URI,
02655                                         HTTP_REFERER,
02656                                         TYPO3_REQUEST_HOST,
02657                                         TYPO3_REQUEST_URL,
02658                                         TYPO3_REQUEST_SCRIPT,
02659                                         TYPO3_REQUEST_DIR,
02660                                         TYPO3_SITE_URL,
02661                                         TYPO3_SITE_SCRIPT,
02662                                         TYPO3_SSL,
02663                                         SCRIPT_NAME,
02664                                         TYPO3_DOCUMENT_ROOT,
02665                                         SCRIPT_FILENAME,
02666                                         REMOTE_ADDR,
02667                                         REMOTE_HOST,
02668                                         HTTP_USER_AGENT,
02669                                         HTTP_ACCEPT_LANGUAGE',1);
02670                                 reset($envTestVars);
02671                                 while(list(,$v)=each($envTestVars))     {
02672                                         $out[$v]=t3lib_div::getIndpEnv($v);
02673                                 }
02674                                 reset($out);
02675                                 return $out;
02676                         break;
02677                 }
02678         }
02679 
02687         function milliseconds() {
02688                 $p=explode(' ',microtime());
02689                 return round(($p[0]+$p[1])*1000);
02690         }
02691 
02699         function clientInfo($useragent='')      {
02700                 if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
02701 
02702                 $bInfo=array();
02703                         // Which browser?
02704                 if (strstr($useragent,'Konqueror'))     {
02705                         $bInfo['BROWSER']= 'konqu';
02706                 } elseif (strstr($useragent,'Opera'))   {
02707                         $bInfo['BROWSER']= 'opera';
02708                 } elseif (strstr($useragent,'MSIE 4') || strstr($useragent,'MSIE 5') || strstr($useragent,'MSIE 6'))    {
02709                         $bInfo['BROWSER']= 'msie';
02710                 } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5'))     {
02711                         $bInfo['BROWSER']='net';
02712                 }
02713                 if ($bInfo['BROWSER'])  {
02714                                 // Browser version
02715                         switch($bInfo['BROWSER'])       {
02716                                 case 'net':
02717                                         $bInfo['VERSION']= doubleval(substr($useragent,8));
02718                                         if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
02719                                         if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
02720                                 break;
02721                                 case 'msie':
02722                                         $tmp = strstr($useragent,'MSIE');
02723                                         $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
02724                                 break;
02725                                 case 'opera':
02726                                         $tmp = strstr($useragent,'Opera');
02727                                         $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
02728                                 break;
02729                                 case 'konqu':
02730                                         $tmp = strstr($useragent,'Konqueror/');
02731                                         $bInfo['VERSION'] = doubleval(substr($tmp,10));
02732                                 break;
02733                         }
02734                                 // Client system
02735                         if (strstr($useragent,'Win'))   {
02736                                 $bInfo['SYSTEM'] = 'win';
02737                         } elseif (strstr($useragent,'Mac'))     {
02738                                 $bInfo['SYSTEM'] = 'mac';
02739                         } elseif (strstr($useragent,'Linux') || strstr($useragent,'X11') || strstr($useragent,'SGI') || strstr($useragent,' SunOS ') || strstr($useragent,' HP-UX '))   {
02740                                 $bInfo['SYSTEM'] = 'unix';
02741                         }
02742                 }
02743                         // Is true if the browser supports css to format forms, especially the width
02744                 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
02745 
02746                 return $bInfo;
02747         }
02748 
02749 
02750 
02751 
02752 
02753 
02754 
02755 
02756 
02757 
02758 
02759 
02760 
02761 
02762 
02763 
02764 
02765 
02766 
02767 
02768 
02769 
02770 
02771         /*************************
02772          *
02773          * TYPO3 SPECIFIC FUNCTIONS
02774          *
02775          *************************/
02776 
02786         function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)    {
02787                 if (!strcmp($filename,''))              return '';
02788 
02789                 if ($relToTYPO3_mainDir)        {
02790                         if (!defined('PATH_typo3'))     return '';
02791                         $relPathPrefix = PATH_typo3;
02792                 } else {
02793                         $relPathPrefix = PATH_site;
02794                 }
02795                 if (substr($filename,0,4)=='EXT:')      {       // extension
02796                         list($extKey,$local) = explode('/',substr($filename,4),2);
02797                         $filename='';
02798                         if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
02799                                 $filename = t3lib_extMgm::extPath($extKey).$local;
02800                         }
02801                 } elseif (!t3lib_div::isAbsPath($filename))     {       // relative. Prepended with $relPathPrefix
02802                         $filename=$relPathPrefix.$filename;
02803                 } elseif ($onlyRelative && !t3lib_div::isFirstPartOfStr($filename,$relPathPrefix)) {    // absolute, but set to blank if not allowed
02804                         $filename='';
02805                 }
02806                 if (strcmp($filename,'') && t3lib_div::validPathStr($filename)) {       // checks backpath.
02807                         return $filename;
02808                 }
02809         }
02810 
02822         function validPathStr($theFile) {
02823                 if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
02824         }
02825 
02833         function isAbsPath($path)       {
02834                 return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' :  substr($path,0,1)=='/';
02835         }
02836 
02844         function isAllowedAbsPath($path)        {
02845                 if (t3lib_div::isAbsPath($path) &&
02846                         t3lib_div::validPathStr($path) &&
02847                                 (       t3lib_div::isFirstPartOfStr($path,PATH_site)
02848                                         ||
02849                                         ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
02850                                 )
02851                         )       return true;
02852         }
02853 
02861         function verifyFilenameAgainstDenyPattern($filename)    {
02862                 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],''))    {
02863                         $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
02864                         if ($result)    return false;   // so if a matching filename is found, return false;
02865                 }
02866                 return true;
02867         }
02868 
02879         function upload_copy_move($source,$destination) {
02880                 if (is_uploaded_file($source))  {
02881                         $uploaded = TRUE;
02882                         // 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:
02883                         $uploadedResult = move_uploaded_file($source, $destination);
02884                 } else {
02885                         $uploaded = FALSE;
02886                         @copy($source,$destination);
02887                 }
02888 
02889                         // Setting file system mode & group ownership of file:
02890                 if (@is_file($destination) && TYPO3_OS!='WIN')  {
02891                         chmod($destination, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
02892                         if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
02893                                 chgrp($destination, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
02894                         }
02895                 }
02896 
02897                         // 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
02898                 return $uploaded ? $uploadedResult : FALSE;
02899         }
02900 
02911         function upload_to_tempfile($uploadedFileName)  {
02912                 if (is_uploaded_file($uploadedFileName))        {
02913                         $tempFile = t3lib_div::tempnam('upload_temp_');
02914                         move_uploaded_file($uploadedFileName, $tempFile);
02915                         return @is_file($tempFile) ? $tempFile : '';
02916                 }
02917         }
02918 
02929         function unlink_tempfile($uploadedTempFileName) {
02930                 if ($uploadedTempFileName && t3lib_div::validPathStr($uploadedTempFileName) && t3lib_div::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName))    {
02931                         if (unlink($uploadedTempFileName))      return TRUE;
02932                 }
02933         }
02934 
02945         function tempnam($filePrefix)   {
02946                 return tempnam(PATH_site.'typo3temp/',$filePrefix);
02947         }
02948 
02958         function stdAuthCode($uid_or_record,$fields='') {
02959                 if (is_array($uid_or_record))   {
02960                         $recCopy_temp=array();
02961                         if ($fields)    {
02962                                 $fieldArr = t3lib_div::trimExplode(',',$fields,1);
02963                                 reset($fieldArr);
02964                                 while(list($k,$v)=each($fieldArr))      {
02965                                         $recCopy_temp[$k]=$recCopy[$v];
02966                                 }
02967                         } else {
02968                                 $recCopy_temp=$recCopy;
02969                         }
02970                         $preKey = implode('|',$recCopy_temp);
02971                 } else {
02972                         $preKey = $uid_or_record;
02973                 }
02974 
02975                 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
02976                 $authCode = substr(md5($authCode),0,8);
02977                 return $authCode;
02978         }
02979 
02992         function loadTCA($table)        {
02993                 global $TCA,$LANG_GENERAL_LABELS;
02994                 if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile'])     {
02995                         if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:'))    {
02996                                 include(PATH_t3lib.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
02997                         } elseif (t3lib_div::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file($TCA[$table]['ctrl']['dynamicConfigFile']))       {       // Absolute path...
02998                                 include($TCA[$table]['ctrl']['dynamicConfigFile']);
02999                         } else include(PATH_typo3conf.$TCA[$table]['ctrl']['dynamicConfigFile']);
03000                 }
03001         }
03002 
03012         function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')    {
03013                 if (is_array($dataStructArray['sheets']))       {
03014                         $singleSheet = FALSE;
03015                         if (!isset($dataStructArray['sheets'][$sheet])) {
03016                                 $sheet='sDEF';
03017                         }
03018                         $dataStruct =  $dataStructArray['sheets'][$sheet];
03019 
03020                                 // If not an array, but still set, then regard it as a relative reference to a file:
03021                         if ($dataStruct && !is_array($dataStruct))      {
03022                                 $file = t3lib_div::getFileAbsFileName($dataStruct);
03023                                 if ($file && @is_file($file))   {
03024                                         $dataStruct = t3lib_div::xml2array(t3lib_div::getUrl($file));
03025                                 }
03026                         }
03027                 } else {
03028                         $singleSheet = TRUE;
03029                         $dataStruct = $dataStructArray;
03030                         $sheet = 'sDEF';        // Default sheet
03031                 }
03032                 return array($dataStruct,$sheet,$singleSheet);
03033         }
03034 
03042         function resolveAllSheetsInDS($dataStructArray) {
03043                 if (is_array($dataStructArray['sheets']))       {
03044                         $out=array('sheets'=>array());
03045                         foreach($dataStructArray['sheets'] as $sheetId => $sDat)        {
03046                                 list($ds,$aS) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sheetId);
03047                                 if ($sheetId==$aS)      {
03048                                         $out['sheets'][$aS]=$ds;
03049                                 }
03050                         }
03051                 } else {
03052                         list($ds) = t3lib_div::resolveSheetDefInDS($dataStructArray);
03053                         $out = array('sheets' => array('sDEF' => $ds));
03054                 }
03055                 return $out;
03056         }
03057 
03071         function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)      {
03072                 global $TYPO3_CONF_VARS;
03073 
03074                         // Check persistent object and if found, call directly and exit.
03075                 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName]))        {
03076                         return call_user_method(
03077                                                 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method'],
03078                                                 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
03079                                                 $params,
03080                                                 $ref
03081                                         );
03082                 }
03083 
03084                         // Check file-reference prefix; if found, require_once() the file (should be library of code)
03085                 if (strstr($funcName,':'))      {
03086                         list($file,$funcRef) = t3lib_div::revExplode(':',$funcName,2);
03087                         $requireFile = t3lib_div::getFileAbsFileName($file);
03088                         if ($requireFile) require_once($requireFile);
03089                 } else {
03090                         $funcRef = $funcName;
03091                 }
03092 
03093                         // Check for persistent object token, "&"
03094                 if (substr($funcRef,0,1)=='&')  {
03095                         $funcRef = substr($funcRef,1);
03096                         $storePersistentObject = TRUE;
03097                 } else {
03098                         $storePersistentObject = FALSE;
03099                 }
03100 
03101                         // Check prefix is valid:
03102                 if ($checkPrefix &&
03103                         !t3lib_div::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
03104                         !t3lib_div::isFirstPartOfStr(trim($funcRef),'tx_')
03105                         )       {
03106                         if (!$silent)   debug("Function/Class '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
03107                         return FALSE;
03108                 }
03109 
03110                         // Call function or method:
03111                 $parts = explode('->',$funcRef);
03112                 if (count($parts)==2)   {       // Class
03113 
03114                                 // Check if class/method exists:
03115                         if (class_exists($parts[0]))    {
03116 
03117                                         // Get/Create object of class:
03118                                 if ($storePersistentObject)     {       // Get reference to current instance of class:
03119                                         if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]]))    {
03120                                                 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = &t3lib_div::makeInstance($parts[0]);
03121                                         }
03122                                         $classObj = &$GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
03123                                 } else {        // Create new object:
03124                                         $classObj = &t3lib_div::makeInstance($parts[0]);
03125                                 }
03126 
03127                                 if (method_exists($classObj, $parts[1]))        {
03128 
03129                                                 // If persistent object should be created, set reference:
03130                                         if ($storePersistentObject)     {
03131                                                 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
03132                                                         'method' => $parts[1],
03133                                                         'obj' => &$classObj
03134                                                 );
03135                                         }
03136                                                 // Call method:
03137                                         $content = call_user_method(
03138                                                 $parts[1],
03139                                                 $classObj,
03140                                                 $params,
03141                                                 $ref
03142                                         );
03143                                 } else {
03144                                         if (!$silent)   debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
03145                                 }
03146                         } else {
03147                                 if (!$silent)   debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
03148                         }
03149                 } else {        // Function
03150                         if (function_exists($funcRef))  {
03151                                 $content = call_user_func($funcRef, $params, $ref);
03152                         } else {
03153                                 if (!$silent)   debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
03154                         }
03155                 }
03156                 return $content;
03157         }
03158 
03170         function &getUserObj($classRef,$checkPrefix='user_',$silent=0)  {
03171                 global $TYPO3_CONF_VARS;
03172                         // Check persistent object and if found, call directly and exit.
03173                 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef]))     {
03174                         return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
03175                 } else {
03176 
03177                                 // Check file-reference prefix; if found, require_once() the file (should be library of code)
03178                         if (strstr($classRef,':'))      {
03179                                 list($file,$class) = t3lib_div::revExplode(':',$classRef,2);
03180                                 $requireFile = t3lib_div::getFileAbsFileName($file);
03181                                 if ($requireFile)       require_once($requireFile);
03182                         } else {
03183                                 $class = $classRef;
03184                         }
03185 
03186                                 // Check for persistent object token, "&"
03187                         if (substr($class,0,1)=='&')    {
03188                                 $class = substr($class,1);
03189                                 $storePersistentObject = TRUE;
03190                         } else {
03191                                 $storePersistentObject = FALSE;
03192                         }
03193 
03194                                 // Check prefix is valid:
03195                         if ($checkPrefix &&
03196                                 !t3lib_div::isFirstPartOfStr(trim($class),$checkPrefix) &&
03197                                 !t3lib_div::isFirstPartOfStr(trim($class),'tx_')
03198                                 )       {
03199                                 if (!$silent)   debug("Class '".$class."' was not prepended with '".$checkPrefix."'",1);
03200                                 return FALSE;
03201                         }
03202 
03203                                 // Check if class exists:
03204                         if (class_exists($class))       {
03205                                 $classObj = &t3lib_div::makeInstance($class);
03206 
03207                                         // If persistent object should be created, set reference:
03208                                 if ($storePersistentObject)     {
03209                                         $GLOBALS['T3_VAR']['getUserObj'][$classRef] = &$classObj;
03210                                 }
03211 
03212                                 return $classObj;
03213                         } else {
03214                                 if (!$silent)   debug("<strong>ERROR:</strong> No class named: ".$class,1);
03215                         }
03216                 }
03217         }
03218 
03228         function &makeInstance($className)      {
03229                 return class_exists('ux_'.$className) ? t3lib_div::makeInstance('ux_'.$className) : new $className;
03230         }
03231 
03240         function makeInstanceClassName($className)      {
03241                 return class_exists('ux_'.$className) ? t3lib_div::makeInstanceClassName('ux_'.$className) : $className;
03242         }
03243 
03254         function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())    {
03255                 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
03256 
03257                 $error = FALSE;
03258 
03259                 if (!is_array($excludeServiceKeys) ) {
03260                         $excludeServiceKeys = t3lib_div::trimExplode(',', $excludeServiceKeys, 1);
03261                 }
03262                 while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys))   {
03263 
03264                                 // Check persistent object and if found, call directly and exit.
03265                         if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']]))   {
03266                                         // reset service and return object
03267                                 $T3_VAR['makeInstanceService'][$info['className']]->reset();
03268                                 return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
03269 
03270                                 // include file and create object
03271                         } elseif (@is_file($info['classFile'])) {
03272                                 require_once ($info['classFile']);
03273                                 $obj = t3lib_div::makeInstance($info['className']);
03274                                 if (is_object($obj)) {
03275                                         if(!@is_callable(array($obj,'init')))   {
03276                                                         // use silent logging??? I don't think so.
03277                                                 die ('Broken service:'.t3lib_div::view_array($info));
03278                                         }
03279                                         $obj->info = $info;
03280                                         if ($obj->init()) { // service available?
03281 
03282                                                         // create persistent object
03283                                                 $T3_VAR['makeInstanceService'][$info['className']] = &$obj;
03284 
03285                                                         // needed to delete temp files
03286                                                 register_shutdown_function(array(&$obj, '__destruct'));
03287 
03288                                                 return $obj; // object is passed as reference by funtion definition
03289                                         }
03290                                         $error = $obj->getLastErrorArray();
03291                                         unset($obj);
03292                                 }
03293                         }
03294                                 // deactivate the service
03295                         t3lib_extMgm::deactivateService($info['serviceType'],$info['serviceKey']);
03296                 }
03297                 return $error;
03298         }
03299 
03315         function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0)      {
03316                 switch((string)$enc)    {
03317                         case 'base64':
03318                                 $headers=trim($headers).chr(10).
03319                                 'Mime-Version: 1.0'.chr(10).
03320                                 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
03321                                 'Content-Transfer-Encoding: base64';
03322 
03323                                 $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.
03324 
03325                                 if (!$dontEncodeSubject)        $subject='=?'.$charset.'?B?'.base64_encode($subject).'?=';
03326                         break;
03327                         case 'quoted-printable':
03328                                 $headers=trim($headers).chr(10).
03329                                 'Mime-Version: 1.0'.chr(10).
03330                                 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
03331                                 'Content-Transfer-Encoding: quoted-printable';
03332 
03333                                 $message=t3lib_div::quoted_printable($message);
03334 
03335                                 if (!$dontEncodeSubject)        $subject='=?'.$charset.'?Q?'.trim(t3lib_div::quoted_printable(ereg_replace('[[:space:]]','_',$subject),1000)).'?=';
03336                         break;
03337                         case '8bit':
03338                                 $headers=trim($headers).chr(10).
03339                                 'Mime-Version: 1.0'.chr(10).
03340                                 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
03341                                 'Content-Transfer-Encoding: 8bit';
03342                         break;
03343                 }
03344                 $headers=trim(implode(chr(10),t3lib_div::trimExplode(chr(10),$headers,1)));     // make sure no empty lines are there.
03345 
03346                 mail($email,$subject,$message,$headers);
03347         }
03348 
03360         function quoted_printable($string,$maxlen=76)   {
03361                 $newString = '';
03362                 $theLines = explode(chr(10),$string);   // Break lines. Doesn't work with mac eol's which seems to be 13. But 13-10 or 10 will work
03363                 while (list(,$val)=each($theLines))     {
03364                         $val = ereg_replace(chr(13).'$','',$val);               // removes possible character 13 at the end of line
03365 
03366                         $newVal = '';
03367                         $theValLen = strlen($val);
03368                         $len = 0;
03369                         for ($index=0;$index<$theValLen;$index++)       {
03370                                 $char = substr($val,$index,1);
03371                                 $ordVal =Ord($char);
03372                                 if ($len>($maxlen-4) || ($len>(($maxlen-10)-4)&&$ordVal==32))   {
03373                                         $len=0;
03374                                         $newVal.='='.chr(13).chr(10);
03375                                 }
03376                                 if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
03377                                         $newVal.=$char;
03378                                         $len++;
03379                                 } else {
03380                                         $newVal.=sprintf('=%02X',$ordVal);
03381                                         $len+=3;
03382                                 }
03383                         }
03384                         $newVal = ereg_replace(chr(32).'$','=20',$newVal);              // replaces a possible SPACE-character at the end of a line
03385                         $newVal = ereg_replace(chr(9).'$','=09',$newVal);               // replaces a possible TAB-character at the end of a line
03386                         $newString.=$newVal.chr(13).chr(10);
03387                 }
03388                 return ereg_replace(chr(13).chr(10).'$','',$newString);
03389         }
03390 
03402         function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')      {
03403                         // Substitute URLs with shorter links:
03404                 $urlSplit=explode('http://',$message);
03405                 reset($urlSplit);
03406                 while(list($c,$v)=each($urlSplit))      {
03407                         if ($c) {
03408                                 $newParts = split('[[:space:]]|\)|\(',$v,2);
03409                                 $newURL='http://'.$newParts[0];
03410                                         switch((string)$urlmode)        {
03411                                                 case 'all':
03412                                                         $newURL=t3lib_div::makeRedirectUrl($newURL,0,$index_script_url);
03413                                                 break;
03414                                                 case '76':
03415                                                         $newURL=t3lib_div::makeRedirectUrl($newURL,76,$index_script_url);
03416                                                 break;
03417                                         }
03418                                 $urlSplit[$c]=$newURL.substr($v,strlen($newParts[0]));
03419                         }
03420                 }
03421 
03422                 $message=implode('',$urlSplit);
03423                 return $message;
03424         }
03425 
03436         function makeRedirectUrl($inUrl,$l=0,$index_script_url='')      {
03437                 if (strlen($inUrl)>$l)  {
03438                         $md5 = substr(md5($inUrl),0,20);
03439                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_md5params', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr($md5, 'cache_md5params').'"');
03440                         if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res))  {
03441                                 $insertFields = array(
03442                                         'md5hash' => $md5,
03443                                         'tstamp' => time(),
03444                                         'type' => 2,
03445                                         'params' => $inUrl
03446                                 );
03447 
03448                                 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
03449                         }
03450                         $inUrl=($index_script_url ? $index_script_url : t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR')).
03451                                 '?RDCT='.$md5;
03452                 }
03453                 return $inUrl;
03454         }
03455 
03463         function freetypeDpiComp($font_size)    {
03464                 $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
03465                 if ($dpi!=72)   $font_size = $font_size/$dpi*72;
03466                 return $font_size;
03467         }
03468 
03482         function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)     {
03483                 global $TYPO3_CONF_VARS;
03484 
03485                 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog']))    {
03486                         $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
03487                         $fakeThis = FALSE;
03488                         foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod)   {
03489                                 t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
03490                         }
03491                 }
03492         }
03493 
03503         function arrayToLogString($arr, $valueList=array(), $valueLength=20) {
03504                 $str = '';
03505                 if(is_array($arr)) {
03506                         if (!is_array($valueList)) {
03507                                 $valueList = explode(',', $valueList);
03508                         }
03509                         foreach($arr as $key => $value) {
03510                                 if (!count($valueList) OR (count($valueList) AND in_array($key, $valueList))) {
03511                                         $str .= (string)$key.trim(': '.t3lib_div::fixed_lgd(str_replace("\n",'|',(string)$value), $valueLength)).'; ';
03512                                 }
03513                         }
03514                 }
03515                 return $str;
03516         }
03517 }
03518 
03519 ?>


Généré par TYPO3 Ameos avec  doxygen 1.4.6