class.t3lib_div.php

Go to the documentation of this file.
00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 1999-2006 Kasper Skaarhoj (kasperYYYY@typo3.com)
00006 *  All rights reserved
00007 *
00008 *  This script is part of the TYPO3 project. The TYPO3 project is
00009 *  free software; you can redistribute it and/or modify
00010 *  it under the terms of the GNU General Public License as published by
00011 *  the Free Software Foundation; either version 2 of the License, or
00012 *  (at your option) any later version.
00013 *
00014 *  The GNU General Public License can be found at
00015 *  http://www.gnu.org/copyleft/gpl.html.
00016 *  A copy is found in the textfile GPL.txt and important notices to the license
00017 *  from the author is found in LICENSE.txt distributed with these scripts.
00018 *
00019 *
00020 *  This script is distributed in the hope that it will be useful,
00021 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023 *  GNU General Public License for more details.
00024 *
00025 *  This copyright notice MUST APPEAR in all copies of the script!
00026 ***************************************************************/
00232 class t3lib_div {
00233 
00234 
00235 
00236 
00237 
00238         /*************************
00239          *
00240          * GET/POST Variables
00241          *
00242          * Background:
00243          * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
00244          * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
00245          * But the clean solution is that quotes are never escaped and that is what the functions below offers.
00246          * Eventually TYPO3 should provide this in the global space as well.
00247          * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
00248          *
00249          *************************/
00250 
00262         function _GP($var)      {
00263                 if(empty($var)) return;
00264                 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00265                 if (isset($value))      {
00266                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00267                 }
00268                 return $value;
00269         }
00270 
00280         function _GET($var=NULL)        {
00281                 $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
00282                 if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
00283                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00284                 }
00285                 return $value;
00286         }
00287 
00297         function _POST($var=NULL)       {
00298                 $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
00299                 if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
00300                         if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
00301                 }
00302                 return $value;
00303         }
00304 
00313         function _GETset($inputGet,$key='')     {
00314                         // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
00315                 if (strcmp($key,''))    {
00316                         if (is_array($inputGet))        { t3lib_div::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); }
00317                         $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
00318                 } elseif (is_array($inputGet)){
00319                         t3lib_div::addSlashesOnArray($inputGet);
00320                         $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
00321                 }
00322         }
00323 
00336         function GPvar($var,$strip=0)   {
00337                 if(empty($var)) return;
00338                 $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
00339                 if (isset($value) && is_string($value)) { $value = stripslashes($value); }      // Originally check '&& get_magic_quotes_gpc() ' but the values of $_GET are always slashed regardless of get_magic_quotes_gpc() because HTTP_POST/GET_VARS are run through addSlashesOnArray in the very beginning of index_ts.php eg.
00340                 if ($strip && isset($value) && is_array($value)) { t3lib_div::stripSlashesOnArray($value); }
00341                 return $value;
00342         }
00343 
00353         function GParrayMerged($var)    {
00354                 $postA = is_array($_POST[$var]) ? $_POST[$var] : array();
00355                 $getA = is_array($_GET[$var]) ? $_GET[$var] : array();
00356                 $mergedA = t3lib_div::array_merge_recursive_overrule($getA,$postA);
00357                 t3lib_div::stripSlashesOnArray($mergedA);
00358                 return $mergedA;
00359         }
00360 
00361 
00362 
00363 
00364 
00365 
00366 
00367 
00368 
00369 
00370         /*************************
00371          *
00372          * IMAGE FUNCTIONS
00373          *
00374          *************************/
00375 
00376 
00397         function gif_compress($theFile, $type)  {
00398                 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
00399                 $returnCode='';
00400                 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif')      {       // GIF...
00401                         if (($type=='IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw'])       {       // IM
00402                                 $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
00403                                 exec($cmd);
00404 
00405                                 $returnCode='IM';
00406                         } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png'])       {       // GD
00407                                 $tempImage = imageCreateFromGif($theFile);
00408                                 imageGif($tempImage, $theFile);
00409                                 imageDestroy($tempImage);
00410                                 $returnCode='GD';
00411                         }
00412                 }
00413                 return $returnCode;
00414         }
00415 
00425         function png_to_gif_by_imagemagick($theFile)    {
00426                 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
00427                         && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
00428                         && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
00429                         && strtolower(substr($theFile,-4,4))=='.png'
00430                         && @is_file($theFile))  {       // IM
00431                                 $newFile = substr($theFile,0,-4).'.gif';
00432                                 $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
00433                                 exec($cmd);
00434                                 $theFile = $newFile;
00435                                         // unlink old file?? May be bad idea bacause TYPO3 would then recreate the file every time as TYPO3 thinks the file is not generated because it's missing!! So do not unlink $theFile here!!
00436                 }
00437                 return $theFile;
00438         }
00439 
00450         function read_png_gif($theFile,$output_png=0)   {
00451                 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile))     {
00452                         $ext = strtolower(substr($theFile,-4,4));
00453                         if (
00454                                         ((string)$ext=='.png' && $output_png)   ||
00455                                         ((string)$ext=='.gif' && !$output_png)
00456                                 )       {
00457                                 return $theFile;
00458                         } else {
00459                                 $newFile = PATH_site.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?'.png':'.gif');
00460                                 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'].'convert "'.$theFile.'" "'.$newFile.'"');
00461                                 if (@is_file($newFile)) return $newFile;
00462                         }
00463                 }
00464         }
00465 
00466 
00467 
00468 
00469 
00470 
00471 
00472 
00473 
00474 
00475 
00476 
00477 
00478 
00479 
00480         /*************************
00481          *
00482          * STRING FUNCTIONS
00483          *
00484          *************************/
00485 
00499         function fixed_lgd($string,$origChars,$preStr='...')    {
00500                 $chars = abs($origChars);
00501                 if ($chars >= 4)        {
00502                         if(strlen($string)>$chars)  {
00503                                 return $origChars < 0 ?
00504                                         $preStr.trim(substr($string, -($chars-3))) :
00505                                         trim(substr($string, 0, $chars-3)).$preStr;
00506                         }
00507                 }
00508                 return $string;
00509         }
00510 
00524         function fixed_lgd_pre($string,$chars)  {
00525                 return strrev(t3lib_div::fixed_lgd(strrev($string),$chars));
00526         }
00527 
00538         function fixed_lgd_cs($string,$chars)   {
00539                 if (is_object($GLOBALS['LANG']))        {
00540                         return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet,$string,$chars,'...');
00541                 } else {
00542                         return t3lib_div::fixed_lgd($string, $chars);
00543                 }
00544         }
00545 
00555         function breakTextForEmail($str,$implChar="\n",$charWidth=76)   {
00556                 $lines = explode(chr(10),$str);
00557                 $outArr=array();
00558                 while(list(,$lStr)=each($lines))        {
00559                         $outArr = array_merge($outArr,t3lib_div::breakLinesForEmail($lStr,$implChar,$charWidth));
00560                 }
00561                 return implode(chr(10),$outArr);
00562         }
00563 
00574         function breakLinesForEmail($str,$implChar="\n",$charWidth=76)  {
00575                 $lines=array();
00576                 $l=$charWidth;
00577                 $p=0;
00578                 while(strlen($str)>$p)  {
00579                         $substr=substr($str,$p,$l);
00580                         if (strlen($substr)==$l)        {
00581                                 $count = count(explode(' ',trim(strrev($substr))));
00582                                 if ($count>1)   {       // OK...
00583                                         $parts = explode(' ',strrev($substr),2);
00584                                         $theLine = strrev($parts[1]);
00585                                 } else {
00586                                         $afterParts = explode(' ',substr($str,$l+$p),2);
00587                                         $theLine = $substr.$afterParts[0];
00588                                 }
00589                                 if (!strlen($theLine))  {break; }       // Error, because this would keep us in an endless loop.
00590                         } else {
00591                                 $theLine=$substr;
00592                         }
00593 
00594                         $lines[]=trim($theLine);
00595                         $p+=strlen($theLine);
00596                         if (!trim(substr($str,$p,$l)))  break;  // added...
00597                 }
00598                 return implode($implChar,$lines);
00599         }
00600 
00610         function cmpIP($baseIP, $list)  {
00611                 if ($list==='*')        return TRUE;
00612                 if (strstr($baseIP, ':') && t3lib_div::validIPv6($baseIP))      {
00613                         return t3lib_div::cmpIPv6($baseIP, $list);
00614                 } else {
00615                         return t3lib_div::cmpIPv4($baseIP, $list);
00616                 }
00617         }
00618 
00626         function cmpIPv4($baseIP, $list)        {
00627                 $IPpartsReq = explode('.',$baseIP);
00628                 if (count($IPpartsReq)==4)      {
00629                         $values = t3lib_div::trimExplode(',',$list,1);
00630 
00631                         foreach($values as $test)       {
00632                                 list($test,$mask) = explode('/',$test);
00633 
00634                                 if(intval($mask)) {
00635                                                 // "192.168.3.0/24"
00636                                         $lnet = ip2long($test);
00637                                         $lip = ip2long($baseIP);
00638                                         $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
00639                                         $firstpart = substr($binnet,0,$mask);
00640                                         $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
00641                                         $firstip = substr($binip,0,$mask);
00642                                         $yes = (strcmp($firstpart,$firstip)==0);
00643                                 } else {
00644                                                 // "192.168.*.*"
00645                                         $IPparts = explode('.',$test);
00646                                         $yes = 1;
00647                                         reset($IPparts);
00648                                         while(list($index,$val)=each($IPparts)) {
00649                                                 $val = trim($val);
00650                                                 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val))       {
00651                                                         $yes=0;
00652                                                 }
00653                                         }
00654                                 }
00655                                 if ($yes) return true;
00656                         }
00657                 }
00658                 return false;
00659         }
00660 
00668         function cmpIPv6($baseIP, $list)        {
00669                 $success = false;       // Policy default: Deny connection
00670                 $baseIP = t3lib_div::normalizeIPv6($baseIP);
00671 
00672                 $values = t3lib_div::trimExplode(',',$list,1);
00673                 foreach ($values as $test)      {
00674                         list($test,$mask) = explode('/',$test);
00675                         if (t3lib_div::validIPv6($test))        {
00676                                 $test = t3lib_div::normalizeIPv6($test);
00677                                 if (intval($mask))      {
00678                                         switch ($mask) {        // test on /48 /64
00679                                                 case '48':
00680                                                         $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 48);
00681                                                         $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 48);
00682                                                         $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00683                                                 break;
00684                                                 case '64':
00685                                                         $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 64);
00686                                                         $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 64);
00687                                                         $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00688                                                 break;
00689                                                 default:
00690                                                         $success = false;
00691                                         }
00692                                 } else {
00693                                         if (t3lib_div::validIPv6($test))        {       // test on full ip address 128 bits
00694                                                 $testBin = t3lib_div::IPv6Hex2Bin($test);
00695                                                 $baseIPBin = t3lib_div::IPv6Hex2Bin($baseIP);
00696                                                 $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
00697                                         }
00698                                 }
00699                         }
00700                         if ($success) return true;
00701                 }
00702                 return false;
00703         }
00704 
00711         function IPv6Hex2Bin ($hex)     {
00712                 $bin = '';
00713                 $hex = str_replace(':', '', $hex);      // Replace colon to nothing
00714                 for ($i=0; $i<strlen($hex); $i=$i+2)    {
00715                         $bin.= chr(hexdec(substr($hex, $i, 2)));
00716                 }
00717                 return $bin;
00718         }
00719 
00726         function normalizeIPv6($address)        {
00727                 $normalizedAddress = '';
00728                 $stageOneAddress = '';
00729 
00730                 $chunks = explode('::', $address);      // Count 2 if if address has hidden zero blocks
00731                 if (count($chunks)==2)  {
00732                         $chunksLeft = explode(':', $chunks[0]);
00733                         $chunksRight = explode(':', $chunks[1]);
00734                         $left = count($chunksLeft);
00735                         $right = count($chunksRight);
00736 
00737                                 // Special case: leading zero-only blocks count to 1, should be 0
00738                         if ($left==1 && strlen($chunksLeft[0])==0)      $left=0;
00739 
00740                         $hiddenBlocks = 8 - ($left + $right);
00741                         $hiddenPart = '';
00742                         while ($h<$hiddenBlocks)        {
00743                                 $hiddenPart .= '0000:';
00744                                 $h++;
00745                         }
00746 
00747                         if ($left == 0) {
00748                                 $stageOneAddress = $hiddenPart . $chunks[1];
00749                         } else {
00750                                 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
00751                         }
00752                 } else $stageOneAddress = $address;
00753 
00754                         // normalize the blocks:
00755                 $blocks = explode(':', $stageOneAddress);
00756                 $divCounter = 0;
00757                 foreach ($blocks as $block)     {
00758                         $tmpBlock = '';
00759                         $i = 0;
00760                         $hiddenZeros = 4 - strlen($block);
00761                         while ($i < $hiddenZeros)       {
00762                                 $tmpBlock .= '0';
00763                                 $i++;
00764                         }
00765                         $normalizedAddress .= $tmpBlock . $block;
00766                         if ($divCounter < 7)    {
00767                                 $normalizedAddress .= ':';
00768                                 $divCounter++;
00769                         }
00770                 }
00771                 return $normalizedAddress;
00772         }
00773 
00782         function validIPv6($ip) {
00783                 $uppercaseIP = strtoupper($ip);
00784 
00785                 $regex = '/^(';
00786                 $regex.= '(([\dA-F]{1,4}:){7}[\dA-F]{1,4})|';
00787                 $regex.= '(([\dA-F]{1,4}){1}::([\dA-F]{1,4}:){1,5}[\dA-F]{1,4})|';
00788                 $regex.= '(([\dA-F]{1,4}:){2}:([\dA-F]{1,4}:){1,4}[\dA-F]{1,4})|';
00789                 $regex.= '(([\dA-F]{1,4}:){3}:([\dA-F]{1,4}:){1,3}[\dA-F]{1,4})|';
00790                 $regex.= '(([\dA-F]{1,4}:){4}:([\dA-F]{1,4}:){1,2}[\dA-F]{1,4})|';
00791                 $regex.= '(([\dA-F]{1,4}:){5}:([\dA-F]{1,4}:){0,1}[\dA-F]{1,4})|';
00792                 $regex.= '(::([\dA-F]{1,4}:){0,6}[\dA-F]{1,4})';
00793                 $regex.= ')$/';
00794 
00795                 return preg_match($regex, $uppercaseIP) ? true : false;
00796         }
00797 
00805         function cmpFQDN($baseIP, $list)        {
00806                 if (count(explode('.',$baseIP))==4)     {
00807                         $resolvedHostName = explode('.', gethostbyaddr($baseIP));
00808                         $values = t3lib_div::trimExplode(',',$list,1);
00809 
00810                         foreach($values as $test)       {
00811                                 $hostNameParts = explode('.',$test);
00812                                 $yes = 1;
00813 
00814                                 foreach($hostNameParts as $index => $val)       {
00815                                         $val = trim($val);
00816                                         if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
00817                                                 $yes=0;
00818                                         }
00819                                 }
00820                                 if ($yes) return true;
00821                         }
00822                 }
00823                 return false;
00824         }
00825 
00835         function inList($list,$item)    {
00836                 return strstr(','.$list.',', ','.$item.',') ? true : false;
00837         }
00838 
00847         function rmFromList($element,$list)     {
00848                 $items = explode(',',$list);
00849                 while(list($k,$v)=each($items)) {
00850                         if ($v==$element)       {unset($items[$k]);}
00851                 }
00852                 return implode(',',$items);
00853         }
00854 
00863         function expandList($list)      {
00864                 $items = explode(',',$list);
00865                 $list = array();
00866                 while(list(,$item)=each($items))        {
00867                         $range = explode('-',$item);
00868                         if (isset($range[1]))   {
00869                                 $runAwayBrake = 1000;
00870                                 for ($n=$range[0]; $n<=$range[1]; $n++) {
00871                                         $list[] = $n;
00872 
00873                                         $runAwayBrake--;
00874                                         if ($runAwayBrake<=0)   break;
00875                                 }
00876                         } else {
00877                                 $list[] = $item;
00878                         }
00879                 }
00880 
00881                 return implode(',',$list);
00882         }
00883 
00894         function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)  {
00895                 // Returns $theInt as an integer in the integerspace from $min to $max
00896                 $theInt = intval($theInt);
00897                 if ($zeroValue && !$theInt)     {$theInt=$zeroValue;}   // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
00898                 if ($theInt<$min){$theInt=$min;}
00899                 if ($theInt>$max){$theInt=$max;}
00900                 return $theInt;
00901         }
00902 
00910         function intval_positive($theInt)       {
00911                 $theInt = intval($theInt);
00912                 if ($theInt<0){$theInt=0;}
00913                 return $theInt;
00914         }
00915 
00923         function int_from_ver($verNumberStr)    {
00924                 $verParts = explode('.',$verNumberStr);
00925                 return intval((int)$verParts[0].str_pad((int)$verParts[1],3,'0',STR_PAD_LEFT).str_pad((int)$verParts[2],3,'0',STR_PAD_LEFT));
00926         }
00927 
00934         function compat_version($verNumberStr)  {
00935                 global $TYPO3_CONF_VARS;
00936                 $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version']?$TYPO3_CONF_VARS['SYS']['compat_version']:TYPO3_version;
00937 
00938                 if (t3lib_div::int_from_ver($currVersionStr) < t3lib_div::int_from_ver($verNumberStr))  {
00939                         return FALSE;
00940                 } else {
00941                         return TRUE;
00942                 }
00943         }
00944 
00952         function md5int($str)   {
00953                 return hexdec(substr(md5($str),0,7));
00954         }
00955 
00965         function shortMD5($input, $len=10)      {
00966                 return substr(md5($input),0,$len);
00967         }
00968 
00978         function uniqueList($in_list, $secondParameter=NULL)    {
00979                 if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
00980                 if (isset($secondParameter))    die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
00981 
00982                 return implode(',',array_unique(t3lib_div::trimExplode(',',$in_list,1)));
00983         }
00984 
00992         function split_fileref($fileref)        {
00993                 $reg = array();
00994                 if (    ereg('(.*/)(.*)$',$fileref,$reg)        )       {
00995                         $info['path'] = $reg[1];
00996                         $info['file'] = $reg[2];
00997                 } else {
00998                         $info['path'] = '';
00999                         $info['file'] = $fileref;
01000                 }
01001                 $reg='';
01002                 if (    ereg('(.*)\.([^\.]*$)',$info['file'],$reg)      )       {
01003                         $info['filebody'] = $reg[1];
01004                         $info['fileext'] = strtolower($reg[2]);
01005                         $info['realFileext'] = $reg[2];
01006                 } else {
01007                         $info['filebody'] = $info['file'];
01008                         $info['fileext'] = '';
01009                 }
01010                 reset($info);
01011                 return $info;
01012         }
01013 
01030         function dirname($path) {
01031                 $p=t3lib_div::revExplode('/',$path,2);
01032                 return count($p)==2?$p[0]:'';
01033         }
01034 
01046         function modifyHTMLColor($color,$R,$G,$B)       {
01047                 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
01048                 $nR = t3lib_div::intInRange(hexdec(substr($color,1,2))+$R,0,255);
01049                 $nG = t3lib_div::intInRange(hexdec(substr($color,3,2))+$G,0,255);
01050                 $nB = t3lib_div::intInRange(hexdec(substr($color,5,2))+$B,0,255);
01051                 return '#'.
01052                         substr('0'.dechex($nR),-2).
01053                         substr('0'.dechex($nG),-2).
01054                         substr('0'.dechex($nB),-2);
01055         }
01056 
01066         function modifyHTMLColorAll($color,$all)        {
01067                 return t3lib_div::modifyHTMLColor($color,$all,$all,$all);
01068         }
01069 
01077         function rm_endcomma($string)   {
01078                 return ereg_replace(',$','',$string);
01079         }
01080 
01090         function danish_strtoupper($string)     {
01091                 $value = strtoupper($string);
01092                 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
01093         }
01094 
01105         function convUmlauts($str)      {
01106                 $pat  = array ( '/ä/',  '/Ä/',  '/ö/',  '/Ö/',  '/ü/',  '/Ü/',  '/ß/',  '/å/',  '/Å/',  '/ø/',  '/Ø/',  '/æ/',  '/Æ/'   );
01107                 $repl = array ( 'ae',   'Ae',   'oe',   'Oe',   'ue',   'Ue',   'ss',   'aa',   'AA',   'oe',   'OE',   'ae',   'AE'    );
01108                 return preg_replace($pat,$repl,$str);
01109         }
01110 
01118         function testInt($var)  {
01119                 return !strcmp($var,intval($var));
01120         }
01121 
01130         function isFirstPartOfStr($str,$partStr)        {
01131                 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
01132                 $psLen = strlen($partStr);
01133                 if ($psLen)     {
01134                         return substr($str,0,$psLen)==(string)$partStr;
01135                 } else return false;
01136         }
01137 
01146         function formatSize($sizeInBytes,$labels='')    {
01147 
01148                         // Set labels:
01149                 if (strlen($labels) == 0) {
01150                     $labels = ' | K| M| G';
01151                 } else {
01152                     $labels = str_replace('"','',$labels);
01153                 }
01154                 $labelArr = explode('|',$labels);
01155 
01156                         // Find size:
01157                 if ($sizeInBytes>900)   {
01158                         if ($sizeInBytes>900000000)     {       // GB
01159                                 $val = $sizeInBytes/(1024*1024*1024);
01160                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
01161                         }
01162                         elseif ($sizeInBytes>900000)    {       // MB
01163                                 $val = $sizeInBytes/(1024*1024);
01164                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
01165                         } else {        // KB
01166                                 $val = $sizeInBytes/(1024);
01167                                 return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
01168                         }
01169                 } else {        // Bytes
01170                         return $sizeInBytes.$labelArr[0];
01171                 }
01172         }
01173 
01181         function convertMicrotime($microtime)   {
01182                 $parts = explode(' ',$microtime);
01183                 return round(($parts[0]+$parts[1])*1000);
01184         }
01185 
01195         function splitCalc($string,$operators)  {
01196                 $res = Array();
01197                 $sign='+';
01198                 while($string)  {
01199                         $valueLen=strcspn($string,$operators);
01200                         $value=substr($string,0,$valueLen);
01201                         $res[] = Array($sign,trim($value));
01202                         $sign=substr($string,$valueLen,1);
01203                         $string=substr($string,$valueLen+1);
01204                 }
01205                 reset($res);
01206                 return $res;
01207         }
01208 
01217         function calcPriority($string)  {
01218                 $string=ereg_replace('[[:space:]]*','',$string);        // removing all whitespace
01219                 $string='+'.$string;    // Ensuring an operator for the first entrance
01220                 $qm='\*\/\+-^%';
01221                 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
01222                         // split the expression here:
01223                 $reg = array();
01224                 preg_match_all('/'.$regex.'/',$string,$reg);
01225 
01226                 reset($reg[2]);
01227                 $number=0;
01228                 $Msign='+';
01229                 $err='';
01230                 $buffer=doubleval(current($reg[2]));
01231                 next($reg[2]);  // Advance pointer
01232                 while(list($k,$v)=each($reg[2]))        {
01233                         $v=doubleval($v);
01234                         $sign = $reg[1][$k];
01235                         if ($sign=='+' || $sign=='-')   {
01236                                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01237                                 $Msign = $sign;
01238                                 $buffer=$v;
01239                         } else {
01240                                 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
01241                                 if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';}
01242                                 if ($sign=='*') {$buffer*=$v;}
01243                                 if ($sign=='^') {$buffer=pow($buffer,$v);}
01244                         }
01245                 }
01246                 $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
01247                 return $err ? 'ERROR: '.$err : $number;
01248         }
01249 
01258         function calcParenthesis($string)       {
01259                 $securC=100;
01260                 do {
01261                         $valueLenO=strcspn($string,'(');
01262                         $valueLenC=strcspn($string,')');
01263                         if ($valueLenC==strlen($string) || $valueLenC < $valueLenO)     {
01264                                 $value = t3lib_div::calcPriority(substr($string,0,$valueLenC));
01265                                 $string = $value.substr($string,$valueLenC+1);
01266                                 return $string;
01267                         } else {
01268                                 $string = substr($string,0,$valueLenO).t3lib_div::calcParenthesis(substr($string,$valueLenO+1));
01269                         }
01270                                 // Security:
01271                         $securC--;
01272                         if ($securC<=0) break;
01273                 } while($valueLenO<strlen($string));
01274                 return $string;
01275         }
01276 
01284         function htmlspecialchars_decode($value)        {
01285                 $value = str_replace('&gt;','>',$value);
01286                 $value = str_replace('&lt;','<',$value);
01287                 $value = str_replace('&quot;','"',$value);
01288                 $value = str_replace('&amp;','&',$value);
01289                 return $value;
01290         }
01291 
01299         function deHSCentities($str)    {
01300                 return ereg_replace('&amp;([#[:alnum:]]*;)','&\1',$str);
01301         }
01302 
01312         function slashJS($string,$extended=0,$char="'") {
01313                 if ($extended)  {$string = str_replace ("\\", "\\\\", $string);}
01314                 return str_replace ($char, "\\".$char, $string);
01315         }
01316 
01325         function rawUrlEncodeJS($str)   {
01326                 return str_replace('%20',' ',rawurlencode($str));
01327         }
01328 
01337         function rawUrlEncodeFP($str)   {
01338                 return str_replace('%2F','/',rawurlencode($str));
01339         }
01340 
01348         function validEmail($email)     {
01349                 $email = trim ($email);
01350                 if (strstr($email,' '))  return FALSE;
01351                 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE : FALSE;
01352         }
01353 
01363         function formatForTextarea($content)    {
01364                 return chr(10).htmlspecialchars($content);
01365         }
01366 
01367 
01368 
01369 
01370 
01371 
01372 
01373 
01374 
01375 
01376 
01377 
01378         /*************************
01379          *
01380          * ARRAY FUNCTIONS
01381          *
01382          *************************/
01383 
01394         function inArray($in_array,$item)       {
01395                 if (is_array($in_array))        {
01396                         while (list(,$val)=each($in_array))     {
01397                                 if (!is_array($val) && !strcmp($val,$item)) return true;
01398                         }
01399                 }
01400         }
01401 
01411         function intExplode($delim, $string)    {
01412                 $temp = explode($delim,$string);
01413                 while(list($key,$val)=each($temp))      {
01414                         $temp[$key]=intval($val);
01415                 }
01416                 reset($temp);
01417                 return $temp;
01418         }
01419 
01430         function revExplode($delim, $string, $count=0)  {
01431                 $temp = explode($delim,strrev($string),$count);
01432                 while(list($key,$val)=each($temp))      {
01433                         $temp[$key]=strrev($val);
01434                 }
01435                 $temp=array_reverse($temp);
01436                 reset($temp);
01437                 return $temp;
01438         }
01439 
01450         function trimExplode($delim, $string, $onlyNonEmptyValues=0)    {
01451                 $temp = explode($delim,$string);
01452                 $newtemp=array();
01453                 while(list($key,$val)=each($temp))      {
01454                         if (!$onlyNonEmptyValues || strcmp('',trim($val)))      {
01455                                 $newtemp[]=trim($val);
01456                         }
01457                 }
01458                 reset($newtemp);
01459                 return $newtemp;
01460         }
01461 
01472         function uniqueArray($valueArray)       {
01473                 return array_unique($valueArray);
01474         }
01475 
01484         function removeArrayEntryByValue($array,$cmpValue)      {
01485                 if (is_array($array))   {
01486                         reset($array);
01487                         while(list($k,$v)=each($array)) {
01488                                 if (is_array($v))       {
01489                                         $array[$k] = t3lib_div::removeArrayEntryByValue($v,$cmpValue);
01490                                 } else {
01491                                         if (!strcmp($v,$cmpValue))      {
01492                                                 unset($array[$k]);
01493                                         }
01494                                 }
01495                         }
01496                 }
01497                 reset($array);
01498                 return $array;
01499         }
01500 
01513         function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)      {
01514                 if (is_array($theArray))        {
01515                         foreach($theArray as $Akey => $AVal)    {
01516                                 $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
01517                                 if (is_array($AVal))    {
01518                                         $str = t3lib_div::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
01519                                 } else {
01520                                         if (!$skipBlank || strcmp($AVal,''))    {
01521                                                 $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
01522                                                         '='.rawurlencode($AVal);
01523                                         }
01524                                 }
01525                         }
01526                 }
01527                 return $str;
01528         }
01529 
01538         function explodeUrl2Array($string,$multidim=FALSE)      {
01539                 $output = array();
01540                 if ($multidim)  {
01541                         parse_str($string,$output);
01542                 } else {
01543                         $p = explode('&',$string);
01544                         foreach($p as $v)       {
01545                                 if (strlen($v)) {
01546                                         list($pK,$pV) = explode('=',$v,2);
01547                                         $output[rawurldecode($pK)] = rawurldecode($pV);
01548                                 }
01549                         }
01550                 }
01551                 return $output;
01552         }
01553 
01564         function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)        {
01565                 $keys = t3lib_div::trimExplode(',',$varList,1);
01566                 $outArr=array();
01567                 foreach($keys as $v)    {
01568                         if (isset($getArray[$v]))       {
01569                                 $outArr[$v]=$getArray[$v];
01570                         } elseif ($GPvarAlt) {
01571                                 $outArr[$v]=t3lib_div::_GP($v);
01572                         }
01573                 }
01574                 return $outArr;
01575         }
01576 
01587         function addSlashesOnArray(&$theArray)  {
01588                 if (is_array($theArray))        {
01589                         reset($theArray);
01590                         while(list($Akey,$AVal)=each($theArray))        {
01591                                 if (is_array($AVal))    {
01592                                         t3lib_div::addSlashesOnArray($theArray[$Akey]);
01593                                 } else {
01594                                         $theArray[$Akey] = addslashes($AVal);
01595                                 }
01596                         }
01597                         reset($theArray);
01598                 }
01599         }
01600 
01611         function stripSlashesOnArray(&$theArray)        {
01612                 if (is_array($theArray))        {
01613                         reset($theArray);
01614                         while(list($Akey,$AVal)=each($theArray))        {
01615                                 if (is_array($AVal))    {
01616                                         t3lib_div::stripSlashesOnArray($theArray[$Akey]);
01617                                 } else {
01618                                         $theArray[$Akey] = stripslashes($AVal);
01619                                 }
01620                         }
01621                         reset($theArray);
01622                 }
01623         }
01624 
01633         function slashArray($arr,$cmd)  {
01634                 if ($cmd=='strip')      t3lib_div::stripSlashesOnArray($arr);
01635                 if ($cmd=='add')        t3lib_div::addSlashesOnArray($arr);
01636                 return $arr;
01637         }
01638 
01650         function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) {
01651                 reset($arr1);
01652                 while(list($key,$val) = each($arr1)) {
01653                         if(is_array($arr0[$key])) {
01654                                 if (is_array($arr1[$key]))      {
01655                                         $arr0[$key] = t3lib_div::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys);
01656                                 }
01657                         } else {
01658                                 if ($notAddKeys) {
01659                                         if (isset($arr0[$key])) {
01660                                                 if ($includeEmtpyValues OR $val) {
01661                                                         $arr0[$key] = $val;
01662                                                 }
01663                                         }
01664                                 } else {
01665                                         if ($includeEmtpyValues OR $val) {
01666                                                 $arr0[$key] = $val;
01667                                         }
01668                                 }
01669                         }
01670                 }
01671                 reset($arr0);
01672                 return $arr0;
01673         }
01674 
01683         function array_merge($arr1,$arr2)       {
01684                 return $arr2+$arr1;
01685         }
01686 
01696         function csvValues($row,$delim=',',$quote='"')  {
01697                 reset($row);
01698                 $out=array();
01699                 while(list(,$value)=each($row)) {
01700                         list($valPart) = explode(chr(10),$value);
01701                         $valPart = trim($valPart);
01702                         $out[]=str_replace($quote,$quote.$quote,$valPart);
01703                 }
01704                 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
01705                 return $str;
01706         }
01707 
01708 
01709 
01710 
01711 
01712 
01713 
01714 
01715 
01716 
01717 
01718 
01719 
01720 
01721 
01722 
01723         /*************************
01724          *
01725          * HTML/XML PROCESSING
01726          *
01727          *************************/
01728 
01738         function get_tag_attributes($tag)       {
01739                 $components = t3lib_div::split_tag_attributes($tag);
01740                 $name = '';      // attribute name is stored here
01741                 $valuemode = '';
01742                 if (is_array($components))      {
01743                         while (list($key,$val) = each ($components))    {
01744                                 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
01745                                         if ($valuemode) {
01746                                                 if ($name)      {
01747                                                         $attributes[$name] = $val;
01748                                                         $name = '';
01749                                                 }
01750                                         } else {
01751                                                 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val)))    {
01752                                                         $attributes[$key] = '';
01753                                                         $name = $key;
01754                                                 }
01755                                         }
01756                                         $valuemode = '';
01757                                 } else {
01758                                         $valuemode = 'on';
01759                                 }
01760                         }
01761                         if (is_array($attributes))      reset($attributes);
01762                         return $attributes;
01763                 }
01764         }
01765 
01775         function split_tag_attributes($tag)     {
01776                 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
01777                         // Removes any > in the end of the string
01778                 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
01779 
01780                 while (strcmp($tag_tmp,''))     {       // Compared with empty string instead , 030102
01781                         $firstChar=substr($tag_tmp,0,1);
01782                         if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
01783                                 $reg=explode($firstChar,$tag_tmp,3);
01784                                 $value[]=$reg[1];
01785                                 $tag_tmp=trim($reg[2]);
01786                         } elseif (!strcmp($firstChar,'=')) {
01787                                 $value[] = '=';
01788                                 $tag_tmp = trim(substr($tag_tmp,1));            // Removes = chars.
01789                         } else {
01790                                         // There are '' around the value. We look for the next ' ' or '>'
01791                                 $reg = split('[[:space:]=]',$tag_tmp,2);
01792                                 $value[] = trim($reg[0]);
01793                                 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
01794                         }
01795                 }
01796                 if (is_array($value))   reset($value);
01797                 return $value;
01798         }
01799 
01809         function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)   {
01810                 if (is_array($arr))     {
01811                         if ($xhtmlSafe) {
01812                                 $newArr=array();
01813                                 foreach($arr as $p => $v)       {
01814                                         if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
01815                                 }
01816                                 $arr = $newArr;
01817                         }
01818                         $list = array();
01819                         foreach($arr as $p => $v)       {
01820                                 if (strcmp($v,'') || $dontOmitBlankAttribs)     {$list[]=$p.'="'.$v.'"';}
01821                         }
01822                         return implode(' ',$list);
01823                 }
01824         }
01825 
01836         function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)       {
01837                 return t3lib_div::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
01838         }
01839 
01851         function wrapJS($string, $linebreak=TRUE) {
01852                 if(trim($string)) {
01853                                 // <script wrapped in nl?
01854                         $cr = $linebreak? "\n" : '';
01855 
01856                                 // remove nl from the beginning
01857                         $string = preg_replace ('/^\n+/', '', $string);
01858                                 // re-ident to one tab using the first line as reference
01859                         $match = array();
01860                         if(preg_match('/^(\t+)/',$string,$match)) {
01861                                 $string = str_replace($match[1],"\t", $string);
01862                         }
01863                         $string = $cr.'<script type="text/javascript">
01864 /*<![CDATA[*/
01865 '.$string.'
01866 /*]]>*/
01867 </script>'.$cr;
01868                 }
01869                 return trim($string);
01870         }
01871 
01872 
01882         function xml2tree($string,$depth=999) {
01883                 $parser = xml_parser_create();
01884                 $vals = array();
01885                 $index = array();
01886 
01887                 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
01888                 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
01889                 xml_parse_into_struct($parser, $string, $vals, $index);
01890 
01891                 if (xml_get_error_code($parser))        return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
01892                 xml_parser_free($parser);
01893 
01894                 $stack = array( array() );
01895                 $stacktop = 0;
01896                 $startPoint=0;
01897 
01898 // FIXME don't use unset() - what does that mean? Use NULL or similar.
01899                 unset($tagi);
01900                 foreach($vals as $key => $val) {
01901                         $type = $val['type'];
01902 
01903                                 // open tag:
01904                         if ($type=='open' || $type=='complete') {
01905                                 $stack[$stacktop++] = $tagi;
01906 
01907                                 if ($depth==$stacktop)  {
01908                                         $startPoint=$key;
01909                                 }
01910 
01911                                 $tagi = array('tag' => $val['tag']);
01912 
01913                                 if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
01914                                 if(isset($val['value']))        $tagi['values'][] = $val['value'];
01915                         }
01916                                 // finish tag:
01917                         if ($type=='complete' || $type=='close')        {
01918                                 $oldtagi = $tagi;
01919                                 $tagi = $stack[--$stacktop];
01920                                 $oldtag = $oldtagi['tag'];
01921                                 unset($oldtagi['tag']);
01922 
01923                                 if ($depth==($stacktop+1))      {
01924                                         if ($key-$startPoint > 0)       {
01925                                                 $partArray = array_slice(
01926                                                         $vals,
01927                                                         $startPoint+1,
01928                                                         $key-$startPoint-1
01929                                                 );
01930                                                 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
01931                                                 $oldtagi['XMLvalue']=t3lib_div::xmlRecompileFromStructValArray($partArray);
01932                                         } else {
01933                                                 $oldtagi['XMLvalue']=$oldtagi['values'][0];
01934                                         }
01935                                 }
01936 
01937                                 $tagi['ch'][$oldtag][] = $oldtagi;
01938                                 unset($oldtagi);
01939                         }
01940                                 // cdata
01941                         if($type=='cdata') {
01942                                 $tagi['values'][] = $val['value'];
01943                         }
01944                 }
01945                 return $tagi['ch'];
01946         }
01947         
01958         function array2xml_cs($array,$docTag='phparray',$options=array(),$charset='')   {
01959                 
01960                         // Figure out charset if not given explicitly:
01961                 if (!$charset)  {
01962                         if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'])  {       // First priority: forceCharset! If set, this will be authoritative!
01963                                 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
01964                         } elseif (is_object($GLOBALS['LANG']))  {
01965                                 $charset = $GLOBALS['LANG']->charSet;   // If "LANG" is around, that will hold the current charset 
01966                         } else {
01967                                 $charset = 'iso-8859-1';        // THIS is just a hopeful guess! 
01968                         }               
01969                 }
01970                 
01971                         // Return XML:
01972                 return '<?xml version="1.0" encoding="'.htmlspecial