Added argument to debugRows() so it can return HTML instead of echo'ing
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_div.php
index 243aba4..bfa3888 100755 (executable)
@@ -2,7 +2,7 @@
 /***************************************************************
 *  Copyright notice
 *
-*  (c) 1999-2005 Kasper Skaarhoj (kasperYYYY@typo3.com)
+*  (c) 1999-2007 Kasper Skaarhoj (kasperYYYY@typo3.com)
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
  *
  *
  *
- *  211: class t3lib_div
+ *  232: class t3lib_div
  *
  *              SECTION: GET/POST Variables
- *  241:     function _GP($var)
- *  259:     function _GET($var=NULL)
- *  276:     function _POST($var=NULL)
- *  292:     function _GETset($inputGet,$key='')
- *  315:     function GPvar($var,$strip=0)
- *  332:     function GParrayMerged($var)
+ *  262:     function _GP($var)
+ *  280:     function _GET($var=NULL)
+ *  297:     function _POST($var=NULL)
+ *  313:     function _GETset($inputGet,$key='')
+ *  336:     function GPvar($var,$strip=0)
+ *  353:     function GParrayMerged($var)
  *
  *              SECTION: IMAGE FUNCTIONS
- *  376:     function gif_compress($theFile, $type)
- *  402:     function png_to_gif_by_imagemagick($theFile)
- *  426:     function read_png_gif($theFile,$output_png=0)
+ *  397:     function gif_compress($theFile, $type)
+ *  425:     function png_to_gif_by_imagemagick($theFile)
+ *  450:     function read_png_gif($theFile,$output_png=0)
  *
  *              SECTION: STRING FUNCTIONS
- *  475:     function fixed_lgd($string,$origChars,$preStr='...')
- *  500:     function fixed_lgd_pre($string,$chars)
- *  514:     function fixed_lgd_cs($string,$chars)
- *  531:     function breakTextForEmail($str,$implChar="\n",$charWidth=76)
- *  550:     function breakLinesForEmail($str,$implChar="\n",$charWidth=76)
- *  585:     function cmpIP($baseIP, $list)
- *  627:     function cmpFQDN($baseIP, $list)
- *  657:     function inList($in_list,$item)
- *  669:     function rmFromList($element,$list)
- *  687:     function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)
- *  703:     function intval_positive($theInt)
- *  716:     function int_from_ver($verNumberStr)
- *  728:     function md5int($str)
- *  741:     function shortMD5($input, $len=10)
- *  754:     function uniqueList($in_list, $secondParameter=NULL)
- *  768:     function split_fileref($fileref)
- *  805:     function dirname($path)
- *  821:     function modifyHTMLColor($color,$R,$G,$B)
- *  841:     function modifyHTMLColorAll($color,$all)
- *  852:     function rm_endcomma($string)
- *  865:     function danish_strtoupper($string)
- *  880:     function convUmlauts($str)
- *  893:     function testInt($var)
- *  905:     function isFirstPartOfStr($str,$partStr)
- *  921:     function formatSize($sizeInBytes,$labels='')
- *  956:     function convertMicrotime($microtime)
- *  970:     function splitCalc($string,$operators)
- *  992:     function calcPriority($string)
- * 1032:     function calcParenthesis($string)
- * 1058:     function htmlspecialchars_decode($value)
- * 1073:     function deHSCentities($str)
- * 1086:     function slashJS($string,$extended=0,$char="'")
- * 1099:     function rawUrlEncodeJS($str)
- * 1111:     function rawUrlEncodeFP($str)
- * 1122:     function validEmail($email)
- * 1137:     function formatForTextarea($content)
+ *  499:     function fixed_lgd($string,$origChars,$preStr='...')
+ *  524:     function fixed_lgd_pre($string,$chars)
+ *  538:     function fixed_lgd_cs($string,$chars)
+ *  555:     function breakTextForEmail($str,$implChar="\n",$charWidth=76)
+ *  574:     function breakLinesForEmail($str,$implChar="\n",$charWidth=76)
+ *  610:     function cmpIP($baseIP, $list)
+ *  626:     function cmpIPv4($baseIP, $list)
+ *  668:     function cmpIPv6($baseIP, $list)
+ *  711:     function IPv6Hex2Bin ($hex)
+ *  726:     function normalizeIPv6($address)
+ *  782:     function validIPv6($ip)
+ *  805:     function cmpFQDN($baseIP, $list)
+ *  835:     function inList($list,$item)
+ *  847:     function rmFromList($element,$list)
+ *  863:     function expandList($list)
+ *  894:     function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)
+ *  910:     function intval_positive($theInt)
+ *  923:     function int_from_ver($verNumberStr)
+ *  934:     function compat_version($verNumberStr)
+ *  952:     function md5int($str)
+ *  965:     function shortMD5($input, $len=10)
+ *  978:     function uniqueList($in_list, $secondParameter=NULL)
+ *  992:     function split_fileref($fileref)
+ * 1030:     function dirname($path)
+ * 1046:     function modifyHTMLColor($color,$R,$G,$B)
+ * 1066:     function modifyHTMLColorAll($color,$all)
+ * 1077:     function rm_endcomma($string)
+ * 1090:     function danish_strtoupper($string)
+ * 1105:     function convUmlauts($str)
+ * 1118:     function testInt($var)
+ * 1130:     function isFirstPartOfStr($str,$partStr)
+ * 1146:     function formatSize($sizeInBytes,$labels='')
+ * 1181:     function convertMicrotime($microtime)
+ * 1195:     function splitCalc($string,$operators)
+ * 1217:     function calcPriority($string)
+ * 1258:     function calcParenthesis($string)
+ * 1284:     function htmlspecialchars_decode($value)
+ * 1299:     function deHSCentities($str)
+ * 1312:     function slashJS($string,$extended=0,$char="'")
+ * 1325:     function rawUrlEncodeJS($str)
+ * 1337:     function rawUrlEncodeFP($str)
+ * 1348:     function validEmail($email)
+ * 1363:     function formatForTextarea($content)
  *
  *              SECTION: ARRAY FUNCTIONS
- * 1168:     function inArray($in_array,$item)
- * 1185:     function intExplode($delim, $string)
- * 1204:     function revExplode($delim, $string, $count=0)
- * 1224:     function trimExplode($delim, $string, $onlyNonEmptyValues=0)
- * 1246:     function uniqueArray($valueArray)
- * 1258:     function removeArrayEntryByValue($array,$cmpValue)
- * 1286:     function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)
- * 1313:     function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)
- * 1336:     function addSlashesOnArray(&$theArray)
- * 1360:     function stripSlashesOnArray(&$theArray)
- * 1382:     function slashArray($arr,$cmd)
- * 1399:     function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true)
- * 1432:     function array_merge($arr1,$arr2)
- * 1445:     function csvValues($row,$delim=',',$quote='"')
+ * 1394:     function inArray($in_array,$item)
+ * 1411:     function intExplode($delim, $string)
+ * 1430:     function revExplode($delim, $string, $count=0)
+ * 1450:     function trimExplode($delim, $string, $onlyNonEmptyValues=0)
+ * 1472:     function uniqueArray($valueArray)
+ * 1484:     function removeArrayEntryByValue($array,$cmpValue)
+ * 1513:     function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)
+ * 1538:     function explodeUrl2Array($string,$multidim=FALSE)
+ * 1564:     function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)
+ * 1587:     function addSlashesOnArray(&$theArray)
+ * 1611:     function stripSlashesOnArray(&$theArray)
+ * 1633:     function slashArray($arr,$cmd)
+ * 1650:     function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true)
+ * 1683:     function array_merge($arr1,$arr2)
+ * 1696:     function csvValues($row,$delim=',',$quote='"')
  *
  *              SECTION: HTML/XML PROCESSING
- * 1487:     function get_tag_attributes($tag)
- * 1524:     function split_tag_attributes($tag)
- * 1558:     function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
- * 1585:     function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
- * 1600:     function wrapJS($string, $linebreak=TRUE)
- * 1630:     function xml2tree($string,$depth=999)
- * 1716:     function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array())
- * 1830:     function xml2array($string,$NSprefix='',$reportDocTag=FALSE)
- * 1940:     function xmlRecompileFromStructValArray($vals)
- * 1984:     function xmlGetHeaderAttribs($xmlData)
+ * 1738:     function get_tag_attributes($tag)
+ * 1775:     function split_tag_attributes($tag)
+ * 1809:     function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
+ * 1836:     function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
+ * 1851:     function wrapJS($string, $linebreak=TRUE)
+ * 1882:     function xml2tree($string,$depth=999)
+ * 1969:     function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array())
+ * 2088:     function xml2array($string,$NSprefix='',$reportDocTag=FALSE)
+ * 2198:     function xmlRecompileFromStructValArray($vals)
+ * 2242:     function xmlGetHeaderAttribs($xmlData)
  *
  *              SECTION: FILES FUNCTIONS
- * 2016:     function getURL($url)
- * 2058:     function writeFile($file,$content)
- * 2075:     function fixPermissions($file)
- * 2092:     function writeFileToTypo3tempDir($filepath,$content)
- * 2135:     function mkdir($theNewFolder)
- * 2155:     function get_dirs($path)
- * 2180:     function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')
- * 2234:     function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)
- * 2257:     function removePrefixPathFromList($fileArr,$prefixToRemove)
- * 2273:     function fixWindowsFilePath($theFile)
- * 2285:     function resolveBackPath($pathStr)
- * 2312:     function locationHeaderUrl($path)
+ * 2275:     function getURL($url, $includeHeader=0)
+ * 2342:     function writeFile($file,$content)
+ * 2367:     function fixPermissions($file)
+ * 2384:     function writeFileToTypo3tempDir($filepath,$content)
+ * 2427:     function mkdir($theNewFolder)
+ * 2446:     function mkdir_deep($destination,$deepDir)
+ * 2468:     function get_dirs($path)
+ * 2493:     function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')
+ * 2547:     function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)
+ * 2570:     function removePrefixPathFromList($fileArr,$prefixToRemove)
+ * 2586:     function fixWindowsFilePath($theFile)
+ * 2598:     function resolveBackPath($pathStr)
+ * 2626:     function locationHeaderUrl($path)
  *
  *              SECTION: DEBUG helper FUNCTIONS
- * 2352:     function debug_ordvalue($string,$characters=100)
- * 2369:     function view_array($array_in)
- * 2397:     function print_array($array_in)
- * 2412:     function debug($var="",$brOrHeader=0)
+ * 2666:     function debug_ordvalue($string,$characters=100)
+ * 2683:     function view_array($array_in)
+ * 2711:     function print_array($array_in)
+ * 2726:     function debug($var="",$brOrHeader=0)
+ * 2757:     function debug_trail()
+ * 2779:     function debugRows($rows,$header='')
  *
  *              SECTION: SYSTEM INFORMATION
- * 2481:     function getThisUrl()
- * 2497:     function linkThisScript($getParams=array())
- * 2521:     function linkThisUrl($url,$getParams=array())
- * 2546:     function getIndpEnv($getEnvName)
- * 2735:     function milliseconds()
- * 2747:     function clientInfo($useragent='')
+ * 2857:     function getThisUrl()
+ * 2873:     function linkThisScript($getParams=array())
+ * 2897:     function linkThisUrl($url,$getParams=array())
+ * 2920:     function getIndpEnv($getEnvName)
+ * 3113:     function milliseconds()
+ * 3125:     function clientInfo($useragent='')
  *
  *              SECTION: TYPO3 SPECIFIC FUNCTIONS
- * 2834:     function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)
- * 2870:     function validPathStr($theFile)
- * 2881:     function isAbsPath($path)
- * 2892:     function isAllowedAbsPath($path)
- * 2909:     function verifyFilenameAgainstDenyPattern($filename)
- * 2927:     function upload_copy_move($source,$destination)
- * 2953:     function upload_to_tempfile($uploadedFileName)
- * 2971:     function unlink_tempfile($uploadedTempFileName)
- * 2987:     function tempnam($filePrefix)
- * 3000:     function stdAuthCode($uid_or_record,$fields='')
- * 3030:     function cHashParams($addQueryParams)
- * 3059:     function loadTCA($table)
- * 3079:     function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')
- * 3109:     function resolveAllSheetsInDS($dataStructArray)
- * 3138:     function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)
- * 3237:     function &getUserObj($classRef,$checkPrefix='user_',$silent=0)
- * 3295:     function &makeInstance($className)
- * 3307:     function makeInstanceClassName($className)
- * 3321:     function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())
- * 3382:     function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0)
- * 3427:     function quoted_printable($string,$maxlen=76)
- * 3471:     function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')
- * 3505:     function makeRedirectUrl($inUrl,$l=0,$index_script_url='')
- * 3532:     function freetypeDpiComp($font_size)
- * 3551:     function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)
- * 3572:     function arrayToLogString($arr, $valueList=array(), $valueLength=20)
+ * 3212:     function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)
+ * 3248:     function validPathStr($theFile)
+ * 3259:     function isAbsPath($path)
+ * 3270:     function isAllowedAbsPath($path)
+ * 3287:     function verifyFilenameAgainstDenyPattern($filename)
+ * 3305:     function upload_copy_move($source,$destination)
+ * 3331:     function upload_to_tempfile($uploadedFileName)
+ * 3349:     function unlink_tempfile($uploadedTempFileName)
+ * 3365:     function tempnam($filePrefix)
+ * 3379:     function stdAuthCode($uid_or_record,$fields='',$codeLength=8)
+ * 3410:     function cHashParams($addQueryParams)
+ * 3433:     function hideIfNotTranslated($l18n_cfg_fieldValue)
+ * 3448:     function readLLfile($fileRef,$langKey)
+ * 3472:     function readLLXMLfile($fileRef,$langKey)
+ * 3589:     function llXmlAutoFileName($fileRef,$language)
+ * 3633:     function loadTCA($table)
+ * 3653:     function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')
+ * 3686:     function resolveAllSheetsInDS($dataStructArray)
+ * 3715:     function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)
+ * 3813:     function &getUserObj($classRef,$checkPrefix='user_',$silent=0)
+ * 3871:     function &makeInstance($className)
+ * 3883:     function makeInstanceClassName($className)
+ * 3897:     function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())
+ * 3961:     function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='',$dontEncodeHeader=false)
+ * 4031:     function quoted_printable($string,$maxlen=76)
+ * 4078:     function encodeHeader($line,$enc='',$charset='ISO-8859-1')
+ * 4121:     function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')
+ * 4155:     function makeRedirectUrl($inUrl,$l=0,$index_script_url='')
+ * 4182:     function freetypeDpiComp($font_size)
+ * 4194:     function initSysLog()
+ * 4251:     function sysLog($msg, $extKey, $severity=0)
+ * 4334:     function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)
+ * 4355:     function arrayToLogString($arr, $valueList=array(), $valueLength=20)
+ * 4378:     function imageMagickCommand($command, $parameters, $path='')
+ * 4425:     function unQuoteFilenames($parameters,$unQuote=FALSE)
+ * 4459:     function quoteJSvalue($value, $inScriptTags = false)
  *
- * TOTAL FUNCTIONS: 117
+ * TOTAL FUNCTIONS: 138
  * (This index is automatically created/updated by the extension "extdeveval")
  *
  */
@@ -377,8 +398,10 @@ class t3lib_div {
                $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
                $returnCode='';
                if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif')      {       // GIF...
-                       if (($type=='IM' || !$type) && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'])   {       // IM
-                               exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'].'convert "'.$theFile.'" "'.$theFile.'"');
+                       if (($type=='IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw'])       {       // IM
+                               $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
+                               exec($cmd);
+
                                $returnCode='IM';
                        } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png'])       {       // GD
                                $tempImage = imageCreateFromGif($theFile);
@@ -406,7 +429,8 @@ class t3lib_div {
                        && strtolower(substr($theFile,-4,4))=='.png'
                        && @is_file($theFile))  {       // IM
                                $newFile = substr($theFile,0,-4).'.gif';
-                               exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'].'convert "'.$theFile.'" "'.$newFile.'"');
+                               $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
+                               exec($cmd);
                                $theFile = $newFile;
                                        // 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!!
                }
@@ -463,13 +487,13 @@ class t3lib_div {
         * Truncate string
         * Returns a new string of max. $chars length.
         * If the string is longer, it will be truncated and appended with '...'.
-        * DEPRECIATED. Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
         * Usage: 39
         *
-        * @param       string          $string         string to truncate
-        * @param       integer         $chars  must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
+        * @param       string          string to truncate
+        * @param       integer         must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
         * @param       string          String to append to the output if it is truncated, default is '...'
         * @return      string          new string
+        * @deprecated          Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
         * @see fixed_lgd_pre()
         */
        function fixed_lgd($string,$origChars,$preStr='...')    {
@@ -489,12 +513,12 @@ class t3lib_div {
         * Returns a new string of max. $chars length.
         * If the string is longer, it will be truncated and prepended with '...'.
         * This works like fixed_lgd, but is truncated in the start of the string instead of the end
-        * DEPRECIATED. Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
         * Usage: 6
         *
-        * @param       string          $string         string to truncate
-        * @param       integer         $chars  must be an integer of at least 4
+        * @param       string          string to truncate
+        * @param       integer         must be an integer of at least 4
         * @return      string          new string
+        * @deprecated          Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
         * @see fixed_lgd()
         */
        function fixed_lgd_pre($string,$chars)  {
@@ -506,8 +530,8 @@ class t3lib_div {
         * Use only from backend!
         * Usage: 75
         *
-        * @param       string          $string         string to truncate
-        * @param       integer         $chars  must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
+        * @param       string          string to truncate
+        * @param       integer         must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
         * @return      string          New string
         * @see fixed_lgd()
         */
@@ -526,13 +550,14 @@ class t3lib_div {
         * @param       string          The string to break up
         * @param       string          The string to implode the broken lines with (default/typically \n)
         * @param       integer         The line length
+        * @deprecated          Use PHP function wordwrap()
         * @return      string
         */
        function breakTextForEmail($str,$implChar="\n",$charWidth=76)   {
                $lines = explode(chr(10),$str);
                $outArr=array();
                while(list(,$lStr)=each($lines))        {
-                       $outArr = array_merge($outArr,t3lib_div::breakLinesForEmail($lStr,$implChar,$charWidth));
+                       $outArr[] = t3lib_div::breakLinesForEmail($lStr,$implChar,$charWidth);
                }
                return implode(chr(10),$outArr);
        }
@@ -576,13 +601,30 @@ class t3lib_div {
 
        /**
         * Match IP number with list of numbers with wildcard
+        * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
         * Usage: 10
         *
         * @param       string          $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
-        * @param       string          $list is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168)
+        * @param       string          $list is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168). If list is "*" no check is done and the function returns TRUE immediately.
         * @return      boolean         True if an IP-mask from $list matches $baseIP
         */
        function cmpIP($baseIP, $list)  {
+               if ($list==='*')        return TRUE;
+               if (strstr($baseIP, ':') && t3lib_div::validIPv6($baseIP))      {
+                       return t3lib_div::cmpIPv6($baseIP, $list);
+               } else {
+                       return t3lib_div::cmpIPv4($baseIP, $list);
+               }
+       }
+
+       /**
+        * Match IPv4 number with list of numbers with wildcard
+        *
+        * @param       string          $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
+        * @param       string          $list is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168)
+        * @return      boolean         True if an IP-mask from $list matches $baseIP
+        */
+       function cmpIPv4($baseIP, $list)        {
                $IPpartsReq = explode('.',$baseIP);
                if (count($IPpartsReq)==4)      {
                        $values = t3lib_div::trimExplode(',',$list,1);
@@ -618,10 +660,147 @@ class t3lib_div {
        }
 
        /**
+        * Match IPv6 address with a list of IPv6 prefixes
+        *
+        * @param       string          $baseIP is the current remote IP address for instance
+        * @param       string          $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
+        * @return      boolean         True if an baseIP matches any prefix
+        */
+       function cmpIPv6($baseIP, $list)        {
+               $success = false;       // Policy default: Deny connection
+               $baseIP = t3lib_div::normalizeIPv6($baseIP);
+
+               $values = t3lib_div::trimExplode(',',$list,1);
+               foreach ($values as $test)      {
+                       list($test,$mask) = explode('/',$test);
+                       if (t3lib_div::validIPv6($test))        {
+                               $test = t3lib_div::normalizeIPv6($test);
+                               if (intval($mask))      {
+                                       switch ($mask) {        // test on /48 /64
+                                               case '48':
+                                                       $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 48);
+                                                       $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 48);
+                                                       $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
+                                               break;
+                                               case '64':
+                                                       $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 64);
+                                                       $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 64);
+                                                       $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
+                                               break;
+                                               default:
+                                                       $success = false;
+                                       }
+                               } else {
+                                       if (t3lib_div::validIPv6($test))        {       // test on full ip address 128 bits
+                                               $testBin = t3lib_div::IPv6Hex2Bin($test);
+                                               $baseIPBin = t3lib_div::IPv6Hex2Bin($baseIP);
+                                               $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
+                                       }
+                               }
+                       }
+                       if ($success) return true;
+               }
+               return false;
+       }
+
+       /**
+        * [Describe function...]
+        *
+        * @param       [type]          $hex: ...
+        * @return      [type]          ...
+        */
+       function IPv6Hex2Bin ($hex)     {
+               $bin = '';
+               $hex = str_replace(':', '', $hex);      // Replace colon to nothing
+               for ($i=0; $i<strlen($hex); $i=$i+2)    {
+                       $bin.= chr(hexdec(substr($hex, $i, 2)));
+               }
+               return $bin;
+       }
+
+       /**
+        * Normalize an IPv6 address to full length
+        *
+        * @param       string          Given IPv6 address
+        * @return      string          Normalized address
+        */
+       function normalizeIPv6($address)        {
+               $normalizedAddress = '';
+               $stageOneAddress = '';
+
+               $chunks = explode('::', $address);      // Count 2 if if address has hidden zero blocks
+               if (count($chunks)==2)  {
+                       $chunksLeft = explode(':', $chunks[0]);
+                       $chunksRight = explode(':', $chunks[1]);
+                       $left = count($chunksLeft);
+                       $right = count($chunksRight);
+
+                               // Special case: leading zero-only blocks count to 1, should be 0
+                       if ($left==1 && strlen($chunksLeft[0])==0)      $left=0;
+
+                       $hiddenBlocks = 8 - ($left + $right);
+                       $hiddenPart = '';
+                       while ($h<$hiddenBlocks)        {
+                               $hiddenPart .= '0000:';
+                               $h++;
+                       }
+
+                       if ($left == 0) {
+                               $stageOneAddress = $hiddenPart . $chunks[1];
+                       } else {
+                               $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
+                       }
+               } else $stageOneAddress = $address;
+
+                       // normalize the blocks:
+               $blocks = explode(':', $stageOneAddress);
+               $divCounter = 0;
+               foreach ($blocks as $block)     {
+                       $tmpBlock = '';
+                       $i = 0;
+                       $hiddenZeros = 4 - strlen($block);
+                       while ($i < $hiddenZeros)       {
+                               $tmpBlock .= '0';
+                               $i++;
+                       }
+                       $normalizedAddress .= $tmpBlock . $block;
+                       if ($divCounter < 7)    {
+                               $normalizedAddress .= ':';
+                               $divCounter++;
+                       }
+               }
+               return $normalizedAddress;
+       }
+
+       /**
+        * Validate a given IP address to the IPv6 address format.
+        *
+        * Example for possible format:  43FB::BB3F:A0A0:0 | ::1
+        *
+        * @param       string          IP address to be tested
+        * @return      boolean         True if $ip is of IPv6 format.
+        */
+       function validIPv6($ip) {
+               $uppercaseIP = strtoupper($ip);
+
+               $regex = '/^(';
+               $regex.= '(([\dA-F]{1,4}:){7}[\dA-F]{1,4})|';
+               $regex.= '(([\dA-F]{1,4}){1}::([\dA-F]{1,4}:){1,5}[\dA-F]{1,4})|';
+               $regex.= '(([\dA-F]{1,4}:){2}:([\dA-F]{1,4}:){1,4}[\dA-F]{1,4})|';
+               $regex.= '(([\dA-F]{1,4}:){3}:([\dA-F]{1,4}:){1,3}[\dA-F]{1,4})|';
+               $regex.= '(([\dA-F]{1,4}:){4}:([\dA-F]{1,4}:){1,2}[\dA-F]{1,4})|';
+               $regex.= '(([\dA-F]{1,4}:){5}:([\dA-F]{1,4}:){0,1}[\dA-F]{1,4})|';
+               $regex.= '(::([\dA-F]{1,4}:){0,6}[\dA-F]{1,4})';
+               $regex.= ')$/';
+
+               return preg_match($regex, $uppercaseIP) ? true : false;
+       }
+
+       /**
         * Match fully qualified domain name with list of strings with wildcard
         *
-        * @param       string          $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
-        * @param       string          $list is a comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong)
+        * @param       string          The current remote IP address for instance, typ. REMOTE_ADDR
+        * @param       string          A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong)
         * @return      boolean         True if a domain name mask from $list matches $baseIP
         */
        function cmpFQDN($baseIP, $list)        {
@@ -650,20 +829,20 @@ class t3lib_div {
         * Check if an item exists in a comma-separated list of items.
         * Usage: 163
         *
-        * @param       string          $in_list        comma-separated list of items (string)
-        * @param       string          $item   item to check for
-        * @return      boolean         true if $item is in $in_list
+        * @param       string          comma-separated list of items (string)
+        * @param       string          item to check for
+        * @return      boolean         true if $item is in $list
         */
-       function inList($in_list,$item) {
-               return strstr(','.$in_list.',', ','.$item.',');
+       function inList($list,$item)    {
+               return strstr(','.$list.',', ','.$item.',') ? true : false;
        }
 
        /**
         * Removes an item from a comma-separated list of items.
         * Usage: 1
         *
-        * @param       string          $element        element to remove
-        * @param       string          $list   comma-separated list of items (string)
+        * @param       string          element to remove
+        * @param       string          comma-separated list of items (string)
         * @return      string          new comma-separated list of items
         */
        function rmFromList($element,$list)     {
@@ -676,8 +855,9 @@ class t3lib_div {
 
        /**
         * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
+        * Ranges are limited to 1000 values per range.
         *
-        * @param       string          $list   comma-separated list of integers with ranges (string)
+        * @param       string          comma-separated list of integers with ranges (string)
         * @return      string          new comma-separated list of items
         * @author      Martin Kutschker <martin.kutschker@activesolution.at>
         */
@@ -687,8 +867,12 @@ class t3lib_div {
                while(list(,$item)=each($items))        {
                        $range = explode('-',$item);
                        if (isset($range[1]))   {
+                               $runAwayBrake = 1000;
                                for ($n=$range[0]; $n<=$range[1]; $n++) {
                                        $list[] = $n;
+
+                                       $runAwayBrake--;
+                                       if ($runAwayBrake<=0)   break;
                                }
                        } else {
                                $list[] = $item;
@@ -743,6 +927,25 @@ class t3lib_div {
        }
 
        /**
+        * Returns true if the current TYPO3 version (or compatibility version) is compatible to the input version
+        * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
+        *
+        * @param       string          Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
+        * @return      boolean         Returns true if this setup is compatible with the provided version number
+        * @todo        Still needs a function to convert versions to branches
+        */
+       function compat_version($verNumberStr)  {
+               global $TYPO3_CONF_VARS;
+               $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version'] ? $TYPO3_CONF_VARS['SYS']['compat_version'] : TYPO3_branch;
+
+               if (t3lib_div::int_from_ver($currVersionStr) < t3lib_div::int_from_ver($verNumberStr))  {
+                       return FALSE;
+               } else {
+                       return TRUE;
+               }
+       }
+
+       /**
         * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
         * Usage: 5
         *
@@ -772,7 +975,7 @@ class t3lib_div {
         * Usage: 16
         *
         * @param       string          Accept multiple parameters wich can be comma-separated lists of values and arrays.
-        * @param       mixed           $secondParameter: Dummy field, which is set will show a warning!
+        * @param       mixed           $secondParameter: Dummy field, which if set will show a warning!
         * @return      string          Returns the list without any duplicates of values, space around values are trimmed
         */
        function uniqueList($in_list, $secondParameter=NULL)    {
@@ -790,6 +993,7 @@ class t3lib_div {
         * @return      array           Contains keys [path], [file], [filebody], [fileext], [realFileext]
         */
        function split_fileref($fileref)        {
+               $reg = array();
                if (    ereg('(.*/)(.*)$',$fileref,$reg)        )       {
                        $info['path'] = $reg[1];
                        $info['file'] = $reg[2];
@@ -879,11 +1083,11 @@ class t3lib_div {
 
        /**
         * strtoupper which converts danish (and other characters) characters as well
-        * (DEPRECIATED, use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
         * Usage: 0
         *
         * @param       string          String to process
         * @return      string
+        * @deprecated          Use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
         * @ignore
         */
        function danish_strtoupper($string)     {
@@ -894,11 +1098,11 @@ class t3lib_div {
        /**
         * Change umlaut characters to plain ASCII with normally two character target
         * Only known characters will be converted, so don't expect a result for any character.
-        * (DEPRECIATED: Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!)
         *
         * ä => ae, Ö => Oe
         *
         * @param       string          String to convert.
+        * @deprecated          Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!
         * @return      string
         */
        function convUmlauts($str)      {
@@ -1019,6 +1223,7 @@ class t3lib_div {
                $qm='\*\/\+-^%';
                $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
                        // split the expression here:
+               $reg = array();
                preg_match_all('/'.$regex.'/',$string,$reg);
 
                reset($reg[2]);
@@ -1184,8 +1389,8 @@ class t3lib_div {
         * Please note that the order of parameters is reverse compared to the php4-function in_array()!!!
         * Usage: 3
         *
-        * @param       array           $in_array               one-dimensional array of items
-        * @param       string          $item   item to check for
+        * @param       array           one-dimensional array of items
+        * @param       string          item to check for
         * @return      boolean         true if $item is in the one-dimensional array $in_array
         * @internal
         */
@@ -1259,13 +1464,12 @@ class t3lib_div {
 
        /**
         * Remove duplicate values from an array
-        * This function is deprecated, use the PHP function array_unique instead
         * Usage: 0
         *
         * @param       array           Array of values to make unique
         * @return      array
         * @ignore
-        * @deprecated
+        * @deprecated          Use the PHP function array_unique instead
         */
        function uniqueArray($valueArray)       {
                return array_unique($valueArray);
@@ -1304,8 +1508,9 @@ class t3lib_div {
         * @param       array           The (multidim) array to implode
         * @param       string          (keep blank)
         * @param       boolean         If set, parameters which were blank strings would be removed.
-        * @param       boolean         If set, the param name itselt (for example "param[key][key2]") would be rawurlencoded as well.
+        * @param       boolean         If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
         * @return      string          Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
+        * @see explodeUrl2Array()
         */
        function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)      {
                if (is_array($theArray))        {
@@ -1316,7 +1521,7 @@ class t3lib_div {
                                } else {
                                        if (!$skipBlank || strcmp($AVal,''))    {
                                                $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
-                                                       '='.rawurlencode($AVal);        // strips slashes because _POST / _GET input is with slashes...
+                                                       '='.rawurlencode($AVal);
                                        }
                                }
                        }
@@ -1325,6 +1530,30 @@ class t3lib_div {
        }
 
        /**
+        * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
+        *
+        * @param       string          GETvars string
+        * @param       boolean         If set, the string will be parsed into a multidimensional array if square brackets are used in variable names (using PHP function parse_str())
+        * @return      array           Array of values. All values AND keys are rawurldecoded() as they properly should be. But this means that any implosion of the array again must rawurlencode it!
+        * @see implodeArrayForUrl()
+        */
+       function explodeUrl2Array($string,$multidim=FALSE)      {
+               $output = array();
+               if ($multidim)  {
+                       parse_str($string,$output);
+               } else {
+                       $p = explode('&',$string);
+                       foreach($p as $v)       {
+                               if (strlen($v)) {
+                                       list($pK,$pV) = explode('=',$v,2);
+                                       $output[rawurldecode($pK)] = rawurldecode($pV);
+                               }
+                       }
+               }
+               return $output;
+       }
+
+       /**
         * Returns an array with selected keys from incoming data.
         * (Better read source code if you want to find out...)
         * Usage: 3
@@ -1417,7 +1646,7 @@ class t3lib_div {
         * @param       array           First array
         * @param       array           Second array, overruling the first array
         * @param       boolean         If set, keys that are NOT found in $arr0 (first array) will not be set. Thus only existing value can/will be overruled from second array.
-        * @param       boolean         If set, values from $arr1 will overrule if they are empty. Default: true
+        * @param       boolean         If set, values from $arr1 will overrule if they are empty or zero. Default: true
         * @return      array           Resulting array where $arr1 values has overruled $arr0 values
         */
        function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) {
@@ -1425,17 +1654,17 @@ class t3lib_div {
                while(list($key,$val) = each($arr1)) {
                        if(is_array($arr0[$key])) {
                                if (is_array($arr1[$key]))      {
-                                       $arr0[$key] = t3lib_div::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys);
+                                       $arr0[$key] = t3lib_div::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys,$includeEmtpyValues);
                                }
                        } else {
                                if ($notAddKeys) {
                                        if (isset($arr0[$key])) {
-                                               if ($includeEmtpyValues OR $val) {
+                                               if ($includeEmtpyValues || $val) {
                                                        $arr0[$key] = $val;
                                                }
                                        }
                                } else {
-                                       if ($includeEmtpyValues OR $val) {
+                                       if ($includeEmtpyValues || $val) {
                                                $arr0[$key] = $val;
                                        }
                                }
@@ -1469,15 +1698,35 @@ class t3lib_div {
        function csvValues($row,$delim=',',$quote='"')  {
                reset($row);
                $out=array();
-               while(list(,$value)=each($row)) {
-                       list($valPart) = explode(chr(10),$value);
-                       $valPart = trim($valPart);
-                       $out[]=str_replace($quote,$quote.$quote,$valPart);
+               foreach ($row as $value) {
+                       $out[] = str_replace($quote, $quote.$quote, $value);
                }
                $str = $quote.implode($quote.$delim.$quote,$out).$quote;
                return $str;
        }
 
+       /**
+        * Removes dots "." from end of a key identifier of TypoScript styled array.
+        * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
+        *
+        * @param       array   $ts: TypoScript configuration array
+        * @return      array   TypoScript configuration array without dots at the end of all keys
+        */
+       function removeDotsFromTS($ts) {
+               $out = array();
+               if (is_array($ts)) {
+                       foreach ($ts as $key => $value) {
+                               if (is_array($value)) {
+                                       $key = rtrim($key, '.');
+                                       $out[$key] = t3lib_div::removeDotsFromTS($value);
+                               } else {
+                                       $out[$key] = $value;
+                               }
+                       }
+               }
+               return $out;
+       }
+
 
 
 
@@ -1629,6 +1878,7 @@ class t3lib_div {
                                // remove nl from the beginning
                        $string = preg_replace ('/^\n+/', '', $string);
                                // re-ident to one tab using the first line as reference
+                       $match = array();
                        if(preg_match('/^(\t+)/',$string,$match)) {
                                $string = str_replace($match[1],"\t", $string);
                        }
@@ -1667,6 +1917,7 @@ class t3lib_div {
                $stacktop = 0;
                $startPoint=0;
 
+// FIXME don't use unset() - what does that mean? Use NULL or similar.
                unset($tagi);
                foreach($vals as $key => $val) {
                        $type = $val['type'];
@@ -1717,13 +1968,43 @@ class t3lib_div {
        }
 
        /**
+        * Turns PHP array into XML. See array2xml()
+        *
+        * @param       array           The input PHP array with any kind of data; text, binary, integers. Not objects though.
+        * @param       string          Alternative document tag. Default is "phparray".
+        * @param       array           Options for the compilation. See array2xml() for description.
+        * @param       string          Forced charset to prologue
+        * @return      string          An XML string made from the input content in the array.
+        * @see xml2array(),array2xml()
+        */
+       function array2xml_cs($array,$docTag='phparray',$options=array(),$charset='')   {
+
+                       // Figure out charset if not given explicitly:
+               if (!$charset)  {
+                       if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'])  {       // First priority: forceCharset! If set, this will be authoritative!
+                               $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
+                       } elseif (is_object($GLOBALS['LANG']))  {
+                               $charset = $GLOBALS['LANG']->charSet;   // If "LANG" is around, that will hold the current charset
+                       } else {
+                               $charset = 'iso-8859-1';        // THIS is just a hopeful guess!
+                       }
+               }
+
+                       // Return XML:
+               return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.chr(10).
+                               t3lib_div::array2xml($array,'',0,$docTag,0, $options);
+       }
+
+       /**
+        * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
+        *
         * Converts a PHP array into an XML string.
         * The XML output is optimized for readability since associative keys are used as tagnames.
         * This also means that only alphanumeric characters are allowed in the tag names AND only keys NOT starting with numbers (so watch your usage of keys!). However there are options you can set to avoid this problem.
         * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
         * The function handles input values from the PHP array in a binary-safe way; All characters below 32 (except 9,10,13) will trigger the content to be converted to a base64-string
         * The PHP variable type of the data IS preserved as long as the types are strings, arrays, integers and booleans. Strings are the default type unless the "type" attribute is set.
-        * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances.
+        * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances with 4.x versions. However, with PHP5 there seems to be the need to add an XML prologue a la <?xml version="1.0" encoding="[charset]" standalone="yes" ?> - otherwise UTF-8 is assumed! Unfortunately, many times the output from this function is used without adding that prologue meaning that non-ASCII characters will break the parsing!! This suchs of course! Effectively it means that the prologue should always be prepended setting the right characterset, alternatively the system should always run as utf-8!
         * However using MSIE to read the XML output didn't always go well: One reason could be that the character encoding is not observed in the PHP data. The other reason may be if the tag-names are invalid in the eyes of MSIE. Also using the namespace feature will make MSIE break parsing. There might be more reasons...
         * Usage: 5
         *
@@ -1731,7 +2012,7 @@ class t3lib_div {
         * @param       string          tag-prefix, eg. a namespace prefix like "T3:"
         * @param       integer         Current recursion level. Don't change, stay at zero!
         * @param       string          Alternative document tag. Default is "phparray".
-        * @param       integer         If set, the number of spaces corresponding to this number is used for indenting, otherwise a single chr(9) (TAB) is used
+        * @param       integer         If greater than zero, then the number of spaces corresponding to this number is used for indenting, if less than zero - no indentation, if zero - a single chr(9) (TAB) is used
         * @param       array           Options for the compilation. Key "useNindex" => 0/1 (boolean: whether to use "n0, n1, n2" for num. indexes); Key "useIndexTagForNum" => "[tag for numerical indexes]"; Key "useIndexTagForAssoc" => "[tag for associative indexes"; Key "parentTagMap" => array('parentTag' => 'thisLevelTag')
         * @param       string          Stack data. Don't touch.
         * @return      string          An XML string made from the input content in the array.
@@ -1746,6 +2027,7 @@ class t3lib_div {
                        // Set indenting mode:
                $indentChar = $spaceInd ? ' ' : chr(9);
                $indentN = $spaceInd>0 ? $spaceInd : 1;
+               $nl = ($spaceInd >= 0 ? chr(10) : '');
 
                        // Init output variable:
                $output='';
@@ -1760,6 +2042,9 @@ class t3lib_div {
                                if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) {            // Use tag based on grand-parent + parent tag name
                                        $attr.=' index="'.htmlspecialchars($tagName).'"';
                                        $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
+                               }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM']) && t3lib_div::testInt($tagName)) {              // Use tag based on parent tag name + if current tag is numeric
+                                       $attr.=' index="'.htmlspecialchars($tagName).'"';
+                                       $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM'];
                                }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) {            // Use tag based on parent tag name + current tag
                                        $attr.=' index="'.htmlspecialchars($tagName).'"';
                                        $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
@@ -1793,7 +2078,7 @@ class t3lib_div {
                                                $clearStackPath = FALSE;
                                        }
 
-                                       $content = chr(10).
+                                       $content = $nl .
                                                                t3lib_div::array2xml(
                                                                        $v,
                                                                        $NSprefix,
@@ -1807,32 +2092,41 @@ class t3lib_div {
                                                                                'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
                                                                        )
                                                                ).
-                                                               str_pad('',($level+1)*$indentN,$indentChar);
-                                       $attr.=' type="array"';
+                                                               ($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '');
+                                       if ((int)$options['disableTypeAttrib']!=2)      {       // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
+                                               $attr.=' type="array"';
+                                       }
                                } else {        // Just a value:
 
                                                // Look for binary chars:
-                                       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!
+                                       $vLen = strlen($v);     // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
+                                       if ($vLen && strcspn($v,$binaryChars) != $vLen) {       // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
                                                        // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
-                                               $content = chr(10).chunk_split(base64_encode($v));
+                                               $content = $nl.chunk_split(base64_encode($v));
                                                $attr.=' base64="1"';
                                        } else {
                                                        // Otherwise, just htmlspecialchar the stuff:
                                                $content = htmlspecialchars($v);
                                                $dType = gettype($v);
-                                               if ($dType!='string' && !$options['disableTypeAttrib']) { $attr.=' type="'.$dType.'"'; }
+                                               if ($dType == 'string') {
+                                                       if ($options['useCDATA'] && $content != $v) {
+                                                               $content = '<![CDATA[' . $v . ']]>';
+                                                       }
+                                               } elseif (!$options['disableTypeAttrib']) {
+                                                       $attr.= ' type="'.$dType.'"';
+                                               }
                                        }
                                }
 
                                        // Add the element to the output string:
-                               $output.=str_pad('',($level+1)*$indentN,$indentChar).'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.chr(10);
+                               $output.=($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '').'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.$nl;
                        }
                }
 
                        // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
                if (!$level)    {
                        $output =
-                               '<'.$docTag.'>'.chr(10).
+                               '<'.$docTag.'>'.$nl.
                                $output.
                                '</'.$docTag.'>';
                }
@@ -1862,14 +2156,18 @@ class t3lib_div {
                xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
                xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
 
-                       // PHP5 fix of charset awareness:
-                       // 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.
-                       // 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.
-                       // 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.
-               if ((double)phpversion()>=5)    {
-                       unset($ereg_result);
-                       ereg('^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"',substr($string,0,200),$ereg_result);
-                       $theCharset = $ereg_result[1] ? $ereg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
+                       //  PHP4 doesn't like Unicode byte order marks (BOM), so we have to check for them
+                       // The BOM check comes first, so that the PHP5 preg_match() below doesn't have to check for it
+               if(substr($string,0,3)=="\xEF\xBB\xBF") {
+                       xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
+               }
+                       // PHP 4.x: output charset is the same as the input charset, charsets are handled transparently if not specified in xml_parser_create()
+                       // PHP 5.0.0 & 5.0.1: default output charset is ISO-8859-1, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
+                       // PHP 5.0.2+: default output charset is UTF-8  , only ASCII, ISO-8859-1 and UTF-8 are supported!!!
+               elseif ((double)phpversion()>=5)        {
+                       $match = array();
+                       preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$match);
+                       $theCharset = $match[1] ? $match[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
                        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset);  // us-ascii / utf-8 / iso-8859-1
                }
 
@@ -2035,40 +2333,93 @@ class t3lib_div {
         * Usage: 83
         *
         * @param       string          Filepath/URL to read
+        * @param       integer         Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
+        * @param       array           HTTP headers to be used in the request
         * @return      string          The content from the resource given as input.
         */
-       function getURL($url)   {
-               $content = '';
+       function getURL($url, $includeHeader = 0, $requestHeaders = false)      {
+               $content = false;
 
                        // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
-               if((substr($url,0,7)=='http://') && ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse']=='1'))       {
-                       //external URL without error checking.
+               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^https?:\/\//', $url)) {
+                               // External URL without error checking.
                        $ch = curl_init();
-                       curl_setopt ($ch,CURLOPT_URL, $url);
-                       curl_setopt ($ch,CURLOPT_HEADER, 0);
-                       curl_setopt ($ch,CURLOPT_RETURNTRANSFER, 1);
+                       if (!$ch)       {
+                               return false;
+                       }
 
-                       if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
-                               curl_setopt ($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
+                       curl_setopt($ch, CURLOPT_URL, $url);
+                       curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
+                       curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
+                       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
+                       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+                       curl_setopt($ch, CURLOPT_FAILONERROR, 1);
+                       if (is_array($requestHeaders))  {
+                               curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
+                       }
 
-                               // I don't know if it will be needed
-                               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
-                                       curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'] );
+                       if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer'])      {
+                               curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
+
+                                       // Not sure if this is needed
+                               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'])      {
+                                       curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
                                }
-                               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
-                                       curl_setopt ($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'] );
+                               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'])    {
+                                       curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
                                }
                        }
-                       $content=curl_exec ($ch);
-                       curl_close ($ch);
-                       return $content;
-               } elseif($fd = fopen($url,'rb'))    {
-                       while (!feof($fd))      {
-                               $content.=fread($fd, 5000);
+                       $content = curl_exec($ch);
+                       curl_close($ch);
+
+               } elseif ($includeHeader)       {
+                       $parsedURL = parse_url($url);
+                       if (!t3lib_div::inList('ftp,ftps,http,https,gopher,telnet', $parsedURL['scheme']))      {
+                               return false;
+                       }
+
+                       $fp = @fsockopen($parsedURL['host'], ($parsedURL['port'] > 0 ? $parsedURL['port'] : 80), $errno, $errstr, 2.0);
+                       if (!$fp)       {
+                               return false;
+                       }
+
+                       $msg = 'GET ' . $parsedURL['path'] .
+                                       ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
+                                       ' HTTP/1.0' . "\r\n" . 'Host: ' .
+                                       $parsedURL['host'] . "\r\n\r\n";
+                       fputs($fp, $msg);
+                       while (!feof($fp))      {
+                               $line = fgets($fp, 2048);
+                               $content.= $line;
+                               if ($includeHeader == 2 && !strlen(trim($line)))        {
+                                       break;  // Stop at the first empty line (= end of header)
+                               }
+                       }
+                       fclose($fp);
+
+               } elseif (is_array($requestHeaders))    {
+                       $ctx = stream_context_create(array(
+                                               'http' => array(
+                                                       'header' => implode("\r\n", $requestHeaders)
+                                               )
+                                       )
+                               );
+                       if (version_compare(phpversion(), '5.0', '>=')) {
+                               $content = @file_get_contents($url, false, $ctx);
+                       }
+                       elseif (false !== ($fd = @fopen($url, 'rb', false, $ctx)))      {
+                               $content = '';
+                               while (!feof($fd))      {
+                                       $content.= @fread($fd, 4096);
+                               }
+                               fclose($fd);
                        }
-                       fclose($fd);
-                       return $content;
                }
+               else    {
+                       $content = @file_get_contents($url);
+               }
+
+               return $content;
        }
 
        /**
@@ -2080,14 +2431,22 @@ class t3lib_div {
         * @return      boolean         True if the file was successfully opened and written to.
         */
        function writeFile($file,$content)      {
-               if($fd = fopen($file,'wb'))     {
-                       fwrite( $fd, $content);
-                       fclose( $fd );
+               if (!@is_file($file))   $changePermissions = true;
 
-                       t3lib_div::fixPermissions($file);       // Change the permissions of the file
+               if ($fd = fopen($file,'wb'))    {
+                       $res = fwrite($fd,$content);
+                       fclose($fd);
+
+                       if ($res===false)       return false;
+
+                       if ($changePermissions) {       // Change the permissions only if the file has just been created
+                               t3lib_div::fixPermissions($file);
+                       }
 
                        return true;
                }
+
+               return false;
        }
 
        /**
@@ -2106,7 +2465,7 @@ class t3lib_div {
        }
 
        /**
-        * Writes $content to a filename in the typo3temp/ folder (and possibly a subfolder...)
+        * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
         * Accepts an additional subdirectory in the file path!
         *
         * @param       string          Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
@@ -2129,12 +2488,12 @@ class t3lib_div {
                                                        // Checking if the "subdir" is found:
                                                $subdir = substr($fI['dirname'],strlen($dirName));
                                                if ($subdir)    {
-                                                       if (ereg('^[[:alnum:]_]+\/$',$subdir))  {
+                                                       if (ereg('^[[:alnum:]_]+\/$',$subdir) || ereg('^[[:alnum:]_]+\/[[:alnum:]_]+\/$',$subdir))      {
                                                                $dirName.= $subdir;
                                                                if (!@is_dir($dirName)) {
-                                                                       t3lib_div::mkdir($dirName);
+                                                                       t3lib_div::mkdir_deep(PATH_site.'typo3temp/', $subdir);
                                                                }
-                                                       } else return 'Subdir, "'.$subdir.'", was NOT on the form "[a-z]/"';
+                                                       } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or  "[[:alnum:]_]/[[:alnum:]_]/"';
                                                }
                                                        // Checking dir-name again (sub-dir might have been created):
                                                if (@is_dir($dirName))  {
@@ -2157,7 +2516,7 @@ class t3lib_div {
         * @return      boolean         TRUE if @mkdir went well!
         */
        function mkdir($theNewFolder)   {
-               $theNewFolder = ereg_replace('\/$','',$theNewFolder);
+               $theNewFolder = preg_replace('|/$|','',$theNewFolder);
                if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
                        chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
 
@@ -2169,6 +2528,61 @@ class t3lib_div {
        }
 
        /**
+        * Creates a directory - including parent directories if necessary - in the file system
+        *
+        * @param       string          Base folder. This must exist! Must have trailing slash! Example "/root/typo3site/"
+        * @param       string          Deep directory to create, eg. "xx/yy/" which creates "/root/typo3site/xx/yy/" if $destination is "/root/typo3site/"
+        * @return      string          If error, returns error string.
+        */
+       function mkdir_deep($destination,$deepDir)      {
+               $allParts = t3lib_div::trimExplode('/',$deepDir,1);
+               $root = '';
+               foreach($allParts as $part)     {
+                       $root.= $part.'/';
+                       if (!is_dir($destination.$root))        {
+                               t3lib_div::mkdir($destination.$root);
+                               if (!@is_dir($destination.$root))       {
+                                       return 'Error: The directory "'.$destination.$root.'" could not be created...';
+                               }
+                       }
+               }
+       }
+
+       /**
+        * Wrapper function for rmdir, allowing recursive deletion of folders and files
+        *
+        * @param       string          Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
+        * @param       boolean         Allow deletion of non-empty directories
+        * @return      boolean         true if @rmdir went well!
+        */
+       function rmdir($path,$removeNonEmpty=false)     {
+               $OK = false;
+               $path = preg_replace('|/$|','',$path);  // Remove trailing slash
+
+               if (file_exists($path)) {
+                       $OK = true;
+
+                       if (is_dir($path))      {
+                               if ($removeNonEmpty==true && $handle = opendir($path))  {
+                                       while ($OK && false !== ($file = readdir($handle)))     {
+                                               if ($file=='.' || $file=='..') continue;
+                                               $OK = t3lib_div::rmdir($path.'/'.$file,$removeNonEmpty);
+                                       }
+                                       closedir($handle);
+                               }
+                               if ($OK)        { $OK = rmdir($path); }
+
+                       } else {        // If $dirname is a file, simply remove it
+                               $OK = unlink($path);
+                       }
+
+                       clearstatcache();
+               }
+
+               return $OK;
+       }
+
+       /**
         * Returns an array with the names of folders in a specific path
         * Will return 'error' (string) if there were an error with reading directory content.
         * Usage: 11
@@ -2199,9 +2613,10 @@ class t3lib_div {
         * @param       string          $extensionList is the comma list of extensions to read only (blank = all)
         * @param       boolean         If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
         * @param       string          $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
+        * @param       string          A comma seperated list of filenames to exclude, no wildcards
         * @return      array           Array of the files found
         */
-       function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')        {
+       function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='')     {
 
                        // Initialize variabels:
                $filearray = array();
@@ -2217,9 +2632,9 @@ class t3lib_div {
                                        if (@is_file($path.'/'.$entry)) {
                                                $fI = pathinfo($entry);
                                                $key = md5($path.'/'.$entry);   // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
-                                               if (!$extensionList || t3lib_div::inList($extensionList,strtolower($fI['extension'])))  {
+                                               if ((!strlen($extensionList) || t3lib_div::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$entry))) {
                                                    $filearray[$key]=($prependPath?$path.'/':'').$entry;
-                                                       if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
+                                                               if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
                                                                elseif ($order) {$sortarray[$key]=$entry;}
                                                }
                                        }
@@ -2253,17 +2668,18 @@ class t3lib_div {
         * @param       string          $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
         * @param       boolean         $regDirs: If set, directories are also included in output.
         * @param       integer         $recursivityLevels: The number of levels to dig down...
+        * @param string                $excludePattern: regex pattern of files/directories to exclude
         * @return      array           An array with the found files/directories.
         */
-       function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)       {
+       function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='')    {
                if ($regDirs)   $fileArr[] = $path;
-               $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path,$extList,1,1));
+               $fileArr = array_merge($fileArr, t3lib_div::getFilesInDir($path,$extList,1,1,$excludePattern));
 
                $dirs = t3lib_div::get_dirs($path);
                if (is_array($dirs) && $recursivityLevels>0)    {
                        foreach ($dirs as $subdirs)     {
-                               if ((string)$subdirs!=''      {
-                                       $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
+                               if ((string)$subdirs!='' && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$subdirs)))      {
+                                       $fileArr = t3lib_div::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1,$excludePattern);
                                }
                        }
                }
@@ -2309,6 +2725,7 @@ class t3lib_div {
        function resolveBackPath($pathStr)      {
                $parts = explode('/',$pathStr);
                $output=array();
+               $c = 0;
                foreach($parts as $pV)  {
                        if ($pV=='..')  {
                                if ($c) {
@@ -2395,7 +2812,7 @@ class t3lib_div {
                        $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
                        if (!count($array_in))  {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
                        while (list($key,$val)=each($array_in)) {
-                               $result.= '<tr><td><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
+                               $result.= '<tr><td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
                                if (is_array($array_in[$key]))  {
                                        $result.=t3lib_div::view_array($array_in[$key]);
                                } else
@@ -2404,7 +2821,11 @@ class t3lib_div {
                        }
                        $result.= '</table>';
                } else  {
-                       $result  = false;
+                       $result  = '<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">
+                               <tr>
+                                       <td><font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$array_in)).'<br /></font></td>
+                               </tr>
+                       </table>';      // Output it as a string.
                }
                return $result;
        }
@@ -2434,9 +2855,9 @@ class t3lib_div {
         * @return      void
         */
        function debug($var="",$brOrHeader=0)   {
-               if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
-                       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>';
-               } elseif ($brOrHeader<0) {
+               if ($brOrHeader && !t3lib_div::testInt($brOrHeader))    {
+                       echo '<table class="typo3-debug" border="0" cellpadding="0" cellspacing="0" bgcolor="white" style="border:0px; margin-top:3px; margin-bottom:3px;"><tr><td style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;">'.htmlspecialchars((string)$brOrHeader).'</td></tr><tr><td>';
+               } elseif ($brOrHeader<0)        {
                        for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
                }
 
@@ -2446,22 +2867,83 @@ class t3lib_div {
                        echo '<b>|Object:<pre>';
                        print_r($var);
                        echo '</pre>|</b>';
-               } elseif ((string)$var!='') {
+               } elseif ((string)$var!='')     {
                        echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
                } else {
                        echo '<b>| debug |</b>';
                }
 
-               if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
+               if ($brOrHeader && !t3lib_div::testInt($brOrHeader))    {
                        echo '</td></tr></table>';
-               } elseif ($brOrHeader>0) {
+               } elseif ($brOrHeader>0)        {
                        for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
                }
        }
 
+       /**
+        * Displays the "path" of the function call stack in a string, using debug_backtrace
+        *
+        * @return      string
+        */
+       function debug_trail()  {
+               $trail = debug_backtrace();
+               $trail = array_reverse($trail);
+               array_pop($trail);
+
+               $path = array();
+               foreach($trail as $dat) {
+                       $path[] = $dat['class'].$dat['type'].$dat['function'];
+               }
 
+               return implode(' // ',$path);
+       }
 
+       /**
+        * Displays an array as rows in a table. Useful to debug output like an array of database records.
+        *
+        * @param       array           Array of arrays with similar keys
+        * @param       string          Table header
+        * @param       boolean         If TRUE, will return content instead of echo'ing out.
+        * @return      void            Outputs to browser.
+        */
+       function debugRows($rows,$header='',$returnHTML=FALSE)  {
+               if (is_array($rows))    {
+                       reset($rows);
+                       $firstEl = current($rows);
+                       if (is_array($firstEl)) {
+                               $headerColumns = array_keys($firstEl);
+                               $tRows = array();
+
+                                       // Header:
+                               $tRows[] = '<tr><td colspan="'.count($headerColumns).'" style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;"><strong>'.htmlspecialchars($header).'</strong></td></tr>';
+                               $tCells = array();
+                               foreach($headerColumns as $key) {
+                                       $tCells[] = '
+                                                       <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
+                               }
+                               $tRows[] = '
+                                               <tr>'.implode('',$tCells).'
+                                               </tr>';
+
+                                       // Rows:
+                               foreach($rows as $singleRow)    {
+                                       $tCells = array();
+                                       foreach($headerColumns as $key) {
+                                               $tCells[] = '
+                                                       <td><font face="Verdana,Arial" size="1">'.(is_array($singleRow[$key]) ? t3lib_div::debugRows($singleRow[$key],'',TRUE) : htmlspecialchars($singleRow[$key])).'</font></td>';
+                                       }
+                                       $tRows[] = '
+                                               <tr>'.implode('',$tCells).'
+                                               </tr>';
+                               }
 
+                               $table = '
+                                       <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
+                                       </table>';
+                               if ($returnHTML)        return $table; else echo $table;
+                       } else debug('Empty array of rows',$header);
+               } else debug('No array of rows',$header);
+       }
 
 
 
@@ -2512,7 +2994,7 @@ class t3lib_div {
        /**
         * Returns the link-url to the current script.
         * In $getParams you can set associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL.
-        * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
+        * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
         * Usage: 52
         *
         * @param       array           Array of GET parameters to include
@@ -2544,12 +3026,10 @@ class t3lib_div {
         */
        function linkThisUrl($url,$getParams=array())   {
                $parts = parse_url($url);
+               $getP = array();
                if ($parts['query'])    {
                        parse_str($parts['query'],$getP);
-               } else {
-                       $getP = array();
                }
-
                $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
                $uP = explode('?',$url);
 
@@ -2608,15 +3088,16 @@ class t3lib_div {
                                SCRIPT_FILENAME =       Absolute filename of script             (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
 
                        Special extras:
-                               TYPO3_HOST_ONLY =               [host]                  = 192.168.1.4
-                               TYPO3_PORT              =               [port]                  = 8080 (blank if 80, taken from host value)
+                               TYPO3_HOST_ONLY =               [host] = 192.168.1.4
+                               TYPO3_PORT =                    [port] = 8080 (blank if 80, taken from host value)
                                TYPO3_REQUEST_HOST =    [scheme]://[host][:[port]]
-                               TYPO3_REQUEST_URL =             [scheme]://[host][:[port]][path]?[query]        (sheme will by default be 'http' until we can detect if it's https -
+                               TYPO3_REQUEST_URL =             [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
                                TYPO3_REQUEST_SCRIPT =  [scheme]://[host][:[port]][path_script]
                                TYPO3_REQUEST_DIR =             [scheme]://[host][:[port]][path_dir]
                                TYPO3_SITE_URL =                [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
                                TYPO3_SITE_SCRIPT =     [script / Speaking URL] of the TYPO3 website
-                               TYPO3_DOCUMENT_ROOT     =       Absolute path of root of documents:     TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
+                               TYPO3_DOCUMENT_ROOT =   Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
+                               TYPO3_SSL =                     Returns TRUE if this session uses SSL (HTTPS)
 
                        Notice: [fragment] is apparently NEVER available to the script!
 
@@ -2629,19 +3110,25 @@ class t3lib_div {
                */
 
 #              if ($getEnvName=='HTTP_REFERER')        return '';
-               switch((string)$getEnvName)     {
+
+               $retVal = '';
+
+               switch ((string)$getEnvName)    {
                        case 'SCRIPT_NAME':
-                               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']);
+                               $retVal = (php_sapi_name()=='cgi'||php_sapi_name()=='cgi-fcgi')&&($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) ? ($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) : ($_SERVER['ORIG_SCRIPT_NAME']?$_SERVER['ORIG_SCRIPT_NAME']:$_SERVER['SCRIPT_NAME']);
                        break;
                        case 'SCRIPT_FILENAME':
-                               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'])));
+                               $retVal = str_replace('//','/', str_replace('\\','/', (php_sapi_name()=='cgi'||php_sapi_name()=='isapi' ||php_sapi_name()=='cgi-fcgi')&&($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED'])? ($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED']):($_SERVER['ORIG_SCRIPT_FILENAME']?$_SERVER['ORIG_SCRIPT_FILENAME']:$_SERVER['SCRIPT_FILENAME'])));
                        break;
                        case 'REQUEST_URI':
                                        // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
-                               if (!$_SERVER['REQUEST_URI'])   {       // This is for ISS/CGI which does not have the REQUEST_URI available.
-                                       return '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
+                               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar'])        {       // This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL)
+                                       list($v,$n) = explode('|',$GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
+                                       $retVal = $GLOBALS[$v][$n];
+                               } elseif (!$_SERVER['REQUEST_URI'])     {       // This is for ISS/CGI which does not have the REQUEST_URI available.
+                                       $retVal = '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
                                                ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
-                               } else return $_SERVER['REQUEST_URI'];
+                               } else $retVal = $_SERVER['REQUEST_URI'];
                        break;
                        case 'PATH_INFO':
                                        // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
@@ -2649,8 +3136,8 @@ class t3lib_div {
                                        // 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)
 //                             if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1)  {
                                if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi')        {
-                                       return $_SERVER['PATH_INFO'];
-                               } else return '';
+                                       $retVal = $_SERVER['PATH_INFO'];
+                               }
                        break;
                                // These are let through without modification
                        case 'REMOTE_ADDR':
@@ -2660,7 +3147,7 @@ class t3lib_div {
                        case 'HTTP_USER_AGENT':
                        case 'HTTP_ACCEPT_LANGUAGE':
                        case 'QUERY_STRING':
-                               return $_SERVER[$getEnvName];
+                               $retVal = $_SERVER[$getEnvName];
                        break;
                        case 'TYPO3_DOCUMENT_ROOT':
                                // 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.
@@ -2675,29 +3162,29 @@ class t3lib_div {
                                        } else break;
                                }
                                $commonEnd=strrev(implode('/',$acc));
-                               if (strcmp($commonEnd,''))              $DR = substr($SFN,0,-(strlen($commonEnd)+1));
-                               return $DR;
+                               if (strcmp($commonEnd,''))      { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
+                               $retVal = $DR;
                        break;
                        case 'TYPO3_HOST_ONLY':
                                $p = explode(':',$_SERVER['HTTP_HOST']);
-                               return $p[0];
+                               $retVal = $p[0];
                        break;
                        case 'TYPO3_PORT':
                                $p = explode(':',$_SERVER['HTTP_HOST']);
-                               return $p[1];
+                               $retVal = $p[1];
                        break;
                        case 'TYPO3_REQUEST_HOST':
-                               return (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
+                               $retVal = (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
                                        $_SERVER['HTTP_HOST'];
                        break;
                        case 'TYPO3_REQUEST_URL':
-                               return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
+                               $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('REQUEST_URI');
                        break;
                        case 'TYPO3_REQUEST_SCRIPT':
-                               return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
+                               $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::getIndpEnv('SCRIPT_NAME');
                        break;
                        case 'TYPO3_REQUEST_DIR':
-                               return t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
+                               $retVal = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div::dirname(t3lib_div::getIndpEnv('SCRIPT_NAME')).'/';
                        break;
                        case 'TYPO3_SITE_URL':
                                if (defined('PATH_thisScript') && defined('PATH_site')) {
@@ -2705,14 +3192,14 @@ class t3lib_div {
                                        $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
                                        $siteUrl = substr($url,0,-strlen($lPath));
                                        if (substr($siteUrl,-1)!='/')   $siteUrl.='/';
-                                       return $siteUrl;
-                               } else return '';
+                                       $retVal = $siteUrl;
+                               }
                        break;
                        case 'TYPO3_SITE_SCRIPT':
-                               return substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
+                               $retVal = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
                        break;
                        case 'TYPO3_SSL':
-                               return $_SERVER['SSL_SESSION_ID'] || !strcmp($_SERVER['HTTPS'],'on') ? TRUE : FALSE;
+                               $retVal = $_SERVER['SSL_SESSION_ID'] || !strcmp($_SERVER['HTTPS'],'on') || !strcmp($_SERVER['HTTPS'],'1') ? TRUE : FALSE;       // see http://bugs.typo3.org/view.php?id=3909
                        break;
                        case '_ARRAY':
                                $out = array();
@@ -2744,9 +3231,10 @@ class t3lib_div {
                                        $out[$v]=t3lib_div::getIndpEnv($v);
                                }
                                reset($out);
-                               return $out;
+                               $retVal = $out;
                        break;
                }
+               return $retVal;
        }
 
        /**
@@ -2777,7 +3265,7 @@ class t3lib_div {
                        $bInfo['BROWSER']= 'konqu';
                } elseif (strstr($useragent,'Opera'))   {
                        $bInfo['BROWSER']= 'opera';
-               } elseif (strstr($useragent,'MSIE 4') || strstr($useragent,'MSIE 5') || strstr($useragent,'MSIE 6'))    {
+               } elseif (preg_match('/MSIE [4567]/', $useragent))      {
                        $bInfo['BROWSER']= 'msie';
                } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5'))     {
                        $bInfo['BROWSER']='net';
@@ -2787,7 +3275,8 @@ class t3lib_div {
                        switch($bInfo['BROWSER'])       {
                                case 'net':
                                        $bInfo['VERSION']= doubleval(substr($useragent,8));
-                                       if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
+                                       if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape6/'),10));}       // Will we ever know if this was a typo or intention...?! :-(
+                                       if (strstr($useragent,'Netscape/6')) {$bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/6'),10));}
                                        if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
                                break;
                                case 'msie':
@@ -2818,6 +3307,37 @@ class t3lib_div {
                return $bInfo;
        }
 
+       /**
+        * Get the fully-qualified domain name of the host.
+        * Usage: 2
+        *
+        * @param       boolean         Use request host (when not in CLI mode).
+        * @return      string          The fully-qualified host name.
+        */
+       function getHostname($requestHost=TRUE) {
+               $host = '';
+               if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode))      {
+                       $host = $_SERVER['HTTP_HOST'];
+               }
+               if (!$host)     {
+                               // will fail for PHP 4.1 and 4.2
+                       $host = @php_uname('n');
+                               // 'n' is ignored in broken installations
+                       if (strpos($host, ' ')) $host = '';
+               }
+                       // we have not found a FQDN yet
+               if ($host && strpos('.',$host) === FALSE)       {
+                       $ip = gethostbyname($host);
+                               // we got an IP address
+                       if ($ip != $host)       {
+                               $fqdn = gethostbyaddr($ip);
+                               if ($ip != $fqdn)       $host = $fqdn;
+                       }
+               }
+               if (!$host)     $host = 'localhost.localdomain';
+
+               return $host;
+       }
 
 
 
@@ -2888,11 +3408,11 @@ class t3lib_div {
         * Usage: 14
         *
         * @param       string          Filepath to evaluate
-        * @return      boolean         True, if no '//', '..' or '\' is in the $theFile
+        * @return      boolean         True, if no '//', '\', '/../' is in the $theFile and $theFile doesn't begin with '../'
         * @todo        Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
         */
        function validPathStr($theFile) {
-               if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
+               if (!strstr($theFile,'//') && !strstr($theFile,'\\') && !preg_match('#(?:^\.\.|/\.\./)#',$theFile))     return true;
        }
 
        /**
@@ -3013,25 +3533,27 @@ class t3lib_div {
        }
 
        /**
-        * standard authentication code - can't remember what it's used for.
+        * Standard authentication code (used in Direct Mail, checkJumpUrl and setfixed links computations)
         * Usage: 2
         *
         * @param       mixed           Uid (integer) or record (array)
         * @param       string          List of fields from the record if that is given.
+        * @param       integer         Length of returned authentication code.
         * @return      string          MD5 hash of 8 chars.
         * @internal
         */
-       function stdAuthCode($uid_or_record,$fields='') {
+       function stdAuthCode($uid_or_record,$fields='',$codeLength=8)   {
+
                if (is_array($uid_or_record))   {
                        $recCopy_temp=array();
                        if ($fields)    {
                                $fieldArr = t3lib_div::trimExplode(',',$fields,1);
                                reset($fieldArr);
                                while(list($k,$v)=each($fieldArr))      {
-                                       $recCopy_temp[$k]=$recCopy[$v];
+                                       $recCopy_temp[$k]=$uid_or_record[$v];
                                }
                        } else {
-                               $recCopy_temp=$recCopy;
+                               $recCopy_temp=$uid_or_record;
                        }
                        $preKey = implode('|',$recCopy_temp);
                } else {
@@ -3039,7 +3561,7 @@ class t3lib_div {
                }
 
                $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
-               $authCode = substr(md5($authCode),0,8);
+               $authCode = substr(md5($authCode),0,$codeLength);
                return $authCode;
        }
 
@@ -3048,7 +3570,7 @@ class t3lib_div {
         * Used to create the cHash value
         *
         * @param       string          Query-parameters: "&xxx=yyy&zzz=uuu"
-        * @return      array           Array with key/value pairs of query-parameters WITHOUT a certain list of variable names (like id, type, no_cache etc) and WITH a variable, encryptionKey, specific for this server/installation
+        * @return      array           Array with key/value pairs of query-parameters WITHOUT a certain list of variable names (like id, type, no_cache etc.) and WITH a variable, encryptionKey, specific for this server/installation
         * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink()
         */
        function cHashParams($addQueryParams) {
@@ -3058,8 +3580,8 @@ class t3lib_div {
                $pA = array();
                foreach($params as $theP)       {
                        $pKV = explode('=', $theP);     // Splitting single param by '=' sign
-                       if (!t3lib_div::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0]))        {
-                               $pA[$pKV[0]] = (string)rawurldecode($pKV[1]);
+                       if (!t3lib_div::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0]) && !preg_match('/TSFE_ADMIN_PANEL\[.*?\]/',$pKV[0]))    {
+                               $pA[rawurldecode($pKV[0])] = (string)rawurldecode($pKV[1]);
                        }
                }
                $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
@@ -3069,12 +3591,220 @@ class t3lib_div {
        }
 
        /**
+        * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
+        *
+        * @param       integer         Value from "l18n_cfg" field of a page record
+        * @return      boolean         True if the page should be hidden
+        */
+       function hideIfNotTranslated($l18n_cfg_fieldValue)      {
+               if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault'])     {
+                       return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
+               } else {
+                       return $l18n_cfg_fieldValue&2 ? TRUE : FALSE;
+               }
+       }
+
+       /**
+        * Includes a locallang file and returns the $LOCAL_LANG array found inside.
+        *
+        * @param       string          Input is a file-reference (see t3lib_div::getFileAbsFileName) which, if exists, is included. That file is expected to be a 'local_lang' file containing a $LOCAL_LANG array.
+        * @param       string          Language key
+        * @return      array           Value of $LOCAL_LANG found in the included file. If that array is found it's returned. Otherwise an empty array
+        */
+       function readLLfile($fileRef,$langKey)  {
+
+               $file = t3lib_div::getFileAbsFileName($fileRef);
+               if ($file)      {
+                       $baseFile = ereg_replace('\.(php|xml)$', '', $file);
+
+                       if (@is_file($baseFile.'.xml')) {
+                               $LOCAL_LANG = t3lib_div::readLLXMLfile($baseFile.'.xml', $langKey);
+                       } elseif (@is_file($baseFile.'.php'))   {
+                               include($baseFile.'.php');
+                       } else die('Filereference, "'.$file.'", not found!');
+               }
+
+               return is_array($LOCAL_LANG)?$LOCAL_LANG:array();
+       }
+
+       /**
+        * Includes a locallang-xml file and returns the $LOCAL_LANG array
+        * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
+        *
+        * @param       string          Absolute reference to locallang-XML file
+        * @param       string          TYPO3 language key, eg. "dk" or "de" or "default"
+        * @return      array           LOCAL_LANG array in return.
+        */
+       function readLLXMLfile($fileRef,$langKey)       {
+
+               if (is_object($GLOBALS['LANG']))        {
+                       $csConvObj = &$GLOBALS['LANG']->csConvObj;
+               } elseif (is_object($GLOBALS['TSFE']))  {
+                       $csConvObj = &$GLOBALS['TSFE']->csConvObj;
+               } else $csConvObj = NULL;
+
+               if (@is_file($fileRef) && $langKey && is_object($csConvObj))    {
+
+                               // Set charset:
+                       $origCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
+
+                               // Cache file name:
+                       $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.2';
+                       $cacheFileName = PATH_site.'typo3temp/llxml/'.
+                                                       #str_replace('_','',ereg_replace('^.*\/','',dirname($fileRef))).
+                                                       #'_'.basename($fileRef).
+                                                       substr(basename($fileRef),10,15).
+                                                       '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
+
+                               // Check if cache file exists...
+                       if (!@is_file($cacheFileName))  {       // ... if it doesn't, create content and write it:
+
+                                       // Read XML, parse it.
+                               $xmlString = t3lib_div::getUrl($fileRef);
+                               $xmlContent = t3lib_div::xml2array($xmlString);
+                               if (!is_array($xmlContent))     {
+                                       die($fileRef.' was not XML!: '.$xmlContent);
+                               }
+
+                                       // Set default LOCAL_LANG array content:
+                               $LOCAL_LANG = array();
+                               $LOCAL_LANG['default'] = $xmlContent['data']['default'];
+
+                                       // Converting charset of default language from utf-8 to iso-8859-1 (since that is what the system would expect for default langauge in the core due to historical reasons)
+                                       // This conversion is unneccessary for 99,99% of all default labels since they are in english, therefore ASCII.
+                                       // However, an extension like TemplaVoila uses an extended character in its name, even in Default language. To accommodate that (special chars for default) this conversion must be made.
+                                       // Since the output from this function is probably always cached it is considered insignificant to do this conversion.
+                                       // - kasper
+                               if (is_array($LOCAL_LANG['default']))   {
+                                       foreach($LOCAL_LANG['default'] as $labelKey => $labelValue)     {
+                                               $LOCAL_LANG['default'][$labelKey] = $csConvObj->utf8_decode($labelValue,'iso-8859-1');
+                                       }
+                               }
+
+                                       // Specific language, convert from utf-8 to backend language charset:
+                                       // NOTICE: Converting from utf-8 back to "native" language may be a temporary solution until we can totally discard "locallang.php" files altogether (and use utf-8 for everything). But doing this conversion is the quickest way to migrate now and the source is in utf-8 anyway which is the main point.
+                               if ($langKey!='default')        {
+
+                                               // If no entry is found for the language key, then force a value depending on meta-data setting. By default an automated filename will be used:
+                                       if (!isset($xmlContent['data'][$langKey]))      {
+                                               $LOCAL_LANG[$langKey] = t3lib_div::llXmlAutoFileName($fileRef, $langKey);
+                                       } else {
+                                               $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
+                                       }
+
+                                               // Checking if charset should be converted.
+                                       if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8')   {
+                                               foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue)      {
+                                                       $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
+                                               }
+                                       }
+                               }
+
+                                       // Cache the content now:
+                               $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>$LOCAL_LANG);
+                               $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
+                               if ($res)       die('ERROR: '.$res);
+                       } else {
+                                       // Get content from cache:
+                               $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
+                               $LOCAL_LANG = $serContent['LOCAL_LANG'];
+                       }
+
+                               // Checking for EXTERNAL file for non-default language:
+                       if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey]))   {
+
+                                       // Look for localized file:
+                               $localized_file = t3lib_div::getFileAbsFileName($LOCAL_LANG[$langKey]);
+                               if ($localized_file && @is_file($localized_file))       {
+
+                                               // Cache file name:
+                                       $hashSource = substr($localized_file,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($localized_file));
+                                       $cacheFileName = PATH_site.'typo3temp/llxml/ext_'.
+                                                                       substr(basename($localized_file),10,15).
+                                                                       '_'.t3lib_div::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
+
+                                               // Check if cache file exists...
+                                       if (!@is_file($cacheFileName))  {       // ... if it doesn't, create content and write it:
+
+                                                       // Read and parse XML content:
+                                               $local_xmlString = t3lib_div::getUrl($localized_file);
+                                               $local_xmlContent = t3lib_div::xml2array($local_xmlString);
+                                               $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
+
+                                                       // Checking if charset should be converted.
+                                               if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8')   {
+                                                       foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue)      {
+                                                               $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
+                                                       }
+                                               }
+
+                                                       // Cache the content now:
+                                               $serContent = array('extlang'=>$langKey, 'origFile'=>$LOCAL_LANG[$langKey], 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
+                                               $res = t3lib_div::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
+                                               if ($res)       die('ERROR: '.$res);
+                                       } else {
+                                                       // Get content from cache:
+                                               $serContent = unserialize(t3lib_div::getUrl($cacheFileName));
+                                               $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
+                                       }
+                               } else {
+                                       $LOCAL_LANG[$langKey] = array();
+                               }
+                       }
+
+                       return $LOCAL_LANG;
+               }
+       }
+
+       /**
+        * Returns auto-filename for locallang-XML localizations.
+        *
+        * @param       string          Absolute file reference to locallang-XML file. Must be inside system/global/local extension
+        * @param       string          Language key
+        * @return      string          Returns the filename reference for the language unless error occured (or local mode is used) in which case it will be NULL
+        */
+       function llXmlAutoFileName($fileRef,$language)  {
+                       // Analyse file reference:
+               $location = 'typo3conf/l10n/'.$language.'/';    // Default location of translations
+               if (t3lib_div::isFirstPartOfStr($fileRef,PATH_typo3.'sysext/')) {       // Is system:
+                       $validatedPrefix = PATH_typo3.'sysext/';
+                       #$location = 'EXT:csh_'.$language.'/';  // For system extensions translations are found in "csh_*" extensions (language packs)
+               } elseif (t3lib_div::isFirstPartOfStr($fileRef,PATH_typo3.'ext/'))      {       // Is global:
+                       $validatedPrefix = PATH_typo3.'ext/';
+               } elseif (t3lib_div::isFirstPartOfStr($fileRef,PATH_typo3conf.'ext/'))  {       // Is local:
+                       $validatedPrefix = PATH_typo3conf.'ext/';
+               } else {
+                       $validatedPrefix = '';
+               }
+
+               if ($validatedPrefix)   {
+
+                               // Divide file reference into extension key, directory (if any) and base name:
+                       list($file_extKey,$file_extPath) = explode('/',substr($fileRef,strlen($validatedPrefix)),2);
+                       $temp = t3lib_div::revExplode('/',$file_extPath,2);
+                       if (count($temp)==1)    array_unshift($temp,'');        // Add empty first-entry if not there.
+                       list($file_extPath,$file_fileName) = $temp;
+
+                               // The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
+                       return $location.
+                               $file_extKey.'/'.
+                               ($file_extPath?$file_extPath.'/':'').
+                               $language.'.'.$file_fileName;
+               } else return NULL;
+       }
+
+
+       /**
         * Loads the $TCA (Table Configuration Array) for the $table
         *
         * Requirements:
         * 1) must be configured table (the ctrl-section configured),
         * 2) columns must not be an array (which it is always if whole table loaded), and
         * 3) there is a value for dynamicConfigFile (filename in typo3conf)
+        *
+        * Note: For the frontend this loads only 'ctrl' and 'feInterface' parts.
+        * For complete TCA use $GLOBALS['TSFE']->includeTCA() instead.
+        *
         * Usage: 84
         *
         * @param       string          Table name for which to load the full TCA array part into the global $TCA
@@ -3101,6 +3831,8 @@ class t3lib_div {
         * @return      array           An array with two num. keys: key0: The data structure is returned in this key (array) UNLESS an error happend in which case an error string is returned (string). key1: The used sheet key value!
         */
        function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')    {
+               if (!is_array ($dataStructArray)) return 'Data structure must be an array';
+
                if (is_array($dataStructArray['sheets']))       {
                        $singleSheet = FALSE;
                        if (!isset($dataStructArray['sheets'][$sheet])) {
@@ -3118,6 +3850,7 @@ class t3lib_div {
                } else {
                        $singleSheet = TRUE;
                        $dataStruct = $dataStructArray;
+                       if (isset($dataStruct['meta'])) unset($dataStruct['meta']);     // Meta data should not appear there.
                        $sheet = 'sDEF';        // Default sheet
                }
                return array($dataStruct,$sheet,$singleSheet);
@@ -3164,11 +3897,10 @@ class t3lib_div {
 
                        // Check persistent object and if found, call directly and exit.
                if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName]))        {
-                       return call_user_method(
-                                               $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method'],
-                                               $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
-                                               $params,
-                                               $ref
+                       return call_user_func_array(
+                                               array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
+                                                       $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
+                                               array(&$params, &$ref)
                                        );
                }
 
@@ -3176,7 +3908,7 @@ class t3lib_div {
                if (strstr($funcName,':'))      {
                        list($file,$funcRef) = t3lib_div::revExplode(':',$funcName,2);
                        $requireFile = t3lib_div::getFileAbsFileName($file);
-                       if ($requireFile) require_once($requireFile);
+                       if ($requireFile) t3lib_div::requireOnce($requireFile);
                } else {
                        $funcRef = $funcName;
                }
@@ -3225,11 +3957,9 @@ class t3lib_div {
                                                );
                                        }
                                                // Call method:
-                                       $content = call_user_method(
-                                               $parts[1],
-                                               $classObj,
-                                               $params,
-                                               $ref
+                                       $content = call_user_func_array(
+                                               array(&$classObj, $parts[1]),
+                                               array(&$params, &$ref)
                                        );
                                } else {
                                        if (!$silent)   debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
@@ -3239,7 +3969,7 @@ class t3lib_div {
                        }
                } else {        // Function
                        if (function_exists($funcRef))  {
-                               $content = call_user_func($funcRef, $params, $ref);
+                               $content = call_user_func_array($funcRef, array(&$params, &$ref));
                        } else {
                                if (!$silent)   debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
                        }
@@ -3269,7 +3999,7 @@ class t3lib_div {
                        if (strstr($classRef,':'))      {
                                list($file,$class) = t3lib_div::revExplode(':',$classRef,2);
                                $requireFile = t3lib_div::getFileAbsFileName($file);
-                               if ($requireFile)       require_once($requireFile);
+                               if ($requireFile)       t3lib_div::requireOnce($requireFile);
                        } else {
                                $class = $classRef;
                        }
@@ -3314,9 +4044,18 @@ class t3lib_div {
         * Usage: 447
         *
         * @param       string          Class name to instantiate
-        * @return      object          The object
+        * @return      object          A reference to the object
         */
        function &makeInstance($className)      {
+
+                       // Load class file if not found:
+               if (!class_exists($className))  {
+                       if (substr($className,0,6)=='t3lib_')   {
+                               t3lib_div::requireOnce(PATH_t3lib.'class.'.strtolower($className).'.php');
+                       }
+               }
+
+                       // Return object.
                return class_exists('ux_'.$className) ? t3lib_div::makeInstance('ux_'.$className) : new $className;
        }
 
@@ -3359,27 +4098,30 @@ class t3lib_div {
                                return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
 
                                // include file and create object
-                       } elseif (@is_file($info['classFile'])) {
-                               require_once ($info['classFile']);
-                               $obj = t3lib_div::makeInstance($info['className']);
-                               if (is_object($obj)) {
-                                       if(!@is_callable(array($obj,'init')))   {
-                                                       // use silent logging??? I don't think so.
-                                               die ('Broken service:'.t3lib_div::view_array($info));
-                                       }
-                                       $obj->info = $info;
-                                       if ($obj->init()) { // service available?
+                       } else {
+                               $requireFile = t3lib_div::getFileAbsFileName($info['classFile']);
+                               if (@is_file($requireFile)) {
+                                       t3lib_div::requireOnce ($requireFile);
+                                       $obj = t3lib_div::makeInstance($info['className']);
+                                       if (is_object($obj)) {
+                                               if(!@is_callable(array($obj,'init')))   {
+                                                               // use silent logging??? I don't think so.
+                                                       die ('Broken service:'.t3lib_div::view_array($info));
+                                               }
+                                               $obj->info = $info;
+                                               if ($obj->init()) { // service available?
 
-                                                       // create persistent object
-                                               $T3_VAR['makeInstanceService'][$info['className']] = &$obj;
+                                                               // create persistent object
+                                                       $T3_VAR['makeInstanceService'][$info['className']] = &$obj;
 
-                                                       // needed to delete temp files
-                                               register_shutdown_function(array(&$obj, '__destruct'));
+                                                               // needed to delete temp files
+                                                       register_shutdown_function(array(&$obj, '__destruct'));
 
-                                               return $obj; // object is passed as reference by funtion definition
+                                                       return $obj; // object is passed as reference by function definition
+                                               }
+                                               $error = $obj->getLastErrorArray();
+                                               unset($obj);
                                        }
-                                       $error = $obj->getLastErrorArray();
-                                       unset($obj);
                                }
                        }
                                // deactivate the service
@@ -3389,8 +4131,18 @@ class t3lib_div {
        }
 
        /**
+        * Require a class for TYPO3
+        * Useful to require classes from inside other classes (not global scope). A limited set of global variables are available (see function)
+        */
+       function requireOnce($requireFile)      {
+               global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
+
+               require_once ($requireFile);
+       }
+
+       /**
         * Simple substitute for the PHP function mail() which allows you to specify encoding and character set
-        * The fifth parameter, $enc, will allow you to specify 'base64' encryption for the output (set $enc=base64)
+        * The fifth parameter ($encoding) will allow you to specify 'base64' encryption for the output (set $encoding=base64)
         * Further the output has the charset set to ISO-8859-1 by default.
         * Usage: 4
         *
@@ -3398,13 +4150,36 @@ class t3lib_div {
         * @param       string          Subject line, non-encoded. (see PHP function mail())
         * @param       string          Message content, non-encoded. (see PHP function mail())
         * @param       string          Headers, separated by chr(10)
-        * @param       string          Encoding type: "base64", "quoted-printable", "8bit". If blank, no encoding will be used, no encoding headers set.
-        * @param       string          Charset used in encoding-headers (only if $enc is set to a valid value which produces such a header)
-        * @param       boolean         If set, the content of $subject will not be encoded.
-        * @return      void
+        * @param       string          Encoding type: "base64", "quoted-printable", "8bit". Default value is "quoted-printable".
+        * @param       string          Charset used in encoding-headers (only if $encoding is set to a valid value which produces such a header)
+        * @param       boolean         If set, the header content will not be encoded.
+        * @return      boolean         True if mail was accepted for delivery, false otherwise
         */
-       function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0)      {
-               switch((string)$enc)    {
+       function plainMailEncoded($email,$subject,$message,$headers='',$encoding='quoted-printable',$charset='',$dontEncodeHeader=false)        {
+               if (!$charset)  {
+                       $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'ISO-8859-1';
+               }
+
+               if (!$dontEncodeHeader) {
+                               // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
+                       $newHeaders=array();
+                       foreach (explode(chr(10),$headers) as $line)    {       // Split the header in lines and convert each line separately
+                               $parts = explode(': ',$line,2); // Field tags must not be encoded
+                               if (count($parts)==2)   {
+                                       $parts[1] = t3lib_div::encodeHeader($parts[1],$encoding,$charset);
+                                       $newHeaders[] = implode(': ',$parts);
+                               } else {
+                                       $newHeaders[] = $line;  // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
+                               }
+                       }
+                       $headers = implode(chr(10),$newHeaders);
+                       unset($newHeaders);
+
+                       $email = t3lib_div::encodeHeader($email,$encoding,$charset);            // Email address must not be encoded, but it could be appended by a name which should be so (e.g. "Kasper Skårhøj <kasperYYYY@typo3.com>")
+                       $subject = t3lib_div::encodeHeader($subject,$encoding,$charset);
+               }
+
+               switch ((string)$encoding)      {
                        case 'base64':
                                $headers=trim($headers).chr(10).
                                'Mime-Version: 1.0'.chr(10).
@@ -3412,35 +4187,41 @@ class t3lib_div {
                                'Content-Transfer-Encoding: base64';
 
                                $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.
-
-                               if (!$dontEncodeSubject)        $subject='=?'.$charset.'?B?'.base64_encode($subject).'?=';
+                       break;
+                       case '8bit':
+                               $headers=trim($headers).chr(10).
+                               'Mime-Version: 1.0'.chr(10).
+                               'Content-Type: text/plain; charset='.$charset.chr(10).
+                               'Content-Transfer-Encoding: 8bit';
                        break;
                        case 'quoted-printable':
+                       default:
                                $headers=trim($headers).chr(10).
                                'Mime-Version: 1.0'.chr(10).
-                               'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
+                               'Content-Type: text/plain; charset='.$charset.chr(10).
                                'Content-Transfer-Encoding: quoted-printable';
 
                                $message=t3lib_div::quoted_printable($message);
-
-                               if (!$dontEncodeSubject)        $subject='=?'.$charset.'?Q?'.trim(t3lib_div::quoted_printable(ereg_replace('[[:space:]]','_',$subject),1000)).'?=';
-                       break;
-                       case '8bit':
-                               $headers=trim($headers).chr(10).
-                               'Mime-Version: 1.0'.chr(10).
-                               'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
-                               'Content-Transfer-Encoding: 8bit';
                        break;
                }
-               $headers=trim(implode(chr(10),t3lib_div::trimExplode(chr(10),$headers,1)));     // make sure no empty lines are there.
 
-               mail($email,$subject,$message,$headers);
+               $linebreak = chr(10);                   // Default line break for Unix systems.
+               if (TYPO3_OS=='WIN')    {
+                       $linebreak = chr(13).chr(10);   // Line break for Windows. This is needed because PHP on Windows systems send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
+               }
+
+               $headers=trim(implode($linebreak,t3lib_div::trimExplode(chr(10),$headers,1)));  // Make sure no empty lines are there.
+
+               $ret = @mail($email,$subject,$message,$headers);
+               if (!$ret)      {
+                       t3lib_div::sysLog('Mail to "'.$email.'" could not be sent (Subject: "'.$subject.'").', 'Core', 3);
+               }
+               return $ret;
        }
 
        /**
         * Implementation of quoted-printable encode.
         * This functions is buggy. It seems that in the part where the lines are breaked every 76th character, that it fails if the break happens right in a quoted_printable encode character!
-        * Important: For the ease of use, this function internally uses Unix linebreaks ("\n") for breaking lines, but the output must use "\r\n" instead!
         * See RFC 1521, section 5.1 Quoted-Printable Content-Transfer-Encoding
         * Usage: 2
         *
@@ -3453,9 +4234,14 @@ class t3lib_div {
                $string = str_replace(chr(13).chr(10), chr(10), $string);       // Replace Windows breaks (\r\n)
                $string = str_replace(chr(13), chr(10), $string);               // Replace Mac breaks (\r)
 
+               $linebreak = chr(10);                   // Default line break for Unix systems.
+               if (TYPO3_OS=='WIN')    {
+                       $linebreak = chr(13).chr(10);   // Line break for Windows. This is needed because PHP on Windows systems send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
+               }
+
                $newString = '';
                $theLines = explode(chr(10),$string);   // Split lines
-               foreach($theLines as $val)      {
+               foreach ($theLines as $val)     {
                        $newVal = '';
                        $theValLen = strlen($val);
                        $len = 0;
@@ -3463,7 +4249,7 @@ class t3lib_div {
                                $char = substr($val,$index,1);
                                $ordVal = ord($char);
                                if ($len>($maxlen-4) || ($len>(($maxlen-10)-4)&&$ordVal==32))   {
-                                       $newVal.='='.chr(13).chr(10);   // Add a line break
+                                       $newVal.='='.$linebreak;        // Add a line break
                                        $len=0;                 // Reset the length counter
                                }
                                if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
@@ -3474,11 +4260,53 @@ class t3lib_div {
                                        $len+=3;
                                }
                        }
-                       $newVal = ereg_replace(chr(32).'$','=20',$newVal);              // Replaces a possible SPACE-character at the end of a line
-                       $newVal = ereg_replace(chr(9).'$','=09',$newVal);               // Replaces a possible TAB-character at the end of a line
-                       $newString.=$newVal.chr(13).chr(10);
+                       $newVal = preg_replace('/'.chr(32).'$/','=20',$newVal);         // Replaces a possible SPACE-character at the end of a line
+                       $newVal = preg_replace('/'.chr(9).'$/','=09',$newVal);          // Replaces a possible TAB-character at the end of a line
+                       $newString.=$newVal.$linebreak;
                }
-               return ereg_replace(chr(13).chr(10).'$','',$newString);
+               return preg_replace('/'.$linebreak.'$/','',$newString);         // Remove last newline
+       }
+
+       /**
+        * Encode header lines
+        * Email headers must be ASCII, therefore they will be encoded to quoted_printable (default) or base64.
+        *
+        * @param       string          Content to encode
+        * @param       string          Encoding type: "base64" or "quoted-printable". Default value is "quoted-printable".
+        * @param       string          Charset used for encoding
+        * @return      string          The encoded string
+        */
+       function encodeHeader($line,$enc='quoted-printable',$charset='ISO-8859-1')      {
+                       // Avoid problems if "###" is found in $line (would conflict with the placeholder which is used below)
+               if (strstr($line,'###'))        return $line;
+
+                       // Check if any non-ASCII characters are found - otherwise encoding is not needed
+               if (!preg_match('/[^'.chr(32).'-'.chr(127).']/',$line)) return $line;
+
+                       // Wrap email addresses in a special marker
+               $line = preg_replace('/([^ ]+@[^ ]+)/', '###$1###', $line);
+
+               $matches = preg_split('/(.?###.+###.?|\(|\))/', $line, -1, PREG_SPLIT_NO_EMPTY);
+               foreach ($matches as $part)     {
+                       $oldPart = $part;
+                       switch ((string)$enc)   {
+                               case 'base64':
+                                       $part = '=?'.$charset.'?B?'.base64_encode($part).'?=';
+                               break;
+                               case 'quoted-printable':
+                               default:
+                                       $qpValue = t3lib_div::quoted_printable($part,1000);
+                                       if ($part!=$qpValue)    {
+                                               $qpValue = str_replace(' ','_',$qpValue);       // Encoded words in the header should not contain non-encoded spaces. "_" is a shortcut for "=20". See RFC 2047 for details.
+                                               $part = '=?'.$charset.'?Q?'.$qpValue.'?=';
+                                       }
+                               break;
+                       }
+                       $line = str_replace($oldPart, $part, $line);
+               }
+               $line = preg_replace('/###(.+?)###/', '$1', $line);     // Remove the wrappers
+
+               return $line;
        }
 
        /**
@@ -3494,25 +4322,28 @@ class t3lib_div {
         */
        function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')      {
                        // Substitute URLs with shorter links:
-               $urlSplit=explode('http://',$message);
-               reset($urlSplit);
-               while(list($c,$v)=each($urlSplit))      {
-                       if ($c) {
-                               $newParts = split('[[:space:]]|\)|\(',$v,2);
-                               $newURL='http://'.$newParts[0];
-                                       switch((string)$urlmode)        {
+               foreach (array('http','https') as $protocol)    {
+                       $urlSplit = explode($protocol.'://',$message);
+                       reset($urlSplit);
+                       while (list($c,$v) = each($urlSplit))   {
+                               if ($c) {
+                                       $newParts = preg_split('/\s|[<>"{}|\\\^`()\']/', $v, 2);
+                                       $newURL = $protocol.'://'.$newParts[0];
+
+                                       switch ((string)$urlmode)       {
                                                case 'all':
-                                                       $newURL=t3lib_div::makeRedirectUrl($newURL,0,$index_script_url);
+                                                       $newURL = t3lib_div::makeRedirectUrl($newURL,0,$index_script_url);
                                                break;
                                                case '76':
-                                                       $newURL=t3lib_div::makeRedirectUrl($newURL,76,$index_script_url);
+                                                       $newURL = t3lib_div::makeRedirectUrl($newURL,76,$index_script_url);
                                                break;
                                        }
-                               $urlSplit[$c]=$newURL.substr($v,strlen($newParts[0]));
+                                       $urlSplit[$c] = $newURL . substr($v,strlen($newParts[0]));
+                               }
                        }
+                       $message = implode('',$urlSplit);
                }
 
-               $message=implode('',$urlSplit);
                return $message;
        }
 
@@ -3522,7 +4353,7 @@ class t3lib_div {
         *
         * @param       string          Input URL
         * @param       integer         URL string length limit
-        * @param       string          URL of "index script" - the prefix of the "?RDCT=..." parameter. If not supplyed it will default to t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR')
+        * @param       string          URL of "index script" - the prefix of the "?RDCT=..." parameter. If not supplyed it will default to t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php'
         * @return      string          Processed URL
         * @internal
         */
@@ -3540,9 +4371,10 @@ class t3lib_div {
 
                                $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
                        }
-                       $inUrl=($index_script_url ? $index_script_url : t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR')).
+                       $inUrl=($index_script_url ? $index_script_url : t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php').
                                '?RDCT='.$md5;
                }
+
                return $inUrl;
        }
 
@@ -3560,6 +4392,132 @@ class t3lib_div {
        }
 
        /**
+        * Init system error log.
+        *
+        * @return      void
+        * @see sysLog()
+        */
+       function initSysLog()   {
+               global $TYPO3_CONF_VARS;
+
+                       // for CLI logging name is <fqdn-hostname>:<TYPO3-path>
+               if (defined('TYPO3_cliMode') && TYPO3_cliMode)  {
+                       $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = t3lib_div::getHostname($requestHost=FALSE).':'.PATH_site;
+               }
+                       // for Web logging name is <protocol>://<request-hostame>/<site-path>
+               else {
+                       $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = t3lib_div::getIndpEnv('TYPO3_SITE_URL');
+               }
+
+                       // init custom logging
+               if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
+                       $params = array('initLog'=>TRUE);
+                       $fakeThis = FALSE;
+                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod)       {
+                               t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
+                       }
+               }
+
+                       // init TYPO3 logging
+               foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log)   {
+                       list($type,$destination) = explode(',',$log,3);
+
+                       if ($type == 'syslog')  {
+                               define_syslog_variables();
+                               if (TYPO3_OS == 'WIN')  {
+                                       $facility = LOG_USER;
+                               } else {
+                                       $facility = constant('LOG_'.strtoupper($destination));
+                               }
+                               openlog($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'], LOG_ODELAY, $facility);
+                       }
+               }
+
+               $TYPO3_CONF_VARS['SYS']['systemLogLevel'] = t3lib_div::intInRange($TYPO3_CONF_VARS['SYS']['systemLogLevel'],0,4);
+               $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
+       }
+
+       /**
+        * System error log; This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors.
+        * If you want to implement the sysLog in your applications, simply add lines like:
+        *              t3lib_div::sysLog('[write message in English here]', 'extension key');
+        *
+        * @param       string          Message (in English).
+        * @param       string          Extension key (from which extension you are calling the log) or "Core"
+        * @param       integer         Severity: 0 is info, 1 is notice, 2 is warning, 3 is error, 4 is fatal error
+        * @return      void
+        */
+       function sysLog($msg, $extKey, $severity=0) {
+               global $TYPO3_CONF_VARS;
+
+               $severity = t3lib_div::intInRange($severity,0,4);
+
+                       // is message worth logging?
+               if (intval($TYPO3_CONF_VARS['SYS']['systemLogLevel']) > $severity)      return;
+
+                       // initialize logging
+               if (!$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'])      {
+                       t3lib_div::initSysLog();
+               }
+
+                       // do custom logging
+               if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
+                       $params = array('msg'=>$msg, 'extKey'=>$extKey, 'backTrace'=>debug_backtrace());
+                       $fakeThis = FALSE;
+                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod)       {
+                               t3lib_div::callUserFunction($hookMethod,$params,$fakeThis);
+                       }
+               }
+
+                       // TYPO3 logging enabled?
+               if (!$TYPO3_CONF_VARS['SYS']['systemLog'])      return;
+
+               $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
+               $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
+
+                       // use all configured logging options
+               foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log)   {
+                       list($type,$destination,$level) = explode(',',$log,4);
+
+                               // is message worth logging for this log type?
+                       if (intval($level) > $severity) continue;
+
+                       $msgLine = ' - '.$extKey.': '.$msg;
+
+                               // write message to a file
+                       if ($type == 'file')    {
+                               $file = fopen($destination, 'a');
+                               if ($file)     {
+                                       flock($file, LOCK_EX);  // try locking, but ignore if not available (eg. on NFS and FAT)
+                                       fwrite($file, date($dateFormat.' '.$timeFormat).$msgLine.chr(10));
+                                       flock($file, LOCK_UN);    // release the lock
+                                       fclose($file);
+                               }
+                       }
+                               // send message per mail
+                       elseif ($type == 'mail')        {
+                               list($to,$from) = explode('/',$destination);
+                               mail($to, 'Warning - error in TYPO3 installation',
+                                       'Host: '.$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost']."\n".
+                                       'Extension: '.$extKey."\n".
+                                       'Severity: '.$severity."\n".
+                                       "\n".$msg,
+                                       ($from ? 'From: '.$from : '')
+                               );
+                       }
+                               // use the PHP error log
+                       elseif ($type == 'error_log')   {
+                               error_log($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'].$msgLine, 0);
+                       }
+                               // use the system log
+                       elseif ($type == 'syslog')      {
+                               $priority = array(LOG_INFO,LOG_NOTICE,LOG_WARNING,LOG_ERR,LOG_CRIT);
+                               syslog($priority[(int)$severity], $msgLine);
+                       }
+               }
+       }
+
+       /**
         * Developer log; This should be implemented around the source code, both frontend and backend, logging everything from the flow through an application, messages, results from comparisons to fatal errors.
         * The result is meant to make sense to developers during development or debugging of a site.
         * The idea is that this function is only a wrapper for external extensions which can set a hook which will be allowed to handle the logging of the information to any format they might wish and with any kind of filter they would like.
@@ -3595,18 +4553,118 @@ class t3lib_div {
         */
        function arrayToLogString($arr, $valueList=array(), $valueLength=20) {
                $str = '';
-               if(is_array($arr)) {
-                       if (!is_array($valueList)) {
-                               $valueList = explode(',', $valueList);
+               if (is_array($arr))     {
+                       if (!is_array($valueList))      {
+                               $valueList = t3lib_div::trimExplode(',', $valueList, 1);
                        }
-                       foreach($arr as $key => $value) {
-                               if (!count($valueList) OR (count($valueList) AND in_array($key, $valueList))) {
+                       $valListCnt = count($valueList);
+                       foreach ($arr as $key => $value)        {
+                               if (!$valListCnt || in_array($key, $valueList)) {
                                        $str .= (string)$key.trim(': '.t3lib_div::fixed_lgd(str_replace("\n",'|',(string)$value), $valueLength)).'; ';
                                }
                        }
                }
                return $str;
        }
+
+       /**
+        * Compile the command for running ImageMagick/GraphicsMagick.
+        *
+        * @param       string          Command to be run: identify, convert or combine/composite
+        * @param       string          The parameters string
+        * @param       string          Override the default path
+        * @return      string          Compiled command that deals with IM6 & GraphicsMagick
+        */
+       function imageMagickCommand($command, $parameters, $path='')    {
+               $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
+               $isExt = (TYPO3_OS=='WIN' ? '.exe' : '');
+               $switchCompositeParameters=false;
+
+               if(!$path)      { $path = $gfxConf['im_path']; }
+
+               $im_version = strtolower($gfxConf['im_version_5']);
+               $combineScript = $gfxConf['im_combine_filename'] ? trim($gfxConf['im_combine_filename']) : 'combine';
+
+               if($command==='combine')        {       // This is only used internally, has no effect outside
+                       $command = 'composite';
+               }
+
+                       // Compile the path & command
+               if($im_version==='gm')  {
+                       $switchCompositeParameters=true;
+                       $path .= 'gm'.$isExt.' '.$command;
+               } else  {
+                       if($im_version==='im6') { $switchCompositeParameters=true; }
+                       $path .= (($command=='composite') ? $combineScript : $command).$isExt;
+               }
+
+               $cmdLine = $path.' '.$parameters;
+
+               if($command=='composite' && $switchCompositeParameters) {       // Because of some weird incompatibilities between ImageMagick 4 and 6 (plus GraphicsMagick), it is needed to change the parameters order under some preconditions
+                       $paramsArr = t3lib_div::unQuoteFilenames($parameters);
+
+                       if(count($paramsArr)>5) {       // The mask image has been specified => swap the parameters
+                               $tmp = $paramsArr[count($paramsArr)-3];
+                               $paramsArr[count($paramsArr)-3] = $paramsArr[count($paramsArr)-4];
+                               $paramsArr[count($paramsArr)-4] = $tmp;
+                       }
+
+                       $cmdLine = $path.' '.implode(' ', $paramsArr);
+               }
+
+               return $cmdLine;
+       }
+
+       /**
+        * Explode a string (normally a list of filenames) with whitespaces by considering quotes in that string. This is mostly needed by the imageMagickCommand function above.
+        *
+        * @param       string          The whole parameters string
+        * @param       boolean         If set, the elements of the resulting array are unquoted.
+        * @return      array           Exploded parameters
+        */
+       function unQuoteFilenames($parameters,$unQuote=FALSE)   {
+               $paramsArr = explode(' ', trim($parameters));
+
+               $quoteActive = -1;      // Whenever a quote character (") is found, $quoteActive is set to the element number inside of $params. A value of -1 means that there are not open quotes at the current position.
+               foreach($paramsArr as $k=>$v)   {
+                       if($quoteActive > -1)   {
+                               $paramsArr[$quoteActive] .= ' '.$v;
+                               unset($paramsArr[$k]);
+                               if(ereg('"$', $v))      { $quoteActive = -1; }
+
+                       } elseif(!trim($v))     {
+                               unset($paramsArr[$k]);  // Remove empty elements
+
+                       } elseif(ereg('^"', $v))        {
+                               $quoteActive = $k;
+                       }
+               }
+
+               if($unQuote) {
+                       foreach($paramsArr as $key=>$val) {
+                               $paramsArr[$key]=preg_replace('/(^"|"$)/','',$val);
+                       }
+               }
+               return $paramsArr;
+       }
+
+
+       /**
+        * Quotes a string for usage as JS parameter. Depends wheter the value is used in script tags (it doesn't need/must not get htmlspecialchar'ed in this case)
+        *
+        * @param       string          The string to encode.
+        * @param       boolean         If the values get's used in <script> tags.
+        * @return      string          The encoded value already quoted
+        */
+       function quoteJSvalue($value, $inScriptTags = false)    {
+               $value = addcslashes($value, '\''.chr(10).chr(13));
+               if (!$inScriptTags)     {
+                       $value = htmlspecialchars($value);
+               }
+               return '\''.$value.'\'';
+       }
+
+
 }
 
-?>
\ No newline at end of file
+?>