[BUGFIX] Using datetime field with datepicker the time information gets lost
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_div.php
index 9805b4b..c25d124 100644 (file)
@@ -1,29 +1,29 @@
 <?php
 /***************************************************************
 <?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
  *
 /**
  * Contains the reknown class "t3lib_div" with general purpose functions
  *
  *
  *  232: class t3lib_div
  *
  *
  *  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")
  *
  * 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;
 
        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.
         */
         * @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];
                $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;
        }
                }
                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();
         */
        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);
 
                $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()
         */
         * @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]);
                $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;
        }
                }
                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()
         */
         * @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]);
                $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;
        }
                }
                return $value;
        }
@@ -324,16 +359,16 @@ final class t3lib_div {
         * Usage: 2
         *
         * @param mixed $inputGet
         * 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
         * @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
         */
         *
         * @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()
         */
         * @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();
 
                self::logDeprecatedFunction();
 
-               if(empty($var)) return;
+               if (empty($var)) {
+                       return;
+               }
                $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
                $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;
        }
 
                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()
         */
         * @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);
                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
         */
         * @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;
        }
 
 
                $string = RemoveXSS::process($string);
                return $string;
        }
 
 
-
-
-
-
-
-
-
-
        /*************************
         *
         * IMAGE FUNCTIONS
        /*************************
         *
         * 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)
         *
         * 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.
         */
         * 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'];
                $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);
                                $tempImage = imageCreateFromGif($theFile);
                                imageGif($tempImage, $theFile);
                                imageDestroy($tempImage);
-                               $returnCode='GD';
+                               $returnCode = 'GD';
+                               if (@is_file($theFile)) {
+                                       self::fixPermissions($theFile);
+                               }
                        }
                }
                return $returnCode;
                        }
                }
                return $returnCode;
@@ -484,17 +529,20 @@ final class t3lib_div {
         * @param       string          $theFile        the filename with path
         * @return      string          new filename
         */
         * @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']
                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;
        }
                }
                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
         */
         * @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 (
                        if (
-                                       ((string)$ext=='.png' && $output_png)   ||
-                                       ((string)$ext=='.gif' && !$output_png)
-                               )       {
+                               ((string) $ext == '.png' && $output_png) ||
+                               ((string) $ext == '.gif' && !$output_png)
+                       ) {
                                return $theFile;
                        } else {
                                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
        /*************************
         *
         * 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()
         */
         * @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);
                self::logDeprecatedFunction();
 
                $chars = abs($origChars);
-               if ($chars >= 4)        {
-                       if(strlen($string)>$chars)  {
+               if ($chars >= 4) {
+                       if (strlen($string) > $chars) {
                                return $origChars < 0 ?
                                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;
                        }
                }
                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()
         */
         * @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();
 
                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
         */
         * @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'])) {
                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
         */
         * @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();
 
                self::logDeprecatedFunction();
 
-               $lines = explode(LF,$str);
-               $outArr=array();
+               $lines = explode(LF, $str);
+               $outArr = array();
                foreach ($lines as $lStr) {
                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()
         */
         * @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 {
                                        $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 {
                        } 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
         */
         * @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);
                $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);
                        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
         */
         * @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);
                                                // "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);
                                        $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.*.*"
                                } else {
                                                // "192.168.*.*"
-                                       $IPparts = explode('.',$test);
+                                       $IPparts = explode('.', $test);
                                        $yes = 1;
                                        foreach ($IPparts as $index => $val) {
                                                $val = trim($val);
                                        $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
         */
         * @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);
 
                $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);
                                $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);
                                                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);
                                                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:
                                                default:
-                                                       $success = false;
+                                                       $success = FALSE;
                                        }
                                } else {
                                        }
                                } 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);
                                                $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]          ...
         */
         * @param       [type]          $hex: ...
         * @return      [type]          ...
         */
-       public static function IPv6Hex2Bin ($hex)       {
+       public static function IPv6Hex2Bin($hex) {
                $bin = '';
                $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;
        }
                }
                return $bin;
        }
@@ -800,23 +846,26 @@ final class t3lib_div {
         * @param       string          Given IPv6 address
         * @return      string          Normalized address
         */
         * @param       string          Given IPv6 address
         * @return      string          Normalized address
         */
-       public static function normalizeIPv6($address)  {
+       public static function normalizeIPv6($address) {
                $normalizedAddress = '';
                $stageOneAddress = '';
 
                $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
                        $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 = '';
 
                        $hiddenBlocks = 8 - ($left + $right);
                        $hiddenPart = '';
-                       while ($h<$hiddenBlocks)        {
+                       $h = 0;
+                       while ($h < $hiddenBlocks) {
                                $hiddenPart .= '0000:';
                                $h++;
                        }
                                $hiddenPart .= '0000:';
                                $h++;
                        }
@@ -826,21 +875,23 @@ final class t3lib_div {
                        } else {
                                $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
                        }
                        } else {
                                $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
                        }
-               } else $stageOneAddress = $address;
+               } else {
+                       $stageOneAddress = $address;
+               }
 
                        // normalize the blocks:
                $blocks = explode(':', $stageOneAddress);
                $divCounter = 0;
 
                        // normalize the blocks:
                $blocks = explode(':', $stageOneAddress);
                $divCounter = 0;
-               foreach ($blocks as $block)     {
+               foreach ($blocks as $block) {
                        $tmpBlock = '';
                        $i = 0;
                        $hiddenZeros = 4 - strlen($block);
                        $tmpBlock = '';
                        $i = 0;
                        $hiddenZeros = 4 - strlen($block);
-                       while ($i < $hiddenZeros)       {
+                       while ($i < $hiddenZeros) {
                                $tmpBlock .= '0';
                                $i++;
                        }
                        $normalizedAddress .= $tmpBlock . $block;
                                $tmpBlock .= '0';
                                $i++;
                        }
                        $normalizedAddress .= $tmpBlock . $block;
-                       if ($divCounter < 7)    {
+                       if ($divCounter < 7) {
                                $normalizedAddress .= ':';
                                $divCounter++;
                        }
                                $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      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      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.
         */
         * @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
         */
         * @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));
                        $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;
 
                                $yes = 1;
 
-                               foreach($hostNameParts as $index => $val)       {
+                               foreach ($hostNameParts as $index => $val) {
                                        $val = trim($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
         */
         * @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
         */
         * @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) {
                foreach ($items as $k => $v) {
-                       if ($v==$element) {
+                       if ($v == $element) {
                                unset($items[$k]);
                        }
                }
                                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>
         */
         * @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) {
                $list = array();
                foreach ($items as $item) {
-                       $range = explode('-',$item);
-                       if (isset($range[1]))   {
+                       $range = explode('-', $item);
+                       if (isset($range[1])) {
                                $runAwayBrake = 1000;
                                $runAwayBrake = 1000;
-                               for ($n=$range[0]; $n<=$range[1]; $n++) {
+                               for ($n = $range[0]; $n <= $range[1]; $n++) {
                                        $list[] = $n;
 
                                        $runAwayBrake--;
                                        $list[] = $n;
 
                                        $runAwayBrake--;
-                                       if ($runAwayBrake<=0)   break;
+                                       if ($runAwayBrake <= 0) {
+                                               break;
+                                       }
                                }
                        } else {
                                $list[] = $item;
                        }
                }
                                }
                        } 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
         */
         * @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);
                $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;
        }
 
                return $theInt;
        }
 
@@ -1008,9 +1069,11 @@ final class t3lib_div {
         * @param       integer         Integer string to process
         * @return      integer
         */
         * @param       integer         Integer string to process
         * @return      integer
         */
-       public static function intval_positive($theInt) {
+       public static function intval_positive($theInt) {
                $theInt = intval($theInt);
                $theInt = intval($theInt);
-               if ($theInt<0){$theInt=0;}
+               if ($theInt < 0) {
+                       $theInt = 0;
+               }
                return $theInt;
        }
 
                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)
         */
         * @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
         */
         * @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;
 
                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;
                        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
         */
         * @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)
         */
         * @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.
         *
        }
 
        /**
         * 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';
         */
        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));
                        }
                                        // 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;
        }
                }
                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
         */
         * @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!',
                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]
         */
         * @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];
                $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.
         */
         * @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()
         */
         * @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()
         */
         * @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
         */
         * @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, ',');
                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
         */
         * @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);
                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
         */
         * @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();
 
                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);
        }
 
                return str_replace($pattern, $replace, $str);
        }
 
@@ -1285,7 +1348,7 @@ final class t3lib_div {
                if ($var === '') {
                        return FALSE;
                }
                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
         */
         * @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;
        }
 
                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.
         */
         * @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 {
 
                        // 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:
 
                        // 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)
         */
         * @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()
         */
         * @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();
                $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;
                }
                reset($res);
                return $res;
@@ -1379,38 +1442,54 @@ final class t3lib_div {
         * @return      integer         Calculated value. Or error string.
         * @see calcParenthesis()
         */
         * @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();
                        // split the expression here:
                $reg = array();
-               preg_match_all('/'.$regex.'/',$string,$reg);
+               preg_match_all('/' . $regex . '/', $string, $reg);
 
                reset($reg[2]);
 
                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];
                        $sign = $reg[1][$k];
-                       if ($sign=='+' || $sign=='-')   {
-                               $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
+                       if ($sign == '+' || $sign == '-') {
+                               $number = $Msign == '-' ? $number -= $buffer : $number += $buffer;
                                $Msign = $sign;
                                $Msign = $sign;
-                               $buffer=$v;
+                               $buffer = $v;
                        } else {
                        } 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()
         */
         * @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 {
                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 {
                                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--;
                        }
                                // Security:
                        $securC--;
-                       if ($securC<=0) break;
-               } while($valueLenO<strlen($string));
+                       if ($securC <= 0) {
+                               break;
+                       }
+               } while ($valueLenO < strlen($string));
                return $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.
         */
         * @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;
        }
 
                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.
         */
         * @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
         */
         * @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.
         */
         * @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
         */
         * @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
         */
         * @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) {
                        // 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      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) {
         * @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);
                }
                        $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
         */
         * @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.
         *
         * 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) {
         */
        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
         */
         * @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));
                                try {
                                        $com = new COM('CAPICOM.Utilities.1');
                                        $output = base64_decode($com->GetRandom($count, 0));
-                               } catch(Exception $e) {
+                               } catch (Exception $e) {
                                        // CAPICOM not installed
                                }
                        }
                                        // 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')) {
                                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) {
                                        $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']
                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);
                        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);
                }
                        }
                        $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      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
        /*************************
         *
         * ARRAY FUNCTIONS
@@ -1737,10 +1812,10 @@ final class t3lib_div {
         * +---------+-----------+-----------+-----------+
         * | $needle | variant_a | variant_b | variant_c |
         * +---------+-----------+-----------+-----------+
         * +---------+-----------+-----------+-----------+
         * | $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
         *
         * +---------+-----------+-----------+-----------+
         * 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)) {
        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,
         * @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) {
         * @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
         */
         * @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);
                $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
         * @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
         */
         * @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();
                $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;
                                }
                                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
         */
         * @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);
                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
         */
         * @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);
                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(
         *
         * 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(
         * );
         * $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
         * )
         *
         * @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
         */
         * @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)) {
                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)) {
                        }
                                // create_function() returns a string:
                        if (!is_string($getValueFunc)) {
-                               $getValueFunc = null;
+                               $getValueFunc = NULL;
                        }
                                // Do the filtering:
                        if (is_array($keepItems) && count($keepItems)) {
                        }
                                // 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()
         */
         * @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 {
                        } 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()
         */
         * @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();
                $output = array();
-               if ($multidim)  {
-                       parse_str($string,$output);
+               if ($multidim) {
+                       parse_str($string, $output);
                } else {
                } 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);
                                }
                        }
                                        $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.
         */
         * @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();
                $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);
                                $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
         */
         * @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);
                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
         */
         * @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);
                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
         */
         * @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;
        }
 
        /**
                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) {
        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
         */
         * @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) {
                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) {
                                }
                        } else {
                                if ($notAddKeys) {
@@ -2110,8 +2189,8 @@ final class t3lib_div {
         * @param       array           Second array
         * @return      array           Merged result.
         */
         * @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
         */
         * @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);
                reset($row);
-               $out=array();
+               $out = array();
                foreach ($row as $value) {
                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;
        }
 
                return $str;
        }
 
@@ -2190,19 +2269,22 @@ final class t3lib_div {
                return $out;
        }
 
                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.
         */
         * @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);
                $components = self::split_tag_attributes($tag);
-               $name = '';      // attribute name is stored here
-               $valuemode = false;
+               $name = ''; // attribute name is stored here
+               $valuemode = FALSE;
                $attributes = array();
                $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 {
                                                $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;
                                        }
                                }
                                                $attributes[$key] = '';
                                                $name = $key;
                                        }
                                }
-                               $valuemode = false;
+                               $valuemode = FALSE;
                        } else {
                        } else {
-                               $valuemode = true;
+                               $valuemode = TRUE;
                        }
                }
                return $attributes;
                        }
                }
                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.
         */
         * @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();
                        // 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[] = '=';
                                $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]);
                        } 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);
                        }
                }
                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"'
         */
         * @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();
                        }
                        $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()
         */
         * @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();
 
                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>
         */
         * @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?
                                // <script wrapped in nl?
-                       $cr = $linebreak? LF : '';
+                       $cr = $linebreak ? LF : '';
 
                                // remove nl from the beginning
 
                                // 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();
                                // 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[*/
 /*<![CDATA[*/
-'.$string.'
+' . $string . '
 /*]]>*/
 /*]]>*/
-</script>'.$cr;
+</script>' . $cr;
                }
                return trim($string);
        }
                }
                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
         */
         * @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();
                $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);
 
                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);
 
                xml_parser_free($parser);
 
-               $stack = array( array() );
+               $stack = array(array());
                $stacktop = 0;
                $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:
                        $type = $val['type'];
 
                                // open tag:
-                       if ($type=='open' || $type=='complete') {
+                       if ($type == 'open' || $type == 'complete') {
                                $stack[$stacktop++] = $tagi;
 
                                $stack[$stacktop++] = $tagi;
 
-                               if ($depth==$stacktop)  {
-                                       $startPoint=$key;
+                               if ($depth == $stacktop) {
+                                       $startPoint = $key;
                                }
 
                                $tagi = array('tag' => $val['tag']);
 
                                }
 
                                $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:
                        }
                                // finish tag:
-                       if ($type=='complete' || $type=='close')        {
+                       if ($type == 'complete' || $type == 'close') {
                                $oldtagi = $tagi;
                                $tagi = $stack[--$stacktop];
                                $oldtag = $oldtagi['tag'];
                                unset($oldtagi['tag']);
 
                                $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,
                                                $partArray = array_slice(
                                                        $vals,
-                                                       $startPoint+1,
-                                                       $key-$startPoint-1
+                                                               $startPoint + 1,
+                                                               $key - $startPoint - 1
                                                );
                                                #$oldtagi=array('XMLvalue'=>self::xmlRecompileFromStructValArray($partArray));
                                                );
                                                #$oldtagi=array('XMLvalue'=>self::xmlRecompileFromStructValArray($partArray));
-                                               $oldtagi['XMLvalue']=self::xmlRecompileFromStructValArray($partArray);
+                                               $oldtagi['XMLvalue'] = self::xmlRecompileFromStructValArray($partArray);
                                        } else {
                                        } else {
-                                               $oldtagi['XMLvalue']=$oldtagi['values'][0];
+                                               $oldtagi['XMLvalue'] = $oldtagi['values'][0];
                                        }
                                }
 
                                        }
                                }
 
@@ -2421,7 +2512,7 @@ final class t3lib_div {
                                unset($oldtagi);
                        }
                                // cdata
                                unset($oldtagi);
                        }
                                // cdata
-                       if($type=='cdata') {
+                       if ($type == 'cdata') {
                                $tagi['values'][] = $val['value'];
                        }
                }
                                $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()
         */
         * @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:
 
                        // 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'];
                                $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 {
                        } 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:
-               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()
         */
         * @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
                        // 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;
                        // Set indenting mode:
                $indentChar = $spaceInd ? ' ' : TAB;
-               $indentN = $spaceInd>0 ? $spaceInd : 1;
+               $indentN = $spaceInd > 0 ? $spaceInd : 1;
                $nl = ($spaceInd >= 0 ? LF : '');
 
                        // Init output variable:
                $nl = ($spaceInd >= 0 ? LF : '');
 
                        // Init output variable:
-               $output='';
+               $output = '';
 
                        // Traverse the input array
 
                        // Traverse the input array
-               foreach($array as $k=>$v)       {
+               foreach ($array as $k => $v) {
                        $attr = '';
                        $tagName = $k;
 
                                // Construct the tag name.
                        $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';
                                }
                                        $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 = $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 the value is an array then we will call this function recursively:
-                       if (is_array($v))       {
+                       if (is_array($v)) {
 
                                        // Sub elements:
 
                                        // 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;
                                        $clearStackPath = $subOptions['clearStackPath'];
                                } else {
                                        $subOptions = $options;
@@ -2539,31 +2630,31 @@ final class t3lib_div {
                                }
 
                                $content = $nl .
                                }
 
                                $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:
 
                                        // 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:
                                                // 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);
                                } else {
                                                // Otherwise, just htmlspecialchar the stuff:
                                        $content = htmlspecialchars($v);
@@ -2573,21 +2664,21 @@ final class t3lib_div {
                                                        $content = '<![CDATA[' . $v . ']]>';
                                                }
                                        } elseif (!$options['disableTypeAttrib']) {
                                                        $content = '<![CDATA[' . $v . ']]>';
                                                }
                                        } elseif (!$options['disableTypeAttrib']) {
-                                               $attr.= ' type="'.$dType.'"';
+                                               $attr .= ' type="' . $dType . '"';
                                        }
                                }
                        }
 
                                // Add the element to the output string:
                                        }
                                }
                        }
 
                                // 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 =
                        $output =
-                               '<'.$docTag.'>'.$nl.
-                               $output.
-                               '</'.$docTag.'>';
+                                       '<' . $docTag . '>' . $nl .
+                                                       $output .
+                                                       '</' . $docTag . '>';
                }
 
                return $output;
                }
 
                return $output;
@@ -2606,7 +2697,7 @@ final class t3lib_div {
         * @see array2xml(),xml2arrayProcess()
         * @author      Fabrizio Branca <typo3@fabrizio-branca.de> (added caching)
         */
         * @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'));
                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);
 
                        $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');
                        }
                                $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()
         */
         * @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:
                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();
 
                        // 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');
                $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:
 
                        // 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);
 
                }
                xml_parser_free($parser);
 
@@ -2674,63 +2765,67 @@ final class t3lib_div {
                $documentTag = '';
 
                        // Traverse the parsed XML structure:
                $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'];
 
                                // 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:
 
                                // 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":
 
                                // 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:
 
                                // 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:
 
                                // 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();
                                        $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];
                                        $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);
                                        $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] = 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:
 
                                                        // Cast type:
-                                               switch((string)$val['attributes']['type'])      {
+                                               switch ((string) $val['attributes']['type']) {
                                                        case 'integer':
                                                        case 'integer':
-                                                               $current[$tagName] = (integer)$current[$tagName];
-                                                       break;
+                                                               $current[$tagName] = (integer) $current[$tagName];
+                                                               break;
                                                        case 'double':
                                                        case 'double':
-                                                               $current[$tagName] = (double)$current[$tagName];
-                                                       break;
+                                                               $current[$tagName] = (double) $current[$tagName];
+                                                               break;
                                                        case 'boolean':
                                                        case 'boolean':
-                                                               $current[$tagName] = (bool)$current[$tagName];
-                                                       break;
+                                                               $current[$tagName] = (bool) $current[$tagName];
+                                                               break;
                                                        case 'array':
                                                        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;
                }
 
                        $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.
         */
         * @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:
                        $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:
                                }
                        }
                                // finish tag:
-                       if ($type=='close')     {
-                               $XMLcontent.='</'.$val['tag'].'>';
+                       if ($type == 'close') {
+                               $XMLcontent .= '</' . $val['tag'] . '>';
                        }
                                // cdata
                        }
                                // 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)
         */
         * @param       string          XML data
         * @return      array           Attributes of the xml prologue (header)
         */
-       public static function xmlGetHeaderAttribs($xmlData)    {
+       public static function xmlGetHeaderAttribs($xmlData) {
                $match = array();
                $match = array();
-               if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match))    {
+               if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
                        return self::get_tag_attributes($match[1]);
                }
        }
                        return self::get_tag_attributes($match[1]);
                }
        }
@@ -2809,7 +2908,7 @@ final class t3lib_div {
                        $error = '';
                        $script = trim(JSMin::minify(str_replace(CR, '', $script)));
                }
                        $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()));
                        $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
        /*************************
         *
         * 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.
         */
         * @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
                        $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();
                                $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.';
                                }
                                        $report['error'] = -1;
                                        $report['message'] = 'Couldn\'t initialize cURL.';
                                }
-                               return false;
+                               return FALSE;
                        }
 
                        curl_setopt($ch, CURLOPT_URL, $url);
                        }
 
                        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);
 
                                // 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>)
                                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']);
 
                                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']);
                                }
                                        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);
                                        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
                                        $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).';
                                                $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'];
                                                        // 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);
 
                        }
                        curl_close($ch);
 
-               } elseif ($includeHeader)       {
-                       if (isset($report))     {
+               } elseif ($includeHeader) {
+                       if (isset($report)) {
                                $report['lib'] = 'socket';
                        }
                        $parsedURL = parse_url($url);
                                $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.';
                                }
                                        $report['error'] = -1;
                                        $report['message'] = 'Reading headers is not allowed for this protocol.';
                                }
-                               return false;
+                               return FALSE;
                        }
                        $port = intval($parsedURL['port']);
                        }
                        $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 {
                                        $scheme = '';
                                } else {
-                                       $port = ($port>0 ? $port : 443);
+                                       $port = ($port > 0 ? $port : 443);
                                        $scheme = 'ssl://';
                                }
                        }
                        $errno = 0;
                                        $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.';
                                }
                                        $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";
                        }
                        $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);
                                $msg .= implode(CRLF, $requestHeaders) . CRLF;
                        }
                        $msg .= CRLF;
 
                        fputs($fp, $msg);
-                       while (!feof($fp))      {
+                       while (!feof($fp)) {
                                $line = fgets($fp, 2048);
                                $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];
                                        }
                                                $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;
                                                $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);
 
                                $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);
                                $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.';
                                }
                                        $report['error'] = -1;
                                        $report['message'] = 'Sending request headers is not allowed for this protocol.';
                                }
-                               return false;
+                               return FALSE;
                        }
                        $ctx = stream_context_create(array(
                        }
                        $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'];
                        }
                                $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);
                                $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'];
                                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.
         */
         * @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);
 
                        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);
                        }
 
                                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.
         *
        }
 
        /**
         * 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)
         * @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;
         */
        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
                        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
                                }
 
                                        // 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;
                                                // "@" 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) {
                                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);
                                                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
         *
         * @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);
 
                        // Parse filepath into directory and basename:
                $fI = pathinfo($filepath);
-               $fI['dirname'].= '/';
+               $fI['dirname'] .= '/';
 
                        // Check parts:
 
                        // 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:
 
                                                        // 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):
                                                }
                                                        // 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);
                                                                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.
         */
         * @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 = '';
                $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!
         */
         * @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);
                                }
                                        }
                                        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);
                        }
 
                                $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.
         */
         * @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);
                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
         */
         * @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();
 
                        // Initialize variabels:
                $filearray = array();
@@ -3257,33 +3380,39 @@ final class t3lib_div {
                $path = rtrim($path, '/');
 
                        // Find files+directories:
                $path = rtrim($path, '/');
 
                        // Find files+directories:
-               if (@is_dir($path))     {
+               if (@is_dir($path)) {
                        $extensionList = strtolower($extensionList);
                        $d = 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);
                                                $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();
                                                }
                                        }
                                }
                                $d->close();
-                       } else return 'error opening path: "'.$path.'"';
+                       } else {
+                               return 'error opening path: "' . $path . '"';
+                       }
                }
 
                        // Sort them:
                if ($order) {
                        asort($sortarray);
                }
 
                        // Sort them:
                if ($order) {
                        asort($sortarray);
-                       $newArr=array();
+                       $newArr = array();
                        foreach ($sortarray as $k => $v) {
                        foreach ($sortarray as $k => $v) {
-                               $newArr[$k]=$filearray[$k];
+                               $newArr[$k] = $filearray[$k];
                        }
                        }
-                       $filearray=$newArr;
+                       $filearray = $newArr;
                }
 
                        // Return result
                }
 
                        // 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.
         */
         * @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);
 
                $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))) {
+&