[BUGFIX] Using datetime field with datepicker the time information gets lost
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_div.php
index ca275a9..c25d124 100644 (file)
@@ -1,29 +1,29 @@
 <?php
 /***************************************************************
-*  Copyright notice
-*
-*  (c) 1999-2010 Kasper Skårhøj (kasperYYYY@typo3.com)
-*  All rights reserved
-*
-*  This script is part of the TYPO3 project. The TYPO3 project is
-*  free software; you can redistribute it and/or modify
-*  it under the terms of the GNU General Public License as published by
-*  the Free Software Foundation; either version 2 of the License, or
-*  (at your option) any later version.
-*
-*  The GNU General Public License can be found at
-*  http://www.gnu.org/copyleft/gpl.html.
-*  A copy is found in the textfile GPL.txt and important notices to the license
-*  from the author is found in LICENSE.txt distributed with these scripts.
-*
-*
-*  This script is distributed in the hope that it will be useful,
-*  but WITHOUT ANY WARRANTY; without even the implied warranty of
-*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-*  GNU General Public License for more details.
-*
-*  This copyright notice MUST APPEAR in all copies of the script!
-***************************************************************/
+ *  Copyright notice
+ *
+ *  (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
+ *  All rights reserved
+ *
+ *  This script is part of the TYPO3 project. The TYPO3 project is
+ *  free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  The GNU General Public License can be found at
+ *  http://www.gnu.org/copyleft/gpl.html.
+ *  A copy is found in the textfile GPL.txt and important notices to the license
+ *  from the author is found in LICENSE.txt distributed with these scripts.
+ *
+ *
+ *  This script is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  This copyright notice MUST APPEAR in all copies of the script!
+ ***************************************************************/
 /**
  * Contains the reknown class "t3lib_div" with general purpose functions
  *
  *
  *  232: class t3lib_div
  *
- *              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: 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
- *  397:     function gif_compress($theFile, $type)
- *  425:     function png_to_gif_by_imagemagick($theFile)
- *  450:     function read_png_gif($theFile,$output_png=0)
+ *                       SECTION: IMAGE FUNCTIONS
+ *  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
- *  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=LF,$charWidth=76)
- *  574:     function breakLinesForEmail($str,$implChar=LF,$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: STRING FUNCTIONS
+ *  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=LF,$charWidth=76)
+ *  574:        function breakLinesForEmail($str,$implChar=LF,$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
- * 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: ARRAY FUNCTIONS
+ * 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
- * 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: HTML/XML PROCESSING
+ * 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
- * 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: FILES FUNCTIONS
+ * 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
- * 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: DEBUG helper FUNCTIONS
+ * 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
- * 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: SYSTEM INFORMATION
+ * 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
- * 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)
+ *                       SECTION: TYPO3 SPECIFIC FUNCTIONS
+ * 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: 138
  * (This index is automatically created/updated by the extension "extdeveval")
@@ -236,6 +236,27 @@ final class t3lib_div {
        const SYSLOG_SEVERITY_ERROR = 3;
        const SYSLOG_SEVERITY_FATAL = 4;
 
+       /**
+        * Singleton instances returned by makeInstance, using the class names as
+        * array keys
+        *
+        * @var array<t3lib_Singleton>
+        */
+       protected static $singletonInstances = array();
+
+       /**
+        * Instances returned by makeInstance, using the class names as array keys
+        *
+        * @var array<array><object>
+        */
+       protected static $nonSingletonInstances = array();
+
+       /**
+        * Register for makeInstance with given class name and final class names to reduce number of class_exists() calls
+        *
+        * @var array Given class name => final class name
+        */
+       protected static $finalClassNameRegister = array();
 
        /*************************
         *
@@ -260,11 +281,17 @@ final class t3lib_div {
         * @param       string          GET/POST var to return
         * @return      mixed           POST var named $var and if not set, the GET var of the same name.
         */
-       public static function _GP($var)        {
-               if(empty($var)) return;
+       public static function _GP($var) {
+               if (empty($var)) {
+                       return;
+               }
                $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
-               if (isset($value))      {
-                       if (is_array($value))   { self::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
+               if (isset($value)) {
+                       if (is_array($value)) {
+                               self::stripSlashesOnArray($value);
+                       } else {
+                               $value = stripslashes($value);
+                       }
                }
                return $value;
        }
@@ -277,7 +304,7 @@ final class t3lib_div {
         */
        public static function _GPmerged($parameter) {
                $postParameter = (isset($_POST[$parameter]) && is_array($_POST[$parameter])) ? $_POST[$parameter] : array();
-               $getParameter  = (isset($_GET[$parameter]) && is_array($_GET[$parameter])) ? $_GET[$parameter] : array();
+               $getParameter = (isset($_GET[$parameter]) && is_array($_GET[$parameter])) ? $_GET[$parameter] : array();
 
                $mergedParameters = self::array_merge_recursive_overrule($getParameter, $postParameter);
                self::stripSlashesOnArray($mergedParameters);
@@ -294,10 +321,14 @@ final class t3lib_div {
         * @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()
         */
-       public static function _GET($var=NULL)  {
+       public static 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))   { self::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
+               if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
+                       if (is_array($value)) {
+                               self::stripSlashesOnArray($value);
+                       } else {
+                               $value = stripslashes($value);
+                       }
                }
                return $value;
        }
@@ -311,10 +342,14 @@ final class t3lib_div {
         * @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()
         */
-       public static function _POST($var=NULL) {
+       public static 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))   { self::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
+               if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
+                       if (is_array($value)) {
+                               self::stripSlashesOnArray($value);
+                       } else {
+                               $value = stripslashes($value);
+                       }
                }
                return $value;
        }
@@ -324,16 +359,16 @@ final class t3lib_div {
         * Usage: 2
         *
         * @param mixed $inputGet
-        *        array or single value to write to $_GET. Values should NOT be
-        *        escaped at input time (but will be escaped before writing
-        *        according to TYPO3 standards).
+        *              array or single value to write to $_GET. Values should NOT be
+        *              escaped at input time (but will be escaped before writing
+        *              according to TYPO3 standards).
         * @param string $key
-        *        alternative key; If set, this will not set the WHOLE GET array,
-        *        but only the key in it specified by this value!
-        *        You can specify to replace keys on deeper array levels by
-        *        separating the keys with a pipe.
-        *        Example: 'parentKey|childKey' will result in
-        *        array('parentKey' => array('childKey' => $inputGet))
+        *              alternative key; If set, this will not set the WHOLE GET array,
+        *              but only the key in it specified by this value!
+        *              You can specify to replace keys on deeper array levels by
+        *              separating the keys with a pipe.
+        *              Example: 'parentKey|childKey' will result in
+        *              array('parentKey' => array('childKey' => $inputGet))
         *
         * @return      void
         */
@@ -382,13 +417,19 @@ final class t3lib_div {
         * @deprecated since TYPO3 3.6, will be removed in TYPO3 4.6 - Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!)
         * @see _GP()
         */
-       public static function GPvar($var,$strip=0)     {
+       public static function GPvar($var, $strip = 0) {
                self::logDeprecatedFunction();
 
-               if(empty($var)) return;
+               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)) { self::stripSlashesOnArray($value); }
+               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)) {
+                       self::stripSlashesOnArray($value);
+               }
                return $value;
        }
 
@@ -401,7 +442,7 @@ final class t3lib_div {
         * @deprecated since TYPO3 3.7, will be removed in TYPO3 4.6 - Use t3lib_div::_GPmerged instead
         * @see _GP()
         */
-       public static function GParrayMerged($var)      {
+       public static function GParrayMerged($var) {
                self::logDeprecatedFunction();
 
                return self::_GPmerged($var);
@@ -416,21 +457,13 @@ final class t3lib_div {
         * @param       string          Input string
         * @return      string          Input string with potential XSS code removed
         */
-       public static function removeXSS($string)       {
-               require_once(PATH_typo3.'contrib/RemoveXSS/RemoveXSS.php');
+       public static function removeXSS($string) {
+               require_once(PATH_typo3 . 'contrib/RemoveXSS/RemoveXSS.php');
                $string = RemoveXSS::process($string);
                return $string;
        }
 
 
-
-
-
-
-
-
-
-
        /*************************
         *
         * IMAGE FUNCTIONS
@@ -442,35 +475,47 @@ final class t3lib_div {
         * 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: 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.
         */
-       public static function gif_compress($theFile, $type)    {
+       public static function gif_compress($theFile, $type) {
                $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
-               $returnCode='';
-               if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif')      {       // GIF...
-                       if (($type=='IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw'])       {       // IM
-                               $cmd = self::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
-                               exec($cmd);
-
-                               $returnCode='IM';
-                       } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png'])       {       // GD
+               $returnCode = '';
+               if ($gfxConf['gif_compress'] && strtolower(substr($theFile, -4, 4)) == '.gif') { // GIF...
+                       if (($type == 'IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM
+                                       // use temporary file to prevent problems with read and write lock on same file on network file systems
+                               $temporaryName  =  dirname($theFile) . '/' . md5(uniqid()) . '.gif';
+                                       // rename could fail, if a simultaneous thread is currently working on the same thing
+                               if (@rename($theFile, $temporaryName)) {
+                                       $cmd = self::imageMagickCommand('convert', '"' . $temporaryName . '" "' . $theFile . '"', $gfxConf['im_path_lzw']);
+                                       t3lib_utility_Command::exec($cmd);
+                                       unlink($temporaryName);
+                               }
+
+                               $returnCode = 'IM';
+                               if (@is_file($theFile)) {
+                                       self::fixPermissions($theFile);
+                               }
+                       } elseif (($type == 'GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
                                $tempImage = imageCreateFromGif($theFile);
                                imageGif($tempImage, $theFile);
                                imageDestroy($tempImage);
-                               $returnCode='GD';
+                               $returnCode = 'GD';
+                               if (@is_file($theFile)) {
+                                       self::fixPermissions($theFile);
+                               }
                        }
                }
                return $returnCode;
@@ -484,17 +529,20 @@ final class t3lib_div {
         * @param       string          $theFile        the filename with path
         * @return      string          new filename
         */
-       public static function png_to_gif_by_imagemagick($theFile)      {
+       public static function png_to_gif_by_imagemagick($theFile) {
                if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
-                       && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
-                       && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
-                       && strtolower(substr($theFile,-4,4))=='.png'
-                       && @is_file($theFile))  {       // IM
-                               $newFile = substr($theFile,0,-4).'.gif';
-                               $cmd = self::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!!
+                               && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
+                               && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
+                               && strtolower(substr($theFile, -4, 4)) == '.png'
+                               && @is_file($theFile)) { // IM
+                       $newFile = substr($theFile, 0, -4) . '.gif';
+                       $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
+                       t3lib_utility_Command::exec($cmd);
+                       $theFile = $newFile;
+                       if (@is_file($newFile)) {
+                               self::fixPermissions($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!!
                }
                return $theFile;
        }
@@ -508,37 +556,27 @@ final class t3lib_div {
         * @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
         */
-       public static function read_png_gif($theFile,$output_png=0)     {
-               if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile))     {
-                       $ext = strtolower(substr($theFile,-4,4));
+       public static function read_png_gif($theFile, $output_png = 0) {
+               if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) {
+                       $ext = strtolower(substr($theFile, -4, 4));
                        if (
-                                       ((string)$ext=='.png' && $output_png)   ||
-                                       ((string)$ext=='.gif' && !$output_png)
-                               )       {
+                               ((string) $ext == '.png' && $output_png) ||
+                               ((string) $ext == '.gif' && !$output_png)
+                       ) {
                                return $theFile;
                        } else {
-                               $newFile = PATH_site.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?'.png':'.gif');
-                               $cmd = self::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']);
-                               exec($cmd);
-                               if (@is_file($newFile)) return $newFile;
+                               $newFile = PATH_site . 'typo3temp/readPG_' . md5($theFile . '|' . filemtime($theFile)) . ($output_png ? '.png' : '.gif');
+                               $cmd = self::imageMagickCommand('convert', '"' . $theFile . '" "' . $newFile . '"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']);
+                               t3lib_utility_Command::exec($cmd);
+                               if (@is_file($newFile)) {
+                                       self::fixPermissions($newFile);
+                                       return $newFile;
+                               }
                        }
                }
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
        /*************************
         *
         * STRING FUNCTIONS
@@ -558,15 +596,15 @@ final class t3lib_div {
         * @deprecated since TYPO3 4.1, will be removed in TYPO3 4.6 - Works ONLY for single-byte charsets! Use t3lib_div::fixed_lgd_cs() instead
         * @see fixed_lgd_pre()
         */
-       public static function fixed_lgd($string,$origChars,$preStr='...')      {
+       public static function fixed_lgd($string, $origChars, $preStr = '...') {
                self::logDeprecatedFunction();
 
                $chars = abs($origChars);
-               if ($chars >= 4)        {
-                       if(strlen($string)>$chars)  {
+               if ($chars >= 4) {
+                       if (strlen($string) > $chars) {
                                return $origChars < 0 ?
-                                       $preStr.trim(substr($string, -($chars-3))) :
-                                       trim(substr($string, 0, $chars-3)).$preStr;
+                                               $preStr . trim(substr($string, -($chars - 3))) :
+                                               trim(substr($string, 0, $chars - 3)) . $preStr;
                        }
                }
                return $string;
@@ -585,10 +623,10 @@ final class t3lib_div {
         * @deprecated since TYPO3 4.1, will be removed in TYPO3 4.6 - Use t3lib_div::fixed_lgd_cs() instead (with negative input value for $chars)
         * @see fixed_lgd()
         */
-       public static function fixed_lgd_pre($string,$chars)    {
+       public static function fixed_lgd_pre($string, $chars) {
                self::logDeprecatedFunction();
 
-               return strrev(self::fixed_lgd(strrev($string),$chars));
+               return strrev(self::fixed_lgd(strrev($string), $chars));
        }
 
        /**
@@ -600,7 +638,7 @@ final class t3lib_div {
         * @param       string          appendix to the truncated string
         * @return      string          cropped string
         */
-       public static function fixed_lgd_cs($string, $chars, $appendString='...') {
+       public static function fixed_lgd_cs($string, $chars, $appendString = '...') {
                if (is_object($GLOBALS['LANG'])) {
                        return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet, $string, $chars, $appendString);
                } elseif (is_object($GLOBALS['TSFE'])) {
@@ -623,15 +661,15 @@ final class t3lib_div {
         * @deprecated since TYPO3 4.1, will be removed in TYPO3 4.6 - Use PHP function wordwrap()
         * @return      string
         */
-       public static function breakTextForEmail($str,$implChar=LF,$charWidth=76)       {
+       public static function breakTextForEmail($str, $implChar = LF, $charWidth = 76) {
                self::logDeprecatedFunction();
 
-               $lines = explode(LF,$str);
-               $outArr=array();
+               $lines = explode(LF, $str);
+               $outArr = array();
                foreach ($lines as $lStr) {
-                       $outArr[] = self::breakLinesForEmail($lStr,$implChar,$charWidth);
+                       $outArr[] = self::breakLinesForEmail($lStr, $implChar, $charWidth);
                }
-               return implode(LF,$outArr);
+               return implode(LF, $outArr);
        }
 
        /**
@@ -644,31 +682,35 @@ final class t3lib_div {
         * @return      string
         * @see breakTextForEmail()
         */
-       public static function breakLinesForEmail($str,$implChar=LF,$charWidth=76)      {
-               $lines=array();
-               $l=$charWidth;
-               $p=0;
-               while(strlen($str)>$p)  {
-                       $substr=substr($str,$p,$l);
-                       if (strlen($substr)==$l)        {
-                               $count = count(explode(' ',trim(strrev($substr))));
-                               if ($count>1)   {       // OK...
-                                       $parts = explode(' ',strrev($substr),2);
+       public static function breakLinesForEmail($str, $implChar = LF, $charWidth = 76) {
+               $lines = array();
+               $l = $charWidth;
+               $p = 0;
+               while (strlen($str) > $p) {
+                       $substr = substr($str, $p, $l);
+                       if (strlen($substr) == $l) {
+                               $count = count(explode(' ', trim(strrev($substr))));
+                               if ($count > 1) { // OK...
+                                       $parts = explode(' ', strrev($substr), 2);
                                        $theLine = strrev($parts[1]);
                                } else {
-                                       $afterParts = explode(' ',substr($str,$l+$p),2);
-                                       $theLine = $substr.$afterParts[0];
+                                       $afterParts = explode(' ', substr($str, $l + $p), 2);
+                                       $theLine = $substr . $afterParts[0];
                                }
-                               if (!strlen($theLine))  {break; }       // Error, because this would keep us in an endless loop.
+                               if (!strlen($theLine)) {
+                                       break;
+                               } // Error, because this would keep us in an endless loop.
                        } else {
-                               $theLine=$substr;
+                               $theLine = $substr;
                        }
 
-                       $lines[]=trim($theLine);
-                       $p+=strlen($theLine);
-                       if (!trim(substr($str,$p,$l)))  break;  // added...
+                       $lines[] = trim($theLine);
+                       $p += strlen($theLine);
+                       if (!trim(substr($str, $p, $l))) {
+                               break;
+                       } // added...
                }
-               return implode($implChar,$lines);
+               return implode($implChar, $lines);
        }
 
        /**
@@ -680,14 +722,14 @@ final class t3lib_div {
         * @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. An empty list always returns FALSE.
         * @return      boolean         True if an IP-mask from $list matches $baseIP
         */
-       public static function cmpIP($baseIP, $list)    {
+       public static function cmpIP($baseIP, $list) {
                $list = trim($list);
-               if ($list === '')       {
-                       return false;
-               } elseif ($list === '*')        {
-                       return true;
+               if ($list === '') {
+                       return FALSE;
+               } elseif ($list === '*') {
+                       return TRUE;
                }
-               if (strpos($baseIP, ':') !== false && self::validIPv6($baseIP)) {
+               if (strpos($baseIP, ':') !== FALSE && self::validIPv6($baseIP)) {
                        return self::cmpIPv6($baseIP, $list);
                } else {
                        return self::cmpIPv4($baseIP, $list);
@@ -701,38 +743,40 @@ final class t3lib_div {
         * @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
         */
-       public static function cmpIPv4($baseIP, $list)  {
-               $IPpartsReq = explode('.',$baseIP);
-               if (count($IPpartsReq)==4)      {
-                       $values = self::trimExplode(',',$list,1);
+       public static function cmpIPv4($baseIP, $list) {
+               $IPpartsReq = explode('.', $baseIP);
+               if (count($IPpartsReq) == 4) {
+                       $values = self::trimExplode(',', $list, 1);
 
-                       foreach($values as $test)       {
-                               list($test,$mask) = explode('/',$test);
+                       foreach ($values as $test) {
+                               list($test, $mask) = explode('/', $test);
 
-                               if(intval($mask)) {
+                               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);
+                                       $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);
+                                       $firstip = substr($binip, 0, $mask);
+                                       $yes = (strcmp($firstpart, $firstip) == 0);
                                } else {
                                                // "192.168.*.*"
-                                       $IPparts = explode('.',$test);
+                                       $IPparts = explode('.', $test);
                                        $yes = 1;
                                        foreach ($IPparts as $index => $val) {
                                                $val = trim($val);
-                                               if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val))       {
-                                                       $yes=0;
+                                               if (strcmp($val, '*') && strcmp($IPpartsReq[$index], $val)) {
+                                                       $yes = 0;
                                                }
                                        }
                                }
-                               if ($yes) return true;
+                               if ($yes) {
+                                       return TRUE;
+                               }
                        }
                }
-               return false;
+               return FALSE;
        }
 
        /**
@@ -742,41 +786,43 @@ final class t3lib_div {
         * @param       string          $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
         * @return      boolean         True if an baseIP matches any prefix
         */
-       public static function cmpIPv6($baseIP, $list)  {
-               $success = false;       // Policy default: Deny connection
+       public static function cmpIPv6($baseIP, $list) {
+               $success = FALSE; // Policy default: Deny connection
                $baseIP = self::normalizeIPv6($baseIP);
 
-               $values = self::trimExplode(',',$list,1);
-               foreach ($values as $test)      {
-                       list($test,$mask) = explode('/',$test);
-                       if (self::validIPv6($test))     {
+               $values = self::trimExplode(',', $list, 1);
+               foreach ($values as $test) {
+                       list($test, $mask) = explode('/', $test);
+                       if (self::validIPv6($test)) {
                                $test = self::normalizeIPv6($test);
-                               if (intval($mask))      {
-                                       switch ($mask) {        // test on /48 /64
+                               if (intval($mask)) {
+                                       switch ($mask) { // test on /48 /64
                                                case '48':
                                                        $testBin = substr(self::IPv6Hex2Bin($test), 0, 48);
                                                        $baseIPBin = substr(self::IPv6Hex2Bin($baseIP), 0, 48);
-                                                       $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
-                                               break;
+                                                       $success = strcmp($testBin, $baseIPBin) == 0 ? TRUE : FALSE;
+                                                       break;
                                                case '64':
                                                        $testBin = substr(self::IPv6Hex2Bin($test), 0, 64);
                                                        $baseIPBin = substr(self::IPv6Hex2Bin($baseIP), 0, 64);
-                                                       $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
-                                               break;
+                                                       $success = strcmp($testBin, $baseIPBin) == 0 ? TRUE : FALSE;
+                                                       break;
                                                default:
-                                                       $success = false;
+                                                       $success = FALSE;
                                        }
                                } else {
-                                       if (self::validIPv6($test))     {       // test on full ip address 128 bits
+                                       if (self::validIPv6($test)) { // test on full ip address 128 bits
                                                $testBin = self::IPv6Hex2Bin($test);
                                                $baseIPBin = self::IPv6Hex2Bin($baseIP);
-                                               $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
+                                               $success = strcmp($testBin, $baseIPBin) == 0 ? TRUE : FALSE;
                                        }
                                }
                        }
-                       if ($success) return true;
+                       if ($success) {
+                               return TRUE;
+                       }
                }
-               return false;
+               return FALSE;
        }
 
        /**
@@ -785,11 +831,11 @@ final class t3lib_div {
         * @param       [type]          $hex: ...
         * @return      [type]          ...
         */
-       public static function IPv6Hex2Bin ($hex)       {
+       public static 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)));
+               $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;
        }
@@ -800,23 +846,26 @@ final class t3lib_div {
         * @param       string          Given IPv6 address
         * @return      string          Normalized address
         */
-       public static function normalizeIPv6($address)  {
+       public static function normalizeIPv6($address) {
                $normalizedAddress = '';
                $stageOneAddress = '';
 
-               $chunks = explode('::', $address);      // Count 2 if if address has hidden zero blocks
-               if (count($chunks)==2)  {
+               $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;
+                       if ($left == 1 && strlen($chunksLeft[0]) == 0) {
+                               $left = 0;
+                       }
 
                        $hiddenBlocks = 8 - ($left + $right);
                        $hiddenPart = '';
-                       while ($h<$hiddenBlocks)        {
+                       $h = 0;
+                       while ($h < $hiddenBlocks) {
                                $hiddenPart .= '0000:';
                                $h++;
                        }
@@ -826,21 +875,23 @@ final class t3lib_div {
                        } else {
                                $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
                        }
-               } else $stageOneAddress = $address;
+               } else {
+                       $stageOneAddress = $address;
+               }
 
                        // normalize the blocks:
                $blocks = explode(':', $stageOneAddress);
                $divCounter = 0;
-               foreach ($blocks as $block)     {
+               foreach ($blocks as $block) {
                        $tmpBlock = '';
                        $i = 0;
                        $hiddenZeros = 4 - strlen($block);
-                       while ($i < $hiddenZeros)       {
+                       while ($i < $hiddenZeros) {
                                $tmpBlock .= '0';
                                $i++;
                        }
                        $normalizedAddress .= $tmpBlock . $block;
-                       if ($divCounter < 7)    {
+                       if ($divCounter < 7) {
                                $normalizedAddress .= ':';
                                $divCounter++;
                        }
@@ -857,7 +908,7 @@ final class t3lib_div {
         * @return      boolean         True if $ip is either of IPv4 or IPv6 format.
         */
        public static function validIP($ip) {
-               return (filter_var($ip, FILTER_VALIDATE_IP) !== false);
+               return (filter_var($ip, FILTER_VALIDATE_IP) !== FALSE);
        }
 
        /**
@@ -869,7 +920,7 @@ final class t3lib_div {
         * @return      boolean         True if $ip is of IPv4 format.
         */
        public static function validIPv4($ip) {
-               return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false);
+               return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE);
        }
 
        /**
@@ -880,8 +931,8 @@ final class t3lib_div {
         * @param       string          IP address to be tested
         * @return      boolean         True if $ip is of IPv6 format.
         */
-       public static function validIPv6($ip)   {
-               return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false);
+       public static function validIPv6($ip) {
+               return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE);
        }
 
        /**
@@ -891,25 +942,27 @@ final class t3lib_div {
         * @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
         */
-       public static function cmpFQDN($baseIP, $list)        {
-               if (count(explode('.',$baseIP))==4)     {
+       public static function cmpFQDN($baseIP, $list) {
+               if (count(explode('.', $baseIP)) == 4) {
                        $resolvedHostName = explode('.', gethostbyaddr($baseIP));
-                       $values = self::trimExplode(',',$list,1);
+                       $values = self::trimExplode(',', $list, 1);
 
-                       foreach($values as $test)       {
-                               $hostNameParts = explode('.',$test);
+                       foreach ($values as $test) {
+                               $hostNameParts = explode('.', $test);
                                $yes = 1;
 
-                               foreach($hostNameParts as $index => $val)       {
+                               foreach ($hostNameParts as $index => $val) {
                                        $val = trim($val);
-                                       if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
-                                               $yes=0;
+                                       if (strcmp($val, '*') && strcmp($resolvedHostName[$index], $val)) {
+                                               $yes = 0;
                                        }
                                }
-                               if ($yes) return true;
+                               if ($yes) {
+                                       return TRUE;
+                               }
                        }
                }
-               return false;
+               return FALSE;
        }
 
        /**
@@ -932,8 +985,8 @@ final class t3lib_div {
         * @param       string          item to check for
         * @return      boolean         true if $item is in $list
         */
-       public static function inList($list, $item)     {
-               return (strpos(','.$list.',', ','.$item.',')!==false ? true : false);
+       public static function inList($list, $item) {
+               return (strpos(',' . $list . ',', ',' . $item . ',') !== FALSE ? TRUE : FALSE);
        }
 
        /**
@@ -944,14 +997,14 @@ final class t3lib_div {
         * @param       string          comma-separated list of items (string)
         * @return      string          new comma-separated list of items
         */
-       public static function rmFromList($element,$list)       {
-               $items = explode(',',$list);
+       public static function rmFromList($element, $list) {
+               $items = explode(',', $list);
                foreach ($items as $k => $v) {
-                       if ($v==$element) {
+                       if ($v == $element) {
                                unset($items[$k]);
                        }
                }
-               return implode(',',$items);
+               return implode(',', $items);
        }
 
        /**
@@ -962,24 +1015,26 @@ final class t3lib_div {
         * @return      string          new comma-separated list of items
         * @author      Martin Kutschker <martin.kutschker@activesolution.at>
         */
-       public static function expandList($list)      {
-               $items = explode(',',$list);
+       public static function expandList($list) {
+               $items = explode(',', $list);
                $list = array();
                foreach ($items as $item) {
-                       $range = explode('-',$item);
-                       if (isset($range[1]))   {
+                       $range = explode('-', $item);
+                       if (isset($range[1])) {
                                $runAwayBrake = 1000;
-                               for ($n=$range[0]; $n<=$range[1]; $n++) {
+                               for ($n = $range[0]; $n <= $range[1]; $n++) {
                                        $list[] = $n;
 
                                        $runAwayBrake--;
-                                       if ($runAwayBrake<=0)   break;
+                                       if ($runAwayBrake <= 0) {
+                                               break;
+                                       }
                                }
                        } else {
                                $list[] = $item;
                        }
                }
-               return implode(',',$list);
+               return implode(',', $list);
        }
 
        /**
@@ -992,12 +1047,18 @@ final class t3lib_div {
         * @param       integer         Default value if input is false.
         * @return      integer         The input value forced into the boundaries of $min and $max
         */
-       public static function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)    {
-               // Returns $theInt as an integer in the integerspace from $min to $max
+       public static function intInRange($theInt, $min, $max = 2000000000, $zeroValue = 0) {
+                       // Returns $theInt as an integer in the integerspace from $min to $max
                $theInt = intval($theInt);
-               if ($zeroValue && !$theInt)     {$theInt=$zeroValue;}   // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
-               if ($theInt<$min){$theInt=$min;}
-               if ($theInt>$max){$theInt=$max;}
+               if ($zeroValue && !$theInt) {
+                       $theInt = $zeroValue;
+               } // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
+               if ($theInt < $min) {
+                       $theInt = $min;
+               }
+               if ($theInt > $max) {
+                       $theInt = $max;
+               }
                return $theInt;
        }
 
@@ -1008,9 +1069,11 @@ final class t3lib_div {
         * @param       integer         Integer string to process
         * @return      integer
         */
-       public static function intval_positive($theInt) {
+       public static function intval_positive($theInt) {
                $theInt = intval($theInt);
-               if ($theInt<0){$theInt=0;}
+               if ($theInt < 0) {
+                       $theInt = 0;
+               }
                return $theInt;
        }
 
@@ -1021,9 +1084,9 @@ final class t3lib_div {
         * @param       string          Version number on format x.x.x
         * @return      integer         Integer version of version number (where each part can count to 999)
         */
-       public static function int_from_ver($verNumberStr)      {
-               $verParts = explode('.',$verNumberStr);
-               return intval((int)$verParts[0].str_pad((int)$verParts[1],3,'0',STR_PAD_LEFT).str_pad((int)$verParts[2],3,'0',STR_PAD_LEFT));
+       public static function int_from_ver($verNumberStr) {
+               $verParts = explode('.', $verNumberStr);
+               return intval((int) $verParts[0] . str_pad((int) $verParts[1], 3, '0', STR_PAD_LEFT) . str_pad((int) $verParts[2], 3, '0', STR_PAD_LEFT));
        }
 
        /**
@@ -1034,11 +1097,11 @@ final class t3lib_div {
         * @return      boolean         Returns true if this setup is compatible with the provided version number
         * @todo        Still needs a function to convert versions to branches
         */
-       public static function compat_version($verNumberStr)    {
+       public static function compat_version($verNumberStr) {
                global $TYPO3_CONF_VARS;
                $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version'] ? $TYPO3_CONF_VARS['SYS']['compat_version'] : TYPO3_branch;
 
-               if (self::int_from_ver($currVersionStr) < self::int_from_ver($verNumberStr))    {
+               if (self::int_from_ver($currVersionStr) < self::int_from_ver($verNumberStr)) {
                        return FALSE;
                } else {
                        return TRUE;
@@ -1052,8 +1115,8 @@ final class t3lib_div {
         * @param       string          String to md5-hash
         * @return      integer         Returns 28bit integer-hash
         */
-       public static function md5int($str)     {
-               return hexdec(substr(md5($str),0,7));
+       public static function md5int($str) {
+               return hexdec(substr(md5($str), 0, 7));
        }
 
        /**
@@ -1065,15 +1128,15 @@ final class t3lib_div {
         * @param       integer         The string-length of the output
         * @return      string          Substring of the resulting md5-hash, being $len chars long (from beginning)
         */
-       public static function shortMD5($input, $len=10)        {
-               return substr(md5($input),0,$len);
+       public static function shortMD5($input, $len = 10) {
+               return substr(md5($input), 0, $len);
        }
 
        /**
         * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
         *
-        * @param       string          Input string to create HMAC from
-        * @return      string          resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
+        * @param        string         Input string to create HMAC from
+        * @return       string         resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
         */
        public static function hmac($input) {
                $hashAlgorithm = 'sha1';
@@ -1094,7 +1157,7 @@ final class t3lib_div {
                                        // keys shorter than blocksize are zero-padded
                                $key = str_pad($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], $hashBlocksize, chr(0x00));
                        }
-                       $hmac = call_user_func($hashAlgorithm, ($key^$opad) . pack('H*', call_user_func($hashAlgorithm, ($key^$ipad) . $input)));
+                       $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, ($key ^ $ipad) . $input)));
                }
                return $hmac;
        }
@@ -1108,7 +1171,7 @@ final class t3lib_div {
         * @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
         */
-       public static function uniqueList($in_list, $secondParameter=NULL)      {
+       public static function uniqueList($in_list, $secondParameter = NULL) {
                if (is_array($in_list)) {
                        throw new InvalidArgumentException(
                                'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!',
@@ -1122,7 +1185,7 @@ final class t3lib_div {
                        );
                }
 
-               return implode(',',array_unique(self::trimExplode(',',$in_list,1)));
+               return implode(',', array_unique(self::trimExplode(',', $in_list, 1)));
        }
 
        /**
@@ -1132,7 +1195,7 @@ final class t3lib_div {
         * @param       string          Filename/filepath to be analysed
         * @return      array           Contains keys [path], [file], [filebody], [fileext], [realFileext]
         */
-       public static function split_fileref($fileref)  {
+       public static function split_fileref($fileref) {
                $reg = array();
                if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
                        $info['path'] = $reg[1];
@@ -1171,9 +1234,9 @@ final class t3lib_div {
         * @param       string          Directory name / path
         * @return      string          Processed input value. See function description.
         */
-       public static function dirname($path)   {
-               $p = self::revExplode('/',$path,2);
-               return count($p)==2 ? $p[0] : '';
+       public static function dirname($path) {
+               $p = self::revExplode('/', $path, 2);
+               return count($p) == 2 ? $p[0] : '';
        }
 
        /**
@@ -1187,15 +1250,15 @@ final class t3lib_div {
         * @return      string          A hexadecimal color code, #xxxxxx, modified according to input vars
         * @see modifyHTMLColorAll()
         */
-       public static function modifyHTMLColor($color,$R,$G,$B) {
-               // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
-               $nR = self::intInRange(hexdec(substr($color,1,2))+$R,0,255);
-               $nG = self::intInRange(hexdec(substr($color,3,2))+$G,0,255);
-               $nB = self::intInRange(hexdec(substr($color,5,2))+$B,0,255);
-               return '#'.
-                       substr('0'.dechex($nR),-2).
-                       substr('0'.dechex($nG),-2).
-                       substr('0'.dechex($nB),-2);
+       public static function modifyHTMLColor($color, $R, $G, $B) {
+                       // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
+               $nR = self::intInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255);
+               $nG = self::intInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255);
+               $nB = self::intInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255);
+               return '#' .
+                               substr('0' . dechex($nR), -2) .
+                               substr('0' . dechex($nG), -2) .
+                               substr('0' . dechex($nB), -2);
        }
 
        /**
@@ -1207,8 +1270,8 @@ final class t3lib_div {
         * @return      string          A hexadecimal color code, #xxxxxx, modified according to input vars
         * @see modifyHTMLColor()
         */
-       public static function modifyHTMLColorAll($color,$all)  {
-               return self::modifyHTMLColor($color,$all,$all,$all);
+       public static function modifyHTMLColorAll($color, $all) {
+               return self::modifyHTMLColor($color, $all, $all, $all);
        }
 
        /**
@@ -1219,7 +1282,7 @@ final class t3lib_div {
         * @return      string
         * @deprecated since TYPO3 4.5, will be removed in TYPO3 4.7 - Use rtrim() directly
         */
-       public static function rm_endcomma($string)     {
+       public static function rm_endcomma($string) {
                self::logDeprecatedFunction();
 
                return rtrim($string, ',');
@@ -1234,7 +1297,7 @@ final class t3lib_div {
         * @deprecated since TYPO3 3.5, will be removed in TYPO3 4.6 - Use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
         * @ignore
         */
-       public static function danish_strtoupper($string)       {
+       public static function danish_strtoupper($string) {
                self::logDeprecatedFunction();
 
                $value = strtoupper($string);
@@ -1267,11 +1330,11 @@ final class t3lib_div {
         * @deprecated since TYPO3 4.1, will be removed in TYPO3 4.6 - Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!
         * @return      string
         */
-       public static function convUmlauts($str)        {
+       public static function convUmlauts($str) {
                self::logDeprecatedFunction();
 
-               $pattern  = array (chr(228), chr(196), chr(246), chr(214), chr(252), chr(220), chr(223), chr(229), chr(197), chr(248), chr(216), chr(230), chr(198));
-               $replace = array ('ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE');
+               $pattern = array(chr(228), chr(196), chr(246), chr(214), chr(252), chr(220), chr(223), chr(229), chr(197), chr(248), chr(216), chr(230), chr(198));
+               $replace = array('ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE');
                return str_replace($pattern, $replace, $str);
        }
 
@@ -1285,7 +1348,7 @@ final class t3lib_div {
                if ($var === '') {
                        return FALSE;
                }
-               return (string)intval($var) === (string)$var;
+               return (string) intval($var) === (string) $var;
        }
 
        /**
@@ -1296,7 +1359,7 @@ final class t3lib_div {
         * @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
         */
-       public static function isFirstPartOfStr($str,$partStr) {
+       public static function isFirstPartOfStr($str, $partStr) {
                return $partStr != '' && strpos((string) $str, (string) $partStr, 0) === 0;
        }
 
@@ -1308,31 +1371,31 @@ final class t3lib_div {
         * @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.
         */
-       public static function formatSize($sizeInBytes,$labels='')      {
+       public static function formatSize($sizeInBytes, $labels = '') {
 
                        // Set labels:
                if (strlen($labels) == 0) {
                        $labels = ' | K| M| G';
                } else {
-                       $labels = str_replace('"','',$labels);
+                       $labels = str_replace('"', '', $labels);
                }
-               $labelArr = explode('|',$labels);
+               $labelArr = explode('|', $labels);
 
                        // Find size:
-               if ($sizeInBytes>900)   {
-                       if ($sizeInBytes>900000000)     {       // GB
-                               $val = $sizeInBytes/(1024*1024*1024);
-                               return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
+               if ($sizeInBytes > 900) {
+                       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);
-                               return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
-                       } else {        // KB
-                               $val = $sizeInBytes/(1024);
-                               return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
+                       elseif ($sizeInBytes > 900000) { // MB
+                               $val = $sizeInBytes / (1024 * 1024);
+                               return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[2];
+                       } else { // KB
+                               $val = $sizeInBytes / (1024);
+                               return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[1];
                        }
-               } else {        // Bytes
-                       return $sizeInBytes.$labelArr[0];
+               } else { // Bytes
+                       return $sizeInBytes . $labelArr[0];
                }
        }
 
@@ -1343,9 +1406,9 @@ final class t3lib_div {
         * @param       string          Microtime
         * @return      integer         Microtime input string converted to an integer (milliseconds)
         */
-       public static function convertMicrotime($microtime)     {
-               $parts = explode(' ',$microtime);
-               return round(($parts[0]+$parts[1])*1000);
+       public static function convertMicrotime($microtime) {
+               $parts = explode(' ', $microtime);
+               return round(($parts[0] + $parts[1]) * 1000);
        }
 
        /**
@@ -1357,15 +1420,15 @@ final class t3lib_div {
         * @return      array           Array with operators and operands separated.
         * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
         */
-       public static function splitCalc($string,$operators)    {
+       public static function splitCalc($string, $operators) {
                $res = Array();
-               $sign='+';
-               while($string)  {
-                       $valueLen=strcspn($string,$operators);
-                       $value=substr($string,0,$valueLen);
-                       $res[] = Array($sign,trim($value));
-                       $sign=substr($string,$valueLen,1);
-                       $string=substr($string,$valueLen+1);
+               $sign = '+';
+               while ($string) {
+                       $valueLen = strcspn($string, $operators);
+                       $value = substr($string, 0, $valueLen);
+                       $res[] = Array($sign, trim($value));
+                       $sign = substr($string, $valueLen, 1);
+                       $string = substr($string, $valueLen + 1);
                }
                reset($res);
                return $res;
@@ -1379,38 +1442,54 @@ final class t3lib_div {
         * @return      integer         Calculated value. Or error string.
         * @see calcParenthesis()
         */
-       public static function calcPriority($string)    {
-               $string=preg_replace('/[[:space:]]*/','',$string);      // removing all whitespace
-               $string='+'.$string;    // Ensuring an operator for the first entrance
-               $qm='\*\/\+-^%';
-               $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
+       public static function calcPriority($string) {
+               $string = preg_replace('/[[:space:]]*/', '', $string); // removing all whitespace
+               $string = '+' . $string; // Ensuring an operator for the first entrance
+               $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='+';
-               $err='';
-               $buffer=doubleval(current($reg[2]));
-               next($reg[2]);  // Advance pointer
-
-               while(list($k,$v)=each($reg[2])) {
-                       $v=doubleval($v);
+               $number = 0;
+               $Msign = '+';
+               $err = '';
+               $buffer = doubleval(current($reg[2]));
+               next($reg[2]); // Advance pointer
+
+               while (list($k, $v) = each($reg[2])) {
+                       $v = doubleval($v);
                        $sign = $reg[1][$k];
-                       if ($sign=='+' || $sign=='-')   {
-                               $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
+                       if ($sign == '+' || $sign == '-') {
+                               $number = $Msign == '-' ? $number -= $buffer : $number += $buffer;
                                $Msign = $sign;
-                               $buffer=$v;
+                               $buffer = $v;
                        } else {
-                               if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
-                               if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';}
-                               if ($sign=='*') {$buffer*=$v;}
-                               if ($sign=='^') {$buffer=pow($buffer,$v);}
+                               if ($sign == '/') {
+                                       if ($v) {
+                                               $buffer /= $v;
+                                       } else {
+                                               $err = 'dividing by zero';
+                                       }
+                               }
+                               if ($sign == '%') {
+                                       if ($v) {
+                                               $buffer %= $v;
+                                       } else {
+                                               $err = 'dividing by zero';
+                                       }
+                               }
+                               if ($sign == '*') {
+                                       $buffer *= $v;
+                               }
+                               if ($sign == '^') {
+                                       $buffer = pow($buffer, $v);
+                               }
                        }
                }
-               $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
-               return $err ? 'ERROR: '.$err : $number;
+               $number = $Msign == '-' ? $number -= $buffer : $number += $buffer;
+               return $err ? 'ERROR: ' . $err : $number;
        }
 
        /**
@@ -1421,22 +1500,24 @@ final class t3lib_div {
         * @return      integer         Calculated value. Or error string.
         * @see calcPriority(), tslib_cObj::stdWrap()
         */
-       public static function calcParenthesis($string) {
-               $securC=100;
+       public static function calcParenthesis($string) {
+               $securC = 100;
                do {
-                       $valueLenO=strcspn($string,'(');
-                       $valueLenC=strcspn($string,')');
-                       if ($valueLenC==strlen($string) || $valueLenC < $valueLenO)     {
-                               $value = self::calcPriority(substr($string,0,$valueLenC));
-                               $string = $value.substr($string,$valueLenC+1);
+                       $valueLenO = strcspn($string, '(');
+                       $valueLenC = strcspn($string, ')');
+                       if ($valueLenC == strlen($string) || $valueLenC < $valueLenO) {
+                               $value = self::calcPriority(substr($string, 0, $valueLenC));
+                               $string = $value . substr($string, $valueLenC + 1);
                                return $string;
                        } else {
-                               $string = substr($string,0,$valueLenO).self::calcParenthesis(substr($string,$valueLenO+1));
+                               $string = substr($string, 0, $valueLenO) . self::calcParenthesis(substr($string, $valueLenO + 1));
                        }
                                // Security:
                        $securC--;
-                       if ($securC<=0) break;
-               } while($valueLenO<strlen($string));
+                       if ($securC <= 0) {
+                               break;
+                       }
+               } while ($valueLenO < strlen($string));
                return $string;
        }
 
@@ -1447,11 +1528,11 @@ final class t3lib_div {
         * @param       string          Value where &gt;, &lt;, &quot; and &amp; should be converted to regular chars.
         * @return      string          Converted result.
         */
-       public static function htmlspecialchars_decode($value)  {
-               $value = str_replace('&gt;','>',$value);
-               $value = str_replace('&lt;','<',$value);
-               $value = str_replace('&quot;','"',$value);
-               $value = str_replace('&amp;','&',$value);
+       public static function htmlspecialchars_decode($value) {
+               $value = str_replace('&gt;', '>', $value);
+               $value = str_replace('&lt;', '<', $value);
+               $value = str_replace('&quot;', '"', $value);
+               $value = str_replace('&amp;', '&', $value);
                return $value;
        }
 
@@ -1462,8 +1543,8 @@ final class t3lib_div {
         * @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.
         */
-       public static function deHSCentities($str)      {
-               return preg_replace('/&amp;([#[:alnum:]]*;)/','&\1',$str);
+       public static function deHSCentities($str) {
+               return preg_replace('/&amp;([#[:alnum:]]*;)/', '&\1', $str);
        }
 
        /**
@@ -1475,9 +1556,11 @@ final class t3lib_div {
         * @param       string          The character to escape, default is ' (single-quote)
         * @return      string          Processed input string
         */
-       public static function slashJS($string,$extended=0,$char="'")   {
-               if ($extended)  {$string = str_replace ("\\", "\\\\", $string);}
-               return str_replace ($char, "\\".$char, $string);
+       public static function slashJS($string, $extended = 0, $char = "'") {
+               if ($extended) {
+                       $string = str_replace("\\", "\\\\", $string);
+               }
+               return str_replace($char, "\\" . $char, $string);
        }
 
        /**
@@ -1488,8 +1571,8 @@ final class t3lib_div {
         * @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.
         */
-       public static function rawUrlEncodeJS($str)     {
-               return str_replace('%20',' ',rawurlencode($str));
+       public static function rawUrlEncodeJS($str) {
+               return str_replace('%20', ' ', rawurlencode($str));
        }
 
        /**
@@ -1500,8 +1583,8 @@ final class t3lib_div {
         * @param       string          Input string
         * @return      string          Output string
         */
-       public static function rawUrlEncodeFP($str)     {
-               return str_replace('%2F','/',rawurlencode($str));
+       public static function rawUrlEncodeFP($str) {
+               return str_replace('%2F', '/', rawurlencode($str));
        }
 
        /**
@@ -1511,7 +1594,7 @@ final class t3lib_div {
         * @param       string          Input string to evaluate
         * @return      boolean         Returns true if the $email address (input string) is valid
         */
-       public static function validEmail($email)       {
+       public static function validEmail($email) {
                        // enforce maximum length to prevent libpcre recursion crash bug #52929 in PHP
                        // fixed in PHP 5.2+ later than Sept 2010; length restriction per SMTP RFC 2821
                if (strlen($email) > 320) {
@@ -1533,7 +1616,7 @@ final class t3lib_div {
         * @return      boolean true if mail() does not accept recipient name
         */
        public static function isBrokenEmailEnvironment() {
-               return TYPO3_OS == 'WIN' || (false !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
+               return TYPO3_OS == 'WIN' || (FALSE !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
        }
 
        /**
@@ -1544,7 +1627,7 @@ final class t3lib_div {
         * @see t3lib_::isBrokenEmailEnvironment()
         */
        public static function normalizeMailAddress($address) {
-               if (self::isBrokenEmailEnvironment() && false !== ($pos1 = strrpos($address, '<'))) {
+               if (self::isBrokenEmailEnvironment() && FALSE !== ($pos1 = strrpos($address, '<'))) {
                        $pos2 = strpos($address, '>', $pos1);
                        $address = substr($address, $pos1 + 1, ($pos2 ? $pos2 : strlen($address)) - $pos1 - 1);
                }
@@ -1560,8 +1643,8 @@ final class t3lib_div {
         * @param       string          Input string to be formatted.
         * @return      string          Formatted for <textarea>-tags
         */
-       public static function formatForTextarea($content)      {
-               return LF.htmlspecialchars($content);
+       public static function formatForTextarea($content) {
+               return LF . htmlspecialchars($content);
        }
 
        /**
@@ -1570,11 +1653,11 @@ final class t3lib_div {
         * uppercase. It is safe for all supported character sets (incl. utf-8).
         * Unlike strtoupper() it does not honour the locale.
         *
-        * @param   string      Input string
-        * @return  string      Uppercase String
+        * @param   string        Input string
+        * @return  string        Uppercase String
         */
        public static function strtoupper($str) {
-               return strtr((string)$str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
+               return strtr((string) $str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
        }
 
        /**
@@ -1586,8 +1669,8 @@ final class t3lib_div {
         * @param       string          Input string
         * @return      string          Lowercase String
         */
-       public static function strtolower($str) {
-               return strtr((string)$str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
+       public static function strtolower($str) {
+               return strtr((string) $str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
        }
 
        /**
@@ -1610,7 +1693,7 @@ final class t3lib_div {
                                try {
                                        $com = new COM('CAPICOM.Utilities.1');
                                        $output = base64_decode($com->GetRandom($count, 0));
-                               } catch(Exception $e) {
+                               } catch (Exception $e) {
                                        // CAPICOM not installed
                                }
                        }
@@ -1618,7 +1701,7 @@ final class t3lib_div {
                                if (function_exists('mcrypt_create_iv')) {
                                        $output = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
                                } elseif (function_exists('openssl_random_pseudo_bytes')) {
-                                       $isStrong = null;
+                                       $isStrong = NULL;
                                        $output = openssl_random_pseudo_bytes($count, $isStrong);
                                                // skip ssl since it wasn't using the strong algo
                                        if ($isStrong !== TRUE) {
@@ -1632,11 +1715,11 @@ final class t3lib_div {
                if (!isset($output{$count - 1})) {
                                // We initialize with the somewhat random.
                        $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
-                                                       . base_convert(memory_get_usage() % pow(10, 6), 10, 2)
-                                                       . microtime() . uniqid('') . getmypid();
+                                       . base_convert(memory_get_usage() % pow(10, 6), 10, 2)
+                                       . microtime() . uniqid('') . getmypid();
                        while (!isset($output{$count - 1})) {
                                $randomState = sha1(microtime() . mt_rand() . $randomState);
-                               $output .= sha1(mt_rand() . $randomState, true);
+                               $output .= sha1(mt_rand() . $randomState, TRUE);
                        }
                        $output = substr($output, strlen($output) - $count, $count);
                }
@@ -1707,18 +1790,10 @@ final class t3lib_div {
         * @return      boolean         Whether the given URL is valid
         */
        public static function isValidUrl($url) {
-               return (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) !== false);
+               return (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) !== FALSE);
        }
 
 
-
-
-
-
-
-
-
-
        /*************************
         *
         * ARRAY FUNCTIONS
@@ -1737,10 +1812,10 @@ final class t3lib_div {
         * +---------+-----------+-----------+-----------+
         * | $needle | variant_a | variant_b | variant_c |
         * +---------+-----------+-----------+-----------+
-        * | '1a'    | false     | true      | false     |
-        * | ''      | false     | true      | false     |
-        * | '0'     | true      | true      | false     |
-        * | 0       | true      | true      | true      |
+        * | '1a'       | false  | true   | false        |
+        * | ''   | false        | true   | false        |
+        * | '0'         | true   | true          | false        |
+        * | 0     | true         | true          | true          |
         * +---------+-----------+-----------+-----------+
         * Usage: 3
         *
@@ -1751,10 +1826,10 @@ final class t3lib_div {
        public static function inArray(array $in_array, $item) {
                foreach ($in_array as $val) {
                        if (!is_array($val) && !strcmp($val, $item)) {
-                               return true;
+                               return TRUE;
                        }
                }
-               return false;
+               return FALSE;
        }
 
        /**
@@ -1766,8 +1841,8 @@ final class t3lib_div {
         * @param       string          The string to explode
         * @param       boolean         If set, all empty values (='') will NOT be set in output
         * @param       integer         If positive, the result will contain a maximum of limit elements,
-        *                                              if negative, all components except the last -limit are returned,
-        *                                              if zero (default), the result is not limited at all
+        *                                               if negative, all components except the last -limit are returned,
+        *                                               if zero (default), the result is not limited at all
         * @return      array           Exploded values, all converted to integers
         */
        public static function intExplode($delimiter, $string, $onlyNonEmptyValues = FALSE, $limit = 0) {
@@ -1785,7 +1860,7 @@ final class t3lib_div {
         * @param       integer         Number of array entries
         * @return      array           Exploded values
         */
-       public static function revExplode($delimiter, $string, $count=0) {
+       public static function revExplode($delimiter, $string, $count = 0) {
                $explodedValues = explode($delimiter, strrev($string), $count);
                $explodedValues = array_map('strrev', $explodedValues);
                return array_reverse($explodedValues);
@@ -1800,21 +1875,21 @@ final class t3lib_div {
         * @param       string          The string to explode
         * @param       boolean         If set, all empty values will be removed in output
         * @param       integer         If positive, the result will contain a maximum of
-        *                                              $limit elements, if negative, all components except
-        *                                              the last -$limit are returned, if zero (default),
-        *                                              the result is not limited at all. Attention though
-        *                                              that the use of this parameter can slow down this
-        *                                              function.
+        *                                               $limit elements, if negative, all components except
+        *                                               the last -$limit are returned, if zero (default),
+        *                                               the result is not limited at all. Attention though
+        *                                               that the use of this parameter can slow down this
+        *                                               function.
         * @return      array           Exploded values
         */
-       public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0) {
+       public static function trimExplode($delim, $string, $removeEmptyValues = FALSE, $limit = 0) {
                $explodedValues = explode($delim, $string);
 
                $result = array_map('trim', $explodedValues);
 
                if ($removeEmptyValues) {
                        $temp = array();
-                       foreach($result as $value) {
+                       foreach ($result as $value) {
                                if ($value !== '') {
                                        $temp[] = $value;
                                }
@@ -1844,7 +1919,7 @@ final class t3lib_div {
         * @ignore
         * @deprecated since TYPO3 3.5, will be removed in TYPO3 4.6 - Use the PHP function array_unique instead
         */
-       public static function uniqueArray(array $valueArray)   {
+       public static function uniqueArray(array $valueArray) {
                self::logDeprecatedFunction();
 
                return array_unique($valueArray);
@@ -1858,7 +1933,7 @@ final class t3lib_div {
         * @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
         */
-       public static function removeArrayEntryByValue(array $array, $cmpValue) {
+       public static function removeArrayEntryByValue(array $array, $cmpValue) {
                foreach ($array as $k => $v) {
                        if (is_array($v)) {
                                $array[$k] = self::removeArrayEntryByValue($v, $cmpValue);
@@ -1875,16 +1950,16 @@ final class t3lib_div {
         *
         * Example (arguments used to call this function):
         * $array = array(
-        *              array('aa' => array('first', 'second'),
-        *              array('bb' => array('third', 'fourth'),
-        *              array('cc' => array('fifth', 'sixth'),
+        *               array('aa' => array('first', 'second'),
+        *               array('bb' => array('third', 'fourth'),
+        *               array('cc' => array('fifth', 'sixth'),
         * );
         * $keepItems = array('third');
         * $getValueFunc = create_function('$value', 'return $value[0];');
         *
         * Returns:
         * array(
-        *              array('bb' => array('third', 'fourth'),
+        *               array('bb' => array('third', 'fourth'),
         * )
         *
         * @param       array           $array: The initial array to be filtered/reduced
@@ -1892,7 +1967,7 @@ final class t3lib_div {
         * @param       string          $getValueFunc: (optional) Unique function name set by create_function() used to get the value to keep
         * @return      array           The filtered/reduced array with the kept items
         */
-       public static function keepItemsInArray(array $array, $keepItems, $getValueFunc=null) {
+       public static function keepItemsInArray(array $array, $keepItems, $getValueFunc = NULL) {
                if ($array) {
                                // Convert strings to arrays:
                        if (is_string($keepItems)) {
@@ -1900,7 +1975,7 @@ final class t3lib_div {
                        }
                                // create_function() returns a string:
                        if (!is_string($getValueFunc)) {
-                               $getValueFunc = null;
+                               $getValueFunc = NULL;
                        }
                                // Do the filtering:
                        if (is_array($keepItems) && count($keepItems)) {
@@ -1928,15 +2003,15 @@ final class t3lib_div {
         * @return      string          Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
         * @see explodeUrl2Array()
         */
-       public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false) {
-               foreach($theArray as $Akey => $AVal)    {
-                       $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
-                       if (is_array($AVal))    {
-                               $str = self::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
+       public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = FALSE, $rawurlencodeParamName = FALSE) {
+               foreach ($theArray as $Akey => $AVal) {
+                       $thisKeyName = $name ? $name . '[' . $Akey . ']' : $Akey;
+                       if (is_array($AVal)) {
+                               $str = self::implodeArrayForUrl($thisKeyName, $AVal, $str, $skipBlank, $rawurlencodeParamName);
                        } else {
-                               if (!$skipBlank || strcmp($AVal,''))    {
-                                       $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
-                                               '='.rawurlencode($AVal);
+                               if (!$skipBlank || strcmp($AVal, '')) {
+                                       $str .= '&' . ($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName) .
+                                                       '=' . rawurlencode($AVal);
                                }
                        }
                }
@@ -1951,15 +2026,15 @@ final class t3lib_div {
         * @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()
         */
-       public static function explodeUrl2Array($string,$multidim=FALSE)        {
+       public static function explodeUrl2Array($string, $multidim = FALSE) {
                $output = array();
-               if ($multidim)  {
-                       parse_str($string,$output);
+               if ($multidim) {
+                       parse_str($string, $output);
                } else {
-                       $p = explode('&',$string);
-                       foreach($p as $v)       {
-                               if (strlen($v)) {
-                                       list($pK,$pV) = explode('=',$v,2);
+                       $p = explode('&', $string);
+                       foreach ($p as $v) {
+                               if (strlen($v)) {
+                                       list($pK, $pV) = explode('=', $v, 2);
                                        $output[rawurldecode($pK)] = rawurldecode($pV);
                                }
                        }
@@ -1977,11 +2052,11 @@ final class t3lib_div {
         * @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.
         */
-       public static function compileSelectedGetVarsFromArray($varList,array $getArray,$GPvarAlt=1)    {
-               $keys = self::trimExplode(',',$varList,1);
+       public static function compileSelectedGetVarsFromArray($varList, array $getArray, $GPvarAlt = 1) {
+               $keys = self::trimExplode(',', $varList, 1);
                $outArr = array();
-               foreach($keys as $v)    {
-                       if (isset($getArray[$v]))       {
+               foreach ($keys as $v) {
+                       if (isset($getArray[$v])) {
                                $outArr[$v] = $getArray[$v];
                        } elseif ($GPvarAlt) {
                                $outArr[$v] = self::_GP($v);
@@ -2000,7 +2075,7 @@ final class t3lib_div {
         * @param       array           Multidimensional input array, (REFERENCE!)
         * @return      array
         */
-       public static function addSlashesOnArray(array &$theArray)      {
+       public static function addSlashesOnArray(array &$theArray) {
                foreach ($theArray as &$value) {
                        if (is_array($value)) {
                                self::addSlashesOnArray($value);
@@ -2022,7 +2097,7 @@ final class t3lib_div {
         * @param       array           Multidimensional input array, (REFERENCE!)
         * @return      array
         */
-       public static function stripSlashesOnArray(array &$theArray)    {
+       public static function stripSlashesOnArray(array &$theArray) {
                foreach ($theArray as &$value) {
                        if (is_array($value)) {
                                self::stripSlashesOnArray($value);
@@ -2042,17 +2117,21 @@ final class t3lib_div {
         * @param       string          "add" or "strip", depending on usage you wish.
         * @return      array
         */
-       public static function slashArray(array $arr,$cmd)      {
-               if ($cmd=='strip')      self::stripSlashesOnArray($arr);
-               if ($cmd=='add')        self::addSlashesOnArray($arr);
+       public static function slashArray(array $arr, $cmd) {
+               if ($cmd == 'strip') {
+                       self::stripSlashesOnArray($arr);
+               }
+               if ($cmd == 'add') {
+                       self::addSlashesOnArray($arr);
+               }
                return $arr;
        }
 
        /**
-       * Rename Array keys with a given mapping table
-       * @param        array   Array by reference which should be remapped
-       * @param        array   Array with remap information, array/$oldKey => $newKey)
-       */
+        * Rename Array keys with a given mapping table
+        * @param       array   Array by reference which should be remapped
+        * @param       array   Array with remap information, array/$oldKey => $newKey)
+        */
        function remapArrayKeys(&$array, $mappingTable) {
                if (is_array($mappingTable)) {
                        foreach ($mappingTable as $old => $new) {
@@ -2078,11 +2157,11 @@ final class t3lib_div {
         * @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
         */
-       public static function array_merge_recursive_overrule(array $arr0,array $arr1,$notAddKeys=0,$includeEmtpyValues=true) {
+       public static function array_merge_recursive_overrule(array $arr0, array $arr1, $notAddKeys = 0, $includeEmtpyValues = TRUE) {
                foreach ($arr1 as $key => $val) {
-                       if(is_array($arr0[$key])) {
-                               if (is_array($arr1[$key]))      {
-                                       $arr0[$key] = self::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys,$includeEmtpyValues);
+                       if (is_array($arr0[$key])) {
+                               if (is_array($arr1[$key])) {
+                                       $arr0[$key] = self::array_merge_recursive_overrule($arr0[$key], $arr1[$key], $notAddKeys, $includeEmtpyValues);
                                }
                        } else {
                                if ($notAddKeys) {
@@ -2110,8 +2189,8 @@ final class t3lib_div {
         * @param       array           Second array
         * @return      array           Merged result.
         */
-       public static function array_merge(array $arr1,array $arr2)     {
-               return $arr2+$arr1;
+       public static function array_merge(array $arr1, array $arr2) {
+               return $arr2 + $arr1;
        }
 
        /**
@@ -2146,13 +2225,13 @@ final class t3lib_div {
         * @param       string          Quote-character to wrap around the values.
         * @return      string          A single line of CSV
         */
-       public static function csvValues(array $row,$delim=',',$quote='"')      {
+       public static function csvValues(array $row, $delim = ',', $quote = '"') {
                reset($row);
-               $out=array();
+               $out = array();
                foreach ($row as $value) {
-                       $out[] = str_replace($quote, $quote.$quote, $value);
+                       $out[] = str_replace($quote, $quote . $quote, $value);
                }
-               $str = $quote.implode($quote.$delim.$quote,$out).$quote;
+               $str = $quote . implode($quote . $delim . $quote, $out) . $quote;
                return $str;
        }
 
@@ -2190,19 +2269,22 @@ final class t3lib_div {
                return $out;
        }
 
-
-
-
-
-
-
-
-
-
-
-
-
-
+       /**
+        * Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
+        *
+        * @param  array $array  array to be sorted recursively, passed by reference
+        * @return boolean TRUE if param is an array
+        */
+       public static function naturalKeySortRecursive(&$array) {
+               if (!is_array($array)) {
+                       return FALSE;
+               }
+               uksort($array, 'strcasecmp');
+               foreach ($array as $key => $value) {
+                       self::naturalKeySortRecursive($array[$key]);
+               }
+               return TRUE;
+       }
 
 
        /*************************
@@ -2220,27 +2302,27 @@ final class t3lib_div {
         * @param       string          HTML-tag string (or attributes only)
         * @return      array           Array with the attribute values.
         */
-       public static function get_tag_attributes($tag) {
+       public static function get_tag_attributes($tag) {
                $components = self::split_tag_attributes($tag);
-               $name = '';      // attribute name is stored here
-               $valuemode = false;
+               $name = ''; // attribute name is stored here
+               $valuemode = FALSE;
                $attributes = array();
-               foreach ($components as $key => $val)   {
-                       if ($val != '=')        {       // Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value
-                               if ($valuemode) {
-                                       if ($name)      {
+               foreach ($components as $key => $val) {
+                       if ($val != '=') { // Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value
+                               if ($valuemode) {
+                                       if ($name) {
                                                $attributes[$name] = $val;
                                                $name = '';
                                        }
                                } else {
-                                       if ($key = strtolower(preg_replace('/[^a-zA-Z0-9]/','',$val)))  {
+                                       if ($key = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $val))) {
                                                $attributes[$key] = '';
                                                $name = $key;
                                        }
                                }
-                               $valuemode = false;
+                               $valuemode = FALSE;
                        } else {
-                               $valuemode = true;
+                               $valuemode = TRUE;
                        }
                }
                return $attributes;
@@ -2254,26 +2336,26 @@ final class t3lib_div {
         * @param       string          HTML-tag string (or attributes only)
         * @return      array           Array with the attribute values.
         */
-       public static function split_tag_attributes($tag)       {
-               $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/','',trim($tag)));
+       public static function split_tag_attributes($tag) {
+               $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/', '', trim($tag)));
                        // Removes any > in the end of the string
                $tag_tmp = trim(rtrim($tag_tmp, '>'));
 
                $value = array();
-               while (strcmp($tag_tmp,''))     {       // Compared with empty string instead , 030102
-                       $firstChar=substr($tag_tmp,0,1);
-                       if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
-                               $reg=explode($firstChar,$tag_tmp,3);
-                               $value[]=$reg[1];
-                               $tag_tmp=trim($reg[2]);
-                       } elseif (!strcmp($firstChar,'=')) {
+               while (strcmp($tag_tmp, '')) { // Compared with empty string instead , 030102
+                       $firstChar = substr($tag_tmp, 0, 1);
+                       if (!strcmp($firstChar, '"') || !strcmp($firstChar, "'")) {
+                               $reg = explode($firstChar, $tag_tmp, 3);
+                               $value[] = $reg[1];
+                               $tag_tmp = trim($reg[2]);
+                       } elseif (!strcmp($firstChar, '=')) {
                                $value[] = '=';
-                               $tag_tmp = trim(substr($tag_tmp,1));            // Removes = chars.
+                               $tag_tmp = trim(substr($tag_tmp, 1)); // Removes = chars.
                        } else {
                                        // There are '' around the value. We look for the next ' ' or '>'
                                $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
                                $value[] = trim($reg[0]);
-                               $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
+                               $tag_tmp = trim(substr($tag_tmp, strlen($reg[0]), 1) . $reg[1]);
                        }
                }
                reset($value);
@@ -2289,19 +2371,23 @@ final class t3lib_div {
         * @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"'
         */
-       public static function implodeAttributes(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)       {
-               if ($xhtmlSafe) {
-                       $newArr=array();
-                       foreach($arr as $p => $v)       {
-                               if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
+       public static function implodeAttributes(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
+               if ($xhtmlSafe) {
+                       $newArr = array();
+                       foreach ($arr as $p => $v) {
+                               if (!isset($newArr[strtolower($p)])) {
+                                       $newArr[strtolower($p)] = htmlspecialchars($v);
+                               }
                        }
                        $arr = $newArr;
                }
                $list = array();
-               foreach($arr as $p => $v)       {
-                       if (strcmp($v,'') || $dontOmitBlankAttribs)     {$list[]=$p.'="'.$v.'"';}
+               foreach ($arr as $p => $v) {
+                       if (strcmp($v, '') || $dontOmitBlankAttribs) {
+                               $list[] = $p . '="' . $v . '"';
+                       }
                }
-               return implode(' ',$list);
+               return implode(' ', $list);
        }
 
        /**
@@ -2314,10 +2400,10 @@ final class t3lib_div {
         * @deprecated since TYPO3 3.7, will be removed in TYPO3 4.6 - Name was changed into implodeAttributes
         * @see implodeAttributes()
         */
-       public static function implodeParams(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)   {
+       public static function implodeParams(array $arr, $xhtmlSafe = FALSE, $dontOmitBlankAttribs = FALSE) {
                self::logDeprecatedFunction();
 
-               return self::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
+               return self::implodeAttributes($arr, $xhtmlSafe, $dontOmitBlankAttribs);
        }
 
        /**
@@ -2331,23 +2417,23 @@ final class t3lib_div {
         * @author      Ingmar Schlecht <ingmars@web.de>
         * @author      René Fritz <r.fritz@colorcube.de>
         */
-       public static function wrapJS($string, $linebreak=TRUE) {
-               if(trim($string)) {
+       public static function wrapJS($string, $linebreak = TRUE) {
+               if (trim($string)) {
                                // <script wrapped in nl?
-                       $cr = $linebreak? LF : '';
+                       $cr = $linebreak ? LF : '';
 
                                // remove nl from the beginning
-                       $string = preg_replace ('/^\n+/', '', $string);
+                       $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],TAB, $string);
+                       if (preg_match('/^(\t+)/', $string, $match)) {
+                               $string = str_replace($match[1], TAB, $string);
                        }
-                       $string = $cr.'<script type="text/javascript">
+                       $string = $cr . '<script type="text/javascript">
 /*<![CDATA[*/
-'.$string.'
+' . $string . '
 /*]]>*/
-</script>'.$cr;
+</script>' . $cr;
                }
                return trim($string);
        }
@@ -2362,7 +2448,7 @@ final class t3lib_div {
         * @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 + kasperYYYY@typo3.com
         */
-       public static function xml2tree($string,$depth=999) {
+       public static function xml2tree($string, $depth = 999) {
                $parser = xml_parser_create();
                $vals = array();
                $index = array();
@@ -2371,49 +2457,54 @@ final class t3lib_div {
                xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
                xml_parse_into_struct($parser, $string, $vals, $index);
 
-               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);
 
-               $stack = array( array() );
+               $stack = array(array());
                $stacktop = 0;
-               $startPoint=0;
+               $startPoint = 0;
 
-// FIXME don't use unset() - what does that mean? Use NULL or similar.
-               unset($tagi);
-               foreach($vals as $key => $val) {
+               $tagi = array();
+               foreach ($vals as $key => $val) {
                        $type = $val['type'];
 
                                // open tag:
-                       if ($type=='open' || $type=='complete') {
+                       if ($type == 'open' || $type == 'complete') {
                                $stack[$stacktop++] = $tagi;
 
-                               if ($depth==$stacktop)  {
-                                       $startPoint=$key;
+                               if ($depth == $stacktop) {
+                                       $startPoint = $key;
                                }
 
                                $tagi = array('tag' => $val['tag']);
 
-                               if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
-                               if(isset($val['value']))        $tagi['values'][] = $val['value'];
+                               if (isset($val['attributes'])) {
+                                       $tagi['attrs'] = $val['attributes'];
+                               }
+                               if (isset($val['value'])) {
+                                       $tagi['values'][] = $val['value'];
+                               }
                        }
                                // finish tag:
-                       if ($type=='complete' || $type=='close')        {
+                       if ($type == 'complete' || $type == 'close') {
                                $oldtagi = $tagi;
                                $tagi = $stack[--$stacktop];
                                $oldtag = $oldtagi['tag'];
                                unset($oldtagi['tag']);
 
-                               if ($depth==($stacktop+1))      {
-                                       if ($key-$startPoint > 0)       {
+                               if ($depth == ($stacktop + 1)) {
+                                       if ($key - $startPoint > 0) {
                                                $partArray = array_slice(
                                                        $vals,
-                                                       $startPoint+1,
-                                                       $key-$startPoint-1
+                                                               $startPoint + 1,
+                                                               $key - $startPoint - 1
                                                );
                                                #$oldtagi=array('XMLvalue'=>self::xmlRecompileFromStructValArray($partArray));
-                                               $oldtagi['XMLvalue']=self::xmlRecompileFromStructValArray($partArray);
+                                               $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
                                        } else {
-                                               $oldtagi['XMLvalue']=$oldtagi['values'][0];
+                                               $oldtagi['XMLvalue'] = $oldtagi['values'][0];
                                        }
                                }
 
@@ -2421,7 +2512,7 @@ final class t3lib_div {
                                unset($oldtagi);
                        }
                                // cdata
-                       if($type=='cdata') {
+                       if ($type == 'cdata') {
                                $tagi['values'][] = $val['value'];
                        }
                }
@@ -2438,22 +2529,22 @@ final class t3lib_div {
         * @return      string          An XML string made from the input content in the array.
         * @see xml2array(),array2xml()
         */
-       public static function array2xml_cs(array $array,$docTag='phparray',array $options=array(),$charset='') {
+       public static function array2xml_cs(array $array, $docTag = 'phparray', array $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!
+               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
+                       } 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!
+                               $charset = 'iso-8859-1'; // THIS is just a hopeful guess!
                        }
                }
 
                        // Return XML:
-               return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.LF.
-                               self::array2xml($array,'',0,$docTag,0, $options);
+               return '<?xml version="1.0" encoding="' . htmlspecialchars($charset) . '" standalone="yes" ?>' . LF .
+                               self::array2xml($array, '', 0, $docTag, 0, $options);
        }
 
        /**
@@ -2479,59 +2570,59 @@ final class t3lib_div {
         * @return      string          An XML string made from the input content in the array.
         * @see xml2array()
         */
-       public static function array2xml(array $array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0,array $options=array(),array $stackData=array())     {
+       public static function array2xml(array $array, $NSprefix = '', $level = 0, $docTag = 'phparray', $spaceInd = 0, array $options = array(), 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);
+               $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 ? ' ' : TAB;
-               $indentN = $spaceInd>0 ? $spaceInd : 1;
+               $indentN = $spaceInd > 0 ? $spaceInd : 1;
                $nl = ($spaceInd >= 0 ? LF : '');
 
                        // Init output variable:
-               $output='';
+               $output = '';
 
                        // Traverse the input array
-               foreach($array as $k=>$v)       {
+               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']) && self::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.'"';
+                       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']) && self::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).'"';
+                       } 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(preg_replace('/[^[:alnum:]_-]/','',$tagName),0,100);
+                       $tagName = substr(preg_replace('/[^[:alnum:]_-]/', '', $tagName), 0, 100);
 
                                // If the value is an array then we will call this function recursively:
-                       if (is_array($v))       {
+                       if (is_array($v)) {
 
                                        // Sub elements:
-                               if ($options['alt_options'][$stackData['path'].'/'.$tagName])   {
-                                       $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
+                               if ($options['alt_options'][$stackData['path'] . '/' . $tagName]) {
+                                       $subOptions = $options['alt_options'][$stackData['path'] . '/' . $tagName];
                                        $clearStackPath = $subOptions['clearStackPath'];
                                } else {
                                        $subOptions = $options;
@@ -2539,31 +2630,31 @@ final class t3lib_div {
                                }
 
                                $content = $nl .
-                                                       self::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"';
+                                               self::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:
+                       } 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!
+                               $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"';
+                                       $content = $nl . chunk_split(base64_encode($v));
+                                       $attr .= ' base64="1"';
                                } else {
                                                // Otherwise, just htmlspecialchar the stuff:
                                        $content = htmlspecialchars($v);
@@ -2573,21 +2664,21 @@ final class t3lib_div {
                                                        $content = '<![CDATA[' . $v . ']]>';
                                                }
                                        } elseif (!$options['disableTypeAttrib']) {
-                                               $attr.= ' type="'.$dType.'"';
+                                               $attr .= ' type="' . $dType . '"';
                                        }
                                }
                        }
 
                                // Add the element to the output string:
-                       $output.=($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '').'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.$nl;
+                       $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.'>'.$nl.
-                               $output.
-                               '</'.$docTag.'>';
+                                       '<' . $docTag . '>' . $nl .
+                                                       $output .
+                                                       '</' . $docTag . '>';
                }
 
                return $output;
@@ -2606,7 +2697,7 @@ final class t3lib_div {
         * @see array2xml(),xml2arrayProcess()
         * @author      Fabrizio Branca <typo3@fabrizio-branca.de> (added caching)
         */
-       public static function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
+       public static function xml2array($string, $NSprefix = '', $reportDocTag = FALSE) {
                static $firstLevelCache = array();
 
                $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
@@ -2619,7 +2710,7 @@ final class t3lib_div {
                        $cacheContent = t3lib_pageSelect::getHash($identifier, 0);
                        $array = unserialize($cacheContent);
 
-                       if ($array === false) {
+                       if ($array === FALSE) {
                                $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
                                t3lib_pageSelect::storeHash($identifier, serialize($array), 'ident_xml2array');
                        }
@@ -2640,7 +2731,7 @@ final class t3lib_div {
         * @return      mixed           If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
         * @see array2xml()
         */
-       protected function xml2arrayProcess($string,$NSprefix='',$reportDocTag=FALSE) {
+       protected function xml2arrayProcess($string, $NSprefix = '', $reportDocTag = FALSE) {
                global $TYPO3_CONF_VARS;
 
                        // Create parser:
@@ -2653,16 +2744,16 @@ final class t3lib_div {
 
                        // default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
                $match = array();
-               preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$match);
+               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
+               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:
-               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);
 
@@ -2674,63 +2765,67 @@ final class t3lib_div {
                $documentTag = '';
 
                        // Traverse the parsed XML structure:
-               foreach($vals as $key => $val) {
+               foreach ($vals as $key => $val) {
 
                                // First, process the tag-name (which is used in both cases, whether "complete" or "close")
                        $tagName = $val['tag'];
-                       if (!$documentTag)      $documentTag = $tagName;
+                       if (!$documentTag) {
+                               $documentTag = $tagName;
+                       }
 
                                // Test for name space:
-                       $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
+                       $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;
+                       $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']; }
+                       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
+                       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.
+                                       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];
-                                       end($current);  // Going to the end of array to get placeholder key, key($current), and fill in array next:
+                                       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);
-                               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'])       {
+                                       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()!!
+                                               $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'])      {
+                                               switch ((string) $val['attributes']['type']) {
                                                        case 'integer':
-                                                               $current[$tagName] = (integer)$current[$tagName];
-                                                       break;
+                                                               $current[$tagName] = (integer) $current[$tagName];
+                                                               break;
                                                        case 'double':
-                                                               $current[$tagName] = (double)$current[$tagName];
-                                                       break;
+                                                               $current[$tagName] = (double) $current[$tagName];
+                                                               break;
                                                        case 'boolean':
-                                                               $current[$tagName] = (bool)$current[$tagName];
-                                                       break;
+                                                               $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;
+                                                               $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;
+                                       break;
                        }
                }
 
-               if ($reportDocTag)      {
+               if ($reportDocTag) {
                        $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
                }
 
@@ -2745,37 +2840,41 @@ final class t3lib_div {
         * @param       array           A array of XML parts, see xml2tree
         * @return      string          Re-compiled XML data.
         */
-       public static function xmlRecompileFromStructValArray(array $vals)      {
-               $XMLcontent='';
+       public static function xmlRecompileFromStructValArray(array $vals) {
+               $XMLcontent = '';
 
-               foreach($vals as $val) {
+               foreach ($vals as $val) {
                        $type = $val['type'];
 
                                // open tag:
-                       if ($type=='open' || $type=='complete') {
-                               $XMLcontent.='<'.$val['tag'];
-                               if(isset($val['attributes']))  {
-                                       foreach($val['attributes'] as $k => $v) {
-                                               $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
+                       if ($type == 'open' || $type == 'complete') {
+                               $XMLcontent .= '<' . $val['tag'];
+                               if (isset($val['attributes'])) {
+                                       foreach ($val['attributes'] as $k => $v) {
+                                               $XMLcontent .= ' ' . $k . '="' . htmlspecialchars($v) . '"';
                                        }
                                }
-                               if ($type=='complete')  {
-                                       if(isset($val['value']))        {
-                                               $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
-                                       } else $XMLcontent.='/>';
-                               } else $XMLcontent.='>';
-
-                               if ($type=='open' && isset($val['value']))      {
-                                       $XMLcontent.=htmlspecialchars($val['value']);
+                               if ($type == 'complete') {
+                                       if (isset($val['value'])) {
+                                               $XMLcontent .= '>' . htmlspecialchars($val['value']) . '</' . $val['tag'] . '>';
+                                       } else {
+                                               $XMLcontent .= '/>';
+                                       }
+                               } else {
+                                       $XMLcontent .= '>';
+                               }
+
+                               if ($type == 'open' && isset($val['value'])) {
+                                       $XMLcontent .= htmlspecialchars($val['value']);
                                }
                        }
                                // finish tag:
-                       if ($type=='close')     {
-                               $XMLcontent.='</'.$val['tag'].'>';
+                       if ($type == 'close') {
+                               $XMLcontent .= '</' . $val['tag'] . '>';
                        }
                                // cdata
-                       if($type=='cdata') {
-                               $XMLcontent.=htmlspecialchars($val['value']);
+                       if ($type == 'cdata') {
+                               $XMLcontent .= htmlspecialchars($val['value']);
                        }
                }
 
@@ -2789,9 +2888,9 @@ final class t3lib_div {
         * @param       string          XML data
         * @return      array           Attributes of the xml prologue (header)
         */
-       public static function xmlGetHeaderAttribs($xmlData)    {
+       public static function xmlGetHeaderAttribs($xmlData) {
                $match = array();
-               if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match))    {
+               if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
                        return self::get_tag_attributes($match[1]);
                }
        }
@@ -2809,7 +2908,7 @@ final class t3lib_div {
                        $error = '';
                        $script = trim(JSMin::minify(str_replace(CR, '', $script)));
                }
-               catch(JSMinException $e) {
+               catch (JSMinException $e) {
                        $error = 'Error while minifying JavaScript: ' . $e->getMessage();
                        self::devLog($error, 't3lib_div', 2,
                                array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
@@ -2818,12 +2917,6 @@ final class t3lib_div {
        }
 
 
-
-
-
-
-
-
        /*************************
         *
         * FILES FUNCTIONS
@@ -2841,28 +2934,28 @@ final class t3lib_div {
         * @param       array                   Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
         * @return      string  The content from the resource given as input. FALSE if an error has occured.
         */
-       public static function getURL($url, $includeHeader = 0, $requestHeaders = false, &$report = NULL)       {
-               $content = false;
+       public static function getURL($url, $includeHeader = 0, $requestHeaders = FALSE, &$report = NULL) {
+               $content = FALSE;
 
-               if (isset($report))     {
+               if (isset($report)) {
                        $report['error'] = 0;
                        $report['message'] = '';
                }
 
                        // use cURL for: http, https, ftp, ftps, sftp and scp
-               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
-                       if (isset($report))     {
+               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
+                       if (isset($report)) {
                                $report['lib'] = 'cURL';
                        }
 
                                // External URL without error checking.
                        $ch = curl_init();
-                       if (!$ch)       {
-                               if (isset($report))     {
+                       if (!$ch) {
+                               if (isset($report)) {
                                        $report['error'] = -1;
                                        $report['message'] = 'Couldn\'t initialize cURL.';
                                }
-                               return false;
+                               return FALSE;
                        }
 
                        curl_setopt($ch, CURLOPT_URL, $url);
@@ -2876,33 +2969,33 @@ final class t3lib_div {
                                // may fail (PHP 5.2.0+ and 5.1.5+) when open_basedir or safe_mode are enabled
                        $followLocation = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
 
-                       if (is_array($requestHeaders))  {
+                       if (is_array($requestHeaders)) {
                                curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
                        }
 
                                // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
-                       if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer'])      {
+                       if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
                                curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
 
-                               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'])      {
+                               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'])    {
+                               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
                                        curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
                                }
                        }
                        $content = curl_exec($ch);
-                       if (isset($report))     {
-                               if ($content===FALSE)   {
+                       if (isset($report)) {
+                               if ($content === FALSE) {
                                        $report['error'] = curl_errno($ch);
                                        $report['message'] = curl_error($ch);
                                } else {
                                        $curlInfo = curl_getinfo($ch);
                                                // We hit a redirection but we couldn't follow it
-                                       if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400)         {
+                                       if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
                                                $report['error'] = -1;
                                                $report['message'] = 'Couldn\'t follow location redirect (either PHP configuration option safe_mode or open_basedir is in effect).';
-                                       } elseif($includeHeader) {
+                                       } elseif ($includeHeader) {
                                                        // Set only for $includeHeader to work exactly like PHP variant
                                                $report['http_code'] = $curlInfo['http_code'];
                                                $report['content_type'] = $curlInfo['content_type'];
@@ -2911,99 +3004,99 @@ final class t3lib_div {
                        }
                        curl_close($ch);
 
-               } elseif ($includeHeader)       {
-                       if (isset($report))     {
+               } elseif ($includeHeader) {
+                       if (isset($report)) {
                                $report['lib'] = 'socket';
                        }
                        $parsedURL = parse_url($url);
-                       if (!preg_match('/^https?/', $parsedURL['scheme']))     {
-                               if (isset($report))     {
+                       if (!preg_match('/^https?/', $parsedURL['scheme'])) {
+                               if (isset($report)) {
                                        $report['error'] = -1;
                                        $report['message'] = 'Reading headers is not allowed for this protocol.';
                                }
-                               return false;
+                               return FALSE;
                        }
                        $port = intval($parsedURL['port']);
-                       if ($port < 1)  {
-                               if ($parsedURL['scheme'] == 'http')     {
-                                       $port = ($port>0 ? $port : 80);
+                       if ($port < 1) {
+                               if ($parsedURL['scheme'] == 'http') {
+                                       $port = ($port > 0 ? $port : 80);
                                        $scheme = '';
                                } else {
-                                       $port = ($port>0 ? $port : 443);
+                                       $port = ($port > 0 ? $port : 443);
                                        $scheme = 'ssl://';
                                }
                        }
                        $errno = 0;
-                       // $errstr = '';
-                       $fp = @fsockopen($scheme.$parsedURL['host'], $port, $errno, $errstr, 2.0);
-                       if (!$fp || $errno > 0) {
-                               if (isset($report))     {
+                               // $errstr = '';
+                       $fp = @fsockopen($scheme . $parsedURL['host'], $port, $errno, $errstr, 2.0);
+                       if (!$fp || $errno > 0) {
+                               if (isset($report)) {
                                        $report['error'] = $errno ? $errno : -1;
                                        $report['message'] = $errno ? ($errstr ? $errstr : 'Socket error.') : 'Socket initialization error.';
                                }
-                               return false;
+                               return FALSE;
                        }
                        $method = ($includeHeader == 2) ? 'HEAD' : 'GET';
                        $msg = $method . ' ' . $parsedURL['path'] .
                                        ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
                                        ' HTTP/1.0' . CRLF . 'Host: ' .
                                        $parsedURL['host'] . "\r\nConnection: close\r\n";
-                       if (is_array($requestHeaders))  {
+                       if (is_array($requestHeaders)) {
                                $msg .= implode(CRLF, $requestHeaders) . CRLF;
                        }
                        $msg .= CRLF;
 
                        fputs($fp, $msg);
-                       while (!feof($fp))      {
+                       while (!feof($fp)) {
                                $line = fgets($fp, 2048);
-                               if (isset($report))     {
-                                       if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status))        {
+                               if (isset($report)) {
+                                       if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
                                                $report['http_code'] = $status[1];
                                        }
-                                       elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type))    {
+                                       elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
                                                $report['content_type'] = $type[1];
                                        }
                                }
                                $content .= $line;
-                               if (!strlen(trim($line)))       {
-                                       break;  // Stop at the first empty line (= end of header)
+                               if (!strlen(trim($line))) {
+                                       break; // Stop at the first empty line (= end of header)
                                }
                        }
-                       if ($includeHeader != 2)        {
+                       if ($includeHeader != 2) {
                                $content .= stream_get_contents($fp);
                        }
                        fclose($fp);
 
-               } elseif (is_array($requestHeaders))    {
-                       if (isset($report))     {
+               } elseif (is_array($requestHeaders)) {
+                       if (isset($report)) {
                                $report['lib'] = 'file/context';
                        }
                        $parsedURL = parse_url($url);
-                       if (!preg_match('/^https?/', $parsedURL['scheme']))     {
-                               if (isset($report))     {
+                       if (!preg_match('/^https?/', $parsedURL['scheme'])) {
+                               if (isset($report)) {
                                        $report['error'] = -1;
                                        $report['message'] = 'Sending request headers is not allowed for this protocol.';
                                }
-                               return false;
+                               return FALSE;
                        }
                        $ctx = stream_context_create(array(
-                                               'http' => array(
-                                                       'header' => implode(CRLF, $requestHeaders)
-                                               )
-                                       )
-                               );
-                       $content = @file_get_contents($url, false, $ctx);
-                       if ($content === false && isset($report)) {
+                               'http' => array(
+                                       'header' => implode(CRLF, $requestHeaders)
+                               )
+                       )
+                       );
+                       $content = @file_get_contents($url, FALSE, $ctx);
+                       if ($content === FALSE && isset($report)) {
                                $phpError = error_get_last();
                                $report['error'] = $phpError['type'];
                                $report['message'] = $phpError['message'];
                        }
-               } else  {
-                       if (isset($report))     {
+               } else {
+                       if (isset($report)) {
                                $report['lib'] = 'file';
                        }
                        $content = @file_get_contents($url);
-                       if ($content === false && isset($report))       {
+                       if ($content === FALSE && isset($report)) {
                                if (function_exists('error_get_last')) {
                                        $phpError = error_get_last();
                                        $report['error'] = $phpError['type'];
@@ -3026,35 +3119,45 @@ final class t3lib_div {
         * @param       string          Content to write
         * @return      boolean         True if the file was successfully opened and written to.
         */
-       public static function writeFile($file,$content)        {
-               if (!@is_file($file))   $changePermissions = true;
+       public static function writeFile($file, $content) {
+               if (!@is_file($file)) {
+                       $changePermissions = TRUE;
+               }
 
-               if ($fd = fopen($file,'wb'))    {
-                       $res = fwrite($fd,$content);
+               if ($fd = fopen($file, 'wb')) {
+                       $res = fwrite($fd, $content);
                        fclose($fd);
 
-                       if ($res===false)       return false;
+                       if ($res === FALSE) {
+                               return FALSE;
+                       }
 
-                       if ($changePermissions) {       // Change the permissions only if the file has just been created
+                       if ($changePermissions) { // Change the permissions only if the file has just been created
                                self::fixPermissions($file);
                        }
 
-                       return true;
+                       return TRUE;
                }
 
-               return false;
+               return FALSE;
        }
 
        /**
         * Sets the file system mode and group ownership of a file or a folder.
         *
-        * @param   string   Absolute filepath of file or folder, must not be escaped.
+        * @param   string   Path of file or folder, must not be escaped. Path can be absolute or relative
         * @param   boolean  If set, also fixes permissions of files and folders in the folder (if $path is a folder)
-        * @return  mixed    TRUE on success, FALSE on error, always TRUE on Windows OS
+        * @return  mixed       TRUE on success, FALSE on error, always TRUE on Windows OS
         */
        public static function fixPermissions($path, $recursive = FALSE) {
                if (TYPO3_OS != 'WIN') {
                        $result = FALSE;
+
+                               // Make path absolute
+                       if (!self::isAbsPath($path)) {
+                               $path = self::getFileAbsFileName($path, FALSE);
+                       }
+
                        if (self::isAllowedAbsPath($path)) {
                                if (@is_file($path)) {
                                                // "@" is there because file is not necessarily OWNED by the user
@@ -3066,7 +3169,7 @@ final class t3lib_div {
                                }
 
                                        // Set createGroup if not empty
-                               if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) {
+                               if ($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) {
                                                // "@" is there because file is not necessarily OWNED by the user
                                        $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
                                        $result = $changeGroupResult ? $result : FALSE;
@@ -3076,7 +3179,7 @@ final class t3lib_div {
                                if ($recursive && @is_dir($path)) {
                                        $handle = opendir($path);
                                        while (($file = readdir($handle)) !== FALSE) {
-                                               unset($recursionResult);
+                                               $recursionResult = NULL;
                                                if ($file !== '.' && $file !== '..') {
                                                        if (@is_file($path . '/' . $file)) {
                                                                $recursionResult = self::fixPermissions($path . '/' . $file);
@@ -3103,42 +3206,58 @@ final class t3lib_div {
         *
         * @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.
+        * @return      string          Returns NULL on success, otherwise an error string telling about the problem.
         */
-       public static function writeFileToTypo3tempDir($filepath,$content)      {
+       public static function writeFileToTypo3tempDir($filepath, $content) {
 
                        // Parse filepath into directory and basename:
                $fI = pathinfo($filepath);
-               $fI['dirname'].= '/';
+               $fI['dirname'] .= '/';
 
                        // Check parts:
-               if (self::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 (self::isFirstPartOfStr($fI['dirname'],$dirName))    {
+               if (self::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 (self::isFirstPartOfStr($fI['dirname'], $dirName)) {
 
                                                        // Checking if the "subdir" is found:
-                                               $subdir = substr($fI['dirname'],strlen($dirName));
-                                               if ($subdir)    {
-                                                       if (preg_match('/^[[:alnum:]_]+\/$/',$subdir) || preg_match('/^[[:alnum:]_]+\/[[:alnum:]_]+\/$/',$subdir))      {
-                                                               $dirName.= $subdir;
-                                                               if (!@is_dir($dirName)) {
-                                                                       self::mkdir_deep(PATH_site.'typo3temp/', $subdir);
+                                               $subdir = substr($fI['dirname'], strlen($dirName));
+                                               if ($subdir) {
+                                                       if (preg_match('/^[[:alnum:]_]+\/$/', $subdir) || preg_match('/^[[:alnum:]_]+\/[[:alnum:]_]+\/$/', $subdir)) {
+                                                               $dirName .= $subdir;
+                                                               if (!@is_dir($dirName)) {
+                                                                       self::mkdir_deep(PATH_site . 'typo3temp/', $subdir);
                                                                }
-                                                       } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or  "[[:alnum:]_]/[[:alnum:]_]/"';
+                                                       } 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'])      {
+                                               if (@is_dir($dirName)) {
+                                                       if ($filepath == $dirName . $fI['basename']) {
                                                                self::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!';
+                                                               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!';
+               }
        }
 
        /**
@@ -3165,15 +3284,15 @@ final class t3lib_div {
         * @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.
         */
-       public static function mkdir_deep($destination,$deepDir)        {
-               $allParts = self::trimExplode('/',$deepDir,1);
+       public static function mkdir_deep($destination, $deepDir) {
+               $allParts = self::trimExplode('/', $deepDir, 1);
                $root = '';
-               foreach($allParts as $part)     {
-                       $root.= $part.'/';
-                       if (!is_dir($destination.$root))        {
-                               self::mkdir($destination.$root);
-                               if (!@is_dir($destination.$root))       {
-                                       return 'Error: The directory "'.$destination.$root.'" could not be created...';
+               foreach ($allParts as $part) {
+                       $root .= $part . '/';
+                       if (!is_dir($destination . $root)) {
+                               self::mkdir($destination . $root);
+                               if (!@is_dir($destination . $root)) {
+                                       return 'Error: The directory "' . $destination . $root . '" could not be created...';
                                }
                        }
                }
@@ -3186,24 +3305,28 @@ final class t3lib_div {
         * @param       boolean         Allow deletion of non-empty directories
         * @return      boolean         true if @rmdir went well!
         */
-       public static function rmdir($path,$removeNonEmpty=false)       {
-               $OK = false;
-               $path = preg_replace('|/$|','',$path);  // Remove trailing slash
+       public static function rmdir($path, $removeNonEmpty = FALSE) {
+               $OK = FALSE;
+               $path = preg_replace('|/$|', '', $path); // Remove trailing slash
 
-               if (file_exists($path)) {
-                       $OK = true;
+               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 = self::rmdir($path.'/'.$file,$removeNonEmpty);
+                       if (is_dir($path)) {
+                               if ($removeNonEmpty == TRUE && $handle = opendir($path)) {
+                                       while ($OK && FALSE !== ($file = readdir($handle))) {
+                                               if ($file == '.' || $file == '..') {
+                                                       continue;
+                                               }
+                                               $OK = self::rmdir($path . '/' . $file, $removeNonEmpty);
                                        }
                                        closedir($handle);
                                }
-                               if ($OK)        { $OK = rmdir($path); }
+                               if ($OK) {
+                                       $OK = rmdir($path);
+                               }
 
-                       } else {        // If $dirname is a file, simply remove it
+                       } else { // If $dirname is a file, simply remove it
                                $OK = unlink($path);
                        }
 
@@ -3221,7 +3344,7 @@ final class t3lib_div {
         * @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.
         */
-       public static function get_dirs($path)  {
+       public static function get_dirs($path) {
                if ($path) {
                        if (is_dir($path)) {
                                $dir = scandir($path);
@@ -3249,7 +3372,7 @@ final class t3lib_div {
         * @param       string          A comma seperated list of filenames to exclude, no wildcards
         * @return      array           Array of the files found
         */
-       public static function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='')       {
+       public static function getFilesInDir($path, $extensionList = '', $prependPath = 0, $order = '', $excludePattern = '') {
 
                        // Initialize variabels:
                $filearray = array();
@@ -3257,33 +3380,39 @@ final class t3lib_div {
                $path = rtrim($path, '/');
 
                        // Find files+directories:
-               if (@is_dir($path))     {
+               if (@is_dir($path)) {
                        $extensionList = strtolower($extensionList);
                        $d = dir($path);
-                       if (is_object($d))      {
-                               while($entry=$d->read()) {
-                                       if (@is_file($path.'/'.$entry)) {
+                       if (is_object($d)) {
+                               while ($entry = $d->read()) {
+                                       if (@is_file($path . '/' . $entry)) {
                                                $fI = pathinfo($entry);
-                                               $key = md5($path.'/'.$entry);   // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
-                                               if ((!strlen($extensionList) || self::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$entry)))      {
-                                                       $filearray[$key]=($prependPath?$path.'/':'').$entry;
-                                                               if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
-                                                               elseif ($order) {$sortarray[$key]=$entry;}
+                                               $key = md5($path . '/' . $entry); // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
+                                               if ((!strlen($extensionList) || self::inList($extensionList, strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^' . $excludePattern . '$/', $entry))) {
+                                                       $filearray[$key] = ($prependPath ? $path . '/' : '') . $entry;
+                                                       if ($order == 'mtime') {
+                                                               $sortarray[$key] = filemtime($path . '/' . $entry);
+                                                       }
+                                                       elseif ($order) {
+                                                               $sortarray[$key] = $entry;
+                                                       }
                                                }
                                        }
                                }
                                $d->close();
-                       } else return 'error opening path: "'.$path.'"';
+                       } else {
+                               return 'error opening path: "' . $path . '"';
+                       }
                }
 
                        // Sort them:
                if ($order) {
                        asort($sortarray);
-                       $newArr=array();
+                       $newArr = array();
                        foreach ($sortarray as $k => $v) {
-                               $newArr[$k]=$filearray[$k];
+                               $newArr[$k] = $filearray[$k];
                        }
-                       $filearray=$newArr;
+                       $filearray = $newArr;
                }
 
                        // Return result
@@ -3303,15 +3432,17 @@ final class t3lib_div {
         * @param string                $excludePattern: regex pattern of files/directories to exclude
         * @return      array           An array with the found files/directories.
         */
-       public static function getAllFilesAndFoldersInPath(array $fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='')        {
-               if ($regDirs)   $fileArr[] = $path;
-               $fileArr = array_merge($fileArr, self::getFilesInDir($path,$extList,1,1,$excludePattern));
+       public static function getAllFilesAndFoldersInPath(array $fileArr, $path, $extList = '', $regDirs = 0, $recursivityLevels = 99, $excludePattern = '') {
+               if ($regDirs) {
+                       $fileArr[] = $path;
+               }
+               $fileArr = array_merge($fileArr, self::getFilesInDir($path, $extList, 1, 1, $excludePattern));
 
                $dirs = self::get_dirs($path);
-               if (is_array($dirs) && $recursivityLevels>0)    {
-                       foreach ($dirs as $subdirs)     {
-                               if ((string)$subdirs!='' && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$subdirs)))      {
-                                       $fileArr = self::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1,$excludePattern);
+               if (is_array($dirs) && $recursivityLevels > 0) {
+                       foreach ($dirs as $subdirs) {
+                               if ((string) $subdirs != '' && (!strlen($excludePattern) || !preg_match('/^' . $excludePattern . '$/', $subdirs))) {
+                                       $fileArr = self::getAllFilesAndFoldersInPath($fileArr, $path . $subdirs . '/', $extList, $regDirs, $recursivityLevels - 1, $excludePattern);
                                }
                        }
                }
@@ -3326,7 +3457,7 @@ final class t3lib_div {
         * @param       string          $prefixToRemove: The prefix path to remove (if found as first part of string!)
         * @return      array           The input $fileArr processed.
         */
-       public static function removePrefixPathFromList(array $fileArr,$prefixToRemove) {
+       public static function removePrefixPathFromList(array $fileArr, $prefixToRemove) {
                foreach ($fileArr as $k => &$absFileRef) {
                        if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
                                $absFileRef = substr($absFileRef, strlen($prefixToRemove));
@@ -3344,8 +3475,8 @@ final class t3lib_div {
         * @param       string          File path to process
         * @return      string
         */
-       public static function fixWindowsFilePath($theFile)     {
-               return str_replace('//','/', str_replace('\\','/', $theFile));
+       public static function fixWindowsFilePath($theFile) {
+               return str_replace('//', '/', str_replace('\\', '/', $theFile));
        }
 
        /**
@@ -3356,22 +3487,24 @@ final class t3lib_div {
         * @param       string          File path in which "/../" is resolved
         * @return      string
         */
-       public static function resolveBackPath($pathStr)        {
-               $parts = explode('/',$pathStr);
-               $output=array();
+       public static 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) {
                                        array_pop($output);
                                        $c--;
-                               } else $output[]=$pV;
+                               } else {
+                                       $output[] = $pV;
+                               }
                        } else {
                                $c++;
-                               $output[]=$pV;
+                               $output[] = $pV;
                        }
                }
-               return implode('/',$output);
+               return implode('/', $output);
        }
 
        /**
@@ -3384,12 +3517,12 @@ final class t3lib_div {
         * @param       string          URL / path to prepend full URL addressing to.
         * @return      string
         */
-       public static function locationHeaderUrl($path) {
+       public static function locationHeaderUrl($path) {
                $uI = parse_url($path);
-               if (substr($path,0,1)=='/')     { // relative to HOST
-                       $path = self::getIndpEnv('TYPO3_REQUEST_HOST').$path;
-               } elseif (!$uI['scheme'])       { // No scheme either
-                       $path = self::getIndpEnv('TYPO3_REQUEST_DIR').$path;
+               if (substr($path, 0, 1) == '/') { // relative to HOST
+                       $path = self::getIndpEnv('TYPO3_REQUEST_HOST') . $path;
+               } elseif (!$uI['scheme']) { // No scheme either
+                       $path = self::getIndpEnv('TYPO3_REQUEST_DIR') . $path;
                }
                return $path;
        }
@@ -3431,12 +3564,16 @@ final class t3lib_div {
        public static function getBytesFromSizeMeasurement($measurement) {
                if (stripos($measurement, 'G')) {
                        $bytes = doubleval($measurement) * 1024 * 1024 * 1024;
-               } else if (stripos($measurement, 'M')) {
-                       $bytes = doubleval($measurement) * 1024 * 1024;
-               } else if (stripos($measurement, 'K')) {
-                       $bytes = doubleval($measurement) * 1024;
                } else {
-                       $bytes = doubleval($measurement);
+                       if (stripos($measurement, 'M')) {
+                               $bytes = doubleval($measurement) * 1024 * 1024;
+                       } else {
+                               if (stripos($measurement, 'K')) {
+                                       $bytes = doubleval($measurement) * 1024;
+                               } else {
+                                       $bytes = doubleval($measurement);
+                               }
+                       }
                }
                return $bytes;
        }
@@ -3487,63 +3624,63 @@ final class t3lib_div {
         */
        public static function createVersionNumberedFilename($file, $forceQueryString = FALSE) {
                $lookupFile = explode('?', $file);
-               $path = self::resolveBackPath(self::dirname(PATH_thisScript) .'/'. $lookupFile[0]);
+               $path = self::resolveBackPath(self::dirname(PATH_thisScript) . '/' . $lookupFile[0]);
 
                if (TYPO3_MODE == 'FE') {
                        $mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']);
                        if ($mode === 'embed') {
                                $mode = TRUE;
-                       } else if ($mode === 'querystring') {
-                               $mode = FALSE;
                        } else {
-                               $doNothing = TRUE;
+                               if ($mode === 'querystring') {
+                                       $mode = FALSE;
+                               } else {
+                                       $doNothing = TRUE;
+                               }
                        }
                } else {
                        $mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename'];
                }
 
-               if (! file_exists($path) || $doNothing) {
+               if (!file_exists($path) || $doNothing) {
                                // File not found, return filename unaltered
                        $fullName = $file;
 
-               } else if (! $mode || $forceQueryString) {
-                               // If use of .htaccess rule is not configured,
-                               // we use the default query-string method
-                       if ($lookupFile[1]) {
-                               $separator = '&';
-                       } else {
-                               $separator = '?';
-                       }
-                       $fullName = $file . $separator . filemtime($path);
-
                } else {
-                               // Change the filename
-                       $name = explode('.', $lookupFile[0]);
-                       $extension = array_pop($name);
+                       if (!$mode || $forceQueryString) {
+                                       // If use of .htaccess rule is not configured,
+                                       // we use the default query-string method
+                               if ($lookupFile[1]) {
+                                       $separator = '&';
+                               } else {
+                                       $separator = '?';
+                               }
+                               $fullName = $file . $separator . filemtime($path);
+
+                       } else {
+                                       // Change the filename
+                               $name = explode('.', $lookupFile[0]);
+                               $extension = array_pop($name);
 
-                       array_push($name, filemtime($path), $extension);
-                       $fullName = implode('.', $name);
-                               // append potential query string
-                       $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
+                               array_push($name, filemtime($path), $extension);
+                               $fullName = implode('.', $name);
+                                       // append potential query string
+                               $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
+                       }
                }
 
                return $fullName;
        }
 
 
-
-
-
-
-
-
-
        /*************************
         *
         * DEBUG helper FUNCTIONS
         *
         *************************/
 
+       /* Deprecated since 4.5, use t3lib_utility_Debug */
+
+
        /**
         * Returns a string with a list of ascii-values for the first $characters characters in $string
         * Usage: 0
@@ -3551,13 +3688,11 @@ final class t3lib_div {
         * @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.
+        * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::ordinalValue instead
         */
-       public static function debug_ordvalue($string,$characters=100)  {
-               if(strlen($string) < $characters)       $characters = strlen($string);
-               for ($i=0; $i<$characters; $i++)        {
-                       $valuestring.=' '.ord(substr($string,$i,1));
-               }
-               return trim($valuestring);
+       public static function debug_ordvalue($string, $characters = 100) {
+               self::logDeprecatedFunction();
+               return t3lib_utility_Debug::ordinalValue($string, $characters);
        }
 
        /**
@@ -3568,49 +3703,11 @@ final class t3lib_div {
         *
         * @param       mixed           Array to view
         * @return      string          HTML output
+        * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::viewArray instead
         */
-       public static function view_array($array_in)    {
-               if (is_array($array_in))        {
-                       $result='
-                       <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
-                       if (count($array_in) == 0)      {
-                               $result.= '<tr><td><font face="Verdana,Arial" size="1"><strong>EMPTY!</strong></font></td></tr>';
-                       } else  {
-                               foreach ($array_in as $key => $val)     {
-                                       $result.= '<tr>
-                                               <td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td>
-                                               <td>';
-                                       if (is_array($val))     {
-                                               $result.=self::view_array($val);
-                                       } elseif (is_object($val)) {
-                                               $string = '';
-                                               if (method_exists($val, '__toString')) {
-                                                       $string .= get_class($val) . ': ' . (string) $val;
-                                               } else {
-                                                       $string .= print_r($val, TRUE);
-                                               }
-                                               $result .= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
-                                       } else  {
-                                               if (gettype($val) == 'object')  {
-                                                       $string = 'Unknown object';
-                                               } else  {
-                                                       $string = (string)$val;
-                                               }
-                                               $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
-                                       }
-                                       $result.= '</td>
-                                       </tr>';
-                               }
-                       }
-                       $result.= '</table>';
-               } else {
-                       $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;
+       public static function view_array($array_in) {
+               self::logDeprecatedFunction();
+               return t3lib_utility_Debug::viewArray($array_in);
        }
 
        /**
@@ -3620,9 +3717,11 @@ final class t3lib_div {
         * @param       mixed           Array to print visually (in a table).
         * @return      void
         * @see view_array()
+        * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::printArray instead
         */
-       public static function print_array($array_in)   {
-               echo self::view_array($array_in);
+       public static function print_array($array_in) {
+               self::logDeprecatedFunction();
+               t3lib_utility_Debug::printArray($array_in);
        }
 
        /**
@@ -3636,122 +3735,22 @@ final class t3lib_div {
         * @param       string          The header.
         * @param       string          Group for the debug console
         * @return      void
+        * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::debug instead
         */
-       public static function debug($var = '', $header = '', $group = 'Debug') {
-                       // buffer the output of debug if no buffering started before
-               if (ob_get_level()==0) {
-                       ob_start();
-               }
-               $debug = '';
-
-               if ($header) {
-                       $debug .= '
-                       <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) $header) .
-                                       '</td>
-                               </tr>
-                               <tr>
-                                       <td>';
-               }
-
-               if (is_array($var))     {
-                       $debug .= self::view_array($var);
-               } elseif (is_object($var)) {
-                       $debug .=  '<strong>|Object:<pre>';
-                       $debug .= print_r($var, TRUE);
-                       $debug .=  '</pre>|</strong>';
-               } elseif ((string) $var !== '') {
-                       $debug .= '<strong>|' . htmlspecialchars((string)$var) . '|</strong>';
-               } else {
-                       $debug .= '<strong>| debug |</strong>';
-               }
-
-               if ($header) {
-                       $debug .=  '
-                                       </td>
-                               </tr>
-                       </table>';
-               }
-
-               if (TYPO3_MODE === 'BE') {
-                       $group = htmlspecialchars($group);
-
-                       if ($header !== '') {
-                               $tabHeader = htmlspecialchars($header);
-                       } else {
-                               $tabHeader = 'Debug';
-                       }
-
-                       if (is_object($var)) {
-                               $debug = str_replace(
-                                       array('"', '/', '<', "\n", "\r"),
-                                       array('\"', '\/', '\<', '<br />', ''),
-                                       $debug
-                               );
-                       } else {
-                               $debug = str_replace(
-                                       array('"', '/', '<', "\n", "\r"),
-                                       array('\"', '\/', '\<', '', ''),
-                                       $debug
-                               );
-                       }
-
-                       $script = '
-                               (function debug() {
-                                       var debugMessage = "' . $debug . '";
-                                       var header = "' . $tabHeader . '";
-                                       var group = "' . $group . '";
-
-                                       if (typeof Ext !== "object" && (top && typeof top.Ext !== "object")) {
-                                               document.write(debugMessage);
-                                               return;
-                                       }
-
-                                       if (top && typeof Ext !== "object") {
-                                               Ext = top.Ext;
-                                       }
-
-                                       Ext.onReady(function() {
-                                               var TYPO3ViewportInstance = null;
-
-                                               if (top && top.TYPO3 && typeof top.TYPO3.Backend === "object") {
-                                                       TYPO3ViewportInstance = top.TYPO3.Backend;
-                                               } else if (typeof TYPO3 === "object" && typeof TYPO3.Backend === "object") {
-                                                       TYPO3ViewportInstance = TYPO3.Backend;
-                                               }
-
-                                               if (TYPO3ViewportInstance !== null) {
-                                                       TYPO3ViewportInstance.DebugConsole.addTab(debugMessage, header, group);
-                                               } else {
-                                                       document.write(debugMessage);
-                                               }
-                                       });
-                               })();
-                       ';
-                       echo self::wrapJS($script);
-               } else {
-                       echo $debug;
-               }
+       public static function debug($var = '', $header = '', $group = 'Debug') {
+               self::logDeprecatedFunction();
+               t3lib_utility_Debug::debug($var, $header, $group);
        }
 
        /**
         * Displays the "path" of the function call stack in a string, using debug_backtrace
         *
         * @return      string
+        * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::debugTrail instead
         */
-       public static 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'].'#'.$dat['line'];
-               }
-
-               return implode(' // ',$path);
+       public static function debug_trail() {
+               self::logDeprecatedFunction();
+               return t3lib_utility_Debug::debugTrail();
        }
 
        /**
@@ -3761,75 +3760,14 @@ final class t3lib_div {
         * @param       string          Table header
         * @param       boolean         If TRUE, will return content instead of echo'ing out.
         * @return      void            Outputs to browser.
+        * @deprecated since TYPO3 4.5 - Use t3lib_utility_Debug::debugRows instead
         */
-       public static 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]) ? self::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);
-               }
+       public static function debugRows($rows, $header = '', $returnHTML = FALSE) {
+               self::logDeprecatedFunction();
+               t3lib_utility_Debug::debugRows($rows, $header, $returnHTML);
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
        /*************************
         *
         * SYSTEM INFORMATION
@@ -3842,10 +3780,10 @@ final class t3lib_div {
         *
         * @return      string
         */
-       public static function getThisUrl()     {
-               $p=parse_url(self::getIndpEnv('TYPO3_REQUEST_SCRIPT'));         // Url of this script
-               $dir=self::dirname($p['path']).'/';     // Strip file
-               $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
+       public static function getThisUrl() {
+               $p = parse_url(self::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
+               $dir = self::dirname($p['path']) . '/'; // Strip file
+               $url = str_replace('//', '/', $p['host'] . ($p['port'] ? ':' . $p['port'] : '') . $dir);
                return $url;
        }
 
@@ -3884,17 +3822,17 @@ final class t3lib_div {
         * @param       array           Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
         * @return      string          Output URL with added getParams.
         */
-       public static function linkThisUrl($url,array $getParams=array())       {
+       public static function linkThisUrl($url, array $getParams = array()) {
                $parts = parse_url($url);
                $getP = array();
-               if ($parts['query'])    {
-                       parse_str($parts['query'],$getP);
+               if ($parts['query']) {
+                       parse_str($parts['query'], $getP);
                }
-               $getP = self::array_merge_recursive_overrule($getP,$getParams);
-               $uP = explode('?',$url);
+               $getP = self::array_merge_recursive_overrule($getP, $getParams);
+               $uP = explode('?', $url);
 
-               $params = self::implodeArrayForUrl('',$getP);
-               $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
+               $params = self::implodeArrayForUrl('', $getP);
+               $outurl = $uP[0] . ($params ? '?' . substr($params, 1) : '');
 
                return $outurl;
        }
@@ -3907,7 +3845,7 @@ final class t3lib_div {
         * @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.
         */
-       public static function getIndpEnv($getEnvName)  {
+       public static function getIndpEnv($getEnvName) {
                /*
                        Conventions:
                        output from parse_url():
@@ -3971,65 +3909,65 @@ final class t3lib_div {
 
                */
 
-#              if ($getEnvName=='HTTP_REFERER')        return '';
+               #               if ($getEnvName=='HTTP_REFERER')        return '';
 
                $retVal = '';
 
-               switch ((string)$getEnvName)    {
+               switch ((string) $getEnvName) {
                        case 'SCRIPT_NAME':
                                $retVal = (PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == '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']);
+                                               ($_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']);
                                        // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
                                if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
                                        if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
-                                               $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
+                                               $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
                                        } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
-                                               $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
+                                               $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
                                        }
                                }
-                       break;
+                               break;
                        case 'SCRIPT_FILENAME':
                                $retVal = str_replace('//', '/', str_replace('\\', '/',
                                        (PHP_SAPI == 'fpm-fcgi' || PHP_SAPI == 'cgi' || PHP_SAPI == 'isapi' || PHP_SAPI == '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'])));
+                                                       ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) ?
+                                                       ($_SERVER['ORIG_PATH_TRANSLATED'] ? $_SERVER['ORIG_PATH_TRANSLATED'] : $_SERVER['PATH_TRANSLATED']) :
+                                                       ($_SERVER['ORIG_SCRIPT_FILENAME'] ? $_SERVER['ORIG_SCRIPT_FILENAME'] : $_SERVER['SCRIPT_FILENAME'])));
 
                                break;
                        case 'REQUEST_URI':
                                        // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
-                               if ($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']);
+                               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 = '/'.ltrim(self::getIndpEnv('SCRIPT_NAME'), '/').
-                                               ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
+                               } elseif (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
+                                       $retVal = '/' . ltrim(self::getIndpEnv('SCRIPT_NAME'), '/') .
+                                                       ($_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '');
                                } else {
                                        $retVal = $_SERVER['REQUEST_URI'];
                                }
                                        // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
                                if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
                                        if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
-                                               $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
+                                               $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'] . $retVal;
                                        } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
-                                               $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
+                                               $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'] . $retVal;
                                        }
                                }
-                       break;
+                               break;
                        case 'PATH_INFO':
                                        // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
                                        // 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=='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=='cgi' (see above)
-//                             if (strcmp($_SERVER['PATH_INFO'],self::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1)       {
+                                       //                              if (strcmp($_SERVER['PATH_INFO'],self::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1)       {
                                if (PHP_SAPI != 'cgi' && PHP_SAPI != 'cgi-fcgi' && PHP_SAPI != 'fpm-fcgi') {
                                        $retVal = $_SERVER['PATH_INFO'];
                                }
-                       break;
+                               break;
                        case 'TYPO3_REV_PROXY':
                                $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
-                       break;
+                               break;
                        case 'REMOTE_ADDR':
                                $retVal = $_SERVER['REMOTE_ADDR'];
                                if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
@@ -4039,21 +3977,21 @@ final class t3lib_div {
                                                switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
                                                        case 'last':
                                                                $ip = array_pop($ip);
-                                                       break;
+                                                               break;
                                                        case 'first':
                                                                $ip = array_shift($ip);
-                                                       break;
+                                                               break;
                                                        case 'none':
                                                        default:
                                                                $ip = '';
-                                                       break;
+                                                               break;
                                                }
                                        }
                                        if (self::validIP($ip)) {
                                                $retVal = $ip;
                                        }
                                }
-                       break;
+                               break;
                        case 'HTTP_HOST':
                                $retVal = $_SERVER['HTTP_HOST'];
                                if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
@@ -4063,21 +4001,21 @@ final class t3lib_div {
                                                switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
                                                        case 'last':
                                                                $host = array_pop($host);
-                                                       break;
+                                                               break;
                                                        case 'first':
                                                                $host = array_shift($host);
-                                                       break;
+                                                               break;
                                                        case 'none':
                                                        default:
                                                                $host = '';
-                                                       break;
+                                                               break;
                                                }
                                        }
-                                       if ($host)      {
+                                       if ($host) {
                                                $retVal = $host;
                                        }
                                }
-                       break;
+                               break;
                                // These are let through without modification
                        case 'HTTP_REFERER':
                        case 'HTTP_USER_AGENT':
@@ -4086,76 +4024,84 @@ final class t3lib_div {
                        case 'REMOTE_HOST':
                        case 'QUERY_STRING':
                                $retVal = $_SERVER[$getEnvName];
-                       break;
+                               break;
                        case 'TYPO3_DOCUMENT_ROOT':
-                               // Get the web root (it is not the root of the TYPO3 installation)
-                               // The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME
-                               // 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.
-                               // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
+                                       // Get the web root (it is not the root of the TYPO3 installation)
+                                       // The absolute path of the script can be calculated with TYPO3_DOCUMENT_ROOT + SCRIPT_FILENAME
+                                       // 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.
+                                       // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
                                $SFN = self::getIndpEnv('SCRIPT_FILENAME');
-                               $SN_A = explode('/',strrev(self::getIndpEnv('SCRIPT_NAME')));
-                               $SFN_A = explode('/',strrev($SFN));
+                               $SN_A = explode('/', strrev(self::getIndpEnv('SCRIPT_NAME')));
+                               $SFN_A = explode('/', strrev($SFN));
                                $acc = array();
                                foreach ($SN_A as $kk => $vv) {
-                                       if (!strcmp($SFN_A[$kk],$vv))   {
+                                       if (!strcmp($SFN_A[$kk], $vv)) {
                                                $acc[] = $vv;
-                                       } else break;
+                                       } else {
+                                               break;
+                                       }
+                               }
+                               $commonEnd = strrev(implode('/', $acc));
+                               if (strcmp($commonEnd, '')) {
+                                       $DR = substr($SFN, 0, -(strlen($commonEnd) + 1));
                                }
-                               $commonEnd=strrev(implode('/',$acc));
-                               if (strcmp($commonEnd,''))      { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
                                $retVal = $DR;
-                       break;
+                               break;
                        case 'TYPO3_HOST_ONLY':
-                               $p = explode(':',self::getIndpEnv('HTTP_HOST'));
-                               $retVal = $p[0];
-                       break;
+                               $httpHost = self::getIndpEnv('HTTP_HOST');
+                               $httpHostBracketPosition = strpos($httpHost, ']');
+                               $retVal = ($httpHostBracketPosition !== FALSE) ? substr($httpHost, 0, ($httpHostBracketPosition + 1)) : array_shift(explode(':', $httpHost));
+                               break;
                        case 'TYPO3_PORT':
-                               $p = explode(':',self::getIndpEnv('HTTP_HOST'));
-                               $retVal = $p[1];
-                       break;
+                               $httpHost = self::getIndpEnv('HTTP_HOST');
+                               $httpHostOnly = self::getIndpEnv('TYPO3_HOST_ONLY');
+                               $retVal = (strlen($httpHost) > strlen($httpHostOnly)) ? substr($httpHost, strlen($httpHostOnly) + 1) : '';
+                               break;
                        case 'TYPO3_REQUEST_HOST':
-                               $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
-                                       self::getIndpEnv('HTTP_HOST');
-                       break;
+                               $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://') .
+                                               self::getIndpEnv('HTTP_HOST');
+                               break;
                        case 'TYPO3_REQUEST_URL':
-                               $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::getIndpEnv('REQUEST_URI');
-                       break;
+                               $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('REQUEST_URI');
+                               break;
                        case 'TYPO3_REQUEST_SCRIPT':
-                               $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::getIndpEnv('SCRIPT_NAME');
-                       break;
+                               $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::getIndpEnv('SCRIPT_NAME');
+                               break;
                        case 'TYPO3_REQUEST_DIR':
-                               $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::dirname(self::getIndpEnv('SCRIPT_NAME')).'/';
-                       break;
+                               $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST') . self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/';
+                               break;
                        case 'TYPO3_SITE_URL':
-                               if (defined('PATH_thisScript') && defined('PATH_site')) {
-                                       $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
+                               if (defined('PATH_thisScript') && defined('PATH_site')) {
+                                       $lPath = substr(dirname(PATH_thisScript), strlen(PATH_site)) . '/';
                                        $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
-                                       $siteUrl = substr($url,0,-strlen($lPath));
-                                       if (substr($siteUrl,-1)!='/')   $siteUrl.='/';
+                                       $siteUrl = substr($url, 0, -strlen($lPath));
+                                       if (substr($siteUrl, -1) != '/') {
+                                               $siteUrl .= '/';
+                                       }
                                        $retVal = $siteUrl;
                                }
-                       break;
+                               break;
                        case 'TYPO3_SITE_PATH':
                                $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
-                       break;
+                               break;
                        case 'TYPO3_SITE_SCRIPT':
-                               $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'),strlen(self::getIndpEnv('TYPO3_SITE_URL')));
-                       break;
+                               $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'), strlen(self::getIndpEnv('TYPO3_SITE_URL')));
+                               break;
                        case 'TYPO3_SSL':
                                $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']);
                                if ($proxySSL == '*') {
                                        $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
                                }
-                               if (self::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL))    {
-                                       $retVal = true;
+                               if (self::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL)) {
+                                       $retVal = TRUE;
                                } else {
-                                       $retVal = $_SERVER['SSL_SESSION_ID'] || !strcasecmp($_SERVER['HTTPS'], 'on') || !strcmp($_SERVER['HTTPS'], '1') ? true : false; // see http://bugs.typo3.org/view.php?id=3909
+                                       $retVal = $_SERVER['SSL_SESSION_ID'] || !strcasecmp($_SERVER['HTTPS'], 'on') || !strcmp($_SERVER['HTTPS'], '1') ? TRUE : FALSE; // see http://bugs.typo3.org/view.php?id=3909
                                }
-                       break;
+                               break;
                        case '_ARRAY':
                                $out = array();
                                        // Here, list ALL possible keys to this function for debug display.
-                               $envTestVars = self::trimExplode(',','
+                               $envTestVars = self::trimExplode(',', '
                                        HTTP_HOST,
                                        TYPO3_HOST_ONLY,
                                        TYPO3_PORT,
@@ -4177,13 +4123,13 @@ final class t3lib_div {
                                        REMOTE_ADDR,
                                        REMOTE_HOST,
                                        HTTP_USER_AGENT,
-                                       HTTP_ACCEPT_LANGUAGE',1);
+                                       HTTP_ACCEPT_LANGUAGE', 1);
                                foreach ($envTestVars as $v) {
-                                       $out[$v]=self::getIndpEnv($v);
+                                       $out[$v] = self::getIndpEnv($v);
                                }
                                reset($out);
                                $retVal = $out;
-                       break;
+                               break;
                }
                return $retVal;
        }
@@ -4194,7 +4140,7 @@ final class t3lib_div {
         * @return      integer         The unixtime as milliseconds
         */
        public static function milliseconds() {
-               return round(microtime(true) * 1000);
+               return round(microtime(TRUE) * 1000);
        }
 
        /**
@@ -4204,55 +4150,63 @@ final class t3lib_div {
         * @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
         */
-       public static function clientInfo($useragent='')        {
-               if (!$useragent) $useragent=self::getIndpEnv('HTTP_USER_AGENT');
+       public static function clientInfo($useragent = '') {
+               if (!$useragent) {
+                       $useragent = self::getIndpEnv('HTTP_USER_AGENT');
+               }
 
-               $bInfo=array();
+               $bInfo = array();
                        // Which browser?
-               if (strpos($useragent,'Konqueror') !== false)   {
-                       $bInfo['BROWSER']= 'konqu';
-               } elseif (strpos($useragent,'Opera') !== false) {
-                       $bInfo['BROWSER']= 'opera';
-               } elseif (strpos($useragent, 'MSIE') !== false) {
-                       $bInfo['BROWSER']= 'msie';
-               } elseif (strpos($useragent, 'Mozilla') !== false) {
-                       $bInfo['BROWSER']='net';
-               } elseif (strpos($useragent, 'Flash') !== false) {
+               if (strpos($useragent, 'Konqueror') !== FALSE) {
+                       $bInfo['BROWSER'] = 'konqu';
+               } elseif (strpos($useragent, 'Opera') !== FALSE) {
+                       $bInfo['BROWSER'] = 'opera';
+               } elseif (strpos($useragent, 'MSIE') !== FALSE) {
+                       $bInfo['BROWSER'] = 'msie';
+               } elseif (strpos($useragent, 'Mozilla') !== FALSE) {
+                       $bInfo['BROWSER'] = 'net';
+               } elseif (strpos($useragent, 'Flash') !== FALSE) {
                        $bInfo['BROWSER'] = 'flash';
                }
-               if ($bInfo['BROWSER'])  {
+               if ($bInfo['BROWSER']) {
                                // Browser version
-                       switch($bInfo['BROWSER'])       {
+                       switch ($bInfo['BROWSER']) {
                                case 'net':
-                                       $bInfo['VERSION']= doubleval(substr($useragent,8));
-                                       if (strpos($useragent,'Netscape6/') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape6/'),10)); }   // Will we ever know if this was a typo or intention...?! :-(
-                                       if (strpos($useragent,'Netscape/6') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/6'),10)); }
-                                       if (strpos($useragent,'Netscape/7') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/7'),9)); }
-                               break;
+                                       $bInfo['VERSION'] = doubleval(substr($useragent, 8));
+                                       if (strpos($useragent, 'Netscape6/') !== FALSE) {
+                                               $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape6/'), 10));
+                                       } // Will we ever know if this was a typo or intention...?! :-(
+                                       if (strpos($useragent, 'Netscape/6') !== FALSE) {
+                                               $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/6'), 10));
+                                       }
+                                       if (strpos($useragent, 'Netscape/7') !== FALSE) {
+                                               $bInfo['VERSION'] = doubleval(substr(strstr($useragent, 'Netscape/7'), 9));
+                                       }
+                                       break;
                                case 'msie':
-                                       $tmp = strstr($useragent,'MSIE');
-                                       $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,4)));
-                               break;
+                                       $tmp = strstr($useragent, 'MSIE');
+                                       $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 4)));
+                                       break;
                                case 'opera':
-                                       $tmp = strstr($useragent,'Opera');
-                                       $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,5)));
-                               break;
+                                       $tmp = strstr($useragent, 'Opera');
+                                       $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/', '', substr($tmp, 5)));
+                                       break;
                                case 'konqu':
-                                       $tmp = strstr($useragent,'Konqueror/');
-                                       $bInfo['VERSION'] = doubleval(substr($tmp,10));
-                               break;
+                                       $tmp = strstr($useragent, 'Konqueror/');
+                                       $bInfo['VERSION'] = doubleval(substr($tmp, 10));
+                                       break;
                        }
-                               // Client system
-                       if (strpos($useragent,'Win') !== false) {
+                       // Client system
+                       if (strpos($useragent, 'Win') !== FALSE) {
                                $bInfo['SYSTEM'] = 'win';
-                       } elseif (strpos($useragent,'Mac') !== false)   {
+                       } elseif (strpos($useragent, 'Mac') !== FALSE) {
                                $bInfo['SYSTEM'] = 'mac';
-                       } elseif (strpos($useragent,'Linux') !== false || strpos($useragent,'X11') !== false || strpos($useragent,'SGI') !== false || strpos($useragent,' SunOS ') !== false || strpos($useragent,' HP-UX ') !== false) {
+                       } elseif (strpos($useragent, 'Linux') !== FALSE || strpos($useragent, 'X11') !== FALSE || strpos($useragent, 'SGI') !== FALSE || strpos($useragent, ' SunOS ') !== FALSE || strpos($useragent, ' HP-UX ') !== FALSE) {
                                $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');
+               // 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;
        }
@@ -4264,54 +4218,40 @@ final class t3lib_div {
         * @param       boolean         Use request host (when not in CLI mode).
         * @return      string          The fully-qualified host name.
         */
-       public static function getHostname($requestHost=TRUE)   {
+       public static function getHostname($requestHost = TRUE) {
                $host = '';
                        // If not called from the command-line, resolve on getIndpEnv()
                        // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
-               if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode))      {
+               if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) {
                        $host = self::getIndpEnv('HTTP_HOST');
                }
-               if (!$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 = '';
+                       if (strpos($host, ' ')) {
+                               $host = '';
+                       }
                }
                        // we have not found a FQDN yet
-               if ($host && strpos($host, '.') === false) {
+               if ($host && strpos($host, '.') === FALSE) {
                        $ip = gethostbyname($host);
                                // we got an IP address
-                       if ($ip != $host)       {
+                       if ($ip != $host) {
                                $fqdn = gethostbyaddr($ip);
-                               if ($ip != $fqdn)       $host = $fqdn;
+                               if ($ip != $fqdn) {
+                                       $host = $fqdn;
+                               }
                        }
                }
-               if (!$host)     $host = 'localhost.localdomain';
+               if (!$host) {
+                       $host = 'localhost.localdomain';
+               }
 
                return $host;
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
        /*************************
         *
         * TYPO3 SPECIFIC FUNCTIONS
@@ -4327,45 +4267,51 @@ final class t3lib_div {
         * @param       boolean         If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
         * @return      string          Returns the absolute filename of $filename IF valid, otherwise blank string.
         */
-       public static function getFileAbsFileName($filename,$onlyRelative=TRUE,$relToTYPO3_mainDir=FALSE)       {
-               if (!strcmp($filename,''))              return '';
+       public static function getFileAbsFileName($filename, $onlyRelative = TRUE, $relToTYPO3_mainDir = FALSE) {
+               if (!strcmp($filename, '')) {
+                       return '';
+               }
 
-               if ($relToTYPO3_mainDir)        {
-                       if (!defined('PATH_typo3'))     return '';
+               if ($relToTYPO3_mainDir) {
+                       if (!defined('PATH_typo3')) {
+                               return '';
+                       }
                        $relPathPrefix = PATH_typo3;
                } else {
                        $relPathPrefix = PATH_site;
                }
-               if (substr($filename,0,4)=='EXT:')      {       // extension
-                       list($extKey,$local) = explode('/',substr($filename,4),2);
-                       $filename='';
-                       if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
-                               $filename = t3lib_extMgm::extPath($extKey).$local;
+               if (substr($filename, 0, 4) == 'EXT:') { // extension
+                       list($extKey, $local) = explode('/', substr($filename, 4), 2);
+                       $filename = '';
+                       if (strcmp($extKey, '') && t3lib_extMgm::isLoaded($extKey) && strcmp($local, '')) {
+                               $filename = t3lib_extMgm::extPath($extKey) . $local;
                        }
-               } elseif (!self::isAbsPath($filename))  {       // relative. Prepended with $relPathPrefix
-                       $filename=$relPathPrefix.$filename;
-               } elseif ($onlyRelative && !self::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
-                       $filename='';
+               } elseif (!self::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
+                       $filename = $relPathPrefix . $filename;
+               } elseif ($onlyRelative && !self::isFirstPartOfStr($filename, $relPathPrefix)) { // absolute, but set to blank if not allowed
+                       $filename = '';
                }
-               if (strcmp($filename,'') && self::validPathStr($filename))      {       // checks backpath.
+               if (strcmp($filename, '') && self::validPathStr($filename)) { // checks backpath.
                        return $filename;
                }
        }
 
        /**
         * Checks for malicious file paths.
-        * Returns true if no '//', '..' or '\' is in the $theFile
+        *
+        * Returns TRUE if no '//', '..', '\' or control characters are found 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: 14
         *
         * @param       string          Filepath to evaluate
-        * @return      boolean         True, if no '//', '\', '/../' is in the $theFile and $theFile doesn't begin with '../'
+        * @return      boolean         TRUE, $theFile is allowed path string
+        * @see         http://php.net/manual/en/security.filesystem.nullbytes.php
         * @todo        Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
         */
-       public static function validPathStr($theFile)   {
-               if (strpos($theFile, '//')===false && strpos($theFile, '\\')===false && !preg_match('#(?:^\.\.|/\.\./)#', $theFile)) {
-                       return true;
+       public static function validPathStr($theFile) {
+               if (strpos($theFile, '//') === FALSE && strpos($theFile, '\\') === FALSE && !preg_match('#(?:^\.\.|/\.\./|[[:cntrl:]])#', $theFile)) {
+                       return TRUE;
                }
        }
 
@@ -4376,8 +4322,8 @@ final class t3lib_div {
         * @param       string          Filepath to evaluate
         * @return      boolean
         */
-       public static function isAbsPath($path) {
-               return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' :  substr($path,0,1)=='/';
+       public static function isAbsPath($path) {
+               return TYPO3_OS == 'WIN' ? substr($path, 1, 2) == ':/' : substr($path, 0, 1) == '/';
        }
 
        /**
@@ -4387,14 +4333,16 @@ final class t3lib_div {
         * @param       string          Filepath to evaluate
         * @return      boolean
         */
-       public static function isAllowedAbsPath($path)  {
+       public static function isAllowedAbsPath($path) {
                if (self::isAbsPath($path) &&
-                       self::validPathStr($path) &&
-                               (       self::isFirstPartOfStr($path,PATH_site)
-                                       ||
-                                       ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && self::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
+                               self::validPathStr($path) &&
+                               (self::isFirstPartOfStr($path, PATH_site)
+                                               ||
+                                               ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && self::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
                                )
-                       )       return true;
+               ) {
+                       return TRUE;
+               }
        }
 
        /**
@@ -4404,12 +4352,19 @@ final class t3lib_div {
         * @param       string          Filepath to evaluate
         * @return      boolean
         */
-       public static function verifyFilenameAgainstDenyPattern($filename)      {
-               if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],''))    {
-                       $result = preg_match('/'.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'].'/i',$filename);
-                       if ($result)    return false;   // so if a matching filename is found, return false;
+       public static function verifyFilenameAgainstDenyPattern($filename) {
+                       // Filenames are not allowed to contain control characters
+               if (preg_match('/[[:cntrl:]]/', $filename)) {
+                       return FALSE;
+               }
+
+               if (strcmp($filename, '') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'], '')) {
+                       $result = preg_match('/' . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] . '/i', $filename);
+                       if ($result) {
+                               return FALSE;
+                       } // so if a matching filename is found, return FALSE;
                }
-               return true;
+               return TRUE;
        }
 
        /**
@@ -4419,7 +4374,7 @@ final class t3lib_div {
         * @param string $url potential URL to check
         *
         * @return string either $url if $url is considered to be harmless, or an
-        *                empty string otherwise
+        *                              empty string otherwise
         */
        public static function sanitizeLocalUrl($url = '') {
                $sanitizedUrl = '';
@@ -4465,17 +4420,17 @@ final class t3lib_div {
         * @coauthor    Dennis Petersen <fessor@software.dk>
         * @see upload_to_tempfile()
         */
-       public static function upload_copy_move($source,$destination)   {
-               if (is_uploaded_file($source))  {
+       public static 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:
+                               // 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);
+                       @copy($source, $destination);
                }
 
-               self::fixPermissions($destination);     // Change the permissions of the file
+               self::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;
@@ -4491,8 +4446,8 @@ final class t3lib_div {
         * @return      string          If a new file was successfully created, return its filename, otherwise blank string.
         * @see unlink_tempfile(), upload_copy_move()
         */
-       public static function upload_to_tempfile($uploadedFileName)    {
-               if (is_uploaded_file($uploadedFileName))        {
+       public static function upload_to_tempfile($uploadedFileName) {
+               if (is_uploaded_file($uploadedFileName)) {
                        $tempFile = self::tempnam('upload_temp_');
                        move_uploaded_file($uploadedFileName, $tempFile);
                        return @is_file($tempFile) ? $tempFile : '';
@@ -4509,9 +4464,11 @@ final class t3lib_div {
         * @return      boolean         Returns true if the file was unlink()'ed
         * @see upload_to_tempfile(), tempnam()
         */
-       public static function unlink_tempfile($uploadedTempFileName)   {
-               if ($uploadedTempFileName && self::validPathStr($uploadedTempFileName) && self::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName))      {
-                       if (unlink($uploadedTempFileName))      return TRUE;
+       public static function unlink_tempfile($uploadedTempFileName) {
+               if ($uploadedTempFileName && self::validPathStr($uploadedTempFileName) && self::isFirstPartOfStr($uploadedTempFileName, PATH_site . 'typo3temp/') && @is_file($uploadedTempFileName)) {
+                       if (unlink($uploadedTempFileName)) {
+                               return TRUE;
+                       }
                }
        }
 
@@ -4525,8 +4482,8 @@ final class t3lib_div {
         * @return      string          result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
         * @see unlink_tempfile(), upload_to_tempfile()
         */
-       public static function tempnam($filePrefix)     {
-               return tempnam(PATH_site.'typo3temp/',$filePrefix);
+       public static function tempnam($filePrefix) {
+               return tempnam(PATH_site . 'typo3temp/', $filePrefix);
        }
 
        /**
@@ -4538,25 +4495,25 @@ final class t3lib_div {
         * @param       integer         Length of returned authentication code.
         * @return      string          MD5 hash of 8 chars.
         */
-       public static function stdAuthCode($uid_or_record,$fields='',$codeLength=8)     {
+       public static function stdAuthCode($uid_or_record, $fields = '', $codeLength = 8) {
 
-               if (is_array($uid_or_record))   {
-                       $recCopy_temp=array();
-                       if ($fields)    {
-                               $fieldArr = self::trimExplode(',',$fields,1);
+               if (is_array($uid_or_record)) {
+                       $recCopy_temp = array();
+                       if ($fields) {
+                               $fieldArr = self::trimExplode(',', $fields, 1);
                                foreach ($fieldArr as $k => $v) {
-                                       $recCopy_temp[$k]=$uid_or_record[$v];
+                                       $recCopy_temp[$k] = $uid_or_record[$v];
                                }
                        } else {
-                               $recCopy_temp=$uid_or_record;
+                               $recCopy_temp = $uid_or_record;
                        }
-                       $preKey = implode('|',$recCopy_temp);
+                       $preKey = implode('|', $recCopy_temp);
                } else {
                        $preKey = $uid_or_record;
                }
 
-               $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
-               $authCode = substr(md5($authCode),0,$codeLength);
+               $authCode = $preKey . '||' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
+               $authCode = substr(md5($authCode), 0, $codeLength);
                return $authCode;
        }
 
@@ -4569,18 +4526,18 @@ final class t3lib_div {
         * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink(), t3lib_div::calculateCHash()
         */
        public static function cHashParams($addQueryParams) {
-               $params = explode('&',substr($addQueryParams,1));       // Splitting parameters up
+               $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 (!self::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]);
+               foreach ($params as $theP) {
+                       $pKV = explode('=', $theP); // Splitting single param by '=' sign
+                       if (!self::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]);
                        }
                }
                        // Hook: Allows to manipulate the parameters which are taken to build the chash:
-               if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook']))   {
+               if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'])) {
                        $cHashParamsHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'];
                        if (is_array($cHashParamsHook)) {
                                $hookParameters = array(
@@ -4588,8 +4545,8 @@ final class t3lib_div {
                                        'params' => &$params,
                                        'pA' => &$pA,
                                );
-                               $hookReference = null;
-                               foreach ($cHashParamsHook as $hookFunction)     {
+                               $hookReference = NULL;
+                               foreach ($cHashParamsHook as $hookFunction) {
                                        self::callUserFunction($hookFunction, $hookParameters, $hookReference);
                                }
                        }
@@ -4631,11 +4588,11 @@ final class t3lib_div {
         * @param       integer         Value from "l18n_cfg" field of a page record
         * @return      boolean         True if the page should be hidden
         */
-       public static function hideIfNotTranslated($l18n_cfg_fieldValue)        {
-               if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault'])     {
-                       return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
+       public static 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;
+                       return $l18n_cfg_fieldValue & 2 ? TRUE : FALSE;
                }
        }
 
@@ -4647,30 +4604,31 @@ final class t3lib_div {
         * @param       string          Character set (option); if not set, determined by the language key
         * @param       integer         Error mode (when file could not be found): 0 - syslog entry, 1 - do nothing, 2 - throw an exception
         * @return      array           Value of $LOCAL_LANG found in the included file. If that array is found it  will returned.
-        *                                              Otherwise an empty array and it is FALSE in error case.
+        *                                               Otherwise an empty array and it is FALSE in error case.
         */
-       public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0)    {
+       public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0) {