Added argument to debugRows() so it can return HTML instead of echo'ing
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_div.php
index 1a5318e..bfa3888 100755 (executable)
@@ -1,8 +1,8 @@
 <?php
 /***************************************************************
 *  Copyright notice
 <?php
 /***************************************************************
 *  Copyright notice
-*  
-*  (c) 1999-2003 Kasper Skårhøj (kasper@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
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 ***************************************************************/
 /**
  * Contains the reknown class "t3lib_div" with general purpose functions
 ***************************************************************/
 /**
  * Contains the reknown class "t3lib_div" with general purpose functions
- * 
- * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
+ *
+ * $Id$
+ * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
  * XHTML compliant
  * Usage counts are based on search 22/2 2003 through whole source including tslib/
  * XHTML compliant
  * Usage counts are based on search 22/2 2003 through whole source including tslib/
- * 
- * @author     Kasper Skårhøj <kasper@typo3.com>
+ *
+ * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
  */
 /**
  * [CLASS/FUNCTION INDEX of SCRIPT]
  *
  *
  *
  */
 /**
  * [CLASS/FUNCTION INDEX of SCRIPT]
  *
  *
  *
- *  192: class t3lib_div 
+ *  232: class t3lib_div
  *
  *
- *              SECTION: BASIC FUNCTIONS
- *  214:     function milliseconds()   
- *  228:     function setGPvars($list,$strip=0)        
- *  246:     function GPvar($var,$strip=0)     
- *  262:     function GParrayMerged($var)      
- *  278:     function clientInfo($useragent='')        
+ *              SECTION: GET/POST Variables
+ *  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
  *
  *              SECTION: IMAGE FUNCTIONS
- *  365:     function gif_compress($theFile, $type)    
- *  393:     function png_to_gif_by_imagemagick($theFile)      
- *  417:     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
  *
  *              SECTION: STRING FUNCTIONS
- *  466:     function fixed_lgd($string,$chars,$preStr='...')  
- *  488:     function fixed_lgd_pre($string,$chars)    
- *  502:     function breakTextForEmail($str,$implChar="\n",$charWidth=76)     
- *  522:     function breakLinesForEmail($str,$implChar="\n",$charWidth=76)
- *  558:     function cmpIP($baseIP, $list)    
- *  589:     function inList($in_list,$item)   
- *  602:     function rmFromList($element,$list)       
- *  621:     function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)    
- *  638:     function intval_positive($theInt) 
- *  652:     function int_from_ver($verNumberStr)      
- *  665:     function md5int($str)     
- *  677:     function uniqueList($in_list)     
- *  690:     function split_fileref($fileref)  
- *  727:     function dirname($path)   
- *  744:     function modifyHTMLColor($color,$R,$G,$B) 
- *  765:     function modifyHTMLColorAll($color,$all)  
- *  777:     function rm_endcomma($string)     
- *  790:     function danish_strtoupper($string)       
- *  804:     function convUmlauts($str)        
- *  819:     function shortMD5($input, $len=10)        
- *  831:     function testInt($var)    
- *  844:     function isFirstPartOfStr($str,$partStr)  
- *  860:     function formatSize($sizeInBytes) 
- *  882:     function convertMicrotime($microtime)     
- *  896:     function splitCalc($string,$operators)    
- *  918:     function calcPriority($string)    
- *  958:     function calcParenthesis($string) 
- *  985:     function htmlspecialchars_decode($value)  
- *  999:     function deHSCentities($str)      
- * 1012:     function slashJS($string,$extended=0,$char="'")   
- * 1026:     function rawUrlEncodeJS($str)     
- * 1038:     function validEmail($email)       
- * 1053:     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
  *
  *              SECTION: ARRAY FUNCTIONS
- * 1085:     function inArray($in_array,$item) 
- * 1103:     function intExplode($delim, $string)      
- * 1123:     function revExplode($delim, $string, $count=0)    
- * 1144:     function trimExplode($delim, $string, $onlyNonEmptyValues=0)      
- * 1169:     function uniqueArray($valueArray) 
- * 1192:     function removeArrayEntryByValue($array,$cmpValue)        
- * 1221:     function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)        
- * 1249:     function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)  
- * 1273:     function addSlashesOnArray(&$theArray)    
- * 1298:     function stripSlashesOnArray(&$theArray)  
- * 1321:     function slashArray($arr,$cmd)    
- * 1338:     function array_merge_recursive_overrule ($arr0,$arr1,$notAddKeys=0) 
- * 1368:     function array_merge($arr1,$arr2) 
- * 1382:     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
  *
  *              SECTION: HTML/XML PROCESSING
- * 1425:     function get_tag_attributes($tag) 
- * 1463:     function split_tag_attributes($tag)       
- * 1497:     function implodeParams($arr,$xhtmlSafe=0) 
- * 1522:     function xml2tree($string,$depth=999) 
- * 1605:     function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0)   
- * 1663:     function xml2array($string,$NSprefix='') 
- * 1722:     function xmlRecompileFromStructValArray($vals)    
- * 1765:     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
  *
  *              SECTION: FILES FUNCTIONS
- * 1797:     function getURL($url)     
- * 1840:     function writeFile($file,$content)        
- * 1858:     function get_dirs($path)  
- * 1884:     function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')  
- * 1929:     function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) 
- * 1951:     function removePrefixPathFromList($fileArr,$prefixToRemove)       
- * 1970:     function upload_copy_move($source,$destination)   
- * 1988:     function fixWindowsFilePath($theFile)     
- * 1998:     function resolveBackPath($pathStr)        
- * 2026:     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
  *
  *              SECTION: DEBUG helper FUNCTIONS
- * 2066:     function debug_ordvalue($string,$characters=100)  
- * 2083:     function view_array($array_in)    
- * 2110:     function print_array($array_in)   
- * 2126:     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
  *
  *              SECTION: SYSTEM INFORMATION
- * 2191:     function getThisUrl()     
- * 2208:     function linkThisScript($getParams=array())       
- * 2230:     function linkThisUrl($url,$getParams=array())     
- * 2250:     function getIndpEnv($getEnvName)  
+ * 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
  *
  *              SECTION: TYPO3 SPECIFIC FUNCTIONS
- * 2464:     function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)      
- * 2499:     function validPathStr($theFile)   
- * 2511:     function isAbsPath($path) 
- * 2523:     function isAllowedAbsPath($path)  
- * 2541:     function verifyFilenameAgainstDenyPattern($filename)      
- * 2558:     function stdAuthCode($uid_or_record,$fields='')   
- * 2592:     function loadTCA($table)  
- * 2611:     function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')      
- * 2639:     function resolveAllSheetsInDS($dataStructArray)   
- * 2667:     function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)        
- * 2707:     function makeInstance($className) 
- * 2725:     function makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys='')    
- * 2758:     function makeInstanceClassName($className)        
- * 2778:     function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0)        
- * 2825:     function quoted_printable($string,$maxlen=76)     
- * 2867:     function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')        
- * 2902:     function makeRedirectUrl($inUrl,$l=0,$index_script_url='')        
- * 2925:     function freetypeDpiComp($font_size)      
+ * 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: 99
+ * TOTAL FUNCTIONS: 138
  * (This index is automatically created/updated by the extension "extdeveval")
  *
  */
  * (This index is automatically created/updated by the extension "extdeveval")
  *
  */
+
 
 
 
 
 
 
  * However a section of functions requires certain TYPO3 features available
  * See comments in the source.
  * You are encouraged to use this library in your own scripts!
  * However a section of functions requires certain TYPO3 features available
  * See comments in the source.
  * You are encouraged to use this library in your own scripts!
- * 
- * USE: 
+ *
+ * USE:
  * The class is intended to be used without creating an instance of it.
  * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name.
  * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()'
  * The class is intended to be used without creating an instance of it.
  * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name.
  * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()'
- * 
+ *
+ * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
  * @package TYPO3
  * @subpackage t3lib
  * @package TYPO3
  * @subpackage t3lib
- * @author     Kasper Skårhøj <kasper@typo3.com>
  */
 class t3lib_div {
 
  */
 class t3lib_div {
 
@@ -197,38 +237,87 @@ class t3lib_div {
 
        /*************************
         *
 
        /*************************
         *
-        * BASIC FUNCTIONS
+        * GET/POST Variables
+        *
+        * Background:
+        * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
+        * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
+        * But the clean solution is that quotes are never escaped and that is what the functions below offers.
+        * Eventually TYPO3 should provide this in the global space as well.
+        * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
         *
         *************************/
 
         *
         *************************/
 
+       /**
+        * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
+        * Strips slashes from all output, both strings and arrays.
+        * This function substitutes t3lib_div::GPvar()
+        * To enhancement security in your scripts, please consider using t3lib_div::_GET or t3lib_div::_POST if you already know by which method your data is arriving to the scripts!
+        * Usage: 537
+        *
+        * @param       string          GET/POST var to return
+        * @return      mixed           POST var named $var and if not set, the GET var of the same name.
+        * @see GPvar()
+        */
+       function _GP($var)      {
+               if(empty($var)) return;
+               $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
+               if (isset($value))      {
+                       if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
+               }
+               return $value;
+       }
 
        /**
 
        /**
-        * milliseconds
-        * 
-        * microtime recalculated to t3lib_div::milliseconds(1/1000 sec)
-        * 
-        * Usage: 39
-        * 
-        * @return      integer         
+        * Returns the global GET array (or value from) normalized to contain un-escaped values.
+        * ALWAYS use this API function to acquire the GET variables!
+        * Usage: 27
+        *
+        * @param       string          Optional pointer to value in GET array (basically name of GET var)
+        * @return      mixed           If $var is set it returns the value of $_GET[$var]. If $var is NULL (default), returns $_GET itself. In any case *slashes are stipped from the output!*
+        * @see _POST(), _GP(), _GETset()
         */
         */
-       function milliseconds() {
-               $p=explode(' ',microtime());
-               return round(($p[0]+$p[1])*1000);
+       function _GET($var=NULL)        {
+               $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
+               if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
+                       if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
+               }
+               return $value;
        }
        }
-       
+
        /**
        /**
-        * Sets global variables from HTTP_POST_VARS or HTTP_GET_VARS
-        * 
-        * Usage: 9
-        * 
-        * @param       string          List of GET/POST var keys to set globally
-        * @param       boolean         If set, values are passed through stripslashes()
-        * @return      void            
+        * Returns the global POST array (or value from) normalized to contain un-escaped values.
+        * ALWAYS use this API function to acquire the POST variables!
+        * Usage: 41
+        *
+        * @param       string          Optional pointer to value in POST array (basically name of POST var)
+        * @return      mixed           If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself. In any case *slashes are stipped from the output!*
+        * @see _GET(), _GP()
+        */
+       function _POST($var=NULL)       {
+               $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
+               if (isset($value))      {       // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
+                       if (is_array($value))   { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
+               }
+               return $value;
+       }
+
+       /**
+        * Writes input value to $_GET
+        * Usage: 2
+        *
+        * @param       array           Array to write to $_GET. Values should NOT be escaped at input time (but will be escaped before writing according to TYPO3 standards).
+        * @param       string          Alternative key; If set, this will not set the WHOLE GET array, but only the key in it specified by this value!
+        * @return      void
         */
         */
-       function setGPvars($list,$strip=0)      {
-               $vars = t3lib_div::trimExplode(',',$list,1);
-               while(list(,$var)=each($vars))  {
-                       $GLOBALS[$var] = t3lib_div::GPvar($var,$strip);
+       function _GETset($inputGet,$key='')     {
+                       // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
+               if (strcmp($key,''))    {
+                       if (is_array($inputGet))        { t3lib_div::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); }
+                       $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
+               } elseif (is_array($inputGet)){
+                       t3lib_div::addSlashesOnArray($inputGet);
+                       $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
                }
        }
 
                }
        }
 
@@ -236,102 +325,46 @@ class t3lib_div {
         * GET/POST variable
         * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
         * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped.
         * GET/POST variable
         * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
         * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped.
-        * 
-        * Usage: 686
-        * 
+        * Usage: 2
+        *
         * @param       string          GET/POST var to return
         * @param       boolean         If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed()
         * @return      mixed           POST var named $var and if not set, the GET var of the same name.
         * @param       string          GET/POST var to return
         * @param       boolean         If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed()
         * @return      mixed           POST var named $var and if not set, the GET var of the same name.
+        * @deprecated          Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!)
+        * @see _GP()
         */
        function GPvar($var,$strip=0)   {
         */
        function GPvar($var,$strip=0)   {
-               $value = isset($GLOBALS['HTTP_POST_VARS'][$var]) ? $GLOBALS['HTTP_POST_VARS'][$var] : $GLOBALS['HTTP_GET_VARS'][$var];
-               if (isset($value) && is_string($value)) {$value=stripslashes($value);}  // Originally check '&& get_magic_quotes_gpc() ' but the values of HTTP_GET_VARS are always slashed regardless of get_magic_quotes_gpc() because HTTP_POST/GET_VARS are run through addSlashesOnArray in the very beginning of index_ts.php eg.
-               if ($strip && isset($value) && is_array($value)) {t3lib_div::stripSlashesOnArray($value);}
+               if(empty($var)) return;
+               $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
+               if (isset($value) && is_string($value)) { $value = stripslashes($value); }      // Originally check '&& get_magic_quotes_gpc() ' but the values of $_GET are always slashed regardless of get_magic_quotes_gpc() because HTTP_POST/GET_VARS are run through addSlashesOnArray in the very beginning of index_ts.php eg.
+               if ($strip && isset($value) && is_array($value)) { t3lib_div::stripSlashesOnArray($value); }
                return $value;
        }
 
        /**
         * Returns the GET/POST global arrays merged with POST taking precedence.
                return $value;
        }
 
        /**
         * Returns the GET/POST global arrays merged with POST taking precedence.
-        * 
         * Usage: 1
         * Usage: 1
-        * 
+        *
         * @param       string          Key (variable name) from GET or POST vars
         * @return      array           Returns the GET vars merged recursively onto the POST vars.
         * @ignore
         * @param       string          Key (variable name) from GET or POST vars
         * @return      array           Returns the GET vars merged recursively onto the POST vars.
         * @ignore
+        * @deprecated
         */
        function GParrayMerged($var)    {
         */
        function GParrayMerged($var)    {
-               $postA = is_array($GLOBALS['HTTP_POST_VARS'][$var]) ? $GLOBALS['HTTP_POST_VARS'][$var] : array();
-               $getA = is_array($GLOBALS['HTTP_GET_VARS'][$var]) ? $GLOBALS['HTTP_GET_VARS'][$var] : array();
+               $postA = is_array($_POST[$var]) ? $_POST[$var] : array();
+               $getA = is_array($_GET[$var]) ? $_GET[$var] : array();
                $mergedA = t3lib_div::array_merge_recursive_overrule($getA,$postA);
                t3lib_div::stripSlashesOnArray($mergedA);
                return $mergedA;
        }
 
                $mergedA = t3lib_div::array_merge_recursive_overrule($getA,$postA);
                t3lib_div::stripSlashesOnArray($mergedA);
                return $mergedA;
        }
 
-       /**
-        * Client Browser Information
-        * 
-        * Usage: 4
-        * 
-        * @param       string          Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
-        * @return      array           Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
-        */
-       function clientInfo($useragent='')      {
-               if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
 
 
-               $bInfo=array();
-                       // Which browser?
-               if (strstr($useragent,'Konqueror'))     {
-                       $bInfo['BROWSER']= 'konqu';
-               } elseif (strstr($useragent,'Opera'))   {
-                       $bInfo['BROWSER']= 'opera';
-               } elseif (strstr($useragent,'MSIE 4') || strstr($useragent,'MSIE 5') || strstr($useragent,'MSIE 6'))    {
-                       $bInfo['BROWSER']= 'msie';
-               } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5'))     {
-                       $bInfo['BROWSER']='net';
-               }
-               if ($bInfo['BROWSER'])  {
-                               // Browser version
-                       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,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
-                               break;
-                               case 'msie':
-                                       $tmp = strstr($useragent,'MSIE');
-                                       $bInfo['VERSION'] = doubleval(substr($tmp,4));
-                               break;
-                               case 'opera':
-                                       $tmp = strstr($useragent,'Opera');
-                                       $bInfo['VERSION'] = doubleval(substr($tmp,5));
-                               break;
-                               case 'konqu':
-                                       $tmp = strstr($useragent,'Konqueror/');
-                                       $bInfo['VERSION'] = doubleval(substr($tmp,10));
-                               break;
-                       }
-                               // Client system
-                       if (strstr($useragent,'Win'))   {
-                               $bInfo['SYSTEM'] = 'win';
-                       } elseif (strstr($useragent,'Mac'))     {
-                               $bInfo['SYSTEM'] = 'mac';
-                       } elseif (strstr($useragent,'Linux') || strstr($useragent,'X11') || strstr($useragent,'SGI') || strstr($useragent,' SunOS ') || strstr($useragent,' HP-UX '))   {
-                               $bInfo['SYSTEM'] = 'unix';
-                       }
-               }
-                       // Is true if the browser supports css to format forms, especially the width
-               $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
 
 
-               return $bInfo;
-       }
 
 
-       
-       
-       
-       
-       
-       
-       
+
+
+
+
 
 
        /*************************
 
 
        /*************************
@@ -339,24 +372,23 @@ class t3lib_div {
         * IMAGE FUNCTIONS
         *
         *************************/
         * IMAGE FUNCTIONS
         *
         *************************/
-       
-       
+
+
        /**
         * Compressing a GIF file if not already LZW compressed
         * This function is a workaround for the fact that ImageMagick and/or GD does not compress GIF-files to their minimun size (that is RLE or no compression used)
        /**
         * Compressing a GIF file if not already LZW compressed
         * This function is a workaround for the fact that ImageMagick and/or GD does not compress GIF-files to their minimun size (that is RLE or no compression used)
-        * 
+        *
         *              The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
         *              GIF:
         *              If $type is not set, the compression is done with ImageMagick (provided that $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] is pointing to the path of a lzw-enabled version of 'convert') else with GD (should be RLE-enabled!)
         *              If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
         *              PNG:
         *              No changes.
         *              The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
         *              GIF:
         *              If $type is not set, the compression is done with ImageMagick (provided that $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] is pointing to the path of a lzw-enabled version of 'convert') else with GD (should be RLE-enabled!)
         *              If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
         *              PNG:
         *              No changes.
-        * 
+        *
         *              $theFile is expected to be a valid GIF-file!
         *              The function returns a code for the operation.
         *              $theFile is expected to be a valid GIF-file!
         *              The function returns a code for the operation.
-        * 
-        * Usage: 11
-        * 
+        * Usage: 9
+        *
         * @param       string          Filepath
         * @param       string          See description of function
         * @return      string          Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
         * @param       string          Filepath
         * @param       string          See description of function
         * @return      string          Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
@@ -366,8 +398,10 @@ class t3lib_div {
                $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
                $returnCode='';
                if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif')      {       // GIF...
                $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);
                                $returnCode='IM';
                        } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png'])       {       // GD
                                $tempImage = imageCreateFromGif($theFile);
@@ -381,11 +415,9 @@ class t3lib_div {
 
        /**
         * Converts a png file to gif
 
        /**
         * Converts a png file to gif
-        * 
         * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true.
         * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true.
-        * 
         * Usage: 5
         * Usage: 5
-        * 
+        *
         * @param       string          $theFile        the filename with path
         * @return      string          new filename
         * @internal
         * @param       string          $theFile        the filename with path
         * @return      string          new filename
         * @internal
@@ -397,7 +429,8 @@ class t3lib_div {
                        && strtolower(substr($theFile,-4,4))=='.png'
                        && @is_file($theFile))  {       // IM
                                $newFile = substr($theFile,0,-4).'.gif';
                        && 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!!
                }
                                $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!!
                }
@@ -407,8 +440,8 @@ class t3lib_div {
        /**
         * Returns filename of the png/gif version of the input file (which can be png or gif).
         * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
        /**
         * Returns filename of the png/gif version of the input file (which can be png or gif).
         * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
-        * Usage: 1
-        * 
+        * Usage: 2
+        *
         * @param       string          Filepath of image file
         * @param       boolean         If set, then input file is converted to PNG, otherwise to GIF
         * @return      string          If the new image file exists, it's filepath is returned
         * @param       string          Filepath of image file
         * @param       boolean         If set, then input file is converted to PNG, otherwise to GIF
         * @return      string          If the new image file exists, it's filepath is returned
@@ -454,19 +487,22 @@ 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 '...'.
         * Truncate string
         * Returns a new string of max. $chars length.
         * If the string is longer, it will be truncated and appended with '...'.
-        * 
-        * Usage: 119
-        * 
-        * @param       string          $string         string to truncate
-        * @param       integer         $chars  must be an integer of at least 4
-        * @param       string          String to append to the the output if it is truncated, default is '...'
+        * Usage: 39
+        *
+        * @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
         * @return      string          new string
+        * @deprecated          Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
         * @see fixed_lgd_pre()
         */
         * @see fixed_lgd_pre()
         */
-       function fixed_lgd($string,$chars,$preStr='...')        {
+       function fixed_lgd($string,$origChars,$preStr='...')    {
+               $chars = abs($origChars);
                if ($chars >= 4)        {
                        if(strlen($string)>$chars)  {
                if ($chars >= 4)        {
                        if(strlen($string)>$chars)  {
-                               return trim(substr($string, 0, $chars-3)).$preStr;
+                               return $origChars < 0 ?
+                                       $preStr.trim(substr($string, -($chars-3))) :
+                                       trim(substr($string, 0, $chars-3)).$preStr;
                        }
                }
                return $string;
                        }
                }
                return $string;
@@ -477,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
         * 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
-        * 
-        * Usage: 19
-        * 
-        * @param       string          $string         string to truncate
-        * @param       integer         $chars  must be an integer of at least 4
+        * Usage: 6
+        *
+        * @param       string          string to truncate
+        * @param       integer         must be an integer of at least 4
         * @return      string          new string
         * @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)  {
         * @see fixed_lgd()
         */
        function fixed_lgd_pre($string,$chars)  {
@@ -490,33 +526,50 @@ class t3lib_div {
        }
 
        /**
        }
 
        /**
+        * Truncates a string with appended/prepended "..." and takes backend character set into consideration
+        * Use only from backend!
+        * Usage: 75
+        *
+        * @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()
+        */
+       function fixed_lgd_cs($string,$chars)   {
+               if (is_object($GLOBALS['LANG']))        {
+                       return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet,$string,$chars,'...');
+               } else {
+                       return t3lib_div::fixed_lgd($string, $chars);
+               }
+       }
+
+       /**
         * Breaks up the text for emails
         * Breaks up the text for emails
-        * 
         * Usage: 1
         * Usage: 1
-        * 
+        *
         * @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
         * @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
-        * @return      string          
+        * @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))        {
         */
        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);
        }
 
        /**
         * Breaks up a single line of text for emails
                }
                return implode(chr(10),$outArr);
        }
 
        /**
         * Breaks up a single line of text for emails
-        * 
-        * Usage: 3
-        * 
+        * Usage: 5
+        *
         * @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
         * @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
-        * @return      string          
+        * @return      string
         * @see breakTextForEmail()
         */
        function breakLinesForEmail($str,$implChar="\n",$charWidth=76)  {
         * @see breakTextForEmail()
         */
        function breakLinesForEmail($str,$implChar="\n",$charWidth=76)  {
@@ -544,59 +597,252 @@ class t3lib_div {
                        if (!trim(substr($str,$p,$l)))  break;  // added...
                }
                return implode($implChar,$lines);
                        if (!trim(substr($str,$p,$l)))  break;  // added...
                }
                return implode($implChar,$lines);
-       }       
+       }
 
        /**
         * Match IP number with list of numbers with wildcard
 
        /**
         * Match IP number with list of numbers with wildcard
-        * 
-        * Usage: 8
-        * 
+        * 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          $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)  {
         * @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);
                $IPpartsReq = explode('.',$baseIP);
                if (count($IPpartsReq)==4)      {
                        $values = t3lib_div::trimExplode(',',$list,1);
-                       reset($values);
-                       while(list(,$test)=each($values))       {
-                               $IPparts = explode('.',$test);
+
+                       foreach($values as $test)       {
+                               list($test,$mask) = explode('/',$test);
+
+                               if(intval($mask)) {
+                                               // "192.168.3.0/24"
+                                       $lnet = ip2long($test);
+                                       $lip = ip2long($baseIP);
+                                       $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
+                                       $firstpart = substr($binnet,0,$mask);
+                                       $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
+                                       $firstip = substr($binip,0,$mask);
+                                       $yes = (strcmp($firstpart,$firstip)==0);
+                               } else {
+                                               // "192.168.*.*"
+                                       $IPparts = explode('.',$test);
+                                       $yes = 1;
+                                       reset($IPparts);
+                                       while(list($index,$val)=each($IPparts)) {
+                                               $val = trim($val);
+                                               if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val))       {
+                                                       $yes=0;
+                                               }
+                                       }
+                               }
+                               if ($yes) return true;
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * 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          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)        {
+               if (count(explode('.',$baseIP))==4)     {
+                       $resolvedHostName = explode('.', gethostbyaddr($baseIP));
+                       $values = t3lib_div::trimExplode(',',$list,1);
+
+                       foreach($values as $test)       {
+                               $hostNameParts = explode('.',$test);
                                $yes = 1;
                                $yes = 1;
-                               reset($IPparts);
-                               while(list($index,$val)=each($IPparts)) {
+
+                               foreach($hostNameParts as $index => $val)       {
                                        $val = trim($val);
                                        $val = trim($val);
-                                       if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val))       {
+                                       if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
                                                $yes=0;
                                        }
                                }
                                if ($yes) return true;
                        }
                }
                                                $yes=0;
                                        }
                                }
                                if ($yes) return true;
                        }
                }
+               return false;
        }
 
        /**
         * Check for item in list
        }
 
        /**
         * Check for item in list
-        * 
         * Check if an item exists in a comma-separated list of items.
         * Check if an item exists in a comma-separated list of items.
-        * 
-        * Usage: 166
-        * 
-        * @param       string          $in_list        comma-separated list of items (string)
-        * @param       string          $item   item to check for
-        * @return      bool            true if $item is in $in_list
+        * Usage: 163
+        *
+        * @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.
        }
 
        /**
         * Removes an item from a comma-separated list of items.
-        * 
         * Usage: 1
         * 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)     {
         * @return      string          new comma-separated list of items
         */
        function rmFromList($element,$list)     {
@@ -604,14 +850,42 @@ class t3lib_div {
                while(list($k,$v)=each($items)) {
                        if ($v==$element)       {unset($items[$k]);}
                }
                while(list($k,$v)=each($items)) {
                        if ($v==$element)       {unset($items[$k]);}
                }
-               return implode($items,',');
+               return implode(',',$items);
+       }
+
+       /**
+        * 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          comma-separated list of integers with ranges (string)
+        * @return      string          new comma-separated list of items
+        * @author      Martin Kutschker <martin.kutschker@activesolution.at>
+        */
+       function expandList($list)      {
+               $items = explode(',',$list);
+               $list = array();
+               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;
+                       }
+               }
+
+               return implode(',',$list);
        }
 
        /**
         * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied.
        }
 
        /**
         * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied.
-        * 
-        * Usage: 226
-        * 
+        * Usage: 224
+        *
         * @param       integer         Input value
         * @param       integer         Lower limit
         * @param       integer         Higher limit
         * @param       integer         Input value
         * @param       integer         Lower limit
         * @param       integer         Higher limit
@@ -629,11 +903,10 @@ class t3lib_div {
 
        /**
         * Returns the $integer if greater than zero, otherwise returns zero.
 
        /**
         * Returns the $integer if greater than zero, otherwise returns zero.
-        * 
         * Usage: 1
         * Usage: 1
-        * 
-        * @param       integer         
-        * @return      integer         
+        *
+        * @param       integer         Integer string to process
+        * @return      integer
         */
        function intval_positive($theInt)       {
                $theInt = intval($theInt);
         */
        function intval_positive($theInt)       {
                $theInt = intval($theInt);
@@ -643,9 +916,8 @@ class t3lib_div {
 
        /**
         * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
 
        /**
         * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
-        * 
         * Usage: 2
         * Usage: 2
-        * 
+        *
         * @param       string          Version number on format x.x.x
         * @return      integer         Integer version of version number (where each part can count to 999)
         */
         * @param       string          Version number on format x.x.x
         * @return      integer         Integer version of version number (where each part can count to 999)
         */
@@ -655,39 +927,73 @@ 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
         * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
-        * 
-        * Usage: 0
-        * 
+        * Usage: 5
+        *
         * @param       string          String to md5-hash
         * @return      integer         Returns 28bit integer-hash
         */
        function md5int($str)   {
                return hexdec(substr(md5($str),0,7));
        }
         * @param       string          String to md5-hash
         * @return      integer         Returns 28bit integer-hash
         */
        function md5int($str)   {
                return hexdec(substr(md5($str),0,7));
        }
-       
+
+       /**
+        * Returns the first 10 positions of the MD5-hash               (changed from 6 to 10 recently)
+        *
+        * Usage: 37
+        *
+        * @param       string          Input string to be md5-hashed
+        * @param       integer         The string-length of the output
+        * @return      string          Substring of the resulting md5-hash, being $len chars long (from beginning)
+        */
+       function shortMD5($input, $len=10)      {
+               return substr(md5($input),0,$len);
+       }
+
        /**
        /**
-        * Takes a comma-separated list and removes all duplicates
-        * 
+        * Takes comma-separated lists and arrays and removes all duplicates
+        * If a value in the list is trim(empty), the value is ignored.
         * Usage: 16
         * Usage: 16
-        * 
-        * @param       string          $in_list is a comma-separated list of values.
+        *
+        * @param       string          Accept multiple parameters wich can be comma-separated lists of values and arrays.
+        * @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
         */
         * @return      string          Returns the list without any duplicates of values, space around values are trimmed
         */
-       function uniqueList($in_list)   {
-               $theTempArray = explode(',',$in_list);
-               return implode(t3lib_div::uniqueArray($theTempArray),',');
+       function uniqueList($in_list, $secondParameter=NULL)    {
+               if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
+               if (isset($secondParameter))    die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
+
+               return implode(',',array_unique(t3lib_div::trimExplode(',',$in_list,1)));
        }
 
        /**
         * Splits a reference to a file in 5 parts
        }
 
        /**
         * Splits a reference to a file in 5 parts
-        * 
         * Usage: 43
         * Usage: 43
-        * 
+        *
         * @param       string          Filename/filepath to be analysed
         * @return      array           Contains keys [path], [file], [filebody], [fileext], [realFileext]
         */
        function split_fileref($fileref)        {
         * @param       string          Filename/filepath to be analysed
         * @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];
                if (    ereg('(.*/)(.*)$',$fileref,$reg)        )       {
                        $info['path'] = $reg[1];
                        $info['file'] = $reg[2];
@@ -704,15 +1010,15 @@ class t3lib_div {
                        $info['filebody'] = $info['file'];
                        $info['fileext'] = '';
                }
                        $info['filebody'] = $info['file'];
                        $info['fileext'] = '';
                }
-               reset($info);   
+               reset($info);
                return $info;
        }
                return $info;
        }
-       
+
        /**
         * Returns the directory part of a path without trailing slash
         * If there is no dir-part, then an empty string is returned.
         * Behaviour:
        /**
         * Returns the directory part of a path without trailing slash
         * If there is no dir-part, then an empty string is returned.
         * Behaviour:
-        * 
+        *
         * '/dir1/dir2/script.php' => '/dir1/dir2'
         * '/dir1/' => '/dir1'
         * 'dir1/script.php' => 'dir1'
         * '/dir1/dir2/script.php' => '/dir1/dir2'
         * '/dir1/' => '/dir1'
         * 'dir1/script.php' => 'dir1'
@@ -720,7 +1026,7 @@ class t3lib_div {
         * '/script.php' => ''
         * '' => ''
         * Usage: 5
         * '/script.php' => ''
         * '' => ''
         * Usage: 5
-        * 
+        *
         * @param       string          Directory name / path
         * @return      string          Processed input value. See function description.
         */
         * @param       string          Directory name / path
         * @return      string          Processed input value. See function description.
         */
@@ -731,9 +1037,8 @@ class t3lib_div {
 
        /**
         * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
 
        /**
         * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
-        * 
-        * Usage: 37
-        * 
+        * Usage: 11
+        *
         * @param       string          A hexadecimal color code, #xxxxxx
         * @param       integer         Offset value 0-255
         * @param       integer         Offset value 0-255
         * @param       string          A hexadecimal color code, #xxxxxx
         * @param       integer         Offset value 0-255
         * @param       integer         Offset value 0-255
@@ -754,9 +1059,8 @@ class t3lib_div {
 
        /**
         * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
 
        /**
         * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
-        * 
-        * Usage: 4
-        * 
+        * Usage: 6
+        *
         * @param       string          A hexadecimal color code, #xxxxxx
         * @param       integer         Offset value 0-255 for all three channels.
         * @return      string          A hexadecimal color code, #xxxxxx, modified according to input vars
         * @param       string          A hexadecimal color code, #xxxxxx
         * @param       integer         Offset value 0-255 for all three channels.
         * @return      string          A hexadecimal color code, #xxxxxx, modified according to input vars
@@ -768,11 +1072,10 @@ class t3lib_div {
 
        /**
         * Removes comma (if present) in the end of string
 
        /**
         * Removes comma (if present) in the end of string
-        * 
-        * Usage: 4
-        * 
-        * @param       string          
-        * @return      string          
+        * Usage: 2
+        *
+        * @param       string          String from which the comma in the end (if any) will be removed.
+        * @return      string
         */
        function rm_endcomma($string)   {
                return ereg_replace(',$','',$string);
         */
        function rm_endcomma($string)   {
                return ereg_replace(',$','',$string);
@@ -780,11 +1083,11 @@ class t3lib_div {
 
        /**
         * strtoupper which converts danish (and other characters) characters as well
 
        /**
         * strtoupper which converts danish (and other characters) characters as well
-        * (Depreciated, use PHP function with locale settings instead)
-        * Usage: 4
-        * 
-        * @param       string          
-        * @return      string          
+        * 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)     {
         * @ignore
         */
        function danish_strtoupper($string)     {
@@ -793,13 +1096,14 @@ class t3lib_div {
        }
 
        /**
        }
 
        /**
-        * change umlaut characters to plain ASCII with normally two character target
+        * 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.
         * Only known characters will be converted, so don't expect a result for any character.
-        * 
+        *
         * ä => ae, Ö => Oe
         * ä => ae, Ö => Oe
-        * 
-        * @param       string          
-        * @return      string          
+        *
+        * @param       string          String to convert.
+        * @deprecated          Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!
+        * @return      string
         */
        function convUmlauts($str)      {
                $pat  = array ( '/ä/',  '/Ä/',  '/ö/',  '/Ö/',  '/ü/',  '/Ü/',  '/ß/',  '/å/',  '/Å/',  '/ø/',  '/Ø/',  '/æ/',  '/Æ/'   );
         */
        function convUmlauts($str)      {
                $pat  = array ( '/ä/',  '/Ä/',  '/ö/',  '/Ö/',  '/ü/',  '/Ü/',  '/ß/',  '/å/',  '/Å/',  '/ø/',  '/Ø/',  '/æ/',  '/Æ/'   );
@@ -808,23 +1112,9 @@ class t3lib_div {
        }
 
        /**
        }
 
        /**
-        * Returns the first 10 positions of the MD5-hash               (changed from 6 to 10 recently)
-        * 
-        * Usage: 43
-        * 
-        * @param       string          Input string to be md5-hashed
-        * @param       integer         The string-length of the output
-        * @return      string          Substring of the resulting md5-hash, being $len chars long (from beginning)
-        */
-       function shortMD5($input, $len=10)      {
-               return substr(md5($input),0,$len);
-       }
-
-       /**
         * Tests if the input is an integer.
         * Tests if the input is an integer.
-        * 
-        * Usage: 74
-        * 
+        * Usage: 77
+        *
         * @param       mixed           Any input variable to test.
         * @return      boolean         Returns true if string is an integer
         */
         * @param       mixed           Any input variable to test.
         * @return      boolean         Returns true if string is an integer
         */
@@ -834,9 +1124,8 @@ class t3lib_div {
 
        /**
         * Returns true if the first part of $str matches the string $partStr
 
        /**
         * Returns true if the first part of $str matches the string $partStr
-        * 
-        * Usage: 58
-        * 
+        * Usage: 59
+        *
         * @param       string          Full string to check
         * @param       string          Reference string which must be found as the "first part" of the full string
         * @return      boolean         True if $partStr was found to be equal to the first part of $str
         * @param       string          Full string to check
         * @param       string          Reference string which must be found as the "first part" of the full string
         * @return      boolean         True if $partStr was found to be equal to the first part of $str
@@ -851,31 +1140,44 @@ class t3lib_div {
 
        /**
         * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
 
        /**
         * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
-        * 
-        * Usage: 54
-        * 
-        * @param       integer         Bytes
+        * Usage: 53
+        *
+        * @param       integer         Number of bytes to format.
+        * @param       string          Labels for bytes, kilo, mega and giga separated by vertical bar (|) and possibly encapsulated in "". Eg: " | K| M| G" (which is the default value)
         * @return      string          Formatted representation of the byte number, for output.
         */
         * @return      string          Formatted representation of the byte number, for output.
         */
-       function formatSize($sizeInBytes)       {
+       function formatSize($sizeInBytes,$labels='')    {
+
+                       // Set labels:
+               if (strlen($labels) == 0) {
+                   $labels = ' | K| M| G';
+               } else {
+                   $labels = str_replace('"','',$labels);
+               }
+               $labelArr = explode('|',$labels);
+
+                       // Find size:
                if ($sizeInBytes>900)   {
                if ($sizeInBytes>900)   {
-                       if ($sizeInBytes>900000)        {       // MB
+                       if ($sizeInBytes>900000000)     {       // GB
+                               $val = $sizeInBytes/(1024*1024*1024);
+                               return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
+                       }
+                       elseif ($sizeInBytes>900000)    {       // MB
                                $val = $sizeInBytes/(1024*1024);
                                $val = $sizeInBytes/(1024*1024);
-                               return number_format($val, (($val<20)?1:0), '.', '').' M';
+                               return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
                        } else {        // KB
                                $val = $sizeInBytes/(1024);
                        } else {        // KB
                                $val = $sizeInBytes/(1024);
-                               return number_format($val, (($val<20)?1:0), '.', '').' K';
+                               return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
                        }
                } else {        // Bytes
                        }
                } else {        // Bytes
-                       return $sizeInBytes.'&nbsp;&nbsp;';
+                       return $sizeInBytes.$labelArr[0];
                }
        }
 
        /**
         * Returns microtime input to milliseconds
                }
        }
 
        /**
         * Returns microtime input to milliseconds
-        * 
         * Usage: 2
         * Usage: 2
-        * 
+        *
         * @param       string          Microtime
         * @return      integer         Microtime input string converted to an integer (milliseconds)
         */
         * @param       string          Microtime
         * @return      integer         Microtime input string converted to an integer (milliseconds)
         */
@@ -887,7 +1189,7 @@ class t3lib_div {
        /**
         * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
         * Usage: 2
        /**
         * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
         * Usage: 2
-        * 
+        *
         * @param       string          Input string, eg "123 + 456 / 789 - 4"
         * @param       string          Operators to split by, typically "/+-*"
         * @return      array           Array with operators and operands separated.
         * @param       string          Input string, eg "123 + 456 / 789 - 4"
         * @param       string          Operators to split by, typically "/+-*"
         * @return      array           Array with operators and operands separated.
@@ -910,7 +1212,7 @@ class t3lib_div {
        /**
         * Calculates the input by +,-,*,/,%,^ with priority to + and -
         * Usage: 1
        /**
         * Calculates the input by +,-,*,/,%,^ with priority to + and -
         * Usage: 1
-        * 
+        *
         * @param       string          Input string, eg "123 + 456 / 789 - 4"
         * @return      integer         Calculated value. Or error string.
         * @see calcParenthesis()
         * @param       string          Input string, eg "123 + 456 / 789 - 4"
         * @return      integer         Calculated value. Or error string.
         * @see calcParenthesis()
@@ -921,12 +1223,13 @@ class t3lib_div {
                $qm='\*\/\+-^%';
                $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
                        // split the expression here:
                $qm='\*\/\+-^%';
                $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
                        // split the expression here:
+               $reg = array();
                preg_match_all('/'.$regex.'/',$string,$reg);
                preg_match_all('/'.$regex.'/',$string,$reg);
-               
+
                reset($reg[2]);
                $number=0;
                $Msign='+';
                reset($reg[2]);
                $number=0;
                $Msign='+';
-               $err='';        
+               $err='';
                $buffer=doubleval(current($reg[2]));
                next($reg[2]);  // Advance pointer
                while(list($k,$v)=each($reg[2]))        {
                $buffer=doubleval(current($reg[2]));
                next($reg[2]);  // Advance pointer
                while(list($k,$v)=each($reg[2]))        {
@@ -950,7 +1253,7 @@ class t3lib_div {
        /**
         * Calculates the input with parenthesis levels
         * Usage: 2
        /**
         * Calculates the input with parenthesis levels
         * Usage: 2
-        * 
+        *
         * @param       string          Input string, eg "(123 + 456) / 789 - 4"
         * @return      integer         Calculated value. Or error string.
         * @see calcPriority(), tslib_cObj::stdWrap()
         * @param       string          Input string, eg "(123 + 456) / 789 - 4"
         * @return      integer         Calculated value. Or error string.
         * @see calcPriority(), tslib_cObj::stdWrap()
@@ -976,9 +1279,8 @@ class t3lib_div {
 
        /**
         * Inverse version of htmlspecialchars()
 
        /**
         * Inverse version of htmlspecialchars()
-        * 
-        * Usage: 2
-        * 
+        * Usage: 4
+        *
         * @param       string          Value where &gt;, &lt;, &quot; and &amp; should be converted to regular chars.
         * @return      string          Converted result.
         */
         * @param       string          Value where &gt;, &lt;, &quot; and &amp; should be converted to regular chars.
         * @return      string          Converted result.
         */
@@ -992,18 +1294,19 @@ class t3lib_div {
 
        /**
         * Re-converts HTML entities if they have been converted by htmlspecialchars()
 
        /**
         * Re-converts HTML entities if they have been converted by htmlspecialchars()
-        * 
+        * Usage: 10
+        *
         * @param       string          String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;"
         * @return      string          Converted result.
         */
        function deHSCentities($str)    {
                return ereg_replace('&amp;([#[:alnum:]]*;)','&\1',$str);
        }
         * @param       string          String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;"
         * @return      string          Converted result.
         */
        function deHSCentities($str)    {
                return ereg_replace('&amp;([#[:alnum:]]*;)','&\1',$str);
        }
-       
+
        /**
         * This function is used to escape any ' -characters when transferring text to JavaScript!
        /**
         * This function is used to escape any ' -characters when transferring text to JavaScript!
-        * Usage: 6
-        * 
+        * Usage: 3
+        *
         * @param       string          String to escape
         * @param       boolean         If set, also backslashes are escaped.
         * @param       string          The character to escape, default is ' (single-quote)
         * @param       string          String to escape
         * @param       boolean         If set, also backslashes are escaped.
         * @param       string          The character to escape, default is ' (single-quote)
@@ -1012,15 +1315,14 @@ class t3lib_div {
        function slashJS($string,$extended=0,$char="'") {
                if ($extended)  {$string = str_replace ("\\", "\\\\", $string);}
                return str_replace ($char, "\\".$char, $string);
        function slashJS($string,$extended=0,$char="'") {
                if ($extended)  {$string = str_replace ("\\", "\\\\", $string);}
                return str_replace ($char, "\\".$char, $string);
-       }       
+       }
 
        /**
         * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
         * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
 
        /**
         * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
         * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
-        * 
-        * Usage: 8
-        * 
-        * @param       string          
+        * Usage: 4
+        *
+        * @param       string          String to raw-url-encode with spaces preserved
         * @return      string          Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
         */
        function rawUrlEncodeJS($str)   {
         * @return      string          Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
         */
        function rawUrlEncodeJS($str)   {
@@ -1028,25 +1330,36 @@ class t3lib_div {
        }
 
        /**
        }
 
        /**
+        * rawurlencode which preserves "/" chars
+        * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded.
+        * Usage: 5
+        *
+        * @param       string          Input string
+        * @return      string          Output string
+        */
+       function rawUrlEncodeFP($str)   {
+               return str_replace('%2F','/',rawurlencode($str));
+       }
+
+       /**
         * Checking syntax of input email address
         * Checking syntax of input email address
-        * 
-        * Usage: 4
-        * 
+        * Usage: 5
+        *
         * @param       string          Input string to evaluate
         * @return      boolean         Returns true if the $email address (input string) is valid; Has a "@", domain name with at least one period and only allowed a-z characters.
         */
        function validEmail($email)     {
         * @param       string          Input string to evaluate
         * @return      boolean         Returns true if the $email address (input string) is valid; Has a "@", domain name with at least one period and only allowed a-z characters.
         */
        function validEmail($email)     {
-               if (strstr($email,' '))  return 0;
-               return ereg('^[A-Za-z0-9\._-]*[@][A-Za-z0-9\._-]*[\.].[A-Za-z0-9]*$',$email) ? 1 : 0;
+               $email = trim ($email);
+               if (strstr($email,' '))  return FALSE;
+               return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE : FALSE;
        }
 
        /**
         * Formats a string for output between <textarea>-tags
         * All content outputted in a textarea form should be passed through this function
         * Not only is the content htmlspecialchar'ed on output but there is also a single newline added in the top. The newline is necessary because browsers will ignore the first newline after <textarea> if that is the first character. Therefore better set it!
        }
 
        /**
         * Formats a string for output between <textarea>-tags
         * All content outputted in a textarea form should be passed through this function
         * Not only is the content htmlspecialchar'ed on output but there is also a single newline added in the top. The newline is necessary because browsers will ignore the first newline after <textarea> if that is the first character. Therefore better set it!
-        * 
-        * Usage: 30
-        * 
+        * Usage: 23
+        *
         * @param       string          Input string to be formatted.
         * @return      string          Formatted for <textarea>-tags
         */
         * @param       string          Input string to be formatted.
         * @return      string          Formatted for <textarea>-tags
         */
@@ -1055,13 +1368,13 @@ class t3lib_div {
        }
 
 
        }
 
 
-       
-       
-       
-       
-       
-       
-       
+
+
+
+
+
+
+
 
 
 
 
 
 
@@ -1074,11 +1387,10 @@ class t3lib_div {
        /**
         * Check if an item exists in an array
         * Please note that the order of parameters is reverse compared to the php4-function in_array()!!!
        /**
         * Check if an item exists in an array
         * Please note that the order of parameters is reverse compared to the php4-function in_array()!!!
-        * 
         * Usage: 3
         * 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
         */
         * @return      boolean         true if $item is in the one-dimensional array $in_array
         * @internal
         */
@@ -1093,9 +1405,8 @@ class t3lib_div {
        /**
         * Explodes a $string delimited by $delim and passes each item in the array through intval().
         * Corresponds to explode(), but with conversion to integers for all values.
        /**
         * Explodes a $string delimited by $delim and passes each item in the array through intval().
         * Corresponds to explode(), but with conversion to integers for all values.
-        * 
-        * Usage: 86
-        * 
+        * Usage: 76
+        *
         * @param       string          Delimiter string to explode with
         * @param       string          The string to explode
         * @return      array           Exploded values, all converted to integers
         * @param       string          Delimiter string to explode with
         * @param       string          The string to explode
         * @return      array           Exploded values, all converted to integers
@@ -1112,9 +1423,8 @@ class t3lib_div {
        /**
         * Reverse explode which explodes the string counting from behind.
         * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
        /**
         * Reverse explode which explodes the string counting from behind.
         * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
-        * 
-        * Usage: 6
-        * 
+        * Usage: 8
+        *
         * @param       string          Delimiter string to explode with
         * @param       string          The string to explode
         * @param       integer         Number of array entries
         * @param       string          Delimiter string to explode with
         * @param       string          The string to explode
         * @param       integer         Number of array entries
@@ -1133,9 +1443,8 @@ class t3lib_div {
        /**
         * Explodes a string and trims all values for whitespace in the ends.
         * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
        /**
         * Explodes a string and trims all values for whitespace in the ends.
         * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
-        * 
-        * Usage: 239
-        * 
+        * Usage: 256
+        *
         * @param       string          Delimiter string to explode with
         * @param       string          The string to explode
         * @param       boolean         If set, all empty values (='') will NOT be set in output
         * @param       string          Delimiter string to explode with
         * @param       string          The string to explode
         * @param       boolean         If set, all empty values (='') will NOT be set in output
@@ -1154,38 +1463,23 @@ class t3lib_div {
        }
 
        /**
        }
 
        /**
-        * Takes a one-dimensional array and returns an array where the values are unique
-        * The keys in the array are substituted with some md5-hashes
-        * If the value is trim(empty), the value is ignored.
-        * Values are trimmed
-        * (Depreciated, use PHP function array_unique instead)
-        * Usage: 2
-        * 
-        * @param       array           
-        * @return      array           
+        * Remove duplicate values from an array
+        * Usage: 0
+        *
+        * @param       array           Array of values to make unique
+        * @return      array
         * @ignore
         * @ignore
-        * @depreciated
+        * @deprecated          Use the PHP function array_unique instead
         */
        function uniqueArray($valueArray)       {
         */
        function uniqueArray($valueArray)       {
-               $array_out=array();
-               if (is_array($valueArray))      {
-                       while (list($key,$val)=each($valueArray)) {
-                               $val=trim($val);
-                               if ((string)$val!='')   {
-                                       $array_out[md5($val)]=$val;
-                               }
-                       }
-               }
-               reset($array_out);
-               return $array_out;
+               return array_unique($valueArray);
        }
 
        /**
         * Removes the value $cmpValue from the $array if found there. Returns the modified array
        }
 
        /**
         * Removes the value $cmpValue from the $array if found there. Returns the modified array
-        * 
-        * Usage: 2
-        * 
-        * @param       array           
+        * Usage: 3
+        *
+        * @param       array           Array containing the values
         * @param       string          Value to search for and if found remove array entry where found.
         * @return      array           Output array with entries removed if search string is found
         */
         * @param       string          Value to search for and if found remove array entry where found.
         * @return      array           Output array with entries removed if search string is found
         */
@@ -1208,27 +1502,26 @@ class t3lib_div {
 
        /**
         * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
 
        /**
         * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
-        * 
         * Usage: 24
         * Usage: 24
-        * 
+        *
         * @param       string          Name prefix for entries. Set to blank if you wish none.
         * @param       array           The (multidim) array to implode
         * @param       string          Name prefix for entries. Set to blank if you wish none.
         * @param       array           The (multidim) array to implode
-        * @param       boolean         If set, all values that are blank (='') will NOT be imploded
+        * @param       string          (keep blank)
         * @param       boolean         If set, parameters which were blank strings would be removed.
         * @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
         * @return      string          Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
+        * @see explodeUrl2Array()
         */
         */
-       function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)      {       
+       function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)      {
                if (is_array($theArray))        {
                if (is_array($theArray))        {
-                       reset($theArray);
-                       while(list($Akey,$AVal)=each($theArray))        {
+                       foreach($theArray as $Akey => $AVal)    {
                                $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
                                if (is_array($AVal))    {
                                $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
                                if (is_array($AVal))    {
-                                       $str=t3lib_div::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
+                                       $str = t3lib_div::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
                                } else {
                                        if (!$skipBlank || strcmp($AVal,''))    {
                                                $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
                                } else {
                                        if (!$skipBlank || strcmp($AVal,''))    {
                                                $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
-                                                       '='.rawurlencode(stripslashes($AVal));  // strips slashes because HTTP_POST_VARS / GET_VARS input is with slashes...
+                                                       '='.rawurlencode($AVal);
                                        }
                                }
                        }
                                        }
                                }
                        }
@@ -1237,38 +1530,61 @@ 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
         * Returns an array with selected keys from incoming data.
         * (Better read source code if you want to find out...)
         * Usage: 3
-        * 
+        *
         * @param       string          List of variable/key names
         * @param       array           Array from where to get values based on the keys in $varList
         * @param       string          List of variable/key names
         * @param       array           Array from where to get values based on the keys in $varList
-        * @param       boolean         If set, then t3lib_div::GPvar() is used to fetch the value if not found (isset) in the $getArray
+        * @param       boolean         If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
         * @return      array           Output array with selected variables.
         */
        function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)        {
                $keys = t3lib_div::trimExplode(',',$varList,1);
                $outArr=array();
         * @return      array           Output array with selected variables.
         */
        function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)        {
                $keys = t3lib_div::trimExplode(',',$varList,1);
                $outArr=array();
-               while(list(,$v)=each($keys))    {
+               foreach($keys as $v)    {
                        if (isset($getArray[$v]))       {
                                $outArr[$v]=$getArray[$v];
                        } elseif ($GPvarAlt) {
                        if (isset($getArray[$v]))       {
                                $outArr[$v]=$getArray[$v];
                        } elseif ($GPvarAlt) {
-                               $outArr[$v]=t3lib_div::GPvar($v);
+                               $outArr[$v]=t3lib_div::_GP($v);
                        }
                }
                return $outArr;
                        }
                }
                return $outArr;
-       }       
+       }
 
        /**
         * AddSlash array
         * This function traverses a multidimentional array and adds slashes to the values.
         * NOTE that the input array is and argument by reference.!!
         * Twin-function to stripSlashesOnArray
 
        /**
         * AddSlash array
         * This function traverses a multidimentional array and adds slashes to the values.
         * NOTE that the input array is and argument by reference.!!
         * Twin-function to stripSlashesOnArray
-        * 
-        * Usage: 6
-        * 
+        * Usage: 8
+        *
         * @param       array           Multidimensional input array, (REFERENCE!)
         * @param       array           Multidimensional input array, (REFERENCE!)
-        * @return      array           
+        * @return      array
         */
        function addSlashesOnArray(&$theArray)  {
                if (is_array($theArray))        {
         */
        function addSlashesOnArray(&$theArray)  {
                if (is_array($theArray))        {
@@ -1289,11 +1605,10 @@ class t3lib_div {
         * This function traverses a multidimentional array and strips slashes to the values.
         * NOTE that the input array is and argument by reference.!!
         * Twin-function to addSlashesOnArray
         * This function traverses a multidimentional array and strips slashes to the values.
         * NOTE that the input array is and argument by reference.!!
         * Twin-function to addSlashesOnArray
-        * 
-        * Usage: 7
-        * 
+        * Usage: 10
+        *
         * @param       array           Multidimensional input array, (REFERENCE!)
         * @param       array           Multidimensional input array, (REFERENCE!)
-        * @return      array           
+        * @return      array
         */
        function stripSlashesOnArray(&$theArray)        {
                if (is_array($theArray))        {
         */
        function stripSlashesOnArray(&$theArray)        {
                if (is_array($theArray))        {
@@ -1311,12 +1626,11 @@ class t3lib_div {
 
        /**
         * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
 
        /**
         * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
-        * 
-        * Usage: 6
-        * 
+        * Usage: 0
+        *
         * @param       array           Multidimensional input array
         * @param       string          "add" or "strip", depending on usage you wish.
         * @param       array           Multidimensional input array
         * @param       string          "add" or "strip", depending on usage you wish.
-        * @return      array           
+        * @return      array
         */
        function slashArray($arr,$cmd)  {
                if ($cmd=='strip')      t3lib_div::stripSlashesOnArray($arr);
         */
        function slashArray($arr,$cmd)  {
                if ($cmd=='strip')      t3lib_div::stripSlashesOnArray($arr);
@@ -1325,42 +1639,45 @@ class t3lib_div {
        }
 
        /**
        }
 
        /**
-        * Merges two arrays recursively, overruling similar the values in the first array ($arr0) with the values of the second array ($arr1)
+        * Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar values in the first array ($arr0) with the values of the second array ($arr1)
         * In case of identical keys, ie. keeping the values of the second.
         * In case of identical keys, ie. keeping the values of the second.
-        * 
-        * Usage: 26
-        * 
+        * Usage: 0
+        *
         * @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       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 or zero. Default: true
         * @return      array           Resulting array where $arr1 values has overruled $arr0 values
         */
         * @return      array           Resulting array where $arr1 values has overruled $arr0 values
         */
-       function array_merge_recursive_overrule ($arr0,$arr1,$notAddKeys=0) {
+       function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) {
                reset($arr1);
                while(list($key,$val) = each($arr1)) {
                        if(is_array($arr0[$key])) {
                                if (is_array($arr1[$key]))      {
                reset($arr1);
                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])) {
                                }
                        } else {
                                if ($notAddKeys) {
                                        if (isset($arr0[$key])) {
-                                               $arr0[$key] = $val;
+                                               if ($includeEmtpyValues || $val) {
+                                                       $arr0[$key] = $val;
+                                               }
                                        }
                                } else {
                                        }
                                } else {
-                                       $arr0[$key] = $val;
+                                       if ($includeEmtpyValues || $val) {
+                                               $arr0[$key] = $val;
+                                       }
                                }
                        }
                }
                reset($arr0);
                return $arr0;
        }
                                }
                        }
                }
                reset($arr0);
                return $arr0;
        }
-       
+
        /**
        /**
-        * An array_merge function where the keys are NOT renumbered as they happen to be with the real php-array_merge function
-        * 
-        * Usage: 27
-        * 
+        * An array_merge function where the keys are NOT renumbered as they happen to be with the real php-array_merge function. It is "binary safe" in the sense that integer keys are overridden as well.
+        * Usage: 16
+        *
         * @param       array           First array
         * @param       array           Second array
         * @return      array           Merged result.
         * @param       array           First array
         * @param       array           Second array
         * @return      array           Merged result.
@@ -1368,12 +1685,11 @@ class t3lib_div {
        function array_merge($arr1,$arr2)       {
                return $arr2+$arr1;
        }
        function array_merge($arr1,$arr2)       {
                return $arr2+$arr1;
        }
-       
+
        /**
         * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
        /**
         * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
-        * 
         * Usage: 5
         * Usage: 5
-        * 
+        *
         * @param       array           Input array of values
         * @param       string          Delimited, default is comman
         * @param       string          Quote-character to wrap around the values.
         * @param       array           Input array of values
         * @param       string          Delimited, default is comman
         * @param       string          Quote-character to wrap around the values.
@@ -1382,17 +1698,37 @@ class t3lib_div {
        function csvValues($row,$delim=',',$quote='"')  {
                reset($row);
                $out=array();
        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;
        }
 
                }
                $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;
+       }
+
+
 
 
-       
 
 
 
 
 
 
@@ -1413,12 +1749,11 @@ class t3lib_div {
         *************************/
 
        /**
         *************************/
 
        /**
+        * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
         * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
         * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
-        * Returns an array with all attributes as keys. Attributes are only lowercase a-z
         * If a attribute is empty (I call it 'an option'), then the value for the key is empty. You can check if it existed with isset()
         * If a attribute is empty (I call it 'an option'), then the value for the key is empty. You can check if it existed with isset()
-        * 
-        * Usage: 9
-        * 
+        * Usage: 8
+        *
         * @param       string          HTML-tag string (or attributes only)
         * @return      array           Array with the attribute values.
         */
         * @param       string          HTML-tag string (or attributes only)
         * @return      array           Array with the attribute values.
         */
@@ -1453,15 +1788,14 @@ class t3lib_div {
        /**
         * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
         * Removes tag-name if found
        /**
         * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
         * Removes tag-name if found
-        * 
-        * Usage: 1
-        * 
+        * Usage: 2
+        *
         * @param       string          HTML-tag string (or attributes only)
         * @return      array           Array with the attribute values.
         * @internal
         */
        function split_tag_attributes($tag)     {
         * @param       string          HTML-tag string (or attributes only)
         * @return      array           Array with the attribute values.
         * @internal
         */
        function split_tag_attributes($tag)     {
-               $tag_tmp = trim(eregi_replace ('^[ ]*<[^ ]*','',$tag));
+               $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
                        // Removes any > in the end of the string
                $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
 
                        // Removes any > in the end of the string
                $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
 
@@ -1475,7 +1809,7 @@ class t3lib_div {
                                $value[] = '=';
                                $tag_tmp = trim(substr($tag_tmp,1));            // Removes = chars.
                        } else {
                                $value[] = '=';
                                $tag_tmp = trim(substr($tag_tmp,1));            // Removes = chars.
                        } else {
-                               // There are '' around the value. We look for the next ' ' or '>'
+                                       // There are '' around the value. We look for the next ' ' or '>'
                                $reg = split('[[:space:]=]',$tag_tmp,2);
                                $value[] = trim($reg[0]);
                                $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
                                $reg = split('[[:space:]=]',$tag_tmp,2);
                                $value[] = trim($reg[0]);
                                $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
@@ -1487,14 +1821,14 @@ class t3lib_div {
 
        /**
         * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
 
        /**
         * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
-        * 
-        * Usage: 10
-        * 
+        * Usage: 14
+        *
         * @param       array           Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
         * @param       boolean         If set the resulting attribute list will have a) all attributes in lowercase (and duplicates weeded out, first entry taking precedence) and b) all values htmlspecialchar()'ed. It is recommended to use this switch!
         * @param       array           Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
         * @param       boolean         If set the resulting attribute list will have a) all attributes in lowercase (and duplicates weeded out, first entry taking precedence) and b) all values htmlspecialchar()'ed. It is recommended to use this switch!
+        * @param       boolean         If true, don't check if values are blank. Default is to omit attributes with blank values.
         * @return      string          Imploded attributes, eg. 'bgcolor="red" border="0"'
         */
         * @return      string          Imploded attributes, eg. 'bgcolor="red" border="0"'
         */
-       function implodeParams($arr,$xhtmlSafe=0)       {
+       function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)   {
                if (is_array($arr))     {
                        if ($xhtmlSafe) {
                                $newArr=array();
                if (is_array($arr))     {
                        if ($xhtmlSafe) {
                                $newArr=array();
@@ -1505,20 +1839,34 @@ class t3lib_div {
                        }
                        $list = array();
                        foreach($arr as $p => $v)       {
                        }
                        $list = array();
                        foreach($arr as $p => $v)       {
-                               if (strcmp($v,'')     {$list[]=$p.'="'.$v.'"';}
+                               if (strcmp($v,'') || $dontOmitBlankAttribs)     {$list[]=$p.'="'.$v.'"';}
                        }
                        return implode(' ',$list);
                }
        }
                        }
                        return implode(' ',$list);
                }
        }
-       
+
+       /**
+        * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
+        *
+        * @param       array           See implodeAttributes()
+        * @param       boolean         See implodeAttributes()
+        * @param       boolean         See implodeAttributes()
+        * @return      string          See implodeAttributes()
+        * @deprecated  Name was changed into implodeAttributes
+        * @see implodeAttributes()
+        */
+       function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)       {
+               return t3lib_div::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
+       }
+
        /**
         * Wraps JavaScript code XHTML ready with <script>-tags
         * Automatic re-identing of the JS code is done by using the first line as ident reference.
         * This is nice for identing JS code with PHP code on the same level.
         *
        /**
         * Wraps JavaScript code XHTML ready with <script>-tags
         * Automatic re-identing of the JS code is done by using the first line as ident reference.
         * This is nice for identing JS code with PHP code on the same level.
         *
-        * @param    string     JavaScript code
-        * @param       boolean         Wrap script element in linebreaks? Default is TRUE.
-        * @return    string    The wrapped JS code, ready to put into a XHTML page
+        * @param       string          JavaScript code
+        * @param       boolean         Wrap script element in linebreaks? Default is TRUE.
+        * @return      string          The wrapped JS code, ready to put into a XHTML page
         * @author      Ingmar Schlecht <ingmars@web.de>
         * @author      René Fritz <r.fritz@colorcube.de>
         */
         * @author      Ingmar Schlecht <ingmars@web.de>
         * @author      René Fritz <r.fritz@colorcube.de>
         */
@@ -1530,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
                                // 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);
                        }
                        if(preg_match('/^(\t+)/',$string,$match)) {
                                $string = str_replace($match[1],"\t", $string);
                        }
@@ -1545,17 +1894,18 @@ class t3lib_div {
 
        /**
         * Parses XML input into a PHP array with associative keys
 
        /**
         * Parses XML input into a PHP array with associative keys
-        * 
+        * Usage: 0
+        *
         * @param       string          XML data input
         * @param       integer         Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
         * @return      mixed           The array with the parsed structure unless the XML parser returns with an error in which case the error message string is returned.
         * @param       string          XML data input
         * @param       integer         Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
         * @return      mixed           The array with the parsed structure unless the XML parser returns with an error in which case the error message string is returned.
-        * @author bisqwit at iki dot fi dot not dot for dot ads dot invalid / http://dk.php.net/xml_parse_into_struct + kasper@typo3.com
+        * @author bisqwit at iki dot fi dot not dot for dot ads dot invalid / http://dk.php.net/xml_parse_into_struct + kasperYYYY@typo3.com
         */
        function xml2tree($string,$depth=999) {
                $parser = xml_parser_create();
                $vals = array();
                $index = array();
         */
        function xml2tree($string,$depth=999) {
                $parser = xml_parser_create();
                $vals = array();
                $index = array();
-               
+
                xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
                xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
                xml_parse_into_struct($parser, $string, $vals, $index);
                xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
                xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
                xml_parse_into_struct($parser, $string, $vals, $index);
@@ -1566,7 +1916,8 @@ class t3lib_div {
                $stack = array( array() );
                $stacktop = 0;
                $startPoint=0;
                $stack = array( array() );
                $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'];
                unset($tagi);
                foreach($vals as $key => $val) {
                        $type = $val['type'];
@@ -1580,13 +1931,13 @@ class t3lib_div {
                                }
 
                                $tagi = array('tag' => $val['tag']);
                                }
 
                                $tagi = array('tag' => $val['tag']);
-                       
-                               if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];      
+
+                               if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
                                if(isset($val['value']))        $tagi['values'][] = $val['value'];
                        }
                                // finish tag:
                        if ($type=='complete' || $type=='close')        {
                                if(isset($val['value']))        $tagi['values'][] = $val['value'];
                        }
                                // finish tag:
                        if ($type=='complete' || $type=='close')        {
-                               $oldtagi = $tagi; 
+                               $oldtagi = $tagi;
                                $tagi = $stack[--$stacktop];
                                $oldtag = $oldtagi['tag'];
                                unset($oldtagi['tag']);
                                $tagi = $stack[--$stacktop];
                                $oldtag = $oldtagi['tag'];
                                unset($oldtagi['tag']);
@@ -1604,7 +1955,7 @@ class t3lib_div {
                                                $oldtagi['XMLvalue']=$oldtagi['values'][0];
                                        }
                                }
                                                $oldtagi['XMLvalue']=$oldtagi['values'][0];
                                        }
                                }
-                               
+
                                $tagi['ch'][$oldtag][] = $oldtagi;
                                unset($oldtagi);
                        }
                                $tagi['ch'][$oldtag][] = $oldtagi;
                                unset($oldtagi);
                        }
@@ -1614,149 +1965,306 @@ class t3lib_div {
                        }
                }
                return $tagi['ch'];
                        }
                }
                return $tagi['ch'];
-       }       
+       }
+
+       /**
+        * 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);
+       }
 
        /**
 
        /**
-        * Converts a PHP array into an XML file.
-        * The XML output is optimized for readability since associative keys are used as fieldnames. 
-        * This also means that only alphanumeric characters are allowed in the tag names
-        * Numeric keys are converted to "n"+int (which means you should not use this kind of associative key otherwise)
+        * 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 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 NOT preserved; integers will become strings, but arrays will stay arrays of course.
-        * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances.
+        * 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 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...
         * 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
+        *
         * @param       array           The input PHP array with any kind of data; text, binary, integers. Not objects though.
         * @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       array           The input PHP array with any kind of data; text, binary, integers. Not objects though.
         * @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.
         * @see xml2array()
         */
         * @return      string          An XML string made from the input content in the array.
         * @see xml2array()
         */
-       function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0) {
+       function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array())    {
                        // The list of byte values which will trigger binary-safe storage. If any value has one of these char values in it, it will be encoded in base64
                $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
                                                chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
                                                chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
                                                chr(30).chr(31);
                        // The list of byte values which will trigger binary-safe storage. If any value has one of these char values in it, it will be encoded in base64
                $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
                                                chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
                                                chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
                                                chr(30).chr(31);
+                       // Set indenting mode:
                $indentChar = $spaceInd ? ' ' : chr(9);
                $indentN = $spaceInd>0 ? $spaceInd : 1;
                $indentChar = $spaceInd ? ' ' : chr(9);
                $indentN = $spaceInd>0 ? $spaceInd : 1;
-               
-                       // Init output variable
+               $nl = ($spaceInd >= 0 ? chr(10) : '');
+
+                       // Init output variable:
                $output='';
                $output='';
+
                        // Traverse the input array
                        // Traverse the input array
-               foreach($array as $k=>$v)       {
-                       $attr='';
-                               // If the value is an array then we will call this function recursively:
-                       if (is_array($v))       {
-                               // Sub elements:
-                               $content = chr(10).t3lib_div::array2xml($v,$NSprefix,$level+1,'',$spaceInd).
-                                                       str_pad('',($level+1)*$indentN,$indentChar);
-                       } else {        // Just a value:
-                                       // Look for binary chars:
-                               if (strspn($v,$binaryChars))    {
-                                               // 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));
-                                       $attr=' base64="1"';
-                               } else {
-                                               // Otherwise, just htmlspecialchar the stuff:
-                                       $content = htmlspecialchars($v);
+               if (is_array($array))   {
+                       foreach($array as $k=>$v)       {
+                               $attr = '';
+                               $tagName = $k;
+
+                                       // Construct the tag name.
+                               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];
+                               } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) {                // Use tag based on parent tag name:
+                                       $attr.=' index="'.htmlspecialchars($tagName).'"';
+                                       $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
+                               } elseif (!strcmp(intval($tagName),$tagName))   {       // If integer...;
+                                       if ($options['useNindex']) {    // If numeric key, prefix "n"
+                                               $tagName = 'n'.$tagName;
+                                       } else {        // Use special tag for num. keys:
+                                               $attr.=' index="'.$tagName.'"';
+                                               $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
+                                       }
+                               } elseif($options['useIndexTagForAssoc']) {             // Use tag for all associative keys:
+                                       $attr.=' index="'.htmlspecialchars($tagName).'"';
+                                       $tagName = $options['useIndexTagForAssoc'];
+                               }
+
+                                       // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
+                               $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
+
+                                       // If the value is an array then we will call this function recursively:
+                               if (is_array($v))       {
+
+                                               // Sub elements:
+                                       if ($options['alt_options'][$stackData['path'].'/'.$tagName])   {
+                                               $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
+                                               $clearStackPath = $subOptions['clearStackPath'];
+                                       } else {
+                                               $subOptions = $options;
+                                               $clearStackPath = FALSE;
+                                       }
+
+                                       $content = $nl .
+                                                               t3lib_div::array2xml(
+                                                                       $v,
+                                                                       $NSprefix,
+                                                                       $level+1,
+                                                                       '',
+                                                                       $spaceInd,
+                                                                       $subOptions,
+                                                                       array(
+                                                                               'parentTagName' => $tagName,
+                                                                               'grandParentTagName' => $stackData['parentTagName'],
+                                                                               'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
+                                                                       )
+                                                               ).
+                                                               ($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:
+                                       $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 = $nl.chunk_split(base64_encode($v));
+                                               $attr.=' base64="1"';
+                                       } else {
+                                                       // Otherwise, just htmlspecialchar the stuff:
+                                               $content = htmlspecialchars($v);
+                                               $dType = gettype($v);
+                                               if ($dType == 'string') {
+                                                       if ($options['useCDATA'] && $content != $v) {
+                                                               $content = '<![CDATA[' . $v . ']]>';
+                                                       }
+                                               } elseif (!$options['disableTypeAttrib']) {
+                                                       $attr.= ' type="'.$dType.'"';
+                                               }
+                                       }
                                }
                                }
-                       }
-                               // Construct the tag name. If numeric key, prefix "n". Further the tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
-                       if (!strcmp(intval($k),$k))     $k='n'.$k;
-                       $kn = substr(ereg_replace('[^[:alnum:]_-]','',$k),0,100);
 
 
-                               // Add the element to the output string:
-                       $output.=str_pad('',($level+1)*$indentN,$indentChar).'<'.$NSprefix.$kn.$attr.'>'.$content.'</'.$NSprefix.$kn.'>'.chr(10);
+                                       // Add the element to the output string:
+                               $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)    {
                }
 
                        // 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).
+                       $output =
+                               '<'.$docTag.'>'.$nl.
                                $output.
                                '</'.$docTag.'>';
                }
                                $output.
                                '</'.$docTag.'>';
                }
-               
+
                return $output;
        }
                return $output;
        }
-       
+
        /**
        /**
-        * Converts an XML file to a PHP array.
-        * This is the inverse function of array2xml()
-        * 
+        * Converts an XML string to a PHP array.
+        * This is the reverse function of array2xml()
+        * Usage: 17
+        *
         * @param       string          XML content to convert into an array
         * @param       string          The tag-prefix resolve, eg. a namespace like "T3:"
         * @param       string          XML content to convert into an array
         * @param       string          The tag-prefix resolve, eg. a namespace like "T3:"
+        * @param       boolean         If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
         * @return      mixed           If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
         * @see array2xml()
         */
         * @return      mixed           If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
         * @see array2xml()
         */
-       function xml2array($string,$NSprefix='') {
+       function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
+               global $TYPO3_CONF_VARS;
+
                        // Create parser:
                $parser = xml_parser_create();
                $vals = array();
                $index = array();
                        // Create parser:
                $parser = xml_parser_create();
                $vals = array();
                $index = array();
-               
+
                xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
                xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
                xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
                xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
+
+                       //  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
+               }
+
+                       // Parse content:
                xml_parse_into_struct($parser, $string, $vals, $index);
 
                        // If error, return error message:
                xml_parse_into_struct($parser, $string, $vals, $index);
 
                        // If error, return error message:
-               if (xml_get_error_code($parser))        return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
+               if (xml_get_error_code($parser))        {
+                       return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
+               }
                xml_parser_free($parser);
 
                        // Init vars:
                $stack = array(array());
                $stacktop = 0;
                $current=array();
                xml_parser_free($parser);
 
                        // Init vars:
                $stack = array(array());
                $stacktop = 0;
                $current=array();
-               $tagName='';
-               
+               $tagName = '';
+               $documentTag = '';
+
                        // Traverse the parsed XML structure:
                foreach($vals as $key => $val) {
 
                        // Traverse the parsed XML structure:
                foreach($vals as $key => $val) {
 
-                       if ($val['type']=='open') {             // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
-                               $stack[$stacktop++] = $current;
-                               $current=array();
-       
-                       } elseif ($val['type']=='complete' || $val['type']=='close')    {       // If the tag is "complete" then it's a value and we just have to get it. If the tag is "close" then it is an array which is closing and we decrese the stack pointer.
-                                       // First, process the tag-name (which is used in both cases, whether "complete" or "close")
-                               $tagName = $val['tag'];
-                                       // Test for name space:
-                               $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
-                                       // Test for numeric tag:
-                               $testNtag = substr($tagName,1); // Closing tag.
-                               $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
-
-
-                               if ($val['type']=='complete')   {       // If "complete", then its a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
-                                       if ($val['attributes']['base64'])       {
-                                               $current[$tagName] = base64_decode($val['value']);
-                                       } else $current[$tagName] = $val['value'];
-                               } else {        // Implicit "close": Manage the stack...
+                               // First, process the tag-name (which is used in both cases, whether "complete" or "close")
+                       $tagName = $val['tag'];
+                       if (!$documentTag)      $documentTag = $tagName;
+
+                               // Test for name space:
+                       $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
+
+                               // Test for numeric tag, encoded on the form "nXXX":
+                       $testNtag = substr($tagName,1); // Closing tag.
+                       $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
+
+                               // Test for alternative index value:
+                       if (strlen($val['attributes']['index']))        { $tagName = $val['attributes']['index']; }
+
+                               // Setting tag-values, manage stack:
+                       switch($val['type'])    {
+                               case 'open':            // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
+                                       $current[$tagName] = array();   // Setting blank place holder
+                                       $stack[$stacktop++] = $current;
+                                       $current = array();
+                               break;
+                               case 'close':   // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
                                        $oldCurrent = $current;
                                        $current = $stack[--$stacktop];
                                        $oldCurrent = $current;
                                        $current = $stack[--$stacktop];
-                                       $current[$tagName]=$oldCurrent;
+                                       end($current);  // Going to the end of array to get placeholder key, key($current), and fill in array next:
+                                       $current[key($current)] = $oldCurrent;
                                        unset($oldCurrent);
                                        unset($oldCurrent);
-                               }
+                               break;
+                               case 'complete':        // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
+                                       if ($val['attributes']['base64'])       {
+                                               $current[$tagName] = base64_decode($val['value']);
+                                       } else {
+                                               $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
+
+                                                       // Cast type:
+                                               switch((string)$val['attributes']['type'])      {
+                                                       case 'integer':
+                                                               $current[$tagName] = (integer)$current[$tagName];
+                                                       break;
+                                                       case 'double':
+                                                               $current[$tagName] = (double)$current[$tagName];
+                                                       break;
+                                                       case 'boolean':
+                                                               $current[$tagName] = (bool)$current[$tagName];
+                                                       break;
+                                                       case 'array':
+                                                               $current[$tagName] = array();   // MUST be an empty array since it is processed as a value; Empty arrays would end up here because they would have no tags inside...
+                                                       break;
+                                               }
+                                       }
+                               break;
                        }
                }
                        }
                }
+
+               if ($reportDocTag)      {
+                       $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
+               }
+
                        // Finally return the content of the document tag.
                return $current[$tagName];
                        // Finally return the content of the document tag.
                return $current[$tagName];
-       }       
-       
+       }
+
        /**
         * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
        /**
         * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
-        * 
+        * Usage: 2
+        *
         * @param       array           A array of XML parts, see xml2tree
         * @return      string          Re-compiled XML data.
         */
        function xmlRecompileFromStructValArray($vals)  {
                $XMLcontent='';
         * @param       array           A array of XML parts, see xml2tree
         * @return      string          Re-compiled XML data.
         */
        function xmlRecompileFromStructValArray($vals)  {
                $XMLcontent='';
-               
+
                foreach($vals as $val) {
                        $type = $val['type'];
                foreach($vals as $val) {
                        $type = $val['type'];
-                       
+
                                // open tag:
                        if ($type=='open' || $type=='complete') {
                                $XMLcontent.='<'.$val['tag'];
                                // open tag:
                        if ($type=='open' || $type=='complete') {
                                $XMLcontent.='<'.$val['tag'];
@@ -1784,13 +2292,14 @@ class t3lib_div {
                                $XMLcontent.=htmlspecialchars($val['value']);
                        }
                }
                                $XMLcontent.=htmlspecialchars($val['value']);
                        }
                }
-               
+
                return $XMLcontent;
        }
                return $XMLcontent;
        }
-       
+
        /**
         * Extract the encoding scheme as found in the first line of an XML document (typically)
        /**
         * Extract the encoding scheme as found in the first line of an XML document (typically)
-        * 
+        * Usage: 1
+        *
         * @param       string          XML data
         * @return      string          Encoding scheme (lowercase), if found.
         */
         * @param       string          XML data
         * @return      string          Encoding scheme (lowercase), if found.
         */
@@ -1802,16 +2311,16 @@ class t3lib_div {
                }
        }
 
                }
        }
 
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
+
+
+
+
+
+
+
+
+
+
        /*************************
         *
         * FILES FUNCTIONS
        /*************************
         *
         * FILES FUNCTIONS
@@ -1820,71 +2329,265 @@ class t3lib_div {
 
        /**
         * Reads the file or url $url and returns the content
 
        /**
         * Reads the file or url $url and returns the content
-        * 
-        * Usage: 79
-        * 
+        * If you are having trouble with proxys when reading URLs you can configure your way out of that with settings like $TYPO3_CONF_VARS['SYS']['curlUse'] etc.
+        * Usage: 83
+        *
         * @param       string          Filepath/URL to read
         * @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.
         */
         * @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>)
                        // (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();
                        $ch = curl_init();
-                       curl_setopt ($ch,CURLOPT_URL, $url);
-                       curl_setopt ($ch,CURLOPT_HEADER, 0);
-                       curl_setopt ($ch,CURLOPT_RETURNTRANSFER, 1);
-                       
-                       if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
-                               curl_setopt ($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
-                               
-                               // 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 (!$ch)       {
+                               return false;
+                       }
+
+                       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);
+                       }
+
+                       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;
                        }
                        }
-                       fclose($fd);
-                       return $content;
+
+                       $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);
+                       }
+               }
+               else    {
+                       $content = @file_get_contents($url);
                }
                }
+
+               return $content;
        }
 
        /**
         * Writes $content to the file $file
        }
 
        /**
         * Writes $content to the file $file
-        * 
-        * Usage: 31
-        * 
+        * Usage: 30
+        *
         * @param       string          Filepath to write to
         * @param       string          Content to write
         * @return      boolean         True if the file was successfully opened and written to.
         */
        function writeFile($file,$content)      {
         * @param       string          Filepath to write to
         * @param       string          Content to write
         * @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) && TYPO3_OS!='WIN') {@chmod ($file, 0644);}
+               if (!@is_file($file))   $changePermissions = true;
+
+               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 true;
                }
+
+               return false;
        }
 
        /**
        }
 
        /**
-        * 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: 13
-        * 
-        * @param       string          Path to list directories from
+        * Setting file system mode & group ownership of file
+        *
+        * @param       string          Filepath of newly created file
+        * @return      void
+        */
+       function fixPermissions($file)  {
+               if (@is_file($file) && TYPO3_OS!='WIN') {
+                       @chmod($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));             // "@" is there because file is not necessarily OWNED by the user
+                       if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
+                               @chgrp($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);                // "@" is there because file is not necessarily OWNED by the user
+                       }
+               }
+       }
+
+       /**
+        * 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/"
+        * @param       string          Content string to write
+        * @return      string          Returns false on success, otherwise an error string telling about the problem.
+        */
+       function writeFileToTypo3tempDir($filepath,$content)    {
+
+                       // Parse filepath into directory and basename:
+               $fI = pathinfo($filepath);
+               $fI['dirname'].= '/';
+
+                       // Check parts:
+               if (t3lib_div::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60)        {
+                       if (defined('PATH_site'))       {
+                               $dirName = PATH_site.'typo3temp/';      // Setting main temporary directory name (standard)
+                               if (@is_dir($dirName))  {
+                                       if (t3lib_div::isFirstPartOfStr($fI['dirname'],$dirName))       {
+
+                                                       // Checking if the "subdir" is found:
+                                               $subdir = substr($fI['dirname'],strlen($dirName));
+                                               if ($subdir)    {
+                                                       if (ereg('^[[:alnum:]_]+\/$',$subdir) || ereg('^[[:alnum:]_]+\/[[:alnum:]_]+\/$',$subdir))      {
+                                                               $dirName.= $subdir;
+                                                               if (!@is_dir($dirName)) {
+                                                                       t3lib_div::mkdir_deep(PATH_site.'typo3temp/', $subdir);
+                                                               }
+                                                       } 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))  {
+                                                       if ($filepath == $dirName.$fI['basename'])      {
+                                                               t3lib_div::writeFile($filepath, $content);
+                                                               if (!@is_file($filepath))       return 'File not written to disk! Write permission error in filesystem?';
+                                                       } else return 'Calculated filelocation didn\'t match input $filepath!';
+                                               } else return '"'.$dirName.'" is not a directory!';
+                                       } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
+                               } else return 'PATH_site + "typo3temp/" was not a directory!';
+                       } else return 'PATH_site constant was NOT defined!';
+               } else return 'Input filepath "'.$filepath.'" was generally invalid!';
+       }
+
+       /**
+        * Wrapper function for mkdir, setting folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
+        * Usage: 6
+        *
+        * @param       string          Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
+        * @return      boolean         TRUE if @mkdir went well!
+        */
+       function mkdir($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
+
+                       if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup'])    {       // skip this if createGroup is empty
+                               chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
+                       }
+                       return TRUE;
+               }
+       }
+
+       /**
+        * 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
+        *
+        * @param       string          Path to list directories from
         * @return      array           Returns an array with the directory entries as values. If no path, the return value is nothing.
         */
        function get_dirs($path)        {
         * @return      array           Returns an array with the directory entries as values. If no path, the return value is nothing.
         */
        function get_dirs($path)        {
@@ -1904,37 +2607,43 @@ class t3lib_div {
 
        /**
         * Returns an array with the names of files in a specific path
 
        /**
         * Returns an array with the names of files in a specific path
-        * 
-        * Usage: 17
-        * 
+        * Usage: 18
+        *
         * @param       string          $path: Is the path to the file
         * @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          $path: Is the path to the file
         * @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
         */
         * @return      array           Array of the files found
         */
-       function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')        {
-               $filearray=array();
-               $sortarray=array();
-               if ($path)      {
-                       $path = ereg_replace('/$','',$path);
+       function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='')     {
+
+                       // Initialize variabels:
+               $filearray = array();
+               $sortarray = array();
+               $path = ereg_replace('\/$','',$path);
+
+                       // Find files+directories:
+               if (@is_dir($path))     {
                        $extensionList = strtolower($extensionList);
                        $extensionList = strtolower($extensionList);
-                       $d = @dir($path);
+                       $d = dir($path);
                        if (is_object($d))      {
                                while($entry=$d->read()) {
                        if (is_object($d))      {
                                while($entry=$d->read()) {
-                                       if (@is_file($path.'/'.$entry)) {       
+                                       if (@is_file($path.'/'.$entry)) {
                                                $fI = pathinfo($entry);
                                                $fI = pathinfo($entry);
-                                               $key = md5($path.'/'.$entry);
-                                               if (!$extensionList || t3lib_div::inList($extensionList,strtolower($fI['extension'])))  {
+                                               $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 ((!strlen($extensionList) || t3lib_div::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$entry))) {
                                                    $filearray[$key]=($prependPath?$path.'/':'').$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;}
                                                }
                                        }
                                }
                                $d->close();
                                                                elseif ($order) {$sortarray[$key]=$entry;}
                                                }
                                        }
                                }
                                $d->close();
-                       } else return 'error';
+                       } else return 'error opening path: "'.$path.'"';
                }
                }
+
+                       // Sort them:
                if ($order) {
                        asort($sortarray);
                        reset($sortarray);
                if ($order) {
                        asort($sortarray);
                        reset($sortarray);
@@ -1944,29 +2653,33 @@ class t3lib_div {
                        }
                        $filearray=$newArr;
                }
                        }
                        $filearray=$newArr;
                }
+
+                       // Return result
                reset($filearray);
                return $filearray;
        }
 
        /**
         * Recursively gather all files and folders of a path.
                reset($filearray);
                return $filearray;
        }
 
        /**
         * Recursively gather all files and folders of a path.
-        * 
+        * Usage: 5
+        *
         * @param       array           $fileArr: Empty input array (will have files added to it)
         * @param       array           $fileArr: Empty input array (will have files added to it)
-        * @param       string          $path: The path to read recursively from (absolute)
+        * @param       string          $path: The path to read recursively from (absolute) (include trailing slash!)
         * @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          $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.
         */
         * @return      array           An array with the found files/directories.
         */
-       function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)       {
-               if ($regDirs)   $fileArr[]=$path;
-               $fileArr=array_merge($fileArr,t3lib_div::getFilesInDir($path,$extList,1,1));
-               
+       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,$excludePattern));
+
                $dirs = t3lib_div::get_dirs($path);
                if (is_array($dirs) && $recursivityLevels>0)    {
                        foreach ($dirs as $subdirs)     {
                $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);
                                }
                        }
                }
                                }
                        }
                }
@@ -1975,61 +2688,44 @@ class t3lib_div {
 
        /**
         * Removes the absolute part of all files/folders in fileArr
 
        /**
         * Removes the absolute part of all files/folders in fileArr
-        * 
+        * Usage: 2
+        *
         * @param       array           $fileArr: The file array to remove the prefix from
         * @param       string          $prefixToRemove: The prefix path to remove (if found as first part of string!)
         * @return      array           The input $fileArr processed.
         */
        function removePrefixPathFromList($fileArr,$prefixToRemove)     {
         * @param       array           $fileArr: The file array to remove the prefix from
         * @param       string          $prefixToRemove: The prefix path to remove (if found as first part of string!)
         * @return      array           The input $fileArr processed.
         */
        function removePrefixPathFromList($fileArr,$prefixToRemove)     {
-               reset($fileArr);
-               while(list($k,$absFileRef)=each($fileArr))      {
+               foreach($fileArr as $k => $absFileRef)  {
                        if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove))    {
                        if(t3lib_div::isFirstPartOfStr($absFileRef,$prefixToRemove))    {
-                               $fileArr[$k]=substr($absFileRef,strlen($prefixToRemove));
+                               $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
                        } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
                }
                return $fileArr;
        }
 
        /**
                        } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
                }
                return $fileArr;
        }
 
        /**
-        * Moves $source file to $destination if uploaded, otherwise try to make a copy
-        * Usage: 3
-        * 
-        * @param       string          Source file, absolute path
-        * @param       string          Destination file, absolute path
-        * @return      boolean         Returns true if the file was moved.
-        * @coauthor    Dennis Petersen <fessor@software.dk>
-        */
-       function upload_copy_move($source,$destination) {
-               if (is_uploaded_file($source))  {
-                       // Return the value of move_uploaded_file, and if false the temporary $source is still around so the user can use unlink to delete it:
-                       return move_uploaded_file($source, $destination);
-               } else @copy($source,$destination);
-               if (@is_file($destination) && TYPO3_OS!='WIN')  {@chmod ($destination, 0644);}
-                       // If here the file is copied and the temporary $source is still around, so when returning false the user can try unlink to delete the $source
-               return false;
-       }
-       
-       /**
         * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
         * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
-        * 
         * Usage: 2
         * Usage: 2
-        * 
-        * @param       string          
-        * @return      string          
+        *
+        * @param       string          File path to process
+        * @return      string
         */
        function fixWindowsFilePath($theFile)   {
                return str_replace('//','/', str_replace('\\','/', $theFile));
        }
         */
        function fixWindowsFilePath($theFile)   {
                return str_replace('//','/', str_replace('\\','/', $theFile));
        }
-       
+
        /**
        /**
-        * Resolves "../" sections in the input path string
-        * 
-        * @param       string          
-        * @return      string          
+        * Resolves "../" sections in the input path string.
+        * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
+        * Usage: 2
+        *
+        * @param       string          File path in which "/../" is resolved
+        * @return      string
         */
        function resolveBackPath($pathStr)      {
                $parts = explode('/',$pathStr);
                $output=array();
         */
        function resolveBackPath($pathStr)      {
                $parts = explode('/',$pathStr);
                $output=array();
+               $c = 0;
                foreach($parts as $pV)  {
                        if ($pV=='..')  {
                                if ($c) {
                foreach($parts as $pV)  {
                        if ($pV=='..')  {
                                if ($c) {
@@ -2049,11 +2745,10 @@ class t3lib_div {
         * - If already having a scheme, nothing is prepended
         * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
         * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
         * - If already having a scheme, nothing is prepended
         * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
         * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
-        * 
-        * Usage: 31
-        * 
-        * @param       string          
-        * @return      string          
+        * Usage: 30
+        *
+        * @param       string          URL / path to prepend full URL addressing to.
+        * @return      string
         */
        function locationHeaderUrl($path)       {
                $uI = parse_url($path);
         */
        function locationHeaderUrl($path)       {
                $uI = parse_url($path);
@@ -2061,25 +2756,25 @@ class t3lib_div {
                        $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
                } elseif (!$uI['scheme'])       { // No scheme either
                        $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
                        $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST').$path;
                } elseif (!$uI['scheme'])       { // No scheme either
                        $path = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').$path;
-               } 
+               }
                return $path;
                return $path;
-       }       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
+       }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
        /*************************
         *
         * DEBUG helper FUNCTIONS
        /*************************
         *
         * DEBUG helper FUNCTIONS
@@ -2088,8 +2783,8 @@ class t3lib_div {
 
        /**
         * Returns a string with a list of ascii-values for the first $characters characters in $string
 
        /**
         * Returns a string with a list of ascii-values for the first $characters characters in $string
-        * Usage: 5
-        * 
+        * Usage: 0
+        *
         * @param       string          String to show ASCII value for
         * @param       integer         Number of characters to show
         * @return      string          The string with ASCII values in separated by a space char.
         * @param       string          String to show ASCII value for
         * @param       integer         Number of characters to show
         * @return      string          The string with ASCII values in separated by a space char.
@@ -2107,37 +2802,42 @@ class t3lib_div {
         * Returns HTML-code, which is a visual representation of a multidimensional array
         * use t3lib_div::print_array() in order to print an array
         * Returns false if $array_in is not an array
         * Returns HTML-code, which is a visual representation of a multidimensional array
         * use t3lib_div::print_array() in order to print an array
         * Returns false if $array_in is not an array
-        * Usage: 27
-        * 
-        * @param       array           
+        * Usage: 31
+        *
+        * @param       array           Array to view
         * @return      string          HTML output
         */
        function view_array($array_in)  {
                if (is_array($array_in))        {
                        $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
         * @return      string          HTML output
         */
        function view_array($array_in)  {
                if (is_array($array_in))        {
                        $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>';}
+                       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)) {
                        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
                                if (is_array($array_in[$key]))  {
                                        $result.=t3lib_div::view_array($array_in[$key]);
                                } else
-                                       $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(HTMLSpecialChars((string)$val)).'<br /></font>';
+                                       $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
                                $result.= '</td></tr>';
                        }
                        $result.= '</table>';
                } else  {
                                $result.= '</td></tr>';
                        }
                        $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;
        }
 
        /**
         * Prints an array
                }
                return $result;
        }
 
        /**
         * Prints an array
-        * Usage: 28
-        * 
-        * @param       array           
-        * @return      void            
+        * Usage: 6
+        *
+        * @param       array           Array to print visually (in a table).
+        * @return      void
         * @internal
         * @internal
+        * @see view_array()
         */
        function print_array($array_in) {
                echo t3lib_div::view_array($array_in);
         */
        function print_array($array_in) {
                echo t3lib_div::view_array($array_in);
@@ -2148,17 +2848,16 @@ class t3lib_div {
         * Prints $var in bold between two vertical lines
         * If not $var the word 'debug' is printed
         * If $var is an array, the array is printed by t3lib_div::print_array()
         * Prints $var in bold between two vertical lines
         * If not $var the word 'debug' is printed
         * If $var is an array, the array is printed by t3lib_div::print_array()
-        * 
         * Usage: 8
         * Usage: 8
-        * 
+        *
         * @param       mixed           Variable to print
         * @param       mixed           If the parameter is a string it will be used as header. Otherwise number of break tags to apply after (positive integer) or before (negative integer) the output.
         * @param       mixed           Variable to print
         * @param       mixed           If the parameter is a string it will be used as header. Otherwise number of break tags to apply after (positive integer) or before (negative integer) the output.
-        * @return      void            
+        * @return      void
         */
        function debug($var="",$brOrHeader=0)   {
         */
        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 bgcolor="#bbbbbb"><font face="Verdana,Arial" size="1">&nbsp;<b>'.(string)HTMLSpecialChars($brOrHeader).'</b></font></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 />';}
                }
 
                        for($a=0;$a<abs(intval($brOrHeader));$a++){echo '<br />';}
                }
 
@@ -2168,45 +2867,106 @@ class t3lib_div {
                        echo '<b>|Object:<pre>';
                        print_r($var);
                        echo '</pre>|</b>';
                        echo '<b>|Object:<pre>';
                        print_r($var);
                        echo '</pre>|</b>';
-               } elseif ((string)$var!='') {
-                       echo '<b>|'.HTMLSpecialChars((string)$var).'|</b>';
+               } elseif ((string)$var!='')     {
+                       echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
                } else {
                        echo '<b>| debug |</b>';
                }
 
                } else {
                        echo '<b>| debug |</b>';
                }
 
-               if ($brOrHeader && !t3lib_div::testInt($brOrHeader)) {
+               if ($brOrHeader && !t3lib_div::testInt($brOrHeader))    {
                        echo '</td></tr></table>';
                        echo '</td></tr></table>';
-               } elseif ($brOrHeader>0) {
+               } elseif ($brOrHeader>0)        {
                        for($a=0;$a<intval($brOrHeader);$a++){echo '<br />';}
                }
        }
                        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);
+       }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 
 
 
 
 
 
@@ -2214,15 +2974,15 @@ class t3lib_div {
 
        /*************************
         *
 
        /*************************
         *
-        * SYSTEM INFORMATION   
+        * SYSTEM INFORMATION
         *
         *************************/
         *
         *************************/
-       
+
        /**
         * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
         * Usage: 1
        /**
         * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
         * Usage: 1
-        * 
-        * @return      string          
+        *
+        * @return      string
         */
        function getThisUrl()   {
                $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'));            // Url of this script
         */
        function getThisUrl()   {
                $p=parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_SCRIPT'));            // Url of this script
@@ -2233,24 +2993,25 @@ class t3lib_div {
 
        /**
         * Returns the link-url to the current script.
 
        /**
         * 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)
-        * 
-        * Usage: 54
-        * 
+        * 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 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
         * @param       array           Array of GET parameters to include
-        * @return      string          
+        * @return      string
         */
         */
-       function linkThisScript($getParams=array())     {       
+       function linkThisScript($getParams=array())     {
                $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
                $parts = t3lib_div::getIndpEnv('SCRIPT_NAME');
-               $params = $GLOBALS['HTTP_GET_VARS'];
-               reset($getParams);
-               while(list($k,$v)=each($getParams))     {
+               $params = t3lib_div::_GET();
+
+               foreach($getParams as $k => $v) {
                        if (strcmp($v,''))      {
                                $params[$k]=$v;
                        } else unset($params[$k]);
                }
                        if (strcmp($v,''))      {
                                $params[$k]=$v;
                        } else unset($params[$k]);
                }
+
                $pString = t3lib_div::implodeArrayForUrl('',$params);
                $pString = t3lib_div::implodeArrayForUrl('',$params);
+
                return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
        }
 
                return $pString ? $parts.'?'.ereg_replace('^&','',$pString) : $parts;
        }
 
@@ -2258,34 +3019,36 @@ class t3lib_div {
         * Takes a full URL, $url, possibly with a querystring and overlays the $getParams arrays values onto the quirystring, packs it all together and returns the URL again.
         * So basically it adds the parameters in $getParams to an existing URL, $url
         * Usage: 2
         * Takes a full URL, $url, possibly with a querystring and overlays the $getParams arrays values onto the quirystring, packs it all together and returns the URL again.
         * So basically it adds the parameters in $getParams to an existing URL, $url
         * Usage: 2
-        * 
+        *
         * @param       string          URL string
         * @param       array           Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
         * @return      string          Output URL with added getParams.
         */
        function linkThisUrl($url,$getParams=array())   {
                $parts = parse_url($url);
         * @param       string          URL string
         * @param       array           Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
         * @return      string          Output URL with added getParams.
         */
        function linkThisUrl($url,$getParams=array())   {
                $parts = parse_url($url);
+               $getP = array();
                if ($parts['query'])    {
                        parse_str($parts['query'],$getP);
                if ($parts['query'])    {
                        parse_str($parts['query'],$getP);
-               } else $getP=array();
-               $getP=t3lib_div::array_merge_recursive_overrule($getP,$getParams);
+               }
+               $getP = t3lib_div::array_merge_recursive_overrule($getP,$getParams);
                $uP = explode('?',$url);
                $uP = explode('?',$url);
-               $outurl = $uP[0].'?'.t3lib_div::implodeArrayForUrl('',$getP);
+
+               $params = t3lib_div::implodeArrayForUrl('',$getP);
+               $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
+
                return $outurl;
        }
 
        /**
         * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
                return $outurl;
        }
 
        /**
         * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
-        * This should be used instead of getEnv() and HTTP_SERVER_VARS/ENV_VARS to get reliable values for all situations.
-        * 
-        * Usage: 226
-        * 
+        * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
+        * Usage: 221
+        *
         * @param       string          Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY
         * @return      string          Value based on the input key, independent of server/os environment.
         */
        function getIndpEnv($getEnvName)        {
         * @param       string          Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY
         * @return      string          Value based on the input key, independent of server/os environment.
         */
        function getIndpEnv($getEnvName)        {
-               global $HTTP_SERVER_VARS;
-               /* 
+               /*
                        Conventions:
                        output from parse_url():
                        URL:    http://username:password@192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1
                        Conventions:
                        output from parse_url():
                        URL:    http://username:password@192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1
@@ -2297,12 +3060,12 @@ class t3lib_div {
                            [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
                            [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
                            [fragment] => 'link1'
                            [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
                            [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
                            [fragment] => 'link1'
-                               
+
                                Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
                                                                        [path_dir] = '/typo3/32/temp/phpcheck/'
                                                                        [path_info] = '/arg1/arg2/arg3/'
                                                                        [path] = [path_script/path_dir][path_info]
                                Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
                                                                        [path_dir] = '/typo3/32/temp/phpcheck/'
                                                                        [path_info] = '/arg1/arg2/arg3/'
                                                                        [path] = [path_script/path_dir][path_info]
-                                                                               
+
 
                        Keys supported:
 
 
                        Keys supported:
 
@@ -2320,53 +3083,61 @@ class t3lib_div {
                                REMOTE_HOST             =       (client host)
                                HTTP_USER_AGENT =       (client user agent)
                                HTTP_ACCEPT_LANGUAGE    = (client accept language)
                                REMOTE_HOST             =       (client host)
                                HTTP_USER_AGENT =       (client user agent)
                                HTTP_ACCEPT_LANGUAGE    = (client accept language)
-       
+
                        SERVER____:
                                SCRIPT_FILENAME =       Absolute filename of script             (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
                        SERVER____:
                                SCRIPT_FILENAME =       Absolute filename of script             (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
-                               
+
                        Special extras:
                        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_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_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 
-                               TYPO3_DOCUMENT_ROOT     =       Absolute path of root of documents:     TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
-               
+                               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_SSL =                     Returns TRUE if this session uses SSL (HTTPS)
+
                        Notice: [fragment] is apparently NEVER available to the script!
                        Notice: [fragment] is apparently NEVER available to the script!
-                       
-                       
+
+
                        Testing suggestions:
                        - Output all the values.
                        - In the script, make a link to the script it self, maybe add some parameters and click the link a few times so HTTP_REFERER is seen
                        - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
                        Testing suggestions:
                        - Output all the values.
                        - In the script, make a link to the script it self, maybe add some parameters and click the link a few times so HTTP_REFERER is seen
                        - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
-               
+
                */
                */
-               
+
 #              if ($getEnvName=='HTTP_REFERER')        return '';
 #              if ($getEnvName=='HTTP_REFERER')        return '';
-               switch((string)$getEnvName)     {
+
+               $retVal = '';
+
+               switch ((string)$getEnvName)    {
                        case 'SCRIPT_NAME':
                        case 'SCRIPT_NAME':
-                               return php_sapi_name()=='cgi' ? $HTTP_SERVER_VARS['PATH_INFO'] : $HTTP_SERVER_VARS['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':
                        break;
                        case 'SCRIPT_FILENAME':
-                               return str_replace('//','/', str_replace('\\','/', php_sapi_name()=='cgi'||php_sapi_name()=='isapi' ? $HTTP_SERVER_VARS['PATH_TRANSLATED']:$HTTP_SERVER_VARS['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':
                        break;
                        case 'REQUEST_URI':
-                               // Typical application of REQUEST_URI is return urls, forms submitting to itselt etc. Eg:       returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
-                               if (!$HTTP_SERVER_VARS['REQUEST_URI'])  {       // This is for ISS/CGI which does not have the REQUEST_URI available.
-                                       return '/'.ereg_replace('^/','',t3lib_div::getIndpEnv('SCRIPT_NAME')).
-                                               ($HTTP_SERVER_VARS['QUERY_STRING']?'?'.$HTTP_SERVER_VARS['QUERY_STRING']:'');
-                               } else return $HTTP_SERVER_VARS['REQUEST_URI'];
+                                       // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
+                               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 $retVal = $_SERVER['REQUEST_URI'];
                        break;
                        case 'PATH_INFO':
                        break;
                        case 'PATH_INFO':
-                                       // $HTTP_SERVER_VARS['PATH_INFO']!=$HTTP_SERVER_VARS['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
+                                       // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
                                        // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
                                        // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
-                                       // 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($HTTP_SERVER_VARS['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($HTTP_SERVER_VARS['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$HTTP_SERVER_VARS['PATH_INFO']))>1)        {
-                               if (php_sapi_name()!='cgi')     {
-                                       return $HTTP_SERVER_VARS['PATH_INFO'];
-                               } else return '';
+                                       // 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')        {
+                                       $retVal = $_SERVER['PATH_INFO'];
+                               }
                        break;
                                // These are let through without modification
                        case 'REMOTE_ADDR':
                        break;
                                // These are let through without modification
                        case 'REMOTE_ADDR':
@@ -2376,7 +3147,7 @@ class t3lib_div {
                        case 'HTTP_USER_AGENT':
                        case 'HTTP_ACCEPT_LANGUAGE':
                        case 'QUERY_STRING':
                        case 'HTTP_USER_AGENT':
                        case 'HTTP_ACCEPT_LANGUAGE':
                        case 'QUERY_STRING':
-                               return $HTTP_SERVER_VARS[$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.
                        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.
@@ -2384,36 +3155,36 @@ class t3lib_div {
                                $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
                                $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
                                $SFN_A = explode('/',strrev($SFN));
                                $SFN = t3lib_div::getIndpEnv('SCRIPT_FILENAME');
                                $SN_A = explode('/',strrev(t3lib_div::getIndpEnv('SCRIPT_NAME')));
                                $SFN_A = explode('/',strrev($SFN));
-                               $acc=array();
+                               $acc = array();
                                while(list($kk,$vv)=each($SN_A))        {
                                        if (!strcmp($SFN_A[$kk],$vv))   {
                                while(list($kk,$vv)=each($SN_A))        {
                                        if (!strcmp($SFN_A[$kk],$vv))   {
-                                               $acc[]=$vv;
+                                               $acc[] = $vv;
                                        } else break;
                                }
                                $commonEnd=strrev(implode('/',$acc));
                                        } 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':
                        break;
                        case 'TYPO3_HOST_ONLY':
-                               $p=explode(':',$HTTP_SERVER_VARS['HTTP_HOST']);
-                               return $p[0];
+                               $p = explode(':',$_SERVER['HTTP_HOST']);
+                               $retVal = $p[0];
                        break;
                        case 'TYPO3_PORT':
                        break;
                        case 'TYPO3_PORT':
-                               $p=explode(':',$HTTP_SERVER_VARS['HTTP_HOST']);
-                               return $p[1];
+                               $p = explode(':',$_SERVER['HTTP_HOST']);
+                               $retVal = $p[1];
                        break;
                        case 'TYPO3_REQUEST_HOST':
                        break;
                        case 'TYPO3_REQUEST_HOST':
-                               return 'http'.($HTTP_SERVER_VARS['SSL_SESSION_ID']?'s':'').'://'.       // I hope this: ($HTTP_SERVER_VARS['SSL_SESSION_ID']?'s':'') - is sufficient to detect https...
-                                       $HTTP_SERVER_VARS['HTTP_HOST'];
+                               $retVal = (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
+                                       $_SERVER['HTTP_HOST'];
                        break;
                        case 'TYPO3_REQUEST_URL':
                        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':
                        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':
                        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')) {
                        break;
                        case 'TYPO3_SITE_URL':
                                if (defined('PATH_thisScript') && defined('PATH_site')) {
@@ -2421,12 +3192,17 @@ class t3lib_div {
                                        $url = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
                                        $siteUrl = substr($url,0,-strlen($lPath));
                                        if (substr($siteUrl,-1)!='/')   $siteUrl.='/';
                                        $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':
+                               $retVal = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
+                       break;
+                       case 'TYPO3_SSL':
+                               $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':
                        break;
                        case '_ARRAY':
-                               $out=array();
+                               $out = array();
                                        // Here, list ALL possible keys to this function for debug display.
                                $envTestVars = t3lib_div::trimExplode(',','
                                        HTTP_HOST,
                                        // Here, list ALL possible keys to this function for debug display.
                                $envTestVars = t3lib_div::trimExplode(',','
                                        HTTP_HOST,
@@ -2441,6 +3217,8 @@ class t3lib_div {
                                        TYPO3_REQUEST_SCRIPT,
                                        TYPO3_REQUEST_DIR,
                                        TYPO3_SITE_URL,
                                        TYPO3_REQUEST_SCRIPT,
                                        TYPO3_REQUEST_DIR,
                                        TYPO3_SITE_URL,
+                                       TYPO3_SITE_SCRIPT,
+                                       TYPO3_SSL,
                                        SCRIPT_NAME,
                                        TYPO3_DOCUMENT_ROOT,
                                        SCRIPT_FILENAME,
                                        SCRIPT_NAME,
                                        TYPO3_DOCUMENT_ROOT,
                                        SCRIPT_FILENAME,
@@ -2453,13 +3231,114 @@ class t3lib_div {
                                        $out[$v]=t3lib_div::getIndpEnv($v);
                                }
                                reset($out);
                                        $out[$v]=t3lib_div::getIndpEnv($v);
                                }
                                reset($out);
-                               return $out;
+                               $retVal = $out;
                        break;
                }
                        break;
                }
+               return $retVal;
+       }
+
+       /**
+        * milliseconds
+        * microtime recalculated to t3lib_div::milliseconds(1/1000 sec)
+        * Usage: 20
+        *
+        * @return      integer
+        */
+       function milliseconds() {
+               $p=explode(' ',microtime());
+               return round(($p[0]+$p[1])*1000);
+       }
+
+       /**
+        * Client Browser Information
+        * Usage: 4
+        *
+        * @param       string          Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
+        * @return      array           Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
+        */
+       function clientInfo($useragent='')      {
+               if (!$useragent) $useragent=t3lib_div::getIndpEnv('HTTP_USER_AGENT');
+
+               $bInfo=array();
+                       // Which browser?
+               if (strstr($useragent,'Konqueror'))     {
+                       $bInfo['BROWSER']= 'konqu';
+               } elseif (strstr($useragent,'Opera'))   {
+                       $bInfo['BROWSER']= 'opera';
+               } elseif (preg_match('/MSIE [4567]/', $useragent))      {
+                       $bInfo['BROWSER']= 'msie';
+               } elseif (strstr($useragent,'Mozilla/4') || strstr($useragent,'Mozilla/5'))     {
+                       $bInfo['BROWSER']='net';
+               }
+               if ($bInfo['BROWSER'])  {
+                               // Browser version
+                       switch($bInfo['BROWSER'])       {
+                               case 'net':
+                                       $bInfo['VERSION']= doubleval(substr($useragent,8));
+                                       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':
+                                       $tmp = strstr($useragent,'MSIE');
+                                       $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
+                               break;
+                               case 'opera':
+                                       $tmp = strstr($useragent,'Opera');
+                                       $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
+                               break;
+                               case 'konqu':
+                                       $tmp = strstr($useragent,'Konqueror/');
+                                       $bInfo['VERSION'] = doubleval(substr($tmp,10));
+                               break;
+                       }
+                               // Client system
+                       if (strstr($useragent,'Win'))   {
+                               $bInfo['SYSTEM'] = 'win';
+                       } elseif (strstr($useragent,'Mac'))     {
+                               $bInfo['SYSTEM'] = 'mac';
+                       } elseif (strstr($useragent,'Linux') || strstr($useragent,'X11') || strstr($useragent,'SGI') || strstr($useragent,' SunOS ') || strstr($useragent,' HP-UX '))   {
+                               $bInfo['SYSTEM'] = 'unix';
+                       }
+               }
+                       // Is true if the browser supports css to format forms, especially the width
+               $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
+
+               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;
        }
 
        }
 
-       
-       
 
 
 
 
 
 
@@ -2478,20 +3357,19 @@ class t3lib_div {
 
 
 
 
 
 
-       
-       
+
+
+
        /*************************
         *
        /*************************
         *
-        * TYPO3 SPECIFIC FUNCTIONS     
+        * TYPO3 SPECIFIC FUNCTIONS
         *
         *************************/
         *
         *************************/
-       
+
        /**
        /**
-        * Returns the absolute filename of $filename.
-        * Decodes the prefix EXT: for TYPO3 Extensions.
-        * 
-        * Usage: 9
-        * 
+        * Returns the absolute filename of a relative reference, resolves the "EXT:" prefix (way of referring to files inside extensions) and checks that the file is inside the PATH_site of the TYPO3 installation and implies a check with t3lib_div::validPathStr(). Returns false if checks failed. Does not check if the file exists.
+        * Usage: 24
+        *
         * @param       string          The input filename/filepath to evaluate
         * @param       boolean         If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
         * @param       boolean         If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
         * @param       string          The input filename/filepath to evaluate
         * @param       boolean         If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
         * @param       boolean         If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
@@ -2521,28 +3399,28 @@ class t3lib_div {
                        return $filename;
                }
        }
                        return $filename;
                }
        }
-       
+
        /**
        /**
+        * Checks for malicious file paths.
         * Returns true if no '//', '..' or '\' is in the $theFile
         * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
         * Returns true if no '//', '..' or '\' is in the $theFile
         * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
-        * So it's compatible with  the UNIX style path strings valid for TYPO3 internally.
-        * 
-        * Usage: 8
-        * 
+        * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
+        * Usage: 14
+        *
         * @param       string          Filepath to evaluate
         * @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) {
         */
        function validPathStr($theFile) {
-               if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
+               if (!strstr($theFile,'//') && !strstr($theFile,'\\') && !preg_match('#(?:^\.\.|/\.\./)#',$theFile))     return true;
        }
 
        /**
         * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
        }
 
        /**
         * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
-        * 
-        * Usage: 9
-        * 
+        * Usage: 8
+        *
         * @param       string          Filepath to evaluate
         * @param       string          Filepath to evaluate
-        * @return      boolean         
+        * @return      boolean
         */
        function isAbsPath($path)       {
                return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' :  substr($path,0,1)=='/';
         */
        function isAbsPath($path)       {
                return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' :  substr($path,0,1)=='/';
@@ -2550,29 +3428,27 @@ class t3lib_div {
 
        /**
         * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
 
        /**
         * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
-        * 
-        * Usage: 1
-        * 
+        * Usage: 5
+        *
         * @param       string          Filepath to evaluate
         * @param       string          Filepath to evaluate
-        * @return      boolean         
+        * @return      boolean
         */
        function isAllowedAbsPath($path)        {
                if (t3lib_div::isAbsPath($path) &&
                        t3lib_div::validPathStr($path) &&
         */
        function isAllowedAbsPath($path)        {
                if (t3lib_div::isAbsPath($path) &&
                        t3lib_div::validPathStr($path) &&
-                               (       t3lib_div::isFirstPartOfStr($path,PATH_site) 
-                                       || 
+                               (       t3lib_div::isFirstPartOfStr($path,PATH_site)
+                                       ||
                                        ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
                                )
                        )       return true;
        }
                                        ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
                                )
                        )       return true;
        }
-       
+
        /**
         * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
        /**
         * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
-        * 
         * Usage: 2
         * Usage: 2
-        * 
+        *
         * @param       string          Filepath to evaluate
         * @param       string          Filepath to evaluate
-        * @return      boolean         
+        * @return      boolean
         */
        function verifyFilenameAgainstDenyPattern($filename)    {
                if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],''))    {
         */
        function verifyFilenameAgainstDenyPattern($filename)    {
                if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],''))    {
@@ -2581,27 +3457,103 @@ class t3lib_div {
                }
                return true;
        }
                }
                return true;
        }
-       
+
        /**
        /**
-        * standard authentication code - can't remember what it's used for.
+        * Moves $source file to $destination if uploaded, otherwise try to make a copy
+        * Usage: 4
+        *
+        * @param       string          Source file, absolute path
+        * @param       string          Destination file, absolute path
+        * @return      boolean         Returns true if the file was moved.
+        * @coauthor    Dennis Petersen <fessor@software.dk>
+        * @see upload_to_tempfile()
+        */
+       function upload_copy_move($source,$destination) {
+               if (is_uploaded_file($source))  {
+                       $uploaded = TRUE;
+                       // Return the value of move_uploaded_file, and if false the temporary $source is still around so the user can use unlink to delete it:
+                       $uploadedResult = move_uploaded_file($source, $destination);
+               } else {
+                       $uploaded = FALSE;
+                       @copy($source,$destination);
+               }
+
+               t3lib_div::fixPermissions($destination);        // Change the permissions of the file
+
+                       // If here the file is copied and the temporary $source is still around, so when returning false the user can try unlink to delete the $source
+               return $uploaded ? $uploadedResult : FALSE;
+       }
+
+       /**
+        * Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in PATH_site."typo3temp/" from where TYPO3 can use it under safe_mode.
+        * Use this function to move uploaded files to where you can work on them.
+        * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
+        * Usage: 6
+        *
+        * @param       string          The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
+        * @return      string          If a new file was successfully created, return its filename, otherwise blank string.
+        * @see unlink_tempfile(), upload_copy_move()
+        */
+       function upload_to_tempfile($uploadedFileName)  {
+               if (is_uploaded_file($uploadedFileName))        {
+                       $tempFile = t3lib_div::tempnam('upload_temp_');
+                       move_uploaded_file($uploadedFileName, $tempFile);
+                       return @is_file($tempFile) ? $tempFile : '';
+               }
+       }
+
+       /**
+        * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
+        * The function will check that the file exists, is in PATH_site."typo3temp/" and does not contain back-spaces ("../") so it should be pretty safe.
+        * Use this after upload_to_tempfile() or tempnam() from this class!
+        * Usage: 9
+        *
+        * @param       string          Filepath for a file in PATH_site."typo3temp/". Must be absolute.
+        * @return      boolean         Returns true if the file was unlink()'ed
+        * @see upload_to_tempfile(), tempnam()
+        */
+       function unlink_tempfile($uploadedTempFileName) {
+               if ($uploadedTempFileName && t3lib_div::validPathStr($uploadedTempFileName) && t3lib_div::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName))    {
+                       if (unlink($uploadedTempFileName))      return TRUE;
+               }
+       }
+
+       /**
+        * Create temporary filename (Create file with unique file name)
+        * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
+        * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
+        * Usage: 7
+        *
+        * @param       string          Prefix to temp file (which will have no extension btw)
+        * @return      string          result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
+        * @see unlink_tempfile(), upload_to_tempfile()
+        */
+       function tempnam($filePrefix)   {
+               return tempnam(PATH_site.'typo3temp/',$filePrefix);
+       }
+
+       /**
+        * Standard authentication code (used in Direct Mail, checkJumpUrl and setfixed links computations)
         * Usage: 2
         * Usage: 2
-        * 
+        *
         * @param       mixed           Uid (integer) or record (array)
         * @param       string          List of fields from the record if that is given.
         * @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
         */
         * @return      string          MD5 hash of 8 chars.
         * @internal
         */
-       function stdAuthCode($uid_or_record,$fields='') {
-               if (is_array($uid_or_record))   {       
+       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=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 {
                                }
                        } else {
-                               $recCopy_temp=$recCopy;
+                               $recCopy_temp=$uid_or_record;
                        }
                        $preKey = implode('|',$recCopy_temp);
                } else {
                        }
                        $preKey = implode('|',$recCopy_temp);
                } else {
@@ -2609,21 +3561,254 @@ class t3lib_div {
                }
 
                $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
                }
 
                $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
-               $authCode = substr(md5($authCode),0,8);
+               $authCode = substr(md5($authCode),0,$codeLength);
                return $authCode;
                return $authCode;
-       }       
+       }
+
+       /**
+        * Splits the input query-parameters into an array with certain parameters filtered out.
+        * 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
+        * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink()
+        */
+       function cHashParams($addQueryParams) {
+               $params = explode('&',substr($addQueryParams,1));       // Splitting parameters up
+
+                       // Make array:
+               $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]) && !preg_match('/TSFE_ADMIN_PANEL\[.*?\]/',$pKV[0]))    {
+                               $pA[rawurldecode($pKV[0])] = (string)rawurldecode($pKV[1]);
+                       }
+               }
+               $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
+               ksort($pA);
+
+               return $pA;
+       }
+
+       /**
+        * 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')        {
+
+                                               //