Small things
[Packages/TYPO3.CMS.git] / typo3 / sysext / cms / tslib / class.tslib_content.php
index 4b3fdbb..713ec7d 100755 (executable)
@@ -1,22 +1,22 @@
 <?php
 /***************************************************************
 *  Copyright notice
-*  
-*  (c) 1999-2003 Kasper Skaarhoj (kasper@typo3.com)
+*
+*  (c) 1999-2005 Kasper Skaarhoj (kasperYYYY@typo3.com)
 *  All rights reserved
 *
-*  This script is part of the TYPO3 project. The TYPO3 project is 
+*  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 
+*  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
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/
-/** 
+/**
  * Contains classes for Content Rendering based on TypoScript Template configuration
  *
  * $Id$
  * Revised for TYPO3 3.6 June/2003 by Kasper Skaarhoj
  * XHTML compliant
  *
- * class tslib_cObj                            :               All main TypoScript features, rendering of content objects (cObjects). This class is the backbone of TypoScript Template rendering.
+ * class tslib_cObj                    :               All main TypoScript features, rendering of content objects (cObjects). This class is the backbone of TypoScript Template rendering.
  * class tslib_controlTable            :               Makes a table CTABLE (TS cObject)
  * class tslib_tableOffset             :               Makes a table-offset (TS)
  * class tslib_frameset                        :               Generates framesets (TS)
  *
- * @author     Kasper Skaarhoj <kasper@typo3.com>
+ * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
  */
 /**
  * [CLASS/FUNCTION INDEX of SCRIPT]
  *
  *
  *
- *  242: class tslib_cObj 
- *  339:     function start($data,$table='')   
- *  354:     function setParent($data,$currentRecord)  
+ *  250: class tslib_cObj
+ *  344:     function start($data,$table='')
+ *  359:     function setParent($data,$currentRecord)
  *
  *              SECTION: CONTENT_OBJ:
- *  379:     function getCurrentVal()  
- *  390:     function setCurrentVal($value)    
- *  403:     function cObjGet($setup,$addKey='')       
- *  427:     function cObjGetSingle($name,$conf,$TSkey='__')   
+ *  384:     function getCurrentVal()
+ *  395:     function setCurrentVal($value)
+ *  408:     function cObjGet($setup,$addKey='')
+ *  432:     function cObjGetSingle($name,$conf,$TSkey='__')
  *
  *              SECTION: Functions rendering content objects (cObjects)
- *  566:     function HTML($conf)      
- *  577:     function TEXT($conf)      
- *  588:     function CLEARGIF($conf)  
- *  607:     function COBJ_ARRAY($conf,$ext='')        
- *  643:     function USER($conf,$ext='')      
- *  670:     function FILE($conf)      
- *  686:     function IMAGE($conf)     
- *  705:     function IMG_RESOURCE($conf)      
- *  717:     function IMGTEXT($conf) 
- * 1091:     function CONTENT($conf)   
- * 1144:     function RECORDS($conf)   
- * 1210:     function HMENU($conf)     
- * 1242:     function CTABLE ($conf)   
- * 1280:     function OTABLE ($conf)   
- * 1295:     function COLUMNS ($conf)  
- * 1374:     function HRULER ($conf)   
- * 1398:     function CASEFUNC ($conf)
- * 1423:     function LOAD_REGISTER($conf,$name)       
- * 1463:     function FORM($conf,$formData='')    
- * 1830:     function SEARCHRESULT($conf)      
- * 1987:     function PHP_SCRIPT($conf,$ext='')        
- * 2030:     function TEMPLATE($conf)  
- * 2174:     function MULTIMEDIA($conf)        
+ *  578:     function HTML($conf)
+ *  589:     function TEXT($conf)
+ *  600:     function CLEARGIF($conf)
+ *  619:     function COBJ_ARRAY($conf,$ext='')
+ *  655:     function USER($conf,$ext='')
+ *  682:     function FILE($conf)
+ *  698:     function IMAGE($conf)
+ *  717:     function IMG_RESOURCE($conf)
+ *  729:     function IMGTEXT($conf)
+ * 1125:     function CONTENT($conf)
+ * 1188:     function RECORDS($conf)
+ * 1266:     function HMENU($conf)
+ * 1298:     function CTABLE ($conf)
+ * 1336:     function OTABLE ($conf)
+ * 1351:     function COLUMNS ($conf)
+ * 1430:     function HRULER ($conf)
+ * 1455:     function CASEFUNC ($conf)
+ * 1480:     function LOAD_REGISTER($conf,$name)
+ * 1520:     function FORM($conf,$formData='')
+ * 1970:     function SEARCHRESULT($conf)
+ * 2135:     function PHP_SCRIPT($conf,$ext='')
+ * 2178:     function TEMPLATE($conf)
+ * 2329:     function MULTIMEDIA($conf)
  *
  *              SECTION: Various helper functions for content objects:
- * 2258:     function netprintApplication_offsiteLinkWrap($str,$imgConf,$conf) 
- * 2299:     function getFieldDefaultValue($noValueInsert, $fieldName, $defaultVal) 
- * 2317:     function cImage($file,$conf) 
- * 2344:     function imageLinkWrap($string,$imageFile,$conf) 
- * 2408:     function fileResource($fName)     
- * 2431:     function lastChanged($tstamp)     
- * 2448:     function linkWrap($content,$wrap) 
+ * 2418:     function netprintApplication_offsiteLinkWrap($str,$imgConf,$conf)
+ * 2459:     function getFieldDefaultValue($noValueInsert, $fieldName, $defaultVal)
+ * 2477:     function cImage($file,$conf)
+ * 2510:     function imageLinkWrap($string,$imageFile,$conf)
+ * 2575:     function fileResource($fName, $addParams='alt="" title=""')
+ * 2598:     function lastChanged($tstamp)
+ * 2615:     function linkWrap($content,$wrap)
+ * 2633:     function getAltParam($conf)
  *
  *              SECTION: HTML template processing functions
- * 2493:     function getSubpart($content, $marker)    
- * 2522:     function substituteSubpart($content,$marker,$subpartContent,$recursive=1) 
- * 2564:     function substituteMarker($content,$marker,$markContent)  
- * 2584:     function substituteMarkerArrayCached($content,$markContentArray=array(),$subpartContentArray=array(),$wrappedSubpartContentArray=array()) 
- * 2682:     function substituteMarkerArray($content,$markContentArray,$wrap='',$uppercase=0)  
- * 2703:     function substituteMarkerInObject(&$tree, $markContentArray) 
- * 2725:     function fillInMarkerArray($markContentArray, $row, $fieldList='', $nl2br=1, $prefix='FIELD_')    
+ * 2690:     function getSubpart($content, $marker)
+ * 2719:     function substituteSubpart($content,$marker,$subpartContent,$recursive=1)
+ * 2761:     function substituteMarker($content,$marker,$markContent)
+ * 2781:     function substituteMarkerArrayCached($content,$markContentArray=array(),$subpartContentArray=array(),$wrappedSubpartContentArray=array())
+ * 2879:     function substituteMarkerArray($content,$markContentArray,$wrap='',$uppercase=0)
+ * 2900:     function substituteMarkerInObject(&$tree, $markContentArray)
+ * 2923:     function fillInMarkerArray($markContentArray, $row, $fieldList='', $nl2br=TRUE, $prefix='FIELD_', $HSC=FALSE)
  *
  *              SECTION: "stdWrap" + sub functions
- * 2786:     function stdWrap($content,$conf)  
- * 2926:     function numRows($conf)   
- * 2946:     function listNum($content,$listNum,$char) 
- * 2966:     function checkIf($conf)   
- * 3029:     function filelist($data)  
- * 3108:     function clean_directory($theDir) 
- * 3126:     function HTMLparser_TSbridge($theValue, $conf)    
- * 3140:     function dataWrap($content,$wrap) 
- * 3153:     function insertData($str) 
- * 3182:     function substring($content,$options)     
- * 3200:     function crop($content,$options)  
- * 3226:     function textStyle($theValue, $conf) 
- * 3293:     function tableStyle($theValue, $conf) 
- * 3334:     function addParams($content,$conf) 
- * 3372:     function filelink($theValue, $conf)       
- * 3439:     function locDataJU($jumpUrl,$conf)        
- * 3470:     function calc($val)       
- * 3499:     function calcIntExplode($delim, $string)  
- * 3519:     function splitObj($value, $conf)  
- * 3574:     function parseFunc($theValue, $conf) 
- * 3668:     function _parseFunc ($theValue, $conf) 
- * 3870:     function encaps_lineSplit($theValue, $conf)       
- * 3953:     function http_makelinks($data,$conf)      
- * 4012:     function mailto_makelinks($data,$conf)    
- * 4057:     function getImgResource($file,$fileArray) 
+ * 2986:     function stdWrap($content,$conf)
+ * 3151:     function numRows($conf)
+ * 3172:     function listNum($content,$listNum,$char)
+ * 3192:     function checkIf($conf)
+ * 3255:     function filelist($data)
+ * 3334:     function clean_directory($theDir)
+ * 3352:     function HTMLparser_TSbridge($theValue, $conf)
+ * 3366:     function dataWrap($content,$wrap)
+ * 3379:     function insertData($str)
+ * 3409:     function prefixComment($str,$conf,$content)
+ * 3433:     function substring($content,$options)
+ * 3451:     function crop($content,$options)
+ * 3483:     function removeBadHTML($text, $conf)
+ * 3527:     function textStyle($theValue, $conf)
+ * 3594:     function tableStyle($theValue, $conf)
+ * 3635:     function addParams($content,$conf)
+ * 3678:     function filelink($theValue, $conf)
+ * 3745:     function locDataJU($jumpUrl,$conf)
+ * 3776:     function calc($val)
+ * 3805:     function calcIntExplode($delim, $string)
+ * 3825:     function splitObj($value, $conf)
+ * 3881:     function parseFunc($theValue, $conf, $ref='')
+ * 3991:     function _parseFunc ($theValue, $conf)
+ * 4193:     function encaps_lineSplit($theValue, $conf)
+ * 4276:     function http_makelinks($data,$conf)
+ * 4343:     function mailto_makelinks($data,$conf)
+ * 4406:     function getImgResource($file,$fileArray)
  *
  *              SECTION: Data retrieval etc.
- * 4229:     function getFieldVal($field)      
- * 4249:     function getData($string,$fieldArray)     
- * 4336:     function rootLineValue($key,$field,$slideBack=0,$altRootLine='')  
- * 4357:     function getGlobal($var) 
- * 4382:     function getKey($key,$arr)        
+ * 4583:     function getFieldVal($field)
+ * 4603:     function getData($string,$fieldArray)
+ * 4730:     function rootLineValue($key,$field,$slideBack=0,$altRootLine='')
+ * 4752:     function getGlobal($var, $source=NULL)
+ * 4777:     function getKey($key,$arr)
  *
  *              SECTION: Link functions (typolink)
- * 4437:     function typoLink($linktxt, $conf)        
- * 4682:     function typoLink_URL($conf)      
- * 4700:     function getTypoLink($label,$params,$urlParameters=array(),$target='')    
- * 4730:     function getTypoLink_URL($params,$urlParameters=array(),$target='')       
- * 4742:     function typolinkWrap($conf)      
- * 4755:     function currentPageUrl($urlParameters=array(),$id=0)     
+ * 4829:     function typoLink($linktxt, $conf)
+ * 5111:     function typoLink_URL($conf)
+ * 5129:     function getTypoLink($label,$params,$urlParameters=array(),$target='')
+ * 5159:     function getTypoLink_URL($params,$urlParameters=array(),$target='')
+ * 5171:     function typolinkWrap($conf)
+ * 5184:     function currentPageUrl($urlParameters=array(),$id=0)
+ * 5197:     function getClosestMPvalueForPage($pageId, $raw=FALSE)
  *
  *              SECTION: Miscellaneous functions, stand alone
- * 4799:     function wrap($content,$wrap,$char='|')   
- * 4815:     function noTrimWrap($content,$wrap)       
- * 4829:     function wrapSpace($content, $wrap)       
- * 4855:     function callUserFunction($funcName,$conf,$content)       
- * 4896:     function processParams($params)   
- * 4914:     function keywords($content)       
- * 4931:     function caseshift($theValue, $case)      
- * 4954:     function HTMLcaseshift($theValue, $case)  
- * 4983:     function bytes($sizeInBytes)      
- * 4994:     function calcAge($seconds,$labels)        
- * 5025:     function sendNotifyEmail($msg, $recipients, $cc, $email_from, $email_fromName='', $replyTo='')    
- * 5052:     function URLqMark($url,$params)   
- * 5068:     function checkEmail($email)       
- * 5080:     function clearTSProperties($TSArr,$propList)      
- * 5099:     function mergeTSRef($confArr,$prop)       
- * 5122:     function joinTSarrays($conf,$old_conf)    
- * 5145:     function gifBuilderTextBox($gifbuilderConf, $conf, $text) 
- * 5201:     function linebreaks($string,$chars,$maxLines=0)   
- * 5233:     function getUpdateJS($dataArray, $formName, $arrPrefix, $fieldList, $stripSlashes=1)      
+ * 5273:     function wrap($content,$wrap,$char='|')
+ * 5289:     function noTrimWrap($content,$wrap)
+ * 5303:     function wrapSpace($content, $wrap)
+ * 5329:     function callUserFunction($funcName,$conf,$content)
+ * 5370:     function processParams($params)
+ * 5388:     function keywords($content)
+ * 5405:     function caseshift($theValue, $case)
+ * 5430:     function HTMLcaseshift($theValue, $case)
+ * 5459:     function bytes($sizeInBytes,$labels)
+ * 5470:     function calcAge($seconds,$labels)
+ * 5501:     function sendNotifyEmail($msg, $recipients, $cc, $email_from, $email_fromName='', $replyTo='')
+ * 5528:     function URLqMark($url,$params)
+ * 5544:     function checkEmail($email)
+ * 5556:     function clearTSProperties($TSArr,$propList)
+ * 5575:     function mergeTSRef($confArr,$prop)
+ * 5598:     function joinTSarrays($conf,$old_conf)
+ * 5621:     function gifBuilderTextBox($gifbuilderConf, $conf, $text)
+ * 5677:     function linebreaks($string,$chars,$maxLines=0)
+ * 5708:     function getUpdateJS($dataArray, $formName, $arrPrefix, $fieldList)
  *
  *              SECTION: Database functions, making of queries
- * 5304:     function DBgetDelete($table, $uid)        
- * 5330:     function DBgetUpdate($table, $uid, $dataArr, $fieldList, $addSlashes=0)   
- * 5366:     function DBgetInsert($table, $pid, $dataArr, $fieldList, $addSlashes=0)   
- * 5398:     function DBcompileInsert($table,$fp,$vp)  
- * 5414:     function DBmayFEUserEdit($table,$row, $feUserRow, $allowedGroups='',$feEditSelf=0)        
- * 5454:     function DBmayFEUserEditSelect($table,$feUserRow,$allowedGroups='',$feEditSelf=0) 
- * 5494:     function enableFields($table,$show_hidden=0)      
- * 5517:     function getTreeList($id,$depth,$begin=0,$dontCheckEnableFields=0,$addSelectFields='',$moreWhereClauses='')       
- * 5551:     function whereSelectFromList($field,$value)       
- * 5568:     function mm_query($select,$local_table,$mm_table,$foreign_table,$endClause='')    
- * 5587:     function mm_query_uidList($select,$local_table_uidlist,$mm_table,$foreign_table='',$endClause='') 
- * 5603:     function searchWhere($sw,$searchFieldList,$prefixTableName='')    
- * 5638:     function getQuery($table,$conf)   
- * 5696:     function getWhere($table,$conf)   
- * 5764:     function checkPidArray($listArr)  
- * 5788:     function checkPid($uid)   
+ * 5777:     function DBgetDelete($table, $uid, $doExec=FALSE)
+ * 5809:     function DBgetUpdate($table, $uid, $dataArr, $fieldList, $doExec=FALSE)
+ * 5851:     function DBgetInsert($table, $pid, $dataArr, $fieldList, $doExec=FALSE)
+ * 5888:     function DBmayFEUserEdit($table,$row, $feUserRow, $allowedGroups='',$feEditSelf=0)
+ * 5928:     function DBmayFEUserEditSelect($table,$feUserRow,$allowedGroups='',$feEditSelf=0)
+ * 5968:     function enableFields($table,$show_hidden=0)
+ * 5992:     function getTreeList($id,$depth,$begin=0,$dontCheckEnableFields=FALSE,$addSelectFields='',$moreWhereClauses='', $prevId_array=array(), $recursionLevel=0)
+ * 6092:     function whereSelectFromList($field,$value)
+ * 6110:     function exec_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
+ * 6137:     function exec_mm_query_uidList($select,$local_table_uidlist,$mm_table,$foreign_table='',$whereClause='',$groupBy='',$orderBy='',$limit='')
+ * 6158:     function searchWhere($sw,$searchFieldList,$searchTable='')
+ * 6191:     function exec_getQuery($table, $conf)
+ * 6209:     function getQuery($table, $conf, $returnQueryArray=FALSE)
+ * 6288:     function getWhere($table,$conf, $returnQueryArray=FALSE)
+ * 6382:     function checkPidArray($listArr)
+ * 6405:     function checkPid($uid)
  *
  *              SECTION: Frontend editing functions
- * 5845:     function editPanel($content, $conf, $currentRecord='', $dataArr=array())  
- * 5999:     function editIcons($content,$params, $conf=array(), $currentRecord='', $dataArr=array(),$addUrlParamStr='')       
- * 6057:     function editPanelLinkWrap($string,$formName,$cmd,$currentRecord='',$confirm='')  
- * 6095:     function editPanelLinkWrap_doWrap($string,$url,$currentRecord)    
- * 6122:     function editPanelPreviewBorder($table,$row,$content,$thick)      
- * 6139:     function isDisabled($table,$row)  
+ * 6461:     function editPanel($content, $conf, $currentRecord='', $dataArr=array())
+ * 6626:     function editIcons($content,$params, $conf=array(), $currentRecord='', $dataArr=array(),$addUrlParamStr='')
+ * 6691:     function editPanelLinkWrap($string,$formName,$cmd,$currentRecord='',$confirm='')
+ * 6731:     function editPanelLinkWrap_doWrap($string,$url,$currentRecord)
+ * 6758:     function editPanelPreviewBorder($table,$row,$content,$thick)
+ * 6775:     function isDisabled($table,$row)
  *
  *
- * 6170: class tslib_frameset 
- * 6180:     function make($setup)     
- * 6217:     function frameParams($setup, $typeNum)    
- * 6252:     function framesetParams($setup)   
+ * 6806: class tslib_frameset
+ * 6816:     function make($setup)
+ * 6853:     function frameParams($setup, $typeNum)
+ * 6896:     function framesetParams($setup)
  *
  *
- * 6285: class tslib_tableOffset       
- * 6297:     function start($content,$offset)  
+ * 6929: class tslib_tableOffset
+ * 6941:     function start($content,$offset)
  *
  *
- * 6375: class tslib_controlTable      
- * 6410:     function start($offset,$cMargins) 
+ * 7019: class tslib_controlTable
+ * 7054:     function start($offset,$cMargins)
  *
- * TOTAL FUNCTIONS: 125
+ * TOTAL FUNCTIONS: 129
  * (This index is automatically created/updated by the extension "extdeveval")
  *
  */
 
 
   // Includes this class since it is used for parsing HTML
-require_once (PATH_t3lib."class.t3lib_parsehtml.php");
+require_once(PATH_t3lib."class.t3lib_parsehtml.php");
 
+       // Object TypoScript library included:
+if(t3lib_extMgm::isLoaded('obts')) {
+       require_once(t3lib_extMgm::extPath('obts').'_tsobject/_tso.php');
+}
 
 
 
@@ -229,24 +237,20 @@ require_once (PATH_t3lib."class.t3lib_parsehtml.php");
  * This class contains all main TypoScript features.
  * This includes the rendering of TypoScript content objects (cObjects).
  * Is the backbone of TypoScript Template rendering.
- * 
+ *
  * There are lots of functions you can use from your include-scripts.
  * The class "tslib_cObj" is normally instantiated and referred to as "cObj".
  * When you call your own PHP-code typically through a USER or USER_INT cObject then it is this class that instantiates the object and calls the main method. Before it does so it will set (if you are using classes) a reference to itself in the internal variable "cObj" of the object. Thus you can access all functions and data from this class by $this->cObj->... from within you classes written to be USER or USER_INT content objects.
- * 
- * @author     Kasper Skaarhoj <kasper@typo3.com>
+ *
+ * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
  * @package TYPO3
  * @subpackage tslib
  * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&cHash=4ad9d7acb4
  */
 class tslib_cObj {
        var $align = Array ('center', 'right', 'left');
-       var $caseConvStrings = array(
-                       'áéúíâêûôîæøåäöü', 
-                       'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ'
-               );
 
-       /** 
+       /**
         * Holds ImageMagick parameters and extensions used for compression
         *
         * @see IMGTEXT()
@@ -283,7 +287,7 @@ class tslib_cObj {
                28 => Array('params'=>'-quality 20', 'ext'=>'jpg')
        );
 
-       /** 
+       /**
         * ImageMagick parameters for image effects
         *
         * @see IMGTEXT()
@@ -299,24 +303,24 @@ class tslib_cObj {
                25 => '-gamma 1.3',
                26 => '-gamma 0.8'
        );
-       
-       /** 
+
+       /**
         * Loaded with the current data-record.
         *
         * If the instance of this class is used to render records from the database those records are found in this array.
         * The function stdWrap has TypoScript properties that fetch field-data from this array.
         * @see init()
         */
-       var $data = Array();                    
-       var $oldData = Array();                 // Used for backup...
-       var $alternativeData ='';               // If this is set with an array before stdWrap, it's used instead of $this->data in the data-property in stdWrap
-       var $parameters = Array();              // Used by the parseFunc function and is loaded with tag-parameters when parsing tags.
+       var $data = Array();
+       var $oldData = Array();                         // Used for backup...
+       var $alternativeData ='';                       // If this is set with an array before stdWrap, it's used instead of $this->data in the data-property in stdWrap
+       var $parameters = Array();                      // Used by the parseFunc function and is loaded with tag-parameters when parsing tags.
        var $currentValKey = 'currentValue_kidjls9dksoje';
-       var $currentRecord = '';                // This is set to the [table]:[uid] of the record delivered in the $data-array, if the cObjects CONTENT or RECORD is in operation. Note that $GLOBALS['TSFE']->currentRecord is set to an equal value but always indicating the latest record rendered.
-       var $currentRecordTotal=0;              // Set in cObj->RECORDS and cObj->CONTENT to the current number of records selected in a query.
-       var $currentRecordNumber=0;             // Incremented in cObj->RECORDS and cObj->CONTENT before each record rendering.
-       var $parentRecordNumber=0;              // Incremented in parent cObj->RECORDS and cObj->CONTENT before each record rendering.
-       var $parentRecord=array();              // If the tslib_cObj was started from CONTENT, RECORD or SEARCHRESULT cObject's this array has two keys, 'data' and 'currentRecord' which indicates the record and data for the parent cObj.
+       var $currentRecord = '';                        // This is set to the [table]:[uid] of the record delivered in the $data-array, if the cObjects CONTENT or RECORD is in operation. Note that $GLOBALS['TSFE']->currentRecord is set to an equal value but always indicating the latest record rendered.
+       var $currentRecordTotal = 0;            // Set in cObj->RECORDS and cObj->CONTENT to the current number of records selected in a query.
+       var $currentRecordNumber = 0;           // Incremented in cObj->RECORDS and cObj->CONTENT before each record rendering.
+       var $parentRecordNumber = 0;            // Incremented in parent cObj->RECORDS and cObj->CONTENT before each record rendering.
+       var $parentRecord = array();            // If the tslib_cObj was started from CONTENT, RECORD or SEARCHRESULT cObject's this array has two keys, 'data' and 'currentRecord' which indicates the record and data for the parent cObj.
        var $regObj;            // This may be set as a reference to the calling object of eg. cObjGetSingle. Anyway, just use it as you like. It's used in productsLib.inc for example.
 
        // internal
@@ -326,15 +330,16 @@ class tslib_cObj {
        var $lastTypoLinkUrl='';        // This will be set by typoLink() to the url of the most recent link created.
        var $lastTypoLinkTarget='';     // DO. link target.
        var $substMarkerCache=array();  // Caching substituteMarkerArrayCached function
-       
+       var $recordRegister=array();    // Array that registers rendered content elements (or any table) to make sure they are not rendered recursively!
+
        /**
         * Class constructor.
         * Well, it has to be called manually since it is not a real constructor function.
         * So after making an instance of the class, call this function and pass to it a database record and the tablename from where the record is from. That will then become the "current" record loaded into memory and accessed by the .fields property found in eg. stdWrap.
-        * 
+        *
         * @param       array           $data   the record data that is rendered.
         * @param       string          $table  the table that the data record is from.
-        * @return      void            
+        * @return      void
         */
        function start($data,$table='') {
                $this->data = $data;
@@ -345,17 +350,17 @@ class tslib_cObj {
        /**
         * Sets the internal variable parentRecord with information about current record.
         * If the tslib_cObj was started from CONTENT, RECORD or SEARCHRESULT cObject's this array has two keys, 'data' and 'currentRecord' which indicates the record and data for the parent cObj.
-        * 
+        *
         * @param       array           $data: The record array
         * @param       string          $currentRecord: This is set to the [table]:[uid] of the record delivered in the $data-array, if the cObjects CONTENT or RECORD is in operation. Note that $GLOBALS['TSFE']->currentRecord is set to an equal value but always indicating the latest record rendered.
-        * @return      void            
+        * @return      void
         * @access private
         */
        function setParent($data,$currentRecord)        {
                $this->parentRecord=array('data'=>$data, 'currentRecord'=>$currentRecord);
        }
-       
-       
+
+
 
 
 
@@ -373,7 +378,7 @@ class tslib_cObj {
         * The "current" value is just an internal variable that can be used by functions to pass a single value on to another function later in the TypoScript processing.
         * It's like "load accumulator" in the good old C64 days... basically a "register" you can use as you like.
         * The TSref will tell if functions are setting this value before calling some other object so that you know if it holds any special information.
-        * 
+        *
         * @return      mixed           The "current" value
         */
        function getCurrentVal()        {
@@ -382,9 +387,9 @@ class tslib_cObj {
 
        /**
         * Sets the "current" value.
-        * 
+        *
         * @param       mixed           The variable that you want to set as "current"
-        * @return      void            
+        * @return      void
         * @see getCurrentVal()
         */
        function setCurrentVal($value)  {
@@ -394,7 +399,7 @@ class tslib_cObj {
        /**
         * Rendering of a "numerical array" of cObjects from TypoScript
         * Will call ->cObjGetSingle() for each cObject found and accumulate the output.
-        * 
+        *
         * @param       array           $setup: Array with cObjects as values.
         * @param       string          $addKey: A prefix for the debugging information
         * @return      string          Rendered output from the cObjects in the array.
@@ -417,7 +422,7 @@ class tslib_cObj {
 
        /**
         * Renders a content object
-        * 
+        *
         * @param       string          The content object name, eg. "TEXT" or "USER" or "IMAGE"
         * @param       array           The array with TypoScript properties for the content object
         * @param       string          A string label used for the internal debugging tracking.
@@ -448,93 +453,100 @@ class tslib_cObj {
                                        $content.=$this->cObjGetSingle($name,$conf,$key);
                                $GLOBALS['TT']->decStackPointer();
                        } else {
-                               switch($name)   {
-                                       case 'COBJ_ARRAY':
-                                       case 'COA':
-                                               $content.=$this->COBJ_ARRAY($conf);
-                                       break;
-                                       case 'COA_INT':
-                                               $content.=$this->COBJ_ARRAY($conf,'INT');
-                                       break;
-                                       case 'HTML':
-                                               $content.=$this->HTML($conf);
-                                       break;
-                                       case 'TEXT':
-                                               $content.=$this->TEXT($conf);
-                                       break;
-                                       case 'CLEARGIF':
-                                               $content.=$this->CLEARGIF($conf);
-                                       break;
-                                       case 'FILE':
-                                               $content.=$this->FILE($conf);
-                                       break;
-                                       case 'IMAGE':
-                                               $content.=$this->IMAGE($conf);
-                                       break;
-                                       case 'IMG_RESOURCE':
-                                               $content.=$this->IMG_RESOURCE($conf);
-                                       break;
-                                       case 'IMGTEXT':
-                                               $content.=$this->IMGTEXT($conf);
-                                       break;
-                                       case 'CONTENT':
-                                               $content.=$this->CONTENT($conf);
-                                       break;
-                                       case 'RECORDS':
-                                               $content.=$this->RECORDS($conf);
-                                       break;
-                                       case 'HMENU':
-                                               $content.=$this->HMENU($conf);
-                                       break;
-                                       case 'CTABLE':
-                                               $content.=$this->CTABLE($conf);
-                                       break;
-                                       case 'OTABLE':
-                                               $content.=$this->OTABLE($conf);
-                                       break;
-                                       case 'COLUMNS':
-                                               $content.=$this->COLUMNS($conf);
-                                       break;
-                                       case 'HRULER':
-                                               $content.=$this->HRULER($conf);
-                                       break;
-                                       case 'CASE':
-                                               $content.=$this->CASEFUNC($conf);
-                                       break;
-                                       case 'LOAD_REGISTER':
-                                       case 'RESTORE_REGISTER':
-                                               $this->LOAD_REGISTER($conf,$name);
-                                       break;
-                                       case 'FORM':
-                                               $content.=$this->FORM($conf);
-                                       break;
-                                       case 'SEARCHRESULT':
-                                               $content.=$this->SEARCHRESULT($conf);
-                                       break;
-                                       case 'PHP_SCRIPT':
-                                               $content.=$this->PHP_SCRIPT($conf);
-                                       break;
-                                       case 'PHP_SCRIPT_EXT':
-                                               $content.=$this->PHP_SCRIPT($conf,'EXT');
-                                       break;
-                                       case 'PHP_SCRIPT_INT':
-                                               $content.=$this->PHP_SCRIPT($conf,'INT');
-                                       break;
-                                       case 'USER':
-                                               $content.=$this->USER($conf);
-                                       break;
-                                       case 'USER_INT':
-                                               $content.=$this->USER($conf,'INT');
-                                       break;
-                                       case 'TEMPLATE':
-                                               $content.=$this->TEMPLATE($conf);
-                                       break;
-                                       case 'EDITPANEL':
-                                               if ($GLOBALS['TSFE']->beUserLogin)      {$content.=$this->editPanel($content, $conf);}
-                                       break;
-                                       case 'MULTIMEDIA':
-                                               $content.=$this->MULTIMEDIA($conf);
-                                       break;
+
+                                       // Object TypoScript hook:
+                               if(t3lib_extMgm::isLoaded('obts') && isset($GLOBALS['OBTS']['tso_list'][$name])) {
+                                       $content.= obts_dtutil::renderDatatypeContent($name, $GLOBALS['OBTS']['tso_list'][$name], $conf, $this);
+                               } else {
+                                               // Traditional Content Object branching:
+                                       switch($name)   {
+                                               case 'COBJ_ARRAY':
+                                               case 'COA':
+                                                       $content.=$this->COBJ_ARRAY($conf);
+                                               break;
+                                               case 'COA_INT':
+                                                       $content.=$this->COBJ_ARRAY($conf,'INT');
+                                               break;
+                                               case 'HTML':
+                                                       $content.=$this->HTML($conf);
+                                               break;
+                                               case 'TEXT':
+                                                       $content.=$this->TEXT($conf);
+                                               break;
+                                               case 'CLEARGIF':
+                                                       $content.=$this->CLEARGIF($conf);
+                                               break;
+                                               case 'FILE':
+                                                       $content.=$this->FILE($conf);
+                                               break;
+                                               case 'IMAGE':
+                                                       $content.=$this->IMAGE($conf);
+                                               break;
+                                               case 'IMG_RESOURCE':
+                                                       $content.=$this->IMG_RESOURCE($conf);
+                                               break;
+                                               case 'IMGTEXT':
+                                                       $content.=$this->IMGTEXT($conf);
+                                               break;
+                                               case 'CONTENT':
+                                                       $content.=$this->CONTENT($conf);
+                                               break;
+                                               case 'RECORDS':
+                                                       $content.=$this->RECORDS($conf);
+                                               break;
+                                               case 'HMENU':
+                                                       $content.=$this->HMENU($conf);
+                                               break;
+                                               case 'CTABLE':
+                                                       $content.=$this->CTABLE($conf);
+                                               break;
+                                               case 'OTABLE':
+                                                       $content.=$this->OTABLE($conf);
+                                               break;
+                                               case 'COLUMNS':
+                                                       $content.=$this->COLUMNS($conf);
+                                               break;
+                                               case 'HRULER':
+                                                       $content.=$this->HRULER($conf);
+                                               break;
+                                               case 'CASE':
+                                                       $content.=$this->CASEFUNC($conf);
+                                               break;
+                                               case 'LOAD_REGISTER':
+                                               case 'RESTORE_REGISTER':
+                                                       $this->LOAD_REGISTER($conf,$name);
+                                               break;
+                                               case 'FORM':
+                                                       $content.=$this->FORM($conf);
+                                               break;
+                                               case 'SEARCHRESULT':
+                                                       $content.=$this->SEARCHRESULT($conf);
+                                               break;
+                                               case 'PHP_SCRIPT':
+                                                       $content.=$this->PHP_SCRIPT($conf);
+                                               break;
+                                               case 'PHP_SCRIPT_EXT':
+                                                       $content.=$this->PHP_SCRIPT($conf,'EXT');
+                                               break;
+                                               case 'PHP_SCRIPT_INT':
+                                                       $content.=$this->PHP_SCRIPT($conf,'INT');
+                                               break;
+                                               case 'USER':
+                                                       $content.=$this->USER($conf);
+                                               break;
+                                               case 'USER_INT':
+                                                       $content.=$this->USER($conf,'INT');
+                                               break;
+                                               case 'TEMPLATE':
+                                                       $content.=$this->TEMPLATE($conf);
+                                               break;
+                                               case 'EDITPANEL':
+                                                       if ($GLOBALS['TSFE']->beUserLogin)      {$content.=$this->editPanel($content, $conf);}
+                                               break;
+                                               case 'MULTIMEDIA':
+                                                       $content.=$this->MULTIMEDIA($conf);
+                                               break;
+                                       }
                                }
                        }
                        if ($GLOBALS['TT']->LR) $GLOBALS['TT']->pull($content);
@@ -558,7 +570,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, HTML
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=349&cHash=d3fd0c70b4
@@ -569,7 +581,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, TEXT
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=350&cHash=b49de28f83
@@ -580,7 +592,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, CLEARGIF
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=355&cHash=70c0f19915
@@ -591,14 +603,14 @@ class tslib_cObj {
                $w = $w ? $w : 1;
                $h = $h ? $h : 1;
                $wrap = $conf['wrap'] ? $conf['wrap'] : '|<br />';
-               $theValue = $this->wrap('<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$w.'" height="'.$h.'" border="0" alt="" />', $wrap);
-               
+               $theValue = $this->wrap('<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$w.'" height="'.$h.'"'.$this->getBorderAttr(' border="0"').' alt="" title="" />', $wrap);
+
                return $this->stdWrap($theValue,$conf['stdWrap.']);
        }
 
        /**
         * Rendering the cObject, COBJ_ARRAY / COA and COBJ_ARRAY_INT
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @param       string          If "INT" then the cObject is a "COBJ_ARRAY_INT" (non-cached), otherwise just "COBJ_ARRAY" (cached)
         * @return      string          Output
@@ -611,7 +623,7 @@ class tslib_cObj {
                                $substKey = $ext.'_SCRIPT.'.$GLOBALS['TSFE']->uniqueHash();
                                $content.='<!--'.$substKey.'-->';
                                $GLOBALS['TSFE']->config[$ext.'incScript'][$substKey] = array(
-                                       'file'=>$incFile, 
+                                       'file'=>$incFile,
                                        'conf'=>$conf,
                                        'cObj'=>serialize($this),
                                        'type'=>'COA'
@@ -634,7 +646,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, USER and USER_INT
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @param       string          If "INT" then the cObject is a "USER_INT" (non-cached), otherwise just "USER" (cached)
         * @return      string          Output
@@ -647,10 +659,10 @@ class tslib_cObj {
                                $substKey = $ext.'_SCRIPT.'.$GLOBALS['TSFE']->uniqueHash();
                                $content.='<!--'.$substKey.'-->';
                                $GLOBALS['TSFE']->config[$ext.'incScript'][$substKey] = array(
-                                       'file'=>$incFile, 
-                                       'conf'=>$conf,
-                                       'cObj'=>serialize($this),
-                                       'type'=>'FUNC'
+                                       'file' => $incFile,
+                                       'conf' => $conf,
+                                       'cObj' => serialize($this),
+                                       'type' => 'FUNC'
                                );
                        break;
                        default:
@@ -662,13 +674,13 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, FILE
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=352&cHash=379c60f8bc
         */
        function FILE($conf)    {
-               $theValue = $this->fileResource($this->stdWrap($conf['file'],$conf['file.']));
+               $theValue = $this->fileResource($this->stdWrap($conf['file'],$conf['file.']), trim($this->getAltParam($conf)));
                if ($conf['linkWrap'])  {
                        $theValue = $this->linkWrap($theValue,$conf['linkWrap']);
                }
@@ -677,7 +689,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, IMAGE
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=353&cHash=440681ea56
@@ -696,7 +708,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, IMG_RESOURCE
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=354&cHash=46f9299706
@@ -709,7 +721,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, IMGTEXT
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=363&cHash=cf2969bce1
@@ -721,11 +733,11 @@ class tslib_cObj {
                }
                $imgList=trim($this->stdWrap($conf['imgList'],$conf['imgList.']));      // gets images
                if ($imgList)   {
-                       $imgs = explode(',',$imgList);
+                       $imgs = t3lib_div::trimExplode(',',$imgList);
                        $imgStart = intval($this->stdWrap($conf['imgStart'],$conf['imgStart.']));
-       
+
                        $imgCount= count($imgs)-$imgStart;
-       
+
                        $imgMax = intval($this->stdWrap($conf['imgMax'],$conf['imgMax.']));
                        if ($imgMax)    {
                                $imgCount = t3lib_div::intInRange($imgCount,0,$conf['imgMax']); // reduces the number of images.
@@ -747,20 +759,20 @@ class tslib_cObj {
                                while(list($ca_key,$ca_val)=each($captionArray))        {
                                        $captionArray[$ca_key] = $this->stdWrap(trim($captionArray[$ca_key]), $conf['captionSplit.']['stdWrap.']);
                                }
-                       }                       
-                       
+                       }
+
                        $tablecode='';
                        $position=$this->stdWrap($conf['textPos'],$conf['textPos.']);
 
                        $tmppos = $position&7;
-                       $contentPosition = $position&24; 
+                       $contentPosition = $position&24;
                        $align = $this->align[$tmppos];
                        $cap = ($caption)?1:0;
                        $txtMarg = intval($this->stdWrap($conf['textMargin'],$conf['textMargin.']));
                        if (!$conf['textMargin_outOfText'] && $contentPosition<16)      {
                                $txtMarg=0;
                        }
-                       
+
                        $cols = intval($this->stdWrap($conf['cols'],$conf['cols.']));
                        $rows = intval($this->stdWrap($conf['rows'],$conf['rows.']));
                        $colspacing = intval($this->stdWrap($conf['colSpace'],$conf['colSpace.']));
@@ -769,10 +781,10 @@ class tslib_cObj {
                        $border = intval($this->stdWrap($conf['border'],$conf['border.'])) ? 1:0;
                        $borderColor = $this->stdWrap($conf['borderCol'],$conf['borderCol.']);
                        $borderThickness = intval($this->stdWrap($conf['borderThick'],$conf['borderThick.']));
-                       
+
                        $borderColor=$borderColor?$borderColor:'black';
                        $borderThickness=$borderThickness?$borderThickness:1;
-                       
+
                        $caption_align = $this->stdWrap($conf['captionAlign'],$conf['captionAlign.']);
                        if (!$caption_align) {
                                $caption_align = $align;
@@ -787,16 +799,16 @@ class tslib_cObj {
                                if ($rowCount > $imgCount)      {$rowCount = $imgCount;}
                                $colCount = ($rowCount>1) ? ceil($imgCount / $rowCount) : $imgCount;
                        }
-                       
+
                                // max Width
                        $colRelations = trim($this->stdWrap($conf['colRelations'],$conf['colRelations.']));
                        $maxW = intval($this->stdWrap($conf['maxW'],$conf['maxW.']));
-                       
+
                        $maxWInText = intval($this->stdWrap($conf['maxWInText'],$conf['maxWInText.']));
                        if (!$maxWInText)       {       // If maxWInText is not set, it's calculated to the 70 % of the max...
                                $maxWInText = round($maxW/100*50);
                        }
-                       
+
                        if ($maxWInText && $contentPosition>=16)        {       // inText
                                $maxW = $maxWInText;
                        }
@@ -830,16 +842,12 @@ class tslib_cObj {
                        $image_compression = intval($this->stdWrap($conf['image_compression'],$conf['image_compression.']));
                        $image_effects = intval($this->stdWrap($conf['image_effects'],$conf['image_effects.']));
                        $image_frames = intval($this->stdWrap($conf['image_frames.']['key'],$conf['image_frames.']['key.']));
-                       
+
                                // fetches pictures
                        $splitArr=array();
                        $splitArr['imgObjNum']=$conf['imgObjNum'];
                        $splitArr = $GLOBALS['TSFE']->tmpl->splitConfArray($splitArr,$imgCount);
 
-                       $alttext = $this->stdWrap($conf['altText'],$conf['altText.']);
-                       if ($alttext) {
-                               $altP = ' alt="'.htmlspecialchars(strip_tags($alttext)).'"';
-                       }
                                // EqualHeight
                        $equalHeight = intval($this->stdWrap($conf['equalH'],$conf['equalH.']));
                        if ($equalHeight)       {       // Initiate gifbuilder object in order to get dimensions AND calculate the imageWidth's
@@ -864,7 +872,7 @@ class tslib_cObj {
                        $origImages=array();
                        for($a=0;$a<$imgCount;$a++)     {
                                $GLOBALS['TSFE']->register['IMAGE_NUM'] = $a;
-                               
+
                                $imgKey = $a+$imgStart;
                                $totalImagePath = $imgPath.$imgs[$imgKey];
                                $this->data[$this->currentValKey] = $totalImagePath;
@@ -879,7 +887,7 @@ class tslib_cObj {
                                                        $scale = $rowTotalMaxW / $totalMaxW;
                                                }
                                        }
-                                               // transfer info to the imageObject. Please note, that 
+                                               // transfer info to the imageObject. Please note, that
                                        $imgConf['file.']['height'] = round($equalHeight/$scale);
 
                                        unset($imgConf['file.']['width']);
@@ -894,7 +902,7 @@ class tslib_cObj {
                                        unset($imgConf['file.']['minH.']);
                                        $maxW = 0;      // setting this to zero, so that it doesn't disturb
                                }
-                               
+
                                if ($maxW) {
                                        if (count($colMaxW))    {
                                                $imgConf['file.']['maxW'] = $colMaxW[($a%$colCount)];
@@ -902,9 +910,9 @@ class tslib_cObj {
                                                $imgConf['file.']['maxW'] = $maxW;
                                        }
                                }
-                               
-                               if ($imgConf || $imgConf['file']) {
-                                       $imgConf['params'].=$altP;
+
+                                       // Image Object supplied:
+                               if (is_array($imgConf)) {
                                        if ($this->image_effects[$image_effects])       {
                                                $imgConf['file.']['params'].= ' '.$this->image_effects[$image_effects];
                                        }
@@ -926,10 +934,31 @@ class tslib_cObj {
                                                        unset($imgConf['file.']['ext.']);
                                                }
                                        }
-                                       $imgsTag[$imgKey] = $this->IMAGE($imgConf);
+
+                                               // "alt", "title" and "longdesc" attributes:
+                                       if (!strlen($imgConf['altText']) && !is_array($imgConf['altText.'])) {
+                                               $imgConf['altText'] = $conf['altText'];
+                                               $imgConf['altText.'] = $conf['altText.'];
+                                       }
+                                       if (!strlen($imgConf['titleText']) && !is_array($imgConf['titleText.'])) {
+                                               $imgConf['titleText'] = $conf['titleText'];
+                                               $imgConf['titleText.'] = $conf['titleText.'];
+                                       }
+                                       if (!strlen($imgConf['longdescURL']) && !is_array($imgConf['longdescURL.'])) {
+                                               $imgConf['longdescURL'] = $conf['longdescURL'];
+                                               $imgConf['longdescURL.'] = $conf['longdescURL.'];
+                                       }
                                } else {
-                                       $imgsTag[$imgKey] = $this->IMAGE(Array('params'=>$altP, 'file'=>$totalImagePath));      // currentValKey !!!
+                                       $imgConf = array(
+                                               'altText' => $conf['altText'],
+                                               'titleText' => $conf['titleText'],
+                                               'longdescURL' => $conf['longdescURL'],
+                                               'file' => $totalImagePath
+                                       );
                                }
+
+                               $imgsTag[$imgKey] = $this->IMAGE($imgConf);
+
                                        // Store the original filepath
                                $origImages[$imgKey]=$GLOBALS['TSFE']->lastImageInfo;
 
@@ -937,14 +966,14 @@ class tslib_cObj {
                                if ($GLOBALS['TSFE']->lastImageInfo[1]>$imageRowsMaxHeights[floor($a/$colCount)])       {
                                        $imageRowsMaxHeights[floor($a/$colCount)] = $GLOBALS['TSFE']->lastImageInfo[1];
                                }
-                       }                       
+                       }
                                // calculating the tableWidth:
                                // TableWidth problems: It creates problems if the pictures are NOT as wide as the tableWidth.
                        $tableWidth = max($imageRowsFinalWidths)+ $colspacing*($colCount-1) + $colCount*$border*$borderThickness*2;
-                       
+
                                // make table for pictures
                        $index=$imgStart;
-                       
+
                        $noRows = $this->stdWrap($conf['noRows'],$conf['noRows.']);
                        $noCols = $this->stdWrap($conf['noCols'],$conf['noCols.']);
                        if ($noRows) {$noCols=0;}       // noRows overrides noCols. They cannot exist at the same time.
@@ -965,24 +994,24 @@ class tslib_cObj {
                                // col- and rowspans calculated
                        $colspan = (($colspacing) ? $colCount*2-1 : $colCount);
                        $rowspan = (($rowspacing) ? $rowCount*2-1 : $rowCount) + $cap;
-                       
+
 
                                // Edit icons:
                        $editIconsHTML = $conf['editIcons']&&$GLOBALS['TSFE']->beUserLogin ? $this->editIcons('',$conf['editIcons'],$conf['editIcons.']) : '';
-                       
+
                                // strech out table:
                        $tablecode='';
                        $flag=0;
                        if ($conf['noStretchAndMarginCells']!=1)        {
                                $tablecode.='<tr>';
                                if ($txtMarg && $align=='right')        {       // If right aligned, the textborder is added on the right side
-                                       $tablecode.='<td rowspan="'.($rowspan+1).'" valign="top"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$txtMarg.'" height="1" alt="" />'.($editIconsHTML?'<br />'.$editIconsHTML:'').'</td>';
+                                       $tablecode.='<td rowspan="'.($rowspan+1).'" valign="top"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$txtMarg.'" height="1" alt="" title="" />'.($editIconsHTML?'<br />'.$editIconsHTML:'').'</td>';
                                        $editIconsHTML='';
                                        $flag=1;
                                }
                                $tablecode.='<td colspan="'.$colspan.'"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$tableWidth.'" height="1" alt="" /></td>';
                                if ($txtMarg && $align=='left') {       // If left aligned, the textborder is added on the left side
-                                       $tablecode.='<td rowspan="'.($rowspan+1).'" valign="top"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$txtMarg.'" height="1" alt="" />'.($editIconsHTML?'<br />'.$editIconsHTML:'').'</td>';
+                                       $tablecode.='<td rowspan="'.($rowspan+1).'" valign="top"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$txtMarg.'" height="1" alt="" title="" />'.($editIconsHTML?'<br />'.$editIconsHTML:'').'</td>';
                                        $editIconsHTML='';
                                        $flag=1;
                                }
@@ -990,19 +1019,19 @@ class tslib_cObj {
        //                      $tableWidth=0;
                                $tablecode.='</tr>';
                        }
-                               
+
                                // draw table
                        for ($c=0;$c<$rowCount;$c++) {  // Looping through rows. If 'noRows' is set, this is '1 time', but $rowCount_temp will hold the actual number of rows!
                                if ($c && $rowspacing)  {               // If this is NOT the first time in the loop AND if space is required, a row-spacer is added. In case of "noRows" rowspacing is done further down.
-                                       $tablecode.='<tr><td colspan="'.$colspan.'"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$rowspacing.'" border="0" alt="" /></td></tr>';
+                                       $tablecode.='<tr><td colspan="'.$colspan.'"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$rowspacing.'"'.$this->getBorderAttr(' border="0"').' alt="" title="" /></td></tr>';
                                }
                                $tablecode.='<tr>';     // starting row
                                for ($b=0; $b<$colCount_temp; $b++)     {       // Looping through the columns
                                        if ($b && $colspacing)  {               // If this is NOT the first iteration AND if column space is required. In case of "noCols", the space is done without a separate cell.
                                                if (!$noCols)   {
-                                                       $tablecode.='<td><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$colspacing.'" height="1" border="0" alt="" /></td>';
+                                                       $tablecode.='<td><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$colspacing.'" height="1"'.$this->getBorderAttr(' border="0"').' alt="" title="" /></td>';
                                                } else {
-                                                       $colSpacer='<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.($border?$colspacing-6:$colspacing).'" height="'.($imageRowsMaxHeights[$c]+($border?$borderThickness*2:0)).'" border="0" align="'.($border?'left':'top').'" alt="" />';
+                                                       $colSpacer='<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.($border?$colspacing-6:$colspacing).'" height="'.($imageRowsMaxHeights[$c]+($border?$borderThickness*2:0)).'"'.$this->getBorderAttr(' border="0"').' align="'.($border?'left':'top').'" alt="" title="" />';
                                                        $colSpacer='<td valign="top">'.$colSpacer.'</td>';      // added 160301, needed for the new "noCols"-table...
                                                        $tablecode.=$colSpacer;
                                                }
@@ -1015,11 +1044,11 @@ class tslib_cObj {
                                                $imgIndex = $index+$a*$colCount_temp;
                                                if ($imgsTag[$imgIndex])        {
                                                        if ($rowspacing && $noRows && $a) {             // Puts distance between the images IF "noRows" is set and this is the first iteration of the loop
-                                                               $tablecode.= '<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$rowspacing.'" alt="" /><br />';
+                                                               $tablecode.= '<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$rowspacing.'" alt="" title="" /><br />';
                                                        }
 
                                                        $imageHTML = $imgsTag[$imgIndex].'<br />';
-                                                       $Talign = (!trim($captionArray[$imgIndex]) && !$noRows && !$conf['netprintApplicationLink']) ? ' align="left"' : '';  // this is necessary if the tablerows are supposed to space properly together! "noRows" is excluded because else the images "layer" together. 
+                                                       $Talign = (!trim($captionArray[$imgIndex]) && !$noRows && !$conf['netprintApplicationLink']) ? ' align="left"' : '';  // this is necessary if the tablerows are supposed to space properly together! "noRows" is excluded because else the images "layer" together.
                                                        if ($border)    {$imageHTML='<table border="0" cellpadding="'.$borderThickness.'" cellspacing="0" bgcolor="'.$borderColor.'"'.$Talign.'><tr><td>'.$imageHTML.'</td></tr></table>';}             // break-tag added 160301  , ($noRows?'':' align="left"')  removed 160301, break tag removed 160301 (later...)
                                                        $imageHTML.=$editIconsHTML;             $editIconsHTML='';
                                                        if ($conf['netprintApplicationLink'])   {$imageHTML = $this->netprintApplication_offsiteLinkWrap($imageHTML,$origImages[$imgIndex],$conf['netprintApplicationLink.']);}
@@ -1040,7 +1069,7 @@ class tslib_cObj {
                                // Table-tag is inserted
                                $i=$contentPosition;
                                $table_align = (($i==16) ? 'align="'.$align.'"' : '');
-                               $tablecode = '<table'.($tableWidth?' width="'.$tableWidth.'"':'').' border="0" cellspacing="0" cellpadding="0" '.$table_align.'>'.$tablecode;
+                               $tablecode = '<table'.($tableWidth?' width="'.$tableWidth.'"':'').' border="0" cellspacing="0" cellpadding="0" '.$table_align.' class="imgtext-table">'.$tablecode;
                                if ($editIconsHTML)     {       // IF this value is not long since reset.
                                        $tablecode.='<tr><td colspan="'.$colspan.'">'.$editIconsHTML.'</td></tr>';
                                        $editIconsHTML='';
@@ -1055,17 +1084,17 @@ class tslib_cObj {
                        $spaceBelowAbove = intval($this->stdWrap($conf['spaceBelowAbove'],$conf['spaceBelowAbove.']));
                        switch ($contentPosition)       {
                                case '0':       // above
-                                       $output= '<div align="'.$align.'">'.$tablecode.'</div>'.$this->wrapSpace($content, $spaceBelowAbove.'|0');
+                                       $output= '<div style="text-align:'.$align.';">'.$tablecode.'</div>'.$this->wrapSpace($content, $spaceBelowAbove.'|0');
                                break;
                                case '8':       // below
-                                       $output= $this->wrapSpace($content, '0|'.$spaceBelowAbove).'<div align="'.$align.'">'.$tablecode.'</div>';
+                                       $output= $this->wrapSpace($content, '0|'.$spaceBelowAbove).'<div style="text-align:'.$align.';">'.$tablecode.'</div>';
                                break;
                                case '16':      // in text
                                        $output= $tablecode.$content;
                                break;
                                case '24':      // in text, no wrap
                                        $theResult = '';
-                                       $theResult.= '<table border="0" cellspacing="0" cellpadding="0"><tr>';
+                                       $theResult.= '<table border="0" cellspacing="0" cellpadding="0" class="imgtext-nowrap"><tr>';
                                        if ($align=='right')    {
                                                $theResult.= '<td valign="top">'.$content.'</td><td valign="top">'.$tablecode.'</td>';
                                        } else {
@@ -1078,12 +1107,17 @@ class tslib_cObj {
                } else {
                        $output= $content;
                }
+
+               if ($conf['stdWrap.']) {
+                       $output = $this->stdWrap($output, $conf['stdWrap.']);
+               }
+
                return $output;
        }
 
        /**
         * Rendering the cObject, CONTENT
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=356&cHash=9f3b5c6ba2
@@ -1091,9 +1125,9 @@ class tslib_cObj {
        function CONTENT($conf) {
                $theValue='';
 
-               $originalRec=$GLOBALS['TSFE']->currentRecord;   
+               $originalRec = $GLOBALS['TSFE']->currentRecord;
                if ($originalRec)       {               // If the currentRecord is set, we register, that this record has invoked this function. It's should not be allowed to do this again then!!
-                       $GLOBALS['TSFE']->recordRegister[md5($originalRec)]++;
+                       $GLOBALS['TSFE']->recordRegister[$originalRec]++;
                }
 
                if ($conf['table']=='pages' || substr($conf['table'],0,3)=='tt_' || substr($conf['table'],0,3)=='fe_' || substr($conf['table'],0,3)=='tx_' || substr($conf['table'],0,4)=='ttx_' || substr($conf['table'],0,5)=='user_')        {
@@ -1102,41 +1136,77 @@ class tslib_cObj {
                        $renderObjKey = $conf['renderObj'] ? 'renderObj' : '';
                        $renderObjConf = $conf['renderObj.'];
 
-                       $query = $this->getQuery($conf['table'],$conf['select.']);
-                       $res = @mysql(TYPO3_db,$query);
-                       if ($error = mysql_error())     {
-                               $GLOBALS['TT']->setTSlogMessage($error.':   '.$query,3);
-                       } else {
-                               $this->currentRecordTotal = mysql_num_rows($res);
-                               $GLOBALS['TT']->setTSlogMessage($query);
-                               $GLOBALS['TT']->setTSlogMessage('NUMROWS: '.mysql_num_rows($res));
-                               $cObj =t3lib_div::makeInstance('tslib_cObj');
-                               $cObj->setParent($this->data,$this->currentRecord);
-                               $this->currentRecordNumber=0;
-                               while ($row = mysql_fetch_assoc($res))  {
-                                       if (!$GLOBALS['TSFE']->recordRegister[md5($val['table'].':'.$val['id'])])       {
-                                               $this->currentRecordNumber++;
-                                               $cObj->parentRecordNumber=$this->currentRecordNumber;
-                                               $GLOBALS['TSFE']->currentRecord=$conf['table'].':'.$row['uid'];
-                                               $this->lastChanged($row['tstamp']);
-                                               $cObj->start($row,$conf['table']);
-                                               if ($GLOBALS['TSFE']->config['config']['insertDmailerBoundaries'])      {$theValue.='<!--DMAILER_SECTION_BOUNDARY_'.intval($row['module_sys_dmail_category']).'-->';}
-                                               $theValue.=$cObj->cObjGetSingle($renderObjName, $renderObjConf, $renderObjKey);
-                                       } else {debug($val['table'].':'.$val['id']);}
+                       $slide = intval($conf['slide'])?intval($conf['slide']):0;
+                       $slideCollect = intval($conf['slide.']['collect'])?intval($conf['slide.']['collect']):0;
+                       $slideCollectReverse = intval($conf['slide.']['collectReverse'])?true:false;
+                       $slideCollectFuzzy = $slideCollect?(intval($conf['slide.']['collectFuzzy'])?true:false):true;
+                       $again = false;
+
+                       do {
+                               $res = $this->exec_getQuery($conf['table'],$conf['select.']);
+                               if ($error = $GLOBALS['TYPO3_DB']->sql_error()) {
+                                       $GLOBALS['TT']->setTSlogMessage($error,3);
+                               } else {
+                                       $this->currentRecordTotal = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
+                                       $GLOBALS['TT']->setTSlogMessage('NUMROWS: '.$GLOBALS['TYPO3_DB']->sql_num_rows($res));
+                                       $cObj =t3lib_div::makeInstance('tslib_cObj');
+                                       $cObj->setParent($this->data,$this->currentRecord);
+                                       $this->currentRecordNumber=0;
+                                       $cobjValue = '';
+                                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+
+                                               // Versioning preview:
+                                               $GLOBALS['TSFE']->sys_page->versionOL($conf['table'],$row);
+
+                                               // Language Overlay:
+                                               if (is_array($row) && $GLOBALS['TSFE']->sys_language_contentOL) {
+                                               $row = $GLOBALS['TSFE']->sys_page->getRecordOverlay($conf['table'],$row,$GLOBALS['TSFE']->sys_language_content,$GLOBALS['TSFE']->sys_language_contentOL);
+                                               }
+
+                                               if (is_array($row)) { // Might be unset in the sys_language_contentOL
+                                                       if (!$GLOBALS['TSFE']->recordRegister[$conf['table'].':'.$row['uid']]) {
+                                                               $this->currentRecordNumber++;
+                                                               $cObj->parentRecordNumber = $this->currentRecordNumber;
+                                                               $GLOBALS['TSFE']->currentRecord = $conf['table'].':'.$row['uid'];
+                                                               $this->lastChanged($row['tstamp']);
+                                                               $cObj->start($row,$conf['table']);
+                                                               if ($GLOBALS['TSFE']->config['config']['insertDmailerBoundaries']) { $cobjValue.='<!--DMAILER_SECTION_BOUNDARY_'.intval($row['module_sys_dmail_category']).'-->'; }
+                                                               $tmpValue = $cObj->cObjGetSingle($renderObjName, $renderObjConf, $renderObjKey);
+                                                               $cobjValue .= $tmpValue;
+                                                       }# else debug($GLOBALS['TSFE']->recordRegister,'CONTENT');
+                                               }
+                                       }
+
+                                       if ($GLOBALS['TSFE']->config['config']['insertDmailerBoundaries']) { $cobjValue.='<!--DMAILER_SECTION_BOUNDARY_END-->'; }
                                }
-                               if ($GLOBALS['TSFE']->config['config']['insertDmailerBoundaries'])      {$theValue.='<!--DMAILER_SECTION_BOUNDARY_END-->';}
-                       }
+                               if ($slideCollectReverse) {
+                                       $theValue = $cobjValue.$theValue;
+                               } else {
+                                       $theValue .= $cobjValue;
+                               }
+                               if ($slideCollect>0) {
+                                       $slideCollect--;
+                               }
+                               if ($slide) {
+                                       if ($slide>0) {
+                                               $slide--;
+                                       }
+                                       $conf['select.']['pidInList'] = $this->getSlidePids($conf['select.']['pidInList'], $conf['select.']['pidInList.']);
+                                       $again = strlen($conf['select.']['pidInList'])?true:false;
+                               }
+                       } while ($again&&(($slide&&!strlen($tmpValue)&&$slideCollectFuzzy)||($slide&&$slideCollect)));
                }
-               
+
                $theValue = $this->wrap($theValue,$conf['wrap']);
                if ($conf['stdWrap.']) $theValue = $this->stdWrap($theValue,$conf['stdWrap.']);
-               $GLOBALS['TSFE']->currentRecord=$originalRec;
+
+               $GLOBALS['TSFE']->currentRecord = $originalRec; // Restore
                return $theValue;
        }
 
        /**
         * Rendering the cObject, RECORDS
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=357&cHash=303e959472
@@ -1144,9 +1214,9 @@ class tslib_cObj {
        function RECORDS($conf) {
                $theValue='';
 
-               $originalRec=$GLOBALS['TSFE']->currentRecord;   
+               $originalRec = $GLOBALS['TSFE']->currentRecord;
                if ($originalRec)       {               // If the currentRecord is set, we register, that this record has invoked this function. It's should not be allowed to do this again then!!
-                       $GLOBALS['TSFE']->recordRegister[md5($originalRec)]++;
+                       $GLOBALS['TSFE']->recordRegister[$originalRec]++;
                }
 
                $conf['source'] = $this->stdWrap($conf['source'],$conf['source.']);
@@ -1158,7 +1228,7 @@ class tslib_cObj {
                                        if (substr($k,-1)!='.')         $allowedTables.=','.$k;
                                }
                        }
-                       
+
                        $loadDB = t3lib_div::makeInstance('FE_loadDBGroup');
                        $loadDB->start($conf['source'], $allowedTables);
                        reset($loadDB->tableArray);
@@ -1179,30 +1249,42 @@ class tslib_cObj {
                        reset($loadDB->itemArray);
                        while(list(,$val)=each($loadDB->itemArray))     {
                                $row = $data[$val['table']][$val['id']];
-                               if (!$conf['dontCheckPid'])     {
-                                       $row = $this->checkPid($row['pid']) ? $row : '';
+
+                                       // Versioning preview:
+                               $GLOBALS['TSFE']->sys_page->versionOL($val['table'],$row);
+
+                                       // Language Overlay:
+                               if (is_array($row) && $GLOBALS['TSFE']->sys_language_contentOL) {
+                                       $row = $GLOBALS['TSFE']->sys_page->getRecordOverlay($val['table'],$row,$GLOBALS['TSFE']->sys_language_content,$GLOBALS['TSFE']->sys_language_contentOL);
                                }
-                               if ($row && !$GLOBALS['TSFE']->recordRegister[md5($val['table'].':'.$val['id'])])       {
-                                       $renderObjName = $conf['conf.'][$val['table']] ? $conf['conf.'][$val['table']] : '<'.$val['table'];
-                                       $renderObjKey = $conf['conf.'][$val['table']] ? 'conf.'.$val['table'] : '';
-                                       $renderObjConf = $conf['conf.'][$val['table'].'.'];
-                                       $this->currentRecordNumber++;
-                                       $GLOBALS['TSFE']->currentRecord=$val['table'].':'.$val['id'];
-                                       $this->lastChanged($row['tstamp']);
-                                       $cObj->start($row,$val['table']);
-                                       if ($GLOBALS['TSFE']->config['config']['insertDmailerBoundaries'])      {$theValue.='<!--DMAILER_SECTION_BOUNDARY_'.intval($row['module_sys_dmail_category']).'-->';}
-                                       $theValue.=$cObj->cObjGetSingle($renderObjName, $renderObjConf, $renderObjKey);
-                                       if ($GLOBALS['TSFE']->config['config']['insertDmailerBoundaries'])      {$theValue.='<!--DMAILER_SECTION_BOUNDARY_END-->';}
+
+                               if (is_array($row))     {       // Might be unset in the content overlay things...
+                                       if (!$conf['dontCheckPid'])     {
+                                               $row = $this->checkPid($row['pid']) ? $row : '';
+                                       }
+                                       if ($row && !$GLOBALS['TSFE']->recordRegister[$val['table'].':'.$val['id']])    {
+                                               $renderObjName = $conf['conf.'][$val['table']] ? $conf['conf.'][$val['table']] : '<'.$val['table'];
+                                               $renderObjKey = $conf['conf.'][$val['table']] ? 'conf.'.$val['table'] : '';
+                                               $renderObjConf = $conf['conf.'][$val['table'].'.'];
+                                               $this->currentRecordNumber++;
+                                               $cObj->parentRecordNumber=$this->currentRecordNumber;
+                                               $GLOBALS['TSFE']->currentRecord = $val['table'].':'.$val['id'];
+                                               $this->lastChanged($row['tstamp']);
+                                               $cObj->start($row,$val['table']);
+                                               if ($GLOBALS['TSFE']->config['config']['insertDmailerBoundaries'])      {$theValue.='<!--DMAILER_SECTION_BOUNDARY_'.intval($row['module_sys_dmail_category']).'-->';}
+                                               $theValue.=$cObj->cObjGetSingle($renderObjName, $renderObjConf, $renderObjKey);
+                                               if ($GLOBALS['TSFE']->config['config']['insertDmailerBoundaries'])      {$theValue.='<!--DMAILER_SECTION_BOUNDARY_END-->';}
+                                       }# else debug($GLOBALS['TSFE']->recordRegister,'RECORDS');
                                }
                        }
                }
-               $GLOBALS['TSFE']->currentRecord=$originalRec;
+               $GLOBALS['TSFE']->currentRecord = $originalRec; // Restore
                return $this->wrap($theValue,$conf['wrap']);
        }
 
        /**
         * Rendering the cObject, HMENU
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=358&cHash=5400c1c06a
@@ -1210,10 +1292,10 @@ class tslib_cObj {
        function HMENU($conf)   {
                $content='';
                if ($this->checkIf($conf['if.']))       {
-                       $cls=strtolower($conf[1]);
+                       $cls = strtolower($conf[1]);
                        if (t3lib_div::inList($GLOBALS['TSFE']->tmpl->menuclasses,$cls))        {
                                if ($conf['special.']['value.'])        {
-                                       $conf['special.']['value']  = $this->stdWrap($conf['special.']['value'],$conf['special.']['value.']);
+                                       $conf['special.']['value']  = $this->stdWrap($conf['special.']['value'], $conf['special.']['value.']);
                                }
                                $GLOBALS['TSFE']->register['count_HMENU']++;
                                $GLOBALS['TSFE']->register['count_HMENU_MENUOBJ']=0;
@@ -1222,7 +1304,7 @@ class tslib_cObj {
 
                                $menu = t3lib_div::makeInstance('tslib_'.$cls);
                                $menu->parent_cObj = $this;
-                               $menu->start($GLOBALS['TSFE']->tmpl,$GLOBALS['TSFE']->sys_page,'',$conf,1);
+                               $menu->start($GLOBALS['TSFE']->tmpl, $GLOBALS['TSFE']->sys_page, '', $conf, 1);
                                $menu->makeMenu();
                                $content.=$menu->writeMenu();
                        }
@@ -1234,7 +1316,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, CTABLE
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=359&cHash=2e0065b4e7
@@ -1272,7 +1354,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, OTABLE
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=360&cHash=02c9552d38
@@ -1287,7 +1369,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, COLUMNS
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=361&cHash=7e4e228cad
@@ -1338,17 +1420,17 @@ class tslib_cObj {
                                                if ($gapLine)   {
                                                        $gapSurround = t3lib_div::intInRange(($gapWidth-$gapLine)/2, 1, 1000);
                                                                // right gap
-                                                       $content.='<td'.$tdPar.'><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$gapSurround.'" height="1" alt="" /></td>';
+                                                       $content.='<td'.$tdPar.'><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$gapSurround.'" height="1" alt="" title="" /></td>';
                                                        $tdRowCount++;
                                                                // line:
                                                        $GtdPar = $gapConf['gapLineCol'] ? ' bgcolor="'.$gapConf['gapLineCol'].'"' : ' bgcolor="black"';
-                                                       $content.='<td'.$GtdPar.'><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$gapLine.'" height="1" alt="" /></td>';
+                                                       $content.='<td'.$GtdPar.'><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$gapLine.'" height="1" alt="" title="" /></td>';
                                                        $tdRowCount++;
                                                                // left gap
-                                                       $content.='<td'.$tdPar.'><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$gapSurround.'" height="1" alt="" /></td>';
+                                                       $content.='<td'.$tdPar.'><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$gapSurround.'" height="1" alt="" title="" /></td>';
                                                        $tdRowCount++;
                                                } else {
-                                                       $content.='<td'.$tdPar.'><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$gapWidth.'" height="1" alt="" /></td>';
+                                                       $content.='<td'.$tdPar.'><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$gapWidth.'" height="1" alt="" title="" /></td>';
                                                        $tdRowCount++;
                                                }
                                        }
@@ -1366,7 +1448,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, HRULER
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=362&cHash=2a462aa084
@@ -1376,12 +1458,13 @@ class tslib_cObj {
                $lineColor = $conf['lineColor'] ? $conf['lineColor'] : 'black';
                $spaceBefore = intval($conf['spaceLeft']);
                $spaceAfter = intval($conf['spaceRight']);
+               $tableWidth = $conf['tableWidth'] ? $conf['tableWidth'] : '99%';
                $content='';
-               
-               $content.='<table border="0" cellspacing="0" cellpadding="0" width="99%"><tr>';
-               if ($spaceBefore)       {$content.='<td width="1"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$spaceBefore.'" height="1" alt="" /></td>'; }
-               $content.='<td bgcolor="'.$lineColor.'"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$lineThickness.'" alt="" /></td>';
-               if ($spaceAfter)        {$content.='<td width="1"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$spaceAfter.'" height="1" alt="" /></td>'; }
+
+               $content.='<table border="0" cellspacing="0" cellpadding="0" width="'.htmlspecialchars($tableWidth).'"><tr>';
+               if ($spaceBefore)       {$content.='<td width="1"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$spaceBefore.'" height="1" alt="" title="" /></td>'; }
+               $content.='<td bgcolor="'.$lineColor.'"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$lineThickness.'" alt="" title="" /></td>';
+               if ($spaceAfter)        {$content.='<td width="1"><img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="'.$spaceAfter.'" height="1" alt="" title="" /></td>'; }
                $content.='</tr></table>';
 
                $content = $this->stdWrap($content, $conf['stdWrap.']);
@@ -1390,7 +1473,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, CASE
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=364&cHash=cffedd09e3
@@ -1405,7 +1488,7 @@ class tslib_cObj {
                        $theValue = $this->cObjGetSingle($name,$conf[$key.'.'], $key);
                        if ($conf['stdWrap.'])  {
                                $theValue = $this->stdWrap($theValue,$conf['stdWrap.']);
-                       }                       
+                       }
                        return $theValue;
                }
        }
@@ -1413,7 +1496,7 @@ class tslib_cObj {
        /**
         * Rendering the cObject, LOAD_REGISTER and RESTORE_REGISTER
         * NOTICE: This cObject does NOT return any content since it just sets internal data based on the TypoScript properties.
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @param       string          If "RESTORE_REGISTER" then the cObject rendered is "RESTORE_REGISTER", otherwise "LOAD_REGISTER"
         * @return      string          Empty string (the cObject only sets internal data!)
@@ -1442,19 +1525,19 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, FORM
-        * 
+        *
         * Note on $formData:
         * In the optional $formData array each entry represents a line in the ordinary setup.
         * In those entries each entry (0,1,2...) represents a space normally divided by the '|' line.
-        * 
+        *
         * $formData [] = array('Name:', 'name=input, 25 ', 'Default value....');
         * $formData [] = array('Email:', 'email=input, 25 ', 'Default value for email....');
-        * 
+        *
         * - corresponds to the $conf['data'] value being :
         * Name:|name=input, 25 |Default value....||Email:|email=input, 25 |Default value for email....
-        * 
+        *
         * If $formData is an array the value of $conf['data'] is ignored.
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @param       array           Alternative formdata overriding whatever comes from TypoScript
         * @return      string          Output
@@ -1472,12 +1555,13 @@ class tslib_cObj {
                        if (trim($data))        {
                                $data = ereg_replace(chr(10),'||',$data);
                                $dataArr = explode('||',$data);
-                       } 
+                       }
                                // Adding the new dataArray config form:
                        if (is_array($conf['dataArray.'])) {    // dataArray is supplied
-                               reset($conf['dataArray.']);
-                               while(list($dAKey,$dAA)=each($conf['dataArray.']))      {
-                                       if (is_array($dAA) && !strcmp(intval($dAKey).'.',$dAKey))       {
+                               $sKeyArray = t3lib_TStemplate::sortedKeyList($conf['dataArray.'], TRUE);
+                               foreach($sKeyArray as $theKey)  {
+                                       $dAA = $conf['dataArray.'][$theKey.'.'];
+                                       if (is_array($dAA))     {
                                                $temp=array();
                                                list($temp[0])= explode('|',$dAA['label.'] ? $this->stdWrap($dAA['label'],$dAA['label.']) : $dAA['label']);
                                                list($temp[1])= explode('|',$dAA['type']);
@@ -1498,27 +1582,37 @@ class tslib_cObj {
                                                        }
                                                        $temp[2] = implode(',',$temp_accum);
                                                }
-                                                       // adding the form entry to the dataArray 
+                                               list($temp[3])= explode('|',$dAA['specialEval.'] ? $this->stdWrap($dAA['specialEval'],$dAA['specialEval.']) : $dAA['specialEval']);
+
+                                                       // adding the form entry to the dataArray
                                                $dataArr[] = implode('|',$temp);
                                        }
                                }
                        }
                }
-               $attachmentCounter='';
-               $hiddenfields='';
-               $fieldlist=Array();
+
+               $attachmentCounter = '';
+               $hiddenfields = '';
+               $fieldlist = Array();
                $propertyOverride = Array();
                $fieldname_hashArray = Array();
-               $cc=0;
-               reset($dataArr);
-               while(list(,$val)=each($dataArr)) {
+               $cc = 0;
+
+                       // Formname;
+               $formname = $GLOBALS['TSFE']->uniqueHash();
+               if (ctype_digit($formname{0}))  {       // form name must start with a letter
+                       $formname = 'a'.$formname;
+               }
+
+               foreach($dataArr as $val)       {
+
                        $cc++;
                        $confData=Array();
                        if (is_array($formData)) {
                                $parts = $val;
-                               $val=1;    // true...
-                       } else {        
-                               $val=trim($val);
+                               $val = 1;    // true...
+                       } else {
+                               $val = trim($val);
                                $parts = explode('|',$val);
                        }
                        if ($val && strcspn($val,'#/')) {
@@ -1550,12 +1644,14 @@ class tslib_cObj {
                                        $confData['fieldname'] = str_replace(' ','_',trim($typeParts[0]));
                                }
                                $fieldCode='';
-                               
-                               
+
                                if ($conf['wrapFieldName'])     {
                                        $confData['fieldname'] = $this->wrap($confData['fieldname'],$conf['wrapFieldName']);
                                }
-                               
+
+                                       // Set field name as current:
+                               $this->setCurrentVal($confData['fieldname']);
+
                                        // Additional parameters
                                if (trim($confData['type']))    {
                                        $addParams=trim($conf['params']);
@@ -1564,50 +1660,65 @@ class tslib_cObj {
                                        }
                                        if (strcmp('',$addParams))      $addParams=' '.$addParams;
                                } else $addParams='';
-                               
+
+                                       // Accessibility: Set id = fieldname attribute:
+                               if ($conf['accessibility'])     {
+                                       $elementIdAttribute = ' id="'.$formname.'_'.md5($confData['fieldname']).'"';
+                               } else {
+                                       $elementIdAttribute = '';
+                               }
+
+                                       // Create form field based on configuration/type:
                                switch($confData['type'])       {
-                                       case'textarea':
+                                       case 'textarea':
                                                $cols=trim($fParts[1]) ? intval($fParts[1]) : 20;
                                                $compWidth = doubleval($conf['compensateFieldWidth'] ? $conf['compensateFieldWidth'] : $GLOBALS['TSFE']->compensateFieldWidth);
                                                $compWidth = $compWidth ? $compWidth : 1;
                                                $cols = t3lib_div::intInRange($cols*$compWidth, 1, 120);
-                                               
+
                                                $rows=trim($fParts[2]) ? t3lib_div::intInRange($fParts[2],1,30) : 5;
-                                               $wrap=trim($fParts[3]) ? ' wrap="'.trim($fParts[3]).'"' : ' wrap="virtual"';
-                                               $default = $this->getFieldDefaultValue($conf['noValueInsert'], $confData['fieldname'], trim($parts[2]));
-                                               $fieldCode=sprintf('<textarea name="%s" cols="%s" rows="%s"%s'.$addParams.'>%s</textarea>',
+                                               $wrap=trim($fParts[3]);
+                                               if ($conf['noWrapAttr'] || $wrap === 'disabled')        {
+                                                       $wrap='';
+                                               } else {
+                                                       $wrap = $wrap ? ' wrap="'.$wrap.'"' : ' wrap="virtual"';
+                                               }
+                                               $default = $this->getFieldDefaultValue($conf['noValueInsert'], $confData['fieldname'], str_replace('\n',chr(10),trim($parts[2])));
+                                               $fieldCode=sprintf('<textarea name="%s"'.$elementIdAttribute.' cols="%s" rows="%s"%s'.$addParams.'>%s</textarea>',
                                                        $confData['fieldname'], $cols, $rows, $wrap, t3lib_div::formatForTextarea($default));
                                        break;
-                                       case'input':
-                                       case'password':
+                                       case 'input':
+                                       case 'password':
                                                $size=trim($fParts[1]) ? intval($fParts[1]) : 20;
                                                $compWidth = doubleval($conf['compensateFieldWidth'] ? $conf['compensateFieldWidth'] : $GLOBALS['TSFE']->compensateFieldWidth);
                                                $compWidth = $compWidth ? $compWidth : 1;
                                                $size = t3lib_div::intInRange($size*$compWidth, 1, 120);
                                                $default = $this->getFieldDefaultValue($conf['noValueInsert'], $confData['fieldname'], trim($parts[2]));
+
                                                if ($confData['type']=='password')      {
                                                        $default='';
                                                }
 
                                                $max=trim($fParts[2]) ? ' maxlength="'.t3lib_div::intInRange($fParts[2],1,1000).'"' : "";
                                                $theType = $confData['type']=='input' ? 'text' : 'password';
-                                               
-                                               $fieldCode=sprintf('<input type="'.$theType.'" name="%s" size="%s"%s value="%s"'.$addParams.' />',
+
+                                               $fieldCode=sprintf('<input type="'.$theType.'" name="%s"'.$elementIdAttribute.' size="%s"%s value="%s"'.$addParams.' />',
                                                        $confData['fieldname'], $size, $max, htmlspecialchars($default));
+
                                        break;
-                                       case'file':
+                                       case 'file':
                                                $size=trim($fParts[1]) ? t3lib_div::intInRange($fParts[1],1,60) : 20;
-                                               $fieldCode=sprintf('<input type="file" name="%s" size="%s"'.$addParams.' />',
+                                               $fieldCode=sprintf('<input type="file" name="%s"'.$elementIdAttribute.' size="%s"'.$addParams.' />',
                                                        $confData['fieldname'], $size);
                                        break;
-                                       case'check':
+                                       case 'check':
                                                        // alternative default value:
                                                $default = $this->getFieldDefaultValue($conf['noValueInsert'], $confData['fieldname'], trim($parts[2]));
                                                $checked = $default ? ' checked="checked"' : '';
-                                               $fieldCode=sprintf('<input type="checkbox" value="%s" name="%s"%s'.$addParams.' />',
+                                               $fieldCode=sprintf('<input type="checkbox" value="%s" name="%s"'.$elementIdAttribute.'%s'.$addParams.' />',
                                                        1, $confData['fieldname'], $checked);
                                        break;
-                                       case'select':
+                                       case 'select':
                                                $option='';
                                                $valueParts = explode(',',$parts[2]);
                                                        // size
@@ -1615,7 +1726,7 @@ class tslib_cObj {
                                                $size=trim($fParts[1]) ? t3lib_div::intInRange($fParts[1],1,20) : 1;
                                                        // multiple
                                                $multiple = strtolower(trim($fParts[2]))=='m' ? ' multiple="multiple"' : '';
-                                               
+
                                                $items=array();         // Where the items will be
                                                $defaults=array(); //RTF
                                                for($a=0;$a<count($valueParts);$a++)    {
@@ -1640,12 +1751,12 @@ class tslib_cObj {
                                                for($a=0;$a<count($items);$a++) {
                                                        $option.='<option value="'.$items[$a][1].'"'.(in_array($items[$a][1],$defaults)?' selected="selected"':'').'>'.trim($items[$a][0]).'</option>'; //RTF
                                                }
-                                               
-                                               if ($multiple)  $confData['fieldname'].='[]';   // The fieldname must be prepended '[]' if multiple select. And the reason why it's prepended is, because the required-field list later must also have [] prepended. 
-                                               $fieldCode=sprintf('<select name="%s" size="%s"%s'.$addParams.'>%s</select>',
+
+                                               if ($multiple)  $confData['fieldname'].='[]';   // The fieldname must be prepended '[]' if multiple select. And the reason why it's prepended is, because the required-field list later must also have [] prepended.
+                                               $fieldCode=sprintf('<select name="%s"'.$elementIdAttribute.' size="%s"%s'.$addParams.'>%s</select>',
                                                        $confData['fieldname'], $size, $multiple, $option); //RTF
                                        break;
-                                       case'radio':
+                                       case 'radio':
                                                $option='';
                                                $valueParts = explode(',',$parts[2]);
                                                $items=array();         // Where the items will be
@@ -1666,19 +1777,25 @@ class tslib_cObj {
                                                $default = $this->getFieldDefaultValue($conf['noValueInsert'], $confData['fieldname'], $default);
                                                        // Create the select-box:
                                                for($a=0;$a<count($items);$a++) {
-                                                       $option.= '<input type="radio" name="'.$confData['fieldname'].'" value="'.$items[$a][1].'"'.(!strcmp($items[$a][1],$default)?' checked="checked"':'').''.$addParams.' />';
+                                                       $option.= '<input type="radio" name="'.$confData['fieldname'].'"'.$elementIdAttribute.' value="'.$items[$a][1].'"'.(!strcmp($items[$a][1],$default)?' checked="checked"':'').''.$addParams.' />';
                                                        $option.= $this->stdWrap(trim($items[$a][0]), $conf['radioWrap.']);
                                                        $option.= '<br />';
                                                }
-                                               $fieldCode=$option;
+                                               $fieldCode = $option;
                                        break;
                                        case 'hidden':
-                                               $value=trim($parts[2]);
-                                               $hiddenfields.=sprintf('<input type="hidden" name="%s" value="%s" />',
-                                                       $confData['fieldname'], $value);
+                                               $value = trim($parts[2]);
+                                               if(strlen($value) && t3lib_div::inList('recipient_copy,recipient',$confData['fieldname']) && $GLOBALS['TYPO3_CONF_VARS']['FE']['secureFormmail']) {
+                                                       break;
+                                               }
+                                               if (strlen($value) && t3lib_div::inList('recipient_copy,recipient',$confData['fieldname']))     {
+                                                       $value = $GLOBALS['TSFE']->codeString($value);
+                                               }
+                                               $hiddenfields.=sprintf('<input type="hidden" name="%s"'.$elementIdAttribute.' value="%s" />',
+                                                       $confData['fieldname'], htmlspecialchars($value));
                                        break;
                                        case 'property':
-                                               if (t3lib_div::inList('type,locationData,goodMess,badMess',$confData['fieldname']))     {
+                                               if (t3lib_div::inList('type,locationData,goodMess,badMess,emailMess',$confData['fieldname']))   {
                                                        $value=trim($parts[2]);
                                                        $propertyOverride[$confData['fieldname']] = $value;
                                                        $conf[$confData['fieldname']] = $value;
@@ -1692,26 +1809,73 @@ class tslib_cObj {
                                                } else $image='';
                                                if($image)      {
                                                        $fieldCode = str_replace('<img','<input type="image"'.$addParams.' name="'.$confData['fieldname'].'"' ,$image);
-                                               } else {
-                                                       $fieldCode=sprintf('<input type="submit" name="%s" value="%s"'.$addParams.' />',
-                                                               $confData['fieldname'], htmlspecialchars($value));
+                                               } else  {
+                                                       $fieldCode=sprintf('<input type="submit" name="%s"'.$elementIdAttribute.' value="%s"'.$addParams.' />',
+                                                               $confData['fieldname'], t3lib_div::deHSCentities(htmlspecialchars($value)));
                                                }
                                        break;
+                                       case 'reset':
+                                               $value=trim($parts[2]);
+                                               $fieldCode=sprintf('<input type="reset" name="%s"'.$elementIdAttribute.' value="%s"'.$addParams.' />',
+                                                       $confData['fieldname'], t3lib_div::deHSCentities(htmlspecialchars($value)));
+                                       break;
+                                       case 'label':
+                                               $fieldCode = nl2br(htmlspecialchars(trim($parts[2])));
+                                       break;
                                        default:
-                                               $confData['type']='comment';
-                                               $fieldCode=trim($parts[2]).'&nbsp;';
+                                               $confData['type'] = 'comment';
+                                               $fieldCode = trim($parts[2]).'&nbsp;';
                                        break;
                                }
                                if ($fieldCode) {
+
+                                               // Checking for special evaluation modes:
+                                       if (t3lib_div::inList('textarea,input,password',$confData['type']) && strlen(trim($parts[3])))  {
+                                               $modeParameters = t3lib_div::trimExplode(':',$parts[3]);
+                                       } else {
+                                               $modeParameters = array();
+                                       }
+
+                                               // Adding evaluation based on settings:
+                                       switch((string)$modeParameters[0])      {
+                                               case 'EREG':
+                                                       $fieldlist[] = '_EREG';
+                                                       $fieldlist[] = rawurlencode($modeParameters[1]);
+                                                       $fieldlist[] = rawurlencode($modeParameters[2]);
+                                                       $fieldlist[] = rawurlencode($confData['fieldname']);
+                                                       $fieldlist[] = rawurlencode($confData['label']);
+                                                       $confData['required'] = 1;      // Setting this so "required" layout is used.
+                                               break;
+                                               case 'EMAIL':
+                                                       $fieldlist[] = '_EMAIL';
+                                                       $fieldlist[] = rawurlencode($confData['fieldname']);
+                                                       $fieldlist[] = rawurlencode($confData['label']);
+                                                       $confData['required'] = 1;      // Setting this so "required" layout is used.
+                                               break;
+                                               default:
+                                                       if ($confData['required'] && $confData['type']!='check')        {
+                                                               $fieldlist[] = rawurlencode($confData['fieldname']);
+                                                               $fieldlist[] = rawurlencode($confData['label']);
+                                                       }
+                                               break;
+                                       }
+
+                                               // Field:
+                                       $fieldLabel = $confData['label'];
+                                       if ($conf['accessibility'])     {
+                                               $fieldLabel = '<label for="'.$formname.'_'.md5($confData['fieldname']).'">'.$fieldLabel.'</label>';
+                                       }
+
+                                               // Getting template code:
                                        $fieldCode = $this->stdWrap($fieldCode, $conf['fieldWrap.']);
-                                       $labelCode = $this->stdWrap($confData['label'], $conf['labelWrap.']);
+                                       $labelCode = $this->stdWrap($fieldLabel, $conf['labelWrap.']);
                                        $commentCode = $this->stdWrap($confData['label'], $conf['commentWrap.']); // RTF
                                        $result = $conf['layout'];
                                        if ($conf['REQ'] && $confData['required'])      {
                                                if (is_array($conf['REQ.']['fieldWrap.']))
                                                        $fieldCode = $this->stdWrap($fieldCode, $conf['REQ.']['fieldWrap.']);
                                                if (is_array($conf['REQ.']['labelWrap.']))
-                                                       $labelCode = $this->stdWrap($confData['label'], $conf['REQ.']['labelWrap.']);
+                                                       $labelCode = $this->stdWrap($fieldLabel, $conf['REQ.']['labelWrap.']);
                                                if ($conf['REQ.']['layout'])    {
                                                        $result = $conf['REQ.']['layout'];
                                                }
@@ -1725,15 +1889,13 @@ class tslib_cObj {
                                        if ($confData['type']=='radio' && $conf['RADIO.']['layout'])    {
                                                $result = $conf['RADIO.']['layout'];
                                        }
+                                       if ($confData['type']=='label' && $conf['LABEL.']['layout']) {
+                                               $result = $conf['LABEL.']['layout'];
+                                       }
                                        $result = str_replace('###FIELD###',$fieldCode,$result);
                                        $result = str_replace('###LABEL###',$labelCode,$result);
                                        $result = str_replace('###COMMENT###',$commentCode,$result); //RTF
-                                       $content.=$result;
-                                               // Required:
-                                       if ($confData['required'] && $confData['type']!='check')        {
-                                               $fieldlist[]=rawurlencode($confData['fieldname']);
-                                               $fieldlist[]=rawurlencode($confData['label']);
-                                       }
+                                       $content.= $result;
                                }
                        }
                }
@@ -1742,45 +1904,46 @@ class tslib_cObj {
 
                        // redirect (external: where to go afterwards. internal: where to submit to)
                $theRedirect = $this->stdWrap($conf['redirect'], $conf['redirect.']);                   // redirect should be set to the page to redirect to after an external script has been used. If internal scripts is used, and if no 'type' is set that dictates otherwise, redirect is used as the url to jump to as long as it's an integer (page)
-               $page=$GLOBALS['TSFE']->page;
+               $page = $GLOBALS['TSFE']->page;
                if (!$theRedirect)      {               // Internal: Just submit to current page
-                       $LD=$GLOBALS['TSFE']->tmpl->linkData($page, $conf['target'], $conf['no_cache'],'index.php');
+                       $LD = $GLOBALS['TSFE']->tmpl->linkData($page, $conf['target'], $conf['no_cache'],'index.php', '', $this->getClosestMPvalueForPage($page['uid']));
                } elseif (t3lib_div::testInt($theRedirect))     {               // Internal: Submit to page with id $theRedirect
                        $page = $GLOBALS['TSFE']->sys_page->getPage_noCheck($theRedirect);
-                       $LD=$GLOBALS['TSFE']->tmpl->linkData($page, $conf['target'], $conf['no_cache'],'index.php');
+                       $LD = $GLOBALS['TSFE']->tmpl->linkData($page, $conf['target'], $conf['no_cache'],'index.php', '', $this->getClosestMPvalueForPage($page['uid']));
                } else {        // External url, redirect-hidden field is rendered!
-                       $LD=$GLOBALS['TSFE']->tmpl->linkData($page, $conf['target'], $conf['no_cache'],'');
-                       $LD['totalURL']=$theRedirect;
-                       $hiddenfields.='<input type="hidden" name="redirect" value="'.htmlspecialchars($LD['totalURL']).'" />';         // 18-09-00 added
+                       $LD = $GLOBALS['TSFE']->tmpl->linkData($page, $conf['target'], $conf['no_cache'],'', '', $this->getClosestMPvalueForPage($page['uid']));
+                       $LD['totalURL'] = $theRedirect;
+                       $hiddenfields.= '<input type="hidden" name="redirect" value="'.htmlspecialchars($LD['totalURL']).'" />';                // 18-09-00 added
                }
 
                        // Formtype (where to submit to!):
                $formtype = $propertyOverride['type'] ? $propertyOverride['type'] : $this->stdWrap($conf['type'], $conf['type.']);
                if (t3lib_div::testInt($formtype))      {       // Submit to a specific page
                        $page = $GLOBALS['TSFE']->sys_page->getPage_noCheck($formtype);
-                       $LD_A=$GLOBALS['TSFE']->tmpl->linkData($page,$conf['target'],$conf['no_cache'],'');
-                       $action=$LD_A['totalURL'];
+                       $LD_A = $GLOBALS['TSFE']->tmpl->linkData($page, $conf['target'], $conf['no_cache'], '', '', $this->getClosestMPvalueForPage($page['uid']));
+                       $action = $LD_A['totalURL'];
                } elseif ($formtype){           // Submit to external script
-                       $LD_A=$LD;
+                       $LD_A = $LD;
                        $action = $formtype;
                } elseif (t3lib_div::testInt($theRedirect)) {
-                       $LD_A=$LD;
-                       $action=$LD_A['totalURL'];
+                       $LD_A = $LD;
+                       $action = $LD_A['totalURL'];
                } else {                // Submit to 'nothing' - which is current page
-                       $LD_A=$GLOBALS['TSFE']->tmpl->linkData($GLOBALS['TSFE']->page,$conf['target'],$conf['no_cache'],'');
-                       $action=$LD_A['totalURL'];
+                       $LD_A = $GLOBALS['TSFE']->tmpl->linkData($GLOBALS['TSFE']->page, $conf['target'], $conf['no_cache'], '', '', $this->getClosestMPvalueForPage($page['uid']));
+                       $action = $LD_A['totalURL'];
                }
 
-                       // copyemail:
+                       // Recipient:
                $theEmail = $this->stdWrap($conf['recipient'], $conf['recipient.']);
-               if ($theEmail)  {
+               if ($theEmail && !$GLOBALS['TYPO3_CONF_VARS']['FE']['secureFormmail'])  {
+                       $theEmail = $GLOBALS['TSFE']->codeString($theEmail);
                        $hiddenfields.='<input type="hidden" name="recipient" value="'.htmlspecialchars($theEmail).'" />';
                }
-               
+
                        // location data:
                if ($conf['locationData'])      {
-                       if ($conf['locationData']=='HTTP_POST_VARS' && isset($GLOBALS['HTTP_POST_VARS']['locationData']))       {
-                               $locationData = $GLOBALS['HTTP_POST_VARS']['locationData'];
+                       if ($conf['locationData']=='HTTP_POST_VARS' && isset($_POST['locationData']))   {
+                               $locationData = t3lib_div::_POST('locationData');
                        } else {
                                $locationData = $GLOBALS['TSFE']->id.':'.$this->currentRecord;  // locationData is [hte page id]:[tablename]:[uid of record]. Indicates on which page the record (from tablename with uid) is shown. Used to check access.
                        }
@@ -1790,21 +1953,28 @@ class tslib_cObj {
                        // hidden fields:
                if (is_array($conf['hiddenFields.']))   {
                        reset($conf['hiddenFields.']);
-                       while(list($hF_key,$hF_conf)=each($conf['hiddenFields.']))      {
+                       while(list($hF_key,$hF_conf) = each($conf['hiddenFields.']))    {
                                if (substr($hF_key,-1)!='.')    {
                                        $hF_value = $this->cObjGetSingle($hF_conf,$conf['hiddenFields.'][$hF_key.'.'],'hiddenfields');
+                                       if (strlen($hF_value) && t3lib_div::inList('recipient_copy,recipient',$hF_key)) {
+                                               if($GLOBALS['TYPO3_CONF_VARS']['FE']['secureFormmail']) {
+                                                       continue;
+                                               }
+                                               $hF_value = $GLOBALS['TSFE']->codeString($hF_value);
+                                       }
                                        $hiddenfields.='<input type="hidden" name="'.$hF_key.'" value="'.htmlspecialchars($hF_value).'" />';
                                }
                        }
                }
-               
-                       // Formname;
-               $formname = $GLOBALS['TSFE']->uniqueHash();
+
+                       // Wrap all hidden fields in a div tag (see http://bugs.typo3.org/view.php?id=678)
+               $hiddenfields = '<div style="display:none;">'.$hiddenfields.'</div>';
+
                if ($conf['REQ'])       {
-                       $validateForm=' onsubmit="return validateForm(\''.$formname.'\',\''.implode($fieldlist,',').'\',\''.rawurlencode($conf['goodMess']).'\',\''.rawurlencode($conf['badMess']).'\')"';
+                       $validateForm=' onsubmit="return validateForm(\''.$formname.'\',\''.implode(',',$fieldlist).'\',\''.rawurlencode($conf['goodMess']).'\',\''.rawurlencode($conf['badMess']).'\',\''.rawurlencode($conf['emailMess']).'\')"';
                        $GLOBALS['TSFE']->additionalHeaderData['JSFormValidate'] = '<script type="text/javascript" src="'.$GLOBALS['TSFE']->absRefPrefix.'t3lib/jsfunc.validateform.js"></script>';
                } else $validateForm='';
-               
+
                        // Create form tag:
                $theTarget = ($theRedirect?$LD['target']:$LD_A['target']);
                $content = Array(
@@ -1822,7 +1992,7 @@ class tslib_cObj {
                if ($conf['arrayReturnMode'])   {
                        $content['validateForm']=$validateForm;
                        $content['formname']=$formname;
-                       return $content;        
+                       return $content;
                } else {
                        return implode('',$content);
                }
@@ -1830,22 +2000,22 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, SEARCHRESULT
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=368&cHash=d00731cd7b
         */
        function SEARCHRESULT($conf)    {
-               if (t3lib_div::GPvar('sword') && t3lib_div::GPvar('scols'))     {
+               if (t3lib_div::_GP('sword') && t3lib_div::_GP('scols')) {
                        $search = t3lib_div::makeInstance('tslib_search');
-                       $search->register_and_explode_search_string(stripSlashes(t3lib_div::GPvar('sword')));
-                       $search->register_tables_and_columns(t3lib_div::GPvar('scols'),$conf['allowedCols']);
-                               // depth                
+                       $search->register_and_explode_search_string(t3lib_div::_GP('sword'));
+                       $search->register_tables_and_columns(t3lib_div::_GP('scols'),$conf['allowedCols']);
+                               // depth
                        $depth=100;
                                // the startId is found
                        $theStartId=0;
-                       if (t3lib_div::testInt(t3lib_div::GPvar('stype')))      {
-                               $temp_theStartId=t3lib_div::GPvar('stype');
+                       if (t3lib_div::testInt(t3lib_div::_GP('stype')))        {
+                               $temp_theStartId=t3lib_div::_GP('stype');
                                $rootLine = $GLOBALS['TSFE']->sys_page->getRootLine($temp_theStartId);
                                        // The page MUST have a rootline with the Level0-page of the current site inside!!
                                while(list(,$val)=each($rootLine))      {
@@ -1853,12 +2023,12 @@ class tslib_cObj {
                                                $theStartId=$temp_theStartId;
                                        }
                                }
-                       } else if (t3lib_div::GPvar('stype'))   {
-                               if (substr(t3lib_div::GPvar('stype'),0,1)=='L') {
-                                       $pointer = intval(substr(t3lib_div::GPvar('stype'),1));
+                       } else if (t3lib_div::_GP('stype'))     {
+                               if (substr(t3lib_div::_GP('stype'),0,1)=='L')   {
+                                       $pointer = intval(substr(t3lib_div::_GP('stype'),1));
                                        $theRootLine = $GLOBALS['TSFE']->tmpl->rootLine;
                                                // location Data:
-                                       $locDat_arr = explode(':',$GLOBALS['HTTP_POST_VARS']['locationData']);
+                                       $locDat_arr = explode(':',t3lib_div::_POST('locationData'));
                                        $pId = intval($locDat_arr[0]);
                                        if ($pId)       {
                                                $altRootLine = $GLOBALS['TSFE']->sys_page->getRootLine($pId);
@@ -1875,7 +2045,7 @@ class tslib_cObj {
                                                                }
                                                        }
                                                        if ($hitRoot)   {
-                                                               $theRootLine = $theNewRoot;             // Override the real rootline if any thing 
+                                                               $theRootLine = $theNewRoot;             // Override the real rootline if any thing
                                                        }
                                                }
                                        }
@@ -1885,60 +2055,68 @@ class tslib_cObj {
                        }
                        if (!$theStartId)       {
                                        // If not set, we use current page
-                               $theStartId=$GLOBALS['TSFE']->id;
+                               $theStartId = $GLOBALS['TSFE']->id;
                        }
                                // generate page-tree
-                       $search->pageIdList.=$this->getTreeList($theStartId,$depth);
-//                     debug($search->pageIdList);
-                       
-                       $endClause = "pages.uid IN (".$search->pageIdList.$theStartId.") AND pages.doktype in (".$GLOBALS['TYPO3_CONF_VARS']['FE']['content_doktypes'].($conf['addExtUrlsAndShortCuts']?',3,4':'').') AND pages.no_search=0';
-#debug($endClause);
-                       $endClause.=$this->enableFields($search->fTable).$this->enableFields('pages');
+                       $search->pageIdList.= $this->getTreeList(-1*$theStartId,$depth);
+
+                       $endClause = 'pages.uid IN ('.$search->pageIdList.')
+                               AND pages.doktype in ('.$GLOBALS['TYPO3_CONF_VARS']['FE']['content_doktypes'].($conf['addExtUrlsAndShortCuts']?',3,4':'').')
+                               AND pages.no_search=0'.
+                               $this->enableFields($search->fTable).
+                               $this->enableFields('pages');
+
+                       if ($conf['languageField.'][$search->fTable])   {
+                               $endClause.= ' AND '.$search->fTable.'.'.$conf['languageField.'][$search->fTable].' = '.intval($GLOBALS['TSFE']->sys_language_uid);     // (using sys_language_uid which is the ACTUAL language of the page. sys_language_content is only for selecting DISPLAY content!)
+                       }
+
                                // build query
-                       $search->build_search_query ($endClause);
-#debug($search->query);
+                       $search->build_search_query($endClause);
 
                                // count...
-                       if (t3lib_div::testInt(t3lib_div::GPvar('scount')))     {
-                               $search->res_count=t3lib_div::GPvar('scount');
+                       if (t3lib_div::testInt(t3lib_div::_GP('scount')))       {
+                               $search->res_count = t3lib_div::_GP('scount');
                        } else {
                                $search->count_query();
                        }
+
                                // range
-                       $spointer = intval(t3lib_div::GPvar('spointer'));
+                       $spointer = intval(t3lib_div::_GP('spointer'));
                        if (isset($conf['range']))      {
                                $theRange = intval($conf['range']);
                        } else {
-                               $theRange=20;
+                               $theRange = 20;
                        }
+
+                               // Order By:
                        if (!$conf['noOrderBy'])        {
-                               $search->query.=' ORDER BY pages.lastUpdated, pages.tstamp';
+                               $search->queryParts['ORDERBY'] = 'pages.lastUpdated, pages.tstamp';
                        }
-                       $search->query.=' LIMIT '.$spointer.','.$theRange;
-                       $GLOBALS['TT']->setTSlogMessage('Search query:   '.$search->query);
-                       
+
+                       $search->queryParts['LIMIT'] = $spointer.','.$theRange;
+
                                // search...
                        $search->execute_query();
-                       if (mysql_num_rows($search->result))    {
+                       if ($GLOBALS['TYPO3_DB']->sql_num_rows($search->result))        {
                                $GLOBALS['TSFE']->register['SWORD_PARAMS'] = $search->get_searchwords();
-                       
-                               $total=$search->res_count;
+
+                               $total = $search->res_count;
                                $rangeLow = t3lib_div::intInRange($spointer+1,1,$total);
                                $rangeHigh = t3lib_div::intInRange($spointer+$theRange,1,$total);
                                        // prev/next url:
-                               $LD=$GLOBALS['TSFE']->tmpl->linkData($GLOBALS['TSFE']->page,$conf['target'],1,'');
-                               $targetPart = $LD['target'] ? ' target="'.$LD['target'].'"' : '';
+                               $LD = $GLOBALS['TSFE']->tmpl->linkData($GLOBALS['TSFE']->page,$conf['target'],1,'', '', $this->getClosestMPvalueForPage($GLOBALS['TSFE']->page['uid']));
+                               $targetPart = $LD['target'] ? ' target="'.htmlspecialchars($LD['target']).'"' : '';
                                $urlParams = $this->URLqMark($LD['totalURL'],
-                                               '&sword='.rawurlencode(t3lib_div::GPvar('sword')).
-                                               '&scols='.rawurlencode(t3lib_div::GPvar('scols')).
-                                               '&stype='.rawurlencode(t3lib_div::GPvar('stype')).
+                                               '&sword='.rawurlencode(t3lib_div::_GP('sword')).
+                                               '&scols='.rawurlencode(t3lib_div::_GP('scols')).
+                                               '&stype='.rawurlencode(t3lib_div::_GP('stype')).
                                                '&scount='.$total);
                                        // substitution:
                                $result= $this->cObjGetSingle($conf['layout'],$conf['layout.'], 'layout');
                                $result = str_replace('###RANGELOW###',$rangeLow,$result);
                                $result = str_replace('###RANGEHIGH###',$rangeHigh,$result);
                                $result = str_replace('###TOTAL###',$total,$result);
-                               
+
                                if ($rangeHigh<$total)  {
                                        $next = $this->cObjGetSingle($conf['next'], $conf['next.'], 'next');
                                        $next = '<a href="'.htmlspecialchars($urlParams.'&spointer='.($spointer+$theRange)).'"'.$targetPart.$GLOBALS['TSFE']->ATagParams.'>'.$next.'</a>';
@@ -1953,10 +2131,11 @@ class tslib_cObj {
 
                                        // searching result
                                $theValue = $this->cObjGetSingle($conf['resultObj'], $conf['resultObj.'],'resultObj');
-                               $cObj =t3lib_div::makeInstance('tslib_cObj');
+                               $cObj = t3lib_div::makeInstance('tslib_cObj');
                                $cObj->setParent($this->data,$this->currentRecord);
                                $renderCode='';
-                               while ($row = mysql_fetch_assoc($search->result))       {
+                               while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($search->result))   {
+                                               // versionOL() here? This is search result displays, is that possible to preview anyway? Or are records selected here already future versions?
                                        $cObj->start($row);
                                        $renderCode.=$cObj->cObjGetSingle($conf['renderObj'], $conf['renderObj.'],'renderObj');
                                }
@@ -1984,7 +2163,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, PHP_SCRIPT, PHP_SCRIPT_INT and PHP_SCRIPT_EXT
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @param       string          If "INT", then rendering "PHP_SCRIPT_INT"; If "EXT", then rendering "PHP_SCRIPT_EXT"; Default is rendering "PHP_SCRIPT" (cached)
         * @return      string          Output
@@ -2029,7 +2208,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, TEMPLATE
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=373&cHash=109a171b1e
@@ -2040,16 +2219,23 @@ class tslib_cObj {
                $marks = Array();
                $wraps = Array();
                $content='';
-               
+
                list($PRE,$POST) = explode('|',$conf['markerWrap'] ? $conf['markerWrap'] : '### | ###');
                $POST = trim($POST);
                $PRE  = trim($PRE);
-               
+
                        // Getting the content
                $content = $this->cObjGetSingle($conf['template'],$conf['template.'],'template');
                if ($conf['workOnSubpart'])     {
                        $content = $this->getSubpart($content, $PRE.$conf['workOnSubpart'].$POST);
                }
+
+                       // Fixing all relative paths found:
+               if ($conf['relPathPrefix'])     {
+                       $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');
+                       $content = $htmlParser->prefixResourcePath($conf['relPathPrefix'],$content,$conf['relPathPrefix.']);
+               }
+
                if ($content)   {
                        if ($conf['nonCachedSubst'])    {               // NON-CACHED:
                                        // Getting marks
@@ -2065,7 +2251,7 @@ class tslib_cObj {
                                        }
                                }
 
-                                       // Getting subparts. 
+                                       // Getting subparts.
                                if (is_array($conf['subparts.']))       {
                                        reset($conf['subparts.']);
                                        while(list($theKey,$theValue)=each($conf['subparts.'])) {
@@ -2102,7 +2288,7 @@ class tslib_cObj {
                                        }
                                }
                        } else {        // CACHED
-                                       // Getting subparts. 
+                                       // Getting subparts.
                                if (is_array($conf['subparts.']))       {
                                        reset($conf['subparts.']);
                                        while(list($theKey,$theValue)=each($conf['subparts.'])) {
@@ -2144,9 +2330,9 @@ class tslib_cObj {
                                        $this->data[$this->currentValKey] = $GLOBALS['TSFE']->register['SUBPART_'.$theKey];
                                                // Get subpart cObject and substitute it!
                                        $subpartArray[$PRE.$theKey.$POST] = $this->cObjGetSingle($theValue['name'],$theValue['conf'],'subparts.'.$theKey);
-                               }       
+                               }
                                $this->data[$this->currentValKey] = ''; // Reset current to empty
-                               
+
                                        // Getting marks
                                $markerArray =array();
                                reset($marks);
@@ -2159,7 +2345,7 @@ class tslib_cObj {
                                while(list($theKey,$theValue)=each($wraps))     {
                                        $subpartWraps[$PRE.$theKey.$POST] = explode('|',$this->cObjGetSingle($theValue['name'],$theValue['conf'],'wraps.'.$theKey));
                                }
-       
+
                                        // Substitution
                                if ($conf['substMarksSeparately'])      {
                                        $content = $this->substituteMarkerArrayCached($content,array(),$subpartArray,$subpartWraps);
@@ -2174,7 +2360,7 @@ class tslib_cObj {
 
        /**
         * Rendering the cObject, MULTIMEDIA
-        * 
+        *
         * @param       array           Array of TypoScript properties
         * @return      string          Output
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=374&cHash=efd88ab4a9
@@ -2205,7 +2391,7 @@ class tslib_cObj {
                                        $parArray['width'] = 'width="200"';
                                        $parArray['height'] = 'height="200"';
                                }
-       
+
                                        // fetching params
                                $lines = explode(chr(10), $this->stdWrap($conf['params'],$conf['params.']));
                                while(list(,$l)=each($lines))   {
@@ -2222,22 +2408,22 @@ class tslib_cObj {
                                        unset($parArray['src']);
                                        $parArray['code'] = 'code="'.htmlspecialchars($fileinfo['file']).'"';
                                        $parArray['codebase'] = 'codebase="'.htmlspecialchars($fileinfo['path']).'"';
-                                       $content='<applet '.implode($parArray,' ').'></applet>';
+                                       $content='<applet '.implode(' ',$parArray).'></applet>';
                                } else {
-                                       $content='<embed '.implode($parArray,' ').'></embed>';
+                                       $content='<embed '.implode(' ',$parArray).'></embed>';
                                }
                        }
                }
+
+               if ($conf['stdWrap.']) {
+                       $content=$this->stdWrap($content, $conf['stdWrap.']);
+               }
+
                return $content;
-       }       
+       }
 
 
 
-       
-       
-       
-       
-       
 
 
 
@@ -2246,17 +2432,52 @@ class tslib_cObj {
 
 
 
-       
-       /************************************
-        *
+
+
+
+
+
+
+       /************************************
+        *
         * Various helper functions for content objects:
         *
         ************************************/
-        
+
+       /**
+        * Returns all parents of the given PID (Page UID) list
+        *
+        * @param       string          A list of page Content-Element PIDs (Page UIDs) / stdWrap
+        * @param       array           stdWrap array for the list
+        * @return      string          A list of PIDs
+        * @access private
+        */
+       function getSlidePids($pidList, $pidConf)       {
+               $pidList = trim($this->stdWrap($pidList,$pidConf));
+               if (!strcmp($pidList,''))       {
+                       $pidList = 'this';
+               }
+               if (trim($pidList))     {
+                       $listArr = t3lib_div::intExplode(',',str_replace('this',$GLOBALS['TSFE']->contentPid,$pidList));
+                       $listArr = $this->checkPidArray($listArr);
+               }
+               $pidList = array();
+               if (is_array($listArr)&&count($listArr))        {
+                       foreach ($listArr as $uid)      {
+                               $page = $GLOBALS['TSFE']->sys_page->getPage($uid);
+                               if (!$page['is_siteroot'])      {
+                                       $pidList[] = $page['pid'];
+                               }
+                       }
+               }
+               return implode(',', $pidList);
+       }
+
+
        /**
         * Creates a link to a netprint application on another website (where the "netprint" extension is running")
         * Related to the extension "netprint"
-        * 
+        *
         * @param       string          The input string to add the link to.
         * @param       array           Array with information about the image.
         * @param       array           TypoScript properties for the netprint application.
@@ -2297,7 +2518,7 @@ class tslib_cObj {
        /**
         * Returns a default value for a form field in the FORM cObject.
         * Page CANNOT be cached because that would include the inserted value for the current user.
-        * 
+        *
         * @param       boolean         If noValueInsert OR if the no_cache flag for this page is NOT set, the original default value is returned.
         * @param       string          $fieldName: The POST var name to get default value for
         * @param       string          $defaultVal: The current default value
@@ -2305,17 +2526,17 @@ class tslib_cObj {
         * @access private
         */
        function getFieldDefaultValue($noValueInsert, $fieldName, $defaultVal) {
-               if (!$GLOBALS['TSFE']->no_cache || (!isset($GLOBALS['HTTP_POST_VARS'][$fieldName]) && !isset($GLOBALS['HTTP_GET_VARS'][$fieldName])) || $noValueInsert) {
+               if (!$GLOBALS['TSFE']->no_cache || (!isset($_POST[$fieldName]) && !isset($_GET[$fieldName])) || $noValueInsert) {
                        return $defaultVal;
                } else {
-                       return t3lib_div::GPvar($fieldName);
+                       return t3lib_div::_GP($fieldName);
                }
        }
 
        /**
         * Returns a <img> tag with the image file defined by $file and processed according to the properties in the TypoScript array.
         * Mostly this function is a sub-function to the IMAGE function which renders the IMAGE cObject in TypoScript. This function is called by "$this->cImage($conf['file'],$conf);" from IMAGE().
-        * 
+        *
         * @param       string          File TypoScript resource
         * @param       array           TypoScript configuration properties
         * @return      string          <img> tag, (possibly wrapped in links and other HTML) if any image found.
@@ -2328,8 +2549,14 @@ class tslib_cObj {
                if (is_array($info))    {
                        $info[3] = t3lib_div::png_to_gif_by_imagemagick($info[3]);
                        $GLOBALS['TSFE']->imagesOnPage[]=$info[3];              // This array is used to collect the image-refs on the page...
-                       $alttext = strip_tags($this->stdWrap($conf['alttext'],$conf['alttext.']));
-                       $theValue = '<img src="'.htmlspecialchars($GLOBALS['TSFE']->absRefPrefix.t3lib_div::rawUrlEncodeFP($info[3])).'" width="'.$info[0].'" height="'.$info[1].'"  border="'.intval($conf['border']).'"'.($conf['params']?' '.$conf['params']:'').($alttext?' alt="'.htmlspecialchars($alttext).'"':' alt=""').' />';
+
+                       if (!strlen($conf['altText']) && !is_array($conf['altText.']))  {       // Backwards compatible:
+                               $conf['altText'] = $conf['alttext'];
+                               $conf['altText.'] = $conf['alttext.'];
+                       }
+                       $altParam = $this->getAltParam($conf);
+
+                       $theValue = '<img src="'.htmlspecialchars($GLOBALS['TSFE']->absRefPrefix.t3lib_div::rawUrlEncodeFP($info[3])).'" width="'.$info[0].'" height="'.$info[1].'"'.$this->getBorderAttr(' border="'.intval($conf['border']).'"').($conf['params']?' '.$conf['params']:'').($altParam).' />';
                        if ($conf['linkWrap'])  {
                                $theValue = $this->linkWrap($theValue,$conf['linkWrap']);
                        } elseif ($conf['imageLinkWrap']) {
@@ -2338,10 +2565,21 @@ class tslib_cObj {
                        return $this->wrap($theValue,$conf['wrap']);
                }
        }
+       /**
+        * Returns the 'border' attribute for an <img> tag only if the doctype is not xhtml_strict,xhtml_11 or xhtml_2 or if the config parameter 'disableImgBorderAttr' is not set.
+        *
+        * @param       string          the border attribute
+        * @return      string          the border attribute
+        */
+       function getBorderAttr($borderAttr) {
+               if (!t3lib_div::inList('xhtml_strict,xhtml_11,xhtml_2',$GLOBALS['TSFE']->config['config']['doctype']) || !$GLOBALS['TSFE']->config['config']['disableImgBorderAttr']) {
+                       return $borderAttr;
+               }
+       }
 
        /**
         * Wraps the input string in link-tags that opens the image in a new window.
-        * 
+        *
         * @param       string          String to wrap, probably an <img> tag
         * @param       string          The original image file
         * @param       array           TypoScript properties for the "imageLinkWrap" function
@@ -2363,13 +2601,13 @@ class tslib_cObj {
                                if ($conf['effects']) {$params.='&effects='.rawurlencode($conf['effects']);}
                                if ($conf['sample']) {$params.='&sample=1';}
                                if ($conf['alternativeTempPath']) {$params.='&alternativeTempPath='.rawurlencode($conf['alternativeTempPath']);}
-       
+
                                if ($conf['bodyTag']) {$params.='&bodyTag='.rawurlencode($conf['bodyTag']);}
                                if ($conf['title']) {$params.='&title='.rawurlencode($conf['title']);}
                                if ($conf['wrap']) {$params.='&wrap='.rawurlencode($conf['wrap']);}
-                               
+
                                $md5_value = md5($imageFile.'|'.$conf['width'].'|'.$conf['height'].'|'.$conf['effects'].'|'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'].'|');
-                               
+
                                $params.= '&md5='.$md5_value;
                                $url = $GLOBALS['TSFE']->absRefPrefix.'showpic.php?file='.rawurlencode($imageFile).$params;
                                if ($conf['JSwindow.']['altUrl'] || $conf['JSwindow.']['altUrl.'])      {
@@ -2378,16 +2616,16 @@ class tslib_cObj {
                                                $url=$altUrl;
                                        }
                                }
-                               
+
                                if ($conf['JSwindow'])  {
                                        $gifCreator = t3lib_div::makeInstance('tslib_gifbuilder');
                                        $gifCreator->init();
                                        $gifCreator->mayScaleUp = 0;
                                        $dims = $gifCreator->getImageScale($gifCreator->getImageDimensions($imageFile),$conf['width'],$conf['height'],'');
                                        $offset = t3lib_div::intExplode(',',$conf['JSwindow.']['expand'].',');
-                                       
+
                                        $a1='<a href="#" onclick="'.
-                                               htmlspecialchars('openPic(\''.$url.'\',\''.($conf['JSwindow.']['newWindow']?md5($url):'thePicture').'\',\'width='.($dims[0]+$offset[0]).',height='.($dims[1]+$offset[1]).',status=0,menubar=0\'); return false;').
+                                               htmlspecialchars('openPic(\''.$GLOBALS['TSFE']->baseUrlWrap($url).'\',\''.($conf['JSwindow.']['newWindow']?md5($url):'thePicture').'\',\'width='.($dims[0]+$offset[0]).',height='.($dims[1]+$offset[1]).',status=0,menubar=0\'); return false;').
                                                '"'.$GLOBALS['TSFE']->ATagParams.'>';
                                        $a2='</a>';
                                        $GLOBALS['TSFE']->setJS('openPic');
@@ -2402,25 +2640,26 @@ class tslib_cObj {
                                $content=$a1.$string.$a2;
                        }
                }
-               
+
                return $content;
        }
 
        /**
-        * Returns content of a file. If its an image the content of the file is not returned but rather an image tag is.
-        * 
+        * Returns content of a file. If it's an image the content of the file is not returned but rather an image tag is.
+        *
         * @param       string          The filename, being a TypoScript resource data type
+        * @param       string          Additional parameters (attributes). Default is empty alt and title tags.
         * @return      string          If jpg,gif,jpeg,png: returns image_tag with picture in. If html,txt: returns content string
         * @see FILE()
         */
-       function fileResource($fName)   {
+       function fileResource($fName, $addParams='alt="" title=""')     {
                $incFile = $GLOBALS['TSFE']->tmpl->getFileName($fName);
                if ($incFile)   {
                        $fileinfo = t3lib_div::split_fileref($incFile);
                        if (t3lib_div::inList('jpg,gif,jpeg,png',$fileinfo['fileext'])) {
                                $imgFile = $incFile;
                                $imgInfo = @getImageSize($imgFile);
-                               return '<img src="'.$GLOBALS['TSFE']->absRefPrefix.$imgFile.'" width="'.$imgInfo[0].'" height="'.$imgInfo[1].'" border="0" alt="" />';
+                               return '<img src="'.$GLOBALS['TSFE']->absRefPrefix.$imgFile.'" width="'.$imgInfo[0].'" height="'.$imgInfo[1].'"'.$this->getBorderAttr(' border="0"').' '.$addParams.' />';
                        } elseif (filesize($incFile)<1024*1024) {
                                return $GLOBALS['TSFE']->tmpl->fileContent($incFile);
                        }
@@ -2431,9 +2670,9 @@ class tslib_cObj {
         * Sets the SYS_LASTCHANGED timestamp if input timestamp is larger than current value.
         * The SYS_LASTCHANGED timestamp can be used by various caching/indexing applications to determine if the page has new content.
         * Therefore you should call this function with the last-changed timestamp of any element you display.
-        * 
+        *
         * @param       integer         Unix timestamp (number of seconds since 1970)
-        * @return      void            
+        * @return      void
         * @see tslib_fe::setSysLastChanged()
         */
        function lastChanged($tstamp)   {
@@ -2446,7 +2685,7 @@ class tslib_cObj {
        /**
         * Wraps the input string by the $wrap value and implements the "linkWrap" data type as well.
         * The "linkWrap" data type means that this function will find any integer encapsulated in {} (curly braces) in the first wrap part and substitute it with the corresponding page uid from the rootline where the found integer is pointing to the key in the rootline. See link below.
-        * 
+        *
         * @param       string          Input string
         * @param       string          A string where the first two parts separated by "|" (vertical line) will be wrapped around the input string
         * @return      string          Wrapped output string
@@ -2463,6 +2702,38 @@ class tslib_cObj {
                return trim($wrapArr[0]).$content.trim($wrapArr[1]);
        }
 
+       /**
+        * An abstraction method which creates an alt or title parameter for an HTML img tag.
+        * From the $conf array it implements the properties "altText", "titleText" and "longdescURL"
+        *
+        * @param       array           TypoScript configuration properties
+        * @return      string          Parameter string containing alt and title parameters (if any)
+        * @see IMGTEXT(), cImage()
+        */
+       function getAltParam($conf)     {
+               $altText = trim($this->stdWrap($conf['altText'], $conf['altText.']));
+               $titleText = trim($this->stdWrap($conf['titleText'],$conf['titleText.']));
+               $longDesc = trim($this->stdWrap($conf['longdescURL'],$conf['longdescURL.']));
+
+                       // "alt":
+               $altParam = ' alt="'.htmlspecialchars(strip_tags($altText)).'"';
+
+                       // "title":
+               if ($titleText) {
+                       $altParam.= ' title="'.htmlspecialchars(strip_tags($titleText)).'"';
+               } else {
+                       $altParam.= ' title="'.htmlspecialchars(strip_tags($altText)).'"';
+               }
+
+                       // "longDesc" URL
+               if ($longDesc)  {
+                       $altParam.= ' longdesc="'.htmlspecialchars($longDesc).'"';
+               }
+
+               return $altParam;
+       }
+
+
 
 
 
@@ -2474,8 +2745,6 @@ class tslib_cObj {
 
 
 
-       
-       
 
 
 
@@ -2492,7 +2761,7 @@ class tslib_cObj {
         * Returns a subpart from the input content stream.
         * A subpart is a part of the input stream which is encapsulated in a string matching the input string, $marker. If this string is found inside of HTML comment tags the start/end points of the content block returned will be that right outside that comment block.
         * Example: The contennt string is "Hello <!--###sub1### begin--> World. How are <!--###sub1### end--> you?" If $marker is "###sub1###" then the content returned is " World. How are ". The input content string could just as well have been "Hello ###sub1### World. How are ###sub1### you?" and the result would be the same
-        * 
+        *
         * @param       string          The content stream, typically HTML template content.
         * @param       string          The marker string, typically on the form "###[the marker string]###"
         * @return      string          The subpart found, if found.
@@ -2503,15 +2772,15 @@ class tslib_cObj {
                        $start = strpos($content, $marker)+strlen($marker);
                        $stop = @strpos($content, $marker, $start+1);
                        $sub = substr($content, $start, $stop-$start);
-       
-                       $reg=Array();           
+
+                       $reg=Array();
                        ereg('^[^<]*-->',$sub,$reg);
                        $start+=strlen($reg[0]);
-                       
-                       $reg=Array();           
+
+                       $reg=Array();
                        ereg('<!--[^>]*$',$sub,$reg);
                        $stop-=strlen($reg[0]);
-                       
+
                        return substr($content, $start, $stop-$start);
                }
        }
@@ -2519,7 +2788,7 @@ class tslib_cObj {
        /**
         * Substitute subpart in input template stream.
         * This function substitutes a subpart in $content with the content of $subpartContent.
-        * 
+        *
         * @param       string          The content stream, typically HTML template content.
         * @param       string          The marker string, typically on the form "###[the marker string]###"
         * @param       mixed           The content to insert instead of the subpart found. If a string, then just plain substitution happens (includes removing the HTML comments of the subpart if found). If $subpartContent happens to be an array, it's [0] and [1] elements are wrapped around the EXISTING content of the subpart (fetched by getSubpart()) thereby not removing the original content.
@@ -2533,13 +2802,13 @@ class tslib_cObj {
                if ($start && $stop>$start)     {
                                // code before
                        $before = substr($content, 0, $start);
-                       $reg=Array();           
+                       $reg=Array();
                        ereg('<!--[^>]*$',$before,$reg);
                        $start-=strlen($reg[0]);
                        $before = substr($content, 0, $start);
                                // code after
                        $after = substr($content, $stop);
-                       $reg=Array();           
+                       $reg=Array();
                        ereg('^[^<]*-->',$after,$reg);
                        $stop+=strlen($reg[0]);
                        $after = substr($content, $stop);
@@ -2549,7 +2818,7 @@ class tslib_cObj {
                        } else {
                                $substContent=$subpartContent;
                        }
-       
+
                        if ($recursive && strpos($after, $marker))      {
                                return $before.$substContent.$this->substituteSubpart($after,$marker,$subpartContent);
                        } else {
@@ -2562,7 +2831,7 @@ class tslib_cObj {
 
        /**
         * Substitutes a marker string in the input content (by a simple str_replace())
-        * 
+        *
         * @param       string          The content stream, typically HTML template content.
         * @param       string          The marker string, typically on the form "###[the marker string]###"
         * @param       mixed           The content to insert instead of the marker string found.
@@ -2575,13 +2844,13 @@ class tslib_cObj {
 
        /**
         * Multi substitution function with caching.
-        * 
+        *
         * This function should be a one-stop substitution function for working with HTML-template. It does not substitute by str_replace but by splitting. This secures that the value inserted does not themselves contain markers or subparts.
         * This function takes three kinds of substitutions in one:
         * $markContentArray is a regular marker-array where the 'keys' are substituted in $content with their values
         * $subpartContentArray works exactly like markContentArray only is whole subparts substituted and not only a single marker.
         * $wrappedSubpartContentArray is an array of arrays with 0/1 keys where the subparts pointed to by the main key is wrapped with the 0/1 value alternating.
-        * 
+        *
         * @param       string          The content stream, typically HTML template content.
         * @param       array           Regular marker-array where the 'keys' are substituted in $content with their values
         * @param       array           Exactly like markContentArray only is whole subparts substituted and not only a single marker.
@@ -2614,19 +2883,19 @@ class tslib_cObj {
                        if (!isset($storeArrDat))       {
                                        // Initialize storeArr
                                $storeArr=array();
-               
+
                                        // Finding subparts and substituting them with the subpart as a marker
                                reset($sPkeys);
                                while(list(,$sPK)=each($sPkeys))        {
                                        $content =$this->substituteSubpart($content,$sPK,$sPK);
                                }
-                               
+
                                        // Finding subparts and wrapping them with markers
                                reset($wPkeys);
                                while(list(,$wPK)=each($wPkeys))        {
                                        $content =$this->substituteSubpart($content,$wPK,array($wPK,$wPK));
                                }
-                               
+
                                        // traverse keys and quote them for reg ex.
                                reset($aKeys);
                                while(list($tK,$tV)=each($aKeys))       {
@@ -2639,10 +2908,10 @@ class tslib_cObj {
                                $storeArr['k']=$keyList[0];
                                        // Setting cache:
                                $this->substMarkerCache[$storeKey] = $storeArr;
-       
+
                                        // Storing the cached data:
                                $GLOBALS['TSFE']->sys_page->storeHash($storeKey, serialize($storeArr), 'substMarkArrayCached');
-                               
+
                                $GLOBALS['TT']->setTSlogMessage('Parsing',0);
                        } else {
                                        // Unserializing
@@ -2653,7 +2922,7 @@ class tslib_cObj {
                        }
                }
 
-                       // Substitution/Merging: 
+                       // Substitution/Merging:
                        // Merging content types together, resetting
                $valueArr = array_merge($markContentArray,$subpartContentArray,$wrappedSubpartContentArray);
 
@@ -2671,7 +2940,7 @@ class tslib_cObj {
                        }
                }
                $content.=$storeArr['c'][count($storeArr['k'])];
-               
+
                $GLOBALS['TT']->pull();
                return $content;
        }
@@ -2679,7 +2948,7 @@ class tslib_cObj {
        /**
         * Traverses the input $markContentArray array and for each key the marker by the same name (possibly wrapped and in upper case) will be substituted with the keys value in the array.
         * This is very useful if you have a data-record to substitute in some content. In particular when you use the $wrap and $uppercase values to pre-process the markers. Eg. a key name like "myfield" could effectively be represented by the marker "###MYFIELD###" if the wrap value was "###|###" and the $uppercase boolean true.
-        * 
+        *
         * @param       string          The content stream, typically HTML template content.
         * @param       array           The array of key/value pairs being marker/content values used in the substitution. For each element in this array the function will substitute a marker in the content stream with the content.
         * @param       string          A wrap value - [part 1] | [part 2] - for the markers before substitution
@@ -2702,7 +2971,7 @@ class tslib_cObj {
 
        /**
         * Substitute marker array in an array of values
-        * 
+        *
         * @param       mixed           If string, then it just calls substituteMarkerArray. If array (and even multi-dim) then for each key/value pair the marker array will be substituted (by calling this function recursively)
         * @param       array           The array of key/value pairs being marker/content values used in the substitution. For each element in this array the function will substitute a marker in the content string/array values.
         * @return      mixed           The processed input variable.
@@ -2722,29 +2991,32 @@ class tslib_cObj {
 
        /**
         * Adds elements to the input $markContentArray based on the values from the fields from $fieldList found in $row
-        * 
+        *
         * @param       array           Array with key/values being marker-strings/substitution values.
         * @param       array           An array with keys found in the $fieldList (typically a record) which values should be moved to the $markContentArray
         * @param       string          A list of fields from the $row array to add to the $markContentArray array. If empty all fields from $row will be added (unless they are integers)
         * @param       boolean         If set, all values added to $markContentArray will be nl2br()'ed
         * @param       string          Prefix string to the fieldname before it is added as a key in the $markContentArray. Notice that the keys added to the $markContentArray always start and end with "###"
+        * @param       boolean         If set, all values are passed through htmlspecialchars() - RECOMMENDED to avoid most obvious XSS and maintain XHTML compliance.
         * @return      array           The modified $markContentArray
         */
-       function fillInMarkerArray($markContentArray, $row, $fieldList='', $nl2br=1, $prefix='FIELD_')  {
+       function fillInMarkerArray($markContentArray, $row, $fieldList='', $nl2br=TRUE, $prefix='FIELD_', $HSC=FALSE)   {
                if ($fieldList) {
-                       $fArr=t3lib_div::trimExplode(',',$fieldList,1);
-                       reset($fArr);
-                       while(list(,$field)=each($fArr))        {
+                       $fArr = t3lib_div::trimExplode(',',$fieldList,1);
+                       foreach($fArr as $field)        {
                                $markContentArray['###'.$prefix.$field.'###'] = $nl2br?nl2br($row[$field]):$row[$field];
                        }
                } else {
                        if (is_array($row))     {
-                               reset($row);
-                               while(list($field,)=each($row)) {
-                                       if (!t3lib_div::testInt($field))        {               $markContentArray['###'.$prefix.$field.'###'] = $nl2br?nl2br($row[$field]):$row[$field];        }
+                               foreach($row as $field => $value)       {
+                                       if (!t3lib_div::testInt($field))        {
+                                               if ($HSC)       $value = htmlspecialchars($value);
+                                               $markContentArray['###'.$prefix.$field.'###'] = $nl2br ? nl2br($value) : $value;
+                                       }
                                }
                        }
                }
+
                return $markContentArray;
        }
 
@@ -2765,7 +3037,7 @@ class tslib_cObj {
 
 
 
-       
+
 
 
 
@@ -2778,14 +3050,14 @@ class tslib_cObj {
         *
         ***********************************************/
 
-       
+
        /**
         * The "stdWrap" function. This is the implementation of what is known as "stdWrap properties" in TypoScript.
         * Basically "stdWrap" performs some processing of a value based on properties in the input $conf array (holding the TypoScript "stdWrap properties")
         * See the link below for a complete list of properties and what they do. The order of the table with properties found in TSref (the link) follows the actual order of implementation in this function.
-        * 
+        *
         * If $this->alternativeData is an array it's used instead of the $this->data array in ->getData
-        * 
+        *
         * @param       string          Input value undergoing processing in this function. Possibly substituted by other values fetched from another source.
         * @param       array           TypoScript "stdWrap properties".
         * @return      string          The processed input value
@@ -2797,22 +3069,22 @@ class tslib_cObj {
                                // Setting current value, if so
                        if ($conf['setContentToCurrent']){$this->data[$this->currentValKey]=$content;}
                        if ($conf['setCurrent'] || $conf['setCurrent.']){$this->data[$this->currentValKey] = $this->stdWrap($conf['setCurrent'], $conf['setCurrent.']);}
-                       
+
                                // Getting data:
                        if (isset($conf['lang.']) && $GLOBALS['TSFE']->config['config']['language'] && isset($conf['lang.'][$GLOBALS['TSFE']->config['config']['language']]))   {
                                $content = $conf['lang.'][$GLOBALS['TSFE']->config['config']['language']];
                        }
                        if ($conf['data']){$content=$this->getData($conf['data'], is_array($this->alternativeData)?$this->alternativeData:$this->data);}
-                               $this->alternativeData='';              // This must be unset directly after 
+                               $this->alternativeData='';              // This must be unset directly after
                        if ($conf['field']) {$content=$this->getFieldVal($conf['field']);}
                        if ($conf['current']) {$content=$this->data[$this->currentValKey];}
                        if ($conf['cObject']) {$content=$this->cObjGetSingle($conf['cObject'],$conf['cObject.'],'/stdWrap/.cObject');}
                        if ($conf['numRows.']) {$content=$this->numRows($conf['numRows.']);}
                        if ($conf['filelist'] || $conf['filelist.'])    {$content=$this->filelist($this->stdWrap($conf['filelist'], $conf['filelist.']));}
                        if ($conf['preUserFunc'])       {$content = $this->callUserFunction($conf['preUserFunc'], $conf['preUserFunc.'], $content);}
-                       
+
                                // Overriding values, evaluating conditions
-                       if ($conf['override'] || $conf['override.']){ 
+                       if ($conf['override'] || $conf['override.']){
                                $override = $this->stdWrap($conf['override'], $conf['override.']);
                                if (trim($override)) {$content=$override;}
                        }
@@ -2821,42 +3093,55 @@ class tslib_cObj {
                                $content=$this->listNum($content,$preIfEmptyListNumber,$conf['preIfEmptyListNum.']['splitChar']);
                        }
                        if (!trim($content) && ($conf['ifEmpty'] || $conf['ifEmpty.'])){ $content = $this->stdWrap($conf['ifEmpty'], $conf['ifEmpty.']);}
-                       
+
 
                                // values...
                        if (isset($conf['listNum']) || isset($conf['listNum.']['stdWrap.'])) {
                                $listNumber = isset($conf['listNum.']['stdWrap.'])  ?  $this->stdWrap($conf['listNum'], $conf['listNum.']['stdWrap.'])  :  $conf['listNum'];
                                $content=$this->listNum($content,$listNumber,$conf['listNum.']['splitChar']);
                        }
-                       
-                       if ($conf['trim']){$content=trim($content);}
+
+                       if ($conf['trim'])      { $content=trim($content); }
+
+                               // Call stdWrap recursively
+                       if ($conf['stdWrap'])   { $content=$this->stdWrap($content,$conf['stdWrap.']); }
+
                        if (   ($conf['required'] && (string)$content=='') || ($conf['if.'] && !$this->checkIf($conf['if.'])) || ($conf['fieldRequired'] && !trim($this->data[$conf['fieldRequired']]))    ){
                                $content = '';
-                       } else {
+                       } else  {
                                        // Perform data processing:
-                               if ($conf['parseFunc.']) {$content=$this->parseFunc($content,$conf['parseFunc.']);}
+                               if ($conf['csConv'])    { $content=$GLOBALS['TSFE']->csConv($content,$conf['csConv']); }
+                               if ($conf['parseFunc.'] || $conf['parseFunc']) {$content=$this->parseFunc($content,$conf['parseFunc.'],$conf['parseFunc']);}
                                if ($conf['HTMLparser'] && is_array($conf['HTMLparser.'])) {$content=$this->HTMLparser_TSbridge($content,$conf['HTMLparser.']);}
                                if ($conf['split.']){$content=$this->splitObj($content,$conf['split.']);}
                                if ($conf['prioriCalc']){$content=t3lib_div::calcParenthesis($content); if ($conf['prioriCalc']=='intval') $content=intval($content);}
                                if ((string)$conf['char']!=''){$content=chr(intval($conf['char']));}
                                if ($conf['intval']){$content=intval($content);}
                                if ($conf['date']){$content=date($conf['date'], $content);}
-                               if ($conf['strftime']){$content=strftime($conf['strftime'], $content);}
+                               if ($conf['strftime']){
+                                       $content = strftime($conf['strftime'], $content);
+                                       $tmp_charset = $conf['strftime.']['charset'] ? $conf['strftime.']['charset'] : $GLOBALS['TSFE']->localeCharset;
+                                       if ($tmp_charset)       {
+                                               $content = $GLOBALS['TSFE']->csConv($content,$tmp_charset);
+                                       }
+                               }
                                if ($conf['age']){$content=$this->calcAge(time()-$content,$conf['age']);}
-                               
+
                                if ($conf['case']){$content=$this->HTMLcaseshift($content, $conf['case']);}
                                if ($conf['bytes']){$content=$this->bytes($content,$conf['bytes.']['labels']);}
                                if ($conf['substring']){$content=$this->substring($content,$conf['substring']);}
+                               if ($conf['removeBadHTML'])     {$content = $this->removeBadHTML($content, $conf['removeBadHTML.']);}
+                               if ($conf['stripHtml']){$content = strip_tags($content);}
                                if ($conf['crop']){$content=$this->crop($content, $conf['crop']);}
-                               if ($conf['stripHtml']){$content=strip_tags($content);}
+                               if ($conf['rawUrlEncode']){$content = rawurlencode($content);}
                                if ($conf['htmlSpecialChars']){
                                        $content=htmlSpecialChars($content);
                                        if ($conf['htmlSpecialChars.']['preserveEntities'])     $content = t3lib_div::deHSCentities($content);
                                }
-       
+
                                if ($conf['doubleBrTag']) {
                                        $content=ereg_replace("\r?\n[\t ]*\r?\n",$conf['doubleBrTag'],$content);
-                               }                               
+                               }
                                if ($conf['br']) {$content=nl2br($content);}
                                if ($conf['brTag']) {$content= ereg_replace(chr(10),$conf['brTag'],$content);}
                                if ($conf['encapsLines.']) {$content=$this->encaps_lineSplit($content,$conf['encapsLines.']);}
@@ -2873,11 +3158,11 @@ class tslib_cObj {
 
                                if ($conf['wrapAlign'] || $conf['wrapAlign.']){
                                        $wrapAlign = trim($this->stdWrap($conf['wrapAlign'], $conf['wrapAlign.']));
-                                       if ($wrapAlign) {$content=$this->wrap($content, '<div align="'.$wrapAlign.'">|</div>');}
+                                       if ($wrapAlign) {$content=$this->wrap($content, '<div style="text-align:'.$wrapAlign.';">|</div>');}
                                }
                                if ($conf['typolink.']){$content=$this->typolink($content, $conf['typolink.']);}
 
-                                       // Spacing                      
+                                       // Spacing
                                if ($conf['space']){$content=$this->wrapSpace($content, $conf['space']);}
                                $spaceBefore = '';
                                if ($conf['spaceBefore'] || $conf['spaceBefore.'])      {$spaceBefore = trim($this->stdWrap($conf['spaceBefore'], $conf['spaceBefore.']));}
@@ -2895,7 +3180,7 @@ class tslib_cObj {
                                if ($conf['wrap3']){$content=$this->wrap($content, $conf['wrap3'], ($conf['wrap.']['splitChar']?$conf['wrap.']['splitChar']:'|'));}
                                if ($conf['outerWrap'] || $conf['outerWrap.']){$content=$this->wrap($content, $this->stdWrap($conf['outerWrap'], $conf['outerWrap.']));}
                                if ($conf['insertData'])        {$content = $this->insertData($content);}
-                               if ($conf['offsetWrap']){       
+                               if ($conf['offsetWrap']){
                                        $controlTable = t3lib_div::makeInstance('tslib_tableOffset');
                                        if ($conf['offsetWrap.']['tableParams'] || $conf['offsetWrap.']['tableParams.'])        {$controlTable->tableParams = $this->stdWrap($conf['offsetWrap.']['tableParams'], $conf['offsetWrap.']['tableParams.']);}
                                        if ($conf['offsetWrap.']['tdParams'] || $conf['offsetWrap.']['tdParams.'])      {$controlTable->tdParams = ' '.$this->stdWrap($conf['offsetWrap.']['tdParams'], $conf['offsetWrap.']['tdParams.']);}
@@ -2903,20 +3188,33 @@ class tslib_cObj {
                                        if ($conf['offsetWrap.']['stdWrap.'])   {       $content=$this->stdWrap($content,$conf['offsetWrap.']['stdWrap.']);     }
                                }
                                if ($conf['postUserFunc'])      {$content = $this->callUserFunction($conf['postUserFunc'], $conf['postUserFunc.'], $content);}
+                               if ($conf['postUserFuncInt'])   {
+                                       $substKey = 'INT_SCRIPT.'.$GLOBALS['TSFE']->uniqueHash();
+                                       $GLOBALS['TSFE']->config['INTincScript'][$substKey] = array(
+                                               'content' => $content,
+                                               'postUserFunc' => $conf['postUserFuncInt'],
+                                               'conf' => $conf['postUserFuncInt.'],
+                                               'type' => 'POSTUSERFUNC',
+                                               'cObj' => serialize($this),
+                                       );
+                                       $content ='<!--'.$substKey.'-->';
+                               }
+                                       // Various:
+                               if ($conf['prefixComment'] && !$GLOBALS['TSFE']->config['config']['disablePrefixComment'])      {$content = $this->prefixComment($conf['prefixComment'], $conf['prefixComment.'], $content);}
 
                                if ($conf['editIcons'] && $GLOBALS['TSFE']->beUserLogin){$content=$this->editIcons($content,$conf['editIcons'],$conf['editIcons.']);}
                                if ($conf['editPanel'] && $GLOBALS['TSFE']->beUserLogin){$content=$this->editPanel($content, $conf['editPanel.']);}
                        }
-                       
+
                                //Debug:
                        if ($conf['debug'])     {$content = '<pre>'.htmlspecialchars($content).'</pre>';}
                        if ($conf['debugFunc']) {debug($conf['debugFunc']==2?array($content):$content);}
                        if ($conf['debugData']) {
                                echo '<b>$cObj->data:</b>';
-                               debug($this->data);
+                               debug($this->data,'$cObj->data:');
                                if (is_array($this->alternativeData))   {
                                        echo '<b>$cObj->alternativeData:</b>';
-                                       debug($this->alternativeData);
+                                       debug($this->alternativeData,'$this->alternativeData');
                                }
                        }
                }
@@ -2926,7 +3224,7 @@ class tslib_cObj {
        /**
         * Returns number of rows selected by the query made by the properties set.
         * Implements the stdWrap "numRows" property
-        * 
+        *
         * @param       array           TypoScript properties for the property (see link to "numRows")
         * @return      integer         The number of rows found by the select
         * @access private
@@ -2935,24 +3233,25 @@ class tslib_cObj {
         * @see stdWrap()
         */
        function numRows($conf) {
-               $query = $this->getQuery($conf['table'],$conf['select.']);
-               $query = str_replace('SELECT *','SELECT count(*)',$query);
-               $res = @mysql(TYPO3_db,$query);
-               if ($error = mysql_error())     {
-                       $GLOBALS['TT']->setTSlogMessage($error.':   '.$query,3);
+               $conf['select.']['selectFields'] = 'count(*)';
+
+               $res = $this->exec_getQuery($conf['table'],$conf['select.']);
+
+               if ($error = $GLOBALS['TYPO3_DB']->sql_error()) {
+                       $GLOBALS['TT']->setTSlogMessage($error,3);
                } else {
-                       $row=mysql_fetch_row($res);
+                       $row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
                        return intval($row[0]);
                }
        }
 
        /**
         * Exploding a string by the $char value (if integer its an ASCII value) and returning index $listNum
-        * 
+        *
         * @param       string          String to explode
         * @param       string          Index-number. You can place the word "last" in it and it will be substituted with the pointer to the last value. You can use math operators like "+-/*" (passed to calc())
         * @param       string          Either a string used to explode the content string or an integer value which will then be changed into a character, eg. "10" for a linebreak char.
-        * @return      string          
+        * @return      string
         */
        function listNum($content,$listNum,$char) {
                $char = $char ? $char : ',';
@@ -2968,9 +3267,9 @@ class tslib_cObj {
        /**
         * Compares values together based on the settings in the input TypoScript array and returns true or false based on the comparison result.
         * Implements the "if" function in TYPO3 TypoScript
-        * 
+        *
         * @param       array           TypoScript properties defining what to compare
-        * @return      boolean         
+        * @return      boolean
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=320&cHash=da01618eab
         * @see HMENU(), CASEFUNC(), IMAGE(), COLUMN(), stdWrap(), _parseFunc()
         */
@@ -3031,7 +3330,7 @@ class tslib_cObj {
        /**
         * Reads a directory for files and returns the filepaths in a string list separated by comma.
         * Implements the stdWrap property "filelist"
-        * 
+        *
         * @param       string          The command which contains information about what files/directory listing to return. See the "filelist" property of stdWrap for details.
         * @return      string          Comma list of files.
         * @access private
@@ -3102,7 +3401,7 @@ class tslib_cObj {
                                        while(list($key,)=each($items['sorting']))      {
                                                $list_arr[]=  $fullPath ? $path.'/'.$items['files'][$key] : $items['files'][$key];
                                        }
-                                       return implode($list_arr,',');
+                                       return implode(',',$list_arr);
                                }
                        }
                }
@@ -3110,7 +3409,7 @@ class tslib_cObj {
 
        /**
         * Cleans $theDir for slashes in the end of the string and returns the new path, if it exists on the server.
-        * 
+        *
         * @param       string          Absolute path to directory
         * @return      string          The directory path if it existed as was valid to access.
         * @access private
@@ -3124,10 +3423,10 @@ class tslib_cObj {
                        }
                }
        }
-       
+
        /**
         * Passes the input value, $theValue, to an instance of "t3lib_parsehtml" together with the TypoScript options which are first converted from a TS style array to a set of arrays with options for the t3lib_parsehtml class.
-        * 
+        *
         * @param       string          The value to parse by the class "t3lib_parsehtml"
         * @param       array           TypoScript properties for the parser. See link.
         * @return      string          Return value.
@@ -3142,7 +3441,7 @@ class tslib_cObj {
 
        /**
         * Wrapping input value in a regular "wrap" but parses the wrapping value first for "insertData" codes.
-        * 
+        *
         * @param       string          Input string being wrapped
         * @param       string          The wrap string, eg. "<b></b>" or more likely here '<a href="index.php?id={TSFE:id}"> | </a>' which will wrap the input string in a <a> tag linking to the current page.
         * @return      string          Output string wrapped in the wrapping value.
@@ -3155,7 +3454,7 @@ class tslib_cObj {
        /**
         * Implements the "insertData" property of stdWrap meaning that if strings matching {...} is found in the input string they will be substituted with the return value from getData (datatype) which is passed the content of the curly braces.
         * Example: If input string is "This is the page title: {page:title}" then the part, '{page:title}', will be substituted with the current pages title field value.
-        * 
+        *
         * @param       string          Input value
         * @return      string          Processed input value
         * @see getData(), stdWrap(), dataWrap()
@@ -3169,11 +3468,11 @@ class tslib_cObj {
                do      {
                        if (!$inside)   {
                                $len = strcspn(substr($str,$pointer),'{');
-                               $newVal.=substr($str,$pointer,$len);
+                               $newVal.= substr($str,$pointer,$len);
                                $inside = 1;
                        } else {
                                $len = strcspn(substr($str,$pointer),'}')+1;
-                               $newVal.=$this->getData(substr($str,$pointer+1,$len-2),$this->data);
+                               $newVal.= $this->getData(substr($str,$pointer+1,$len-2),$this->data);
                                $inside = 0;
                        }
                        $pointer+=$len;
@@ -3182,8 +3481,33 @@ class tslib_cObj {
        }
 
        /**
+        * Returns a HTML comment with the second part of input string (divided by "|") where first part is an integer telling how many trailing tabs to put before the comment on a new line.
+        * Notice; this function (used by stdWrap) can be disabled by a "config.disablePrefixComment" setting in TypoScript.
+        *
+        * @param       string          Input value
+        * @param       array           TypoScript Configuration (not used at this point.)
+        * @param       string          The content to wrap the comment around.
+        * @return      string          Processed input value
+        * @see stdWrap()
+        */
+       function prefixComment($str,$conf,$content)     {
+               $parts = explode('|',$str);
+
+               $output =
+                       chr(10).str_pad('',$parts[0],chr(9)).
+                       '<!-- '.htmlspecialchars($this->insertData($parts[1])).' [begin] -->'.
+                       chr(10).str_pad('',$parts[0]+1,chr(9)).
+                               $content.
+                       chr(10).str_pad('',$parts[0],chr(9)).
+                       '<!-- '.htmlspecialchars($this->insertData($parts[1])).' [end] -->'.
+                       chr(10).str_pad('',$parts[0]+1,chr(9));
+
+               return $output;
+       }
+
+       /**
         * Implements the stdWrap property "substring" which is basically a TypoScript implementation of the PHP function, substr()
-        * 
+        *
         * @param       string          The string to perform the operation on
         * @param       string          The parameters to substring, given as a comma list of integers where the first and second number is passed as arg 1 and 2 to substr().
         * @return      string          The processed input value.
@@ -3193,31 +3517,36 @@ class tslib_cObj {
        function substring($content,$options)   {
                $options = t3lib_div::intExplode(',',$options.',');
                if ($options[1])        {
-                       return substr($content,$options[0],$options[1]);
+                       return $GLOBALS['TSFE']->csConvObj->substr($GLOBALS['TSFE']->renderCharset,$content,$options[0],$options[1]);
                } else {
-                       return substr($content,$options[0]);
+                       return $GLOBALS['TSFE']->csConvObj->substr($GLOBALS['TSFE']->renderCharset,$content,$options[0]);
                }
        }
 
        /**
         * Implements the stdWrap property "crop" which is a modified "substr" function allowing to limit a string lenght to a certain number of chars (from either start or end of string) and having a pre/postfix applied if the string really was cropped.
-        * 
+        *
         * @param       string          The string to perform the operation on
-        * @param       string          The parameters splitted by "|": First parameter is the max number of chars of the string. Negative value means cropping from end of string. Second parameter is the pre/postfix string to apply if cropping occurs.
+        * @param       string          The parameters splitted by "|": First parameter is the max number of chars of the string. Negative value means cropping from end of string. Second parameter is the pre/postfix string to apply if cropping occurs. Third parameter is a boolean value. If set then crop will be applied at nearest space.
         * @return      string          The processed input value.
         * @access private
         * @see stdWrap()
         */
        function crop($content,$options)        {
                $options = explode('|',$options);
-               $chars=intval($options[0]);
-               $afterstring=trim($options[1]);
+               $chars = intval($options[0]);
+               $afterstring = trim($options[1]);
+               $crop2space = trim($options[2]);
                if ($chars)     {
                        if (strlen($content)>abs($chars))       {
                                if ($chars<0)   {
-                                       $content= $afterstring.substr($content,$chars);
+                                       $content = $GLOBALS['TSFE']->csConvObj->substr($GLOBALS['TSFE']->renderCharset,$content,$chars);
+                                       $trunc_at = strpos($content, ' ');
+                                       $content = ($trunc_at&&$crop2space) ? $afterstring.substr($content,$trunc_at) : $afterstring.$content;
                                } else {
-                                       $content= substr($content,0,$chars).$afterstring;
+                                       $content = $GLOBALS['TSFE']->csConvObj->substr($GLOBALS['TSFE']->renderCharset,$content,0,$chars);
+                                       $trunc_at = strrpos($content, ' ');
+                                       $content = ($trunc_at&&$crop2space) ? substr($content, 0, $trunc_at).$afterstring : $content.$afterstring;
                                }
                        }
                }
@@ -3225,8 +3554,53 @@ class tslib_cObj {
        }
 
        /**
+        * Function for removing malicious HTML code when you want to provide some HTML code user-editable.
+        * The purpose is to avoid XSS attacks and the code will be continously modified to remove such code.
+        * For a complete reference with javascript-on-events, see http://www.wdvl.com/Authoring/JavaScript/Events/events_target.html
+        *
+        * @param       string          Input string to be cleaned.
+        * @param       array           TypoScript configuration.
+        * @return      string          Return string
+        * @author      Thomas Bley (all from moregroupware cvs code / readmessage.inc.php, published under gpl by Thomas)
+        * @author      Kasper Skaarhoj
+        */
+       function removeBadHTML($text, $conf)    {
+
+                       // Copyright 2002-2003 Thomas Bley
+               $text = preg_replace(
+                       array(
+                               "'<script[^>]*?>.*?</script[^>]*?>'si",
+                               "'<applet[^>]*?>.*?</applet[^>]*?>'si",
+                               "'<object[^>]*?>.*?</object[^>]*?>'si",
+                               "'<iframe[^>]*?>.*?</iframe[^>]*?>'si",
+                               "'<frameset[^>]*?>.*?</frameset[^>]*?>'si",
+                               "'<style[^>]*?>.*?</style[^>]*?>'si",
+                               "'<marquee[^>]*?>.*?</marquee[^>]*?>'si",
+                               "'<script[^>]*?>'si",
+                               "'<meta[^>]*?>'si",
+                               "'<base[^>]*?>'si",
+                               "'<applet[^>]*?>'si",
+                               "'<object[^>]*?>'si",
+                               "'<link[^>]*?>'si",
+                               "'<iframe[^>]*?>'si",
+                               "'<frame[^>]*?>'si",
+                               "'<frameset[^>]*?>'si",
+                               "'<input[^>]*?>'si",
+                               "'<form[^>]*?>'si",
+                               "'<embed[^>]*?>'si",
+                               "'background-image:url'si",
+                               "'<\w+.*?(onabort|onbeforeunload|onblur|onchange|onclick|ondblclick|ondragdrop|onerror|onfilterchange|onfocus|onhelp|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onmove|onreadystatechange|onreset|onresize|onscroll|onselect|onselectstart|onsubmit|onunload).*?>'si",
+                       ), '', $text);
+
+                       $text = eregi_replace('<a[^>]*href[[:space:]]*=[[:space:]]*["\']?[[:space:]]*javascript[^>]*','',$text);
+
+                       // Return clean content
+               return $text;
+       }
+
+       /**
         * Implements the stdWrap property "textStyle"; This generates a <font>-tag (and a <div>-tag for align-attributes) which is wrapped around the input value.
-        * 
+        *
         * @param       string          The input value
         * @param       array           TypoScript properties for the "TypoScript function" '->textStyle'
         * @return      string          The processed output value
@@ -3234,7 +3608,7 @@ class tslib_cObj {
         * @see stdWrap()
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=322&cHash=a14b745a18
         */
-       function textStyle($theValue, $conf) {  
+       function textStyle($theValue, $conf) {
                $conf['face.'][1] = 'Times New Roman';
                $conf['face.'][2] = 'Verdana,Arial,Helvetica,Sans serif';
                $conf['face.'][3] = 'Arial,Helvetica,Sans serif';
@@ -3246,7 +3620,7 @@ class tslib_cObj {
                $conf['size.'][5] = 5;
                $conf['size.'][10] = '+1';
                $conf['size.'][11] = '-1';
-       
+
                $conf['color.'][240] = 'black';
                $conf['color.'][241] = 'white';
                $conf['color.'][242] = '#333333';
@@ -3258,27 +3632,27 @@ class tslib_cObj {
                $conf['color.'][248] = 'green';
                $conf['color.'][249] = 'olive';
                $conf['color.'][250] = 'maroon';
-       
-               $face = $this->data[$conf['face.']['field']];           
-               $size = $this->data[$conf['size.']['field']];           
-               $color = $this->data[$conf['color.']['field']];         
+
+               $face = $this->data[$conf['face.']['field']];
+               $size = $this->data[$conf['size.']['field']];
+               $color = $this->data[$conf['color.']['field']];
                $align = $this->data[$conf['align.']['field']];
                $properties = $this->data[$conf['properties.']['field']];
                if (!$properties)       {
                        $properties=$this->stdWrap($conf['properties.']['default'],$conf['properties.']['default.']);
                }
-               
+
                        // properties
                if (($properties&8))    {$theValue=$this->HTMLcaseshift($theValue, 'upper');}
                if (($properties&1))    {$theValue='<b>'.$theValue.'</b>';}
                if (($properties&2))    {$theValue='<i>'.$theValue.'</i>';}
                if (($properties&4))    {$theValue='<u>'.$theValue.'</u>';}
-               
+
                        // Fonttag
                $theFace = $conf['face.'][$face] ? $conf['face.'][$face] : $this->stdWrap($conf['face.']['default'],$conf['face.']['default.']);
                $theSize = $conf['size.'][$size] ? $conf['size.'][$size] : $this->stdWrap($conf['size.']['default'],$conf['size.']['default.']);
                $theColor = $conf['color.'][$color] ? $conf['color.'][$color] : $this->stdWrap($conf['color.']['default'],$conf['color.']['default.']);
-               
+
                if ($conf['altWrap'])   {
                        $theValue=$this->wrap($theValue, $conf['altWrap']);
                } elseif ($theFace || $theSize || $theColor)    {
@@ -3286,14 +3660,14 @@ class tslib_cObj {
                        $theValue=$this->wrap($theValue, $fontWrap);
                }
                        // align
-               if ($align)     {$theValue=$this->wrap($theValue, '<div align="'.$align.'">|</div>');}
+               if ($align)     {$theValue=$this->wrap($theValue, '<div style="text-align:'.$align.';">|</div>');}
                        // return
                return $theValue;
        }
 
        /**
         * Implements the stdWrap property "tableStyle"; Basically this generates a <table>-tag with properties which is wrapped around the input value.
-        * 
+        *
         * @param       string          The input value
         * @param       array           TypoScript properties for the "TypoScript function" '->textStyle'
         * @return      string          The processed output value
@@ -3301,7 +3675,7 @@ class tslib_cObj {
         * @see stdWrap()
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=324&cHash=34410ebff3
         */
-       function tableStyle($theValue, $conf) { 
+       function tableStyle($theValue, $conf) {
                $conf['color.'][240] = 'black';
                $conf['color.'][241] = 'white';
                $conf['color.'][242] = '#333333';
@@ -3313,7 +3687,7 @@ class tslib_cObj {
                $cellspacing = intval($this->stdWrap($conf['cellspacing'],$conf['cellspacing.']));
                $cellpadding = intval($this->stdWrap($conf['cellpadding'],$conf['cellpadding.']));
 
-               $color = $this->data[$conf['color.']['field']];         
+               $color = $this->data[$conf['color.']['field']];
                $theColor = $conf['color.'][$color] ? $conf['color.'][$color] : $conf['color.']['default'];
                        // Assembling the table tag
                $tableTagArray = Array('<table');
@@ -3327,15 +3701,15 @@ class tslib_cObj {
                        $tableTagArray[] = $conf['params'];
                }
 
-               $tableWrap = implode($tableTagArray,' ').'> | </table>';
+               $tableWrap = implode(' ',$tableTagArray).'> | </table>';
                $theValue=$this->wrap($theValue, $tableWrap);
                        // return
                return $theValue;
        }
-       
+
        /**
         * Implements the TypoScript function "addParams"
-        * 
+        *
         * @param       string          The string with the HTML tag.
         * @param       array           The TypoScript configuration properties
         * @return      string          The modified string
@@ -3344,9 +3718,9 @@ class tslib_cObj {
         */
        function addParams($content,$conf) {
                $lowerCaseAttributes = TRUE;    // For XHTML compliance.
-               
+
                if (!is_array($conf))   { return $content; }
-               
+
                $key = 1;
                $parts = explode('<',$content);
                if (intval($conf['_offset']))   $key = intval($conf['_offset'])<0 ? count($parts)+intval($conf['_offset']) : intval($conf['_offset']);
@@ -3367,7 +3741,7 @@ class tslib_cObj {
                        }
 
                                // Re-assembles the tag and content
-                       $subparts[0]=trim($tagName.' '.t3lib_div::implodeParams($attribs));
+                       $subparts[0]=trim($tagName.' '.t3lib_div::implodeAttributes($attribs));
                        $parts[$key] = implode('>',$subparts);
                        $content = implode('<',$parts);
                }
@@ -3377,7 +3751,7 @@ class tslib_cObj {
        /**
         * Creates a list of links to files.
         * Implements the stdWrap property "filelink"
-        * 
+        *
         * @param       string          The filename to link to, possibly prefixed with $conf[path]
         * @param       array           TypoScript parameters for the TypoScript function ->filelink
         * @return      string          The link to the file possibly with icons, thumbnails, size in bytes shown etc.
@@ -3396,28 +3770,30 @@ class tslib_cObj {
                        $locDataAdd = $conf['jumpurl.']['secure'] ? $this->locDataJU($theFileEnc,$conf['jumpurl.']['secure.']) : '';
                        $url = ($conf['jumpurl']) ? $GLOBALS['TSFE']->config['mainScript'].$initP.'&jumpurl='.rawurlencode($theFileEnc).$locDataAdd.$GLOBALS['TSFE']->getMethodUrlIdToken : $theFileEnc;                // && $GLOBALS['TSFE']->config['config']['jumpurl_enable']
                        $theLinkWrap = '<a href="'.htmlspecialchars($GLOBALS['TSFE']->absRefPrefix.$url).'"'.($conf['target']?' target="'.$conf['target'].'"':'').$aTagParams.'>|</a>';
-               
+
                        $theSize = filesize($theFile);
                        $fI = t3lib_div::split_fileref($theFile);
                        if ($conf['icon'])      {
                                $iconP = 't3lib/gfx/fileicons/';
                                $icon = @is_file($iconP.$fI['fileext'].'.gif') ? $iconP.$fI['fileext'].'.gif' : $iconP.'default.gif';
                                        // Checking for images: If image, then return link to thumbnail.
-                               $IEList = $this->stdWrap($conf['icon_image_ext_list'],$conf['icon_image_ext_list.']); 
+                               $IEList = $this->stdWrap($conf['icon_image_ext_list'],$conf['icon_image_ext_list.']);
                                $image_ext_list = str_replace(' ','',strtolower($IEList));
                                if ($fI['fileext'] && t3lib_div::inList($image_ext_list, $fI['fileext']))       {
                                        if ($conf['iconCObject'])       {
                                                $icon = $this->cObjGetSingle($conf['iconCObject'],$conf['iconCObject.'],'iconCObject');
                                        } else {
                                                if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'])   {
-                                                       $icon = 't3lib/thumbs.php?&dummy='.$GLOBALS['EXEC_TIME'].'&file='.rawurlencode('../'.$theFile);
+                                                       $thumbSize = '';
+                                                       if ($conf['icon_thumbSize'] || $conf['icon_thumbSize.'])        { $thumbSize = '&size='.$this->stdWrap($conf['icon_thumbSize'], $conf['icon_thumbSize.']); }
+                                                       $icon = 't3lib/thumbs.php?&dummy='.$GLOBALS['EXEC_TIME'].'&file='.rawurlencode('../'.$theFile).$thumbSize;
                                                } else {
                                                        $icon = 't3lib/gfx/notfound_thumb.gif';
                                                }
-                                               $icon = '<img src="'.htmlspecialchars($GLOBALS['TSFE']->absRefPrefix.$icon).'" border="0" alt="" />';
+                                               $icon = '<img src="'.htmlspecialchars($GLOBALS['TSFE']->absRefPrefix.$icon).'"'.$this->getBorderAttr(' border="0"').''.$this->getAltParam($conf).' />';
                                        }
                                } else {
-                                       $icon = '<img src="'.htmlspecialchars($GLOBALS['TSFE']->absRefPrefix.$icon).'" width="18" height="16" border="0" alt="" />';
+                                       $icon = '<img src="'.htmlspecialchars($GLOBALS['TSFE']->absRefPrefix.$icon).'" width="18" height="16"'.$this->getBorderAttr(' border="0"').''.$this->getAltParam($conf).' />';
                                }
                                if ($conf['icon_link']) {$icon = $this->wrap($icon, $theLinkWrap);}
                                $icon = $this->stdWrap($icon,$conf['icon.']);
@@ -3437,15 +3813,15 @@ class tslib_cObj {
                                $theValue = $this->wrap($this->wrap($theValue, $theLinkWrap), $conf['wrap']);
                        }
                        $file = $this->stdWrap($theValue,$conf['file.']);
-                               // output                       
+                               // output
                        return $this->stdWrap($icon.$file.$size, $conf['stdWrap.']);
                }
        }
 
        /**
-        * Returns a URL parameter string setting parameters for secure downloads by "jumpurl". 
+        * Returns a URL parameter string setting parameters for secure downloads by "jumpurl".
         * Helper function for filelink()
-        * 
+        *
         * @param       string          The URL to jump to, basically the filepath
         * @param       array           TypoScript properties for the "jumpurl.secure" property of "filelink"
         * @return      string          URL parameters like "&juSecure=1....."
@@ -3466,8 +3842,8 @@ class tslib_cObj {
                        }
                }
                $locationData = $GLOBALS['TSFE']->id.':'.$this->currentRecord;
-               $rec='&locationData='.$locationData;
-               $hArr = array(  
+               $rec='&locationData='.rawurlencode($locationData);
+               $hArr = array(
                        $jumpUrl,
                        $locationData,
                        $GLOBALS['TSFE']->TYPO3_CONF_VARS['SYS']['encryptionKey']
@@ -3478,7 +3854,7 @@ class tslib_cObj {
 
        /**
         * Performs basic mathematical evaluation of the input string. Does NOT take parathesis and operator precedence into account! (for that, see t3lib_div::calcPriority())
-        * 
+        *
         * @param       string          The string to evaluate. Example: "3+4*10/5" will generate "35". Only integer numbers can be used.
         * @return      integer         The result (might be a float if you did a division of the numbers).
         * @see t3lib_div::calcPriority()
@@ -3506,7 +3882,7 @@ class tslib_cObj {
        /**
         * This explodes a comma-list into an array where the values are parsed through tslib_cObj::calc() and intval() (so you are sure to have integers in the output array)
         * Used to split and calculate min and max values for GMENUs.
-        * 
+        *
         * @param       string          Delimited to explode by
         * @param       string          The string with parts in (where each part is evaluated by ->calc())
         * @return      array           And array with evaluated values.
@@ -3524,7 +3900,7 @@ class tslib_cObj {
         * Implements the "split" property of stdWrap; Splits a string based on a token (given in TypoScript properties), sets the "current" value to each part and then renders a content object pointer to by a number.
         * In classic TypoScript (like 'content (default)'/'styles.content (default)') this is used to render tables, splitting rows and cells by tokens and putting them together again wrapped in <td> tags etc.
         * Implements the "optionSplit" processing of the TypoScript options for each splitted value to parse.
-        * 
+        *
         * @param       string          The string value to explode by $conf[token] and process each part
         * @param       array           TypoScript properties for "split"
         * @return      string          Compiled result
@@ -3534,11 +3910,11 @@ class tslib_cObj {
         */
        function splitObj($value, $conf)        {
                $conf['token']=$this->stdWrap($conf['token'],$conf['token.']);
-               
+
                if ($conf['token'])     {
                        $conf['max']=intval($this->stdWrap($conf['max'],$conf['max.']));
                        $conf['min']=intval($this->stdWrap($conf['min'],$conf['min.']));
-                       
+
                        $valArr=explode($conf['token'],$value);
                                // calculate splitCount
                        $splitCount = count($valArr);
@@ -3575,24 +3951,37 @@ class tslib_cObj {
        }
 
        /**
-        * Implements the stdWrap property, "parseFunc". 
-        * This is a function with a lot of interesting uses. In classic TypoScript this is used to process text from the bodytext field; This included highlighting of search words, changing http:// and mailto: prefixed strings into links, parsing <typolist>, <typohead> and <typocode> tags etc. 
+        * Implements the stdWrap property, "parseFunc".
+        * This is a function with a lot of interesting uses. In classic TypoScript this is used to process text from the bodytext field; This included highlighting of search words, changing http:// and mailto: prefixed strings into links, parsing <typolist>, <typohead> and <typocode> tags etc.
         * It is still a very important function for processing of bodytext which is normally stored in the database in a format which is not fully ready to be outputted. This situation has not become better by having a RTE around...
-        * 
+        *
         * This function is actually just splitting the input content according to the configuration of "external blocks". This means that before the input string is actually "parsed" it will be splitted into the parts configured to BE parsed (while other parts/blocks should NOT be parsed). Therefore the actual processing of the parseFunc properties goes on in ->_parseFunc()
-        * 
+        *
         * @param       string          The value to process.
         * @param       array           TypoScript configuration for parseFunc
+        * @param       string          Reference to get configuration from. Eg. "< lib.parseFunc" which means that the configuration of the object path "lib.parseFunc" will be retrieved and MERGED with what is in $conf!
         * @return      string          The processed value
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=327&cHash=33331f0396
         * @see _parseFunc()
         */
-       function parseFunc($theValue, $conf) {
+       function parseFunc($theValue, $conf, $ref='') {
+
+                       // Fetch / merge reference, if any
+               if ($ref)       {
+                       $temp_conf = array(
+                                                               'parseFunc' => $ref,
+                                                               'parseFunc.' => $conf
+                                                       );
+                       $temp_conf = $this->mergeTSRef($temp_conf, 'parseFunc');
+                       $conf = $temp_conf['parseFunc.'];
+               }
+
+                       // Process:
                if (strcmp($conf['externalBlocks'],'')) {
                        $tags = strtolower(implode(',',t3lib_div::trimExplode(',',$conf['externalBlocks'])));
                        $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');
                        $parts = $htmlParser->splitIntoBlock($tags,$theValue);
-                       
+
                        reset($parts);
                        while(list($k,$v)=each($parts)) {
                                if ($k%2)       {       // font:
@@ -3616,10 +4005,14 @@ class tslib_cObj {
                                        if ($cfg['callRecursive'])      {
                                                $parts[$k]=$this->parseFunc($htmlParser->removeFirstAndLastTag($v), $conf);
                                                if (!$cfg['callRecursive.']['dontWrapSelf'])    {
-                                                       if (is_array($cfg['callRecursive.']['tagStdWrap.']))    {
-                                                               $tag = $this->stdWrap($tag,$cfg['callRecursive.']['tagStdWrap.']);
+                                                       if ($cfg['callRecursive.']['alternativeWrap'])  {
+                                                               $parts[$k] = $this->wrap($parts[$k], $cfg['callRecursive.']['alternativeWrap']);
+                                                       } else {
+                                                               if (is_array($cfg['callRecursive.']['tagStdWrap.']))    {
+                                                                       $tag = $this->stdWrap($tag,$cfg['callRecursive.']['tagStdWrap.']);
+                                                               }
+                                                               $parts[$k]=$tag.$parts[$k].'</'.$tagName.'>';
                                                        }
-                                                       $parts[$k]=$tag.$parts[$k].'</'.$tagName.'>';
                                                }
                                        } elseif($cfg['HTMLtableCells']) {
                                                $rowParts = $htmlParser->splitIntoBlock('tr',$parts[$k]);
@@ -3650,7 +4043,7 @@ class tslib_cObj {
                                                                                if (is_array($stdWrap)) {
                                                                                        $colParts[$kkk] = $this->stdWrap($colParts[$kkk],$stdWrap);
                                                                                }
-                                                                               
+
                                                                                $colParts[$kkk]=$tag.$colParts[$kkk].'</'.$tagName.'>';
                                                                        }
                                                                }
@@ -3659,7 +4052,7 @@ class tslib_cObj {
                                                }
                                                $parts[$k] = implode('',$rowParts);
                                        }
-                                       
+
                                        if (is_array($cfg['stdWrap.'])) {
                                                $parts[$k] = $this->stdWrap($parts[$k],$cfg['stdWrap.']);
                                        }
@@ -3674,7 +4067,7 @@ class tslib_cObj {
 
        /**
         * Helper function for parseFunc()
-        * 
+        *
         * @param       string          The value to process.
         * @param       array           TypoScript configuration for parseFunc
         * @return      string          The processed value
@@ -3708,8 +4101,8 @@ class tslib_cObj {
                                                $endChar = ord(strtolower(substr($theValue,$pointer+$len_p,1)));
                                                $c--;
                                        } while ($c>0 && $endChar && ($endChar<97 || $endChar>122) && $endChar!=47);
-                                       $len = $len_p-1;                                        
-                               } else {                
+                                       $len = $len_p-1;
+                               } else {
                                                // If we're inside a currentTag, just take it to the end of that tag!
                                        $tempContent = strtolower(substr($theValue,$pointer));
                                        $len = strpos ($tempContent, '</'.$currentTag[0]);
@@ -3745,7 +4138,7 @@ class tslib_cObj {
                                                                }
                                                        }
                                                }
-                                               
+
                                                        // stdWrap
                                                if (is_array($conf['plainTextStdWrap.']))       {$data = $this->stdWrap($data,$conf['plainTextStdWrap.']);}
                                                        // userFunc
@@ -3756,7 +4149,7 @@ class tslib_cObj {
                                                        $data = $this->http_makelinks($data,$conf['makelinks.']['http.']);
                                                        $data = $this->mailto_makelinks($data,$conf['makelinks.']['mailto.']);
                                                }
-                                               
+
                                                        // Search Words:
                                                if ($GLOBALS['TSFE']->no_cache && $conf['sword'] && is_array($GLOBALS['TSFE']->sWordList) && $GLOBALS['TSFE']->sWordRegEx)      {
                                                        $newstring = '';
@@ -3839,7 +4232,7 @@ class tslib_cObj {
                                                        unset($contentAccum[$contentAccumP-1]);
                                                        $contentAccumP-=2;
                                                }
-                                               
+
                                                unset($currentTag);
                                                $treated=1;
                                        }
@@ -3876,7 +4269,7 @@ class tslib_cObj {
 
        /**
         * Lets you split the content by chr(10) and proces each line independently. Used to format content made with the RTE.
-        * 
+        *
         * @param       string          The input value
         * @param       array           TypoScript options
         * @return      string          The processed input value being returned; Splitted lines imploded by chr(10) again.
@@ -3889,9 +4282,9 @@ class tslib_cObj {
                $encapTags = t3lib_div::trimExplode(',',strtolower($conf['encapsTagList']),1);
                $nonWrappedTag = $conf['nonWrappedTag'];
                $defaultAlign=trim($this->stdWrap($conf['defaultAlign'],$conf['defaultAlign.']));
-               
+
                if (!strcmp('',$theValue))      return '';
-               
+
                while(list($k,$l)=each($lParts))        {
                        $sameBeginEnd=0;
                        $l=trim($l);
@@ -3941,7 +4334,7 @@ class tslib_cObj {
                                        // Default align
                                if (!$attrib['align'] && $defaultAlign) $attrib['align']=$defaultAlign;
 
-                               $params = t3lib_div::implodeParams($attrib,1);
+                               $params = t3lib_div::implodeAttributes($attrib,1);
                                if ($conf['removeWrapping'])    {
                                        $str_content=$str_content;
                                } else {
@@ -3959,7 +4352,7 @@ class tslib_cObj {
        /**
         * Finds URLS in text and makes it to a real link.
         * Will find all strings prefixed with "http://" in the $data string and make them into a link, linking to the URL we should have found.
-        * 
+        *
         * @param       string          The string in which to search for "http://"
         * @param       array           Configuration for makeLinks, see link
         * @return      string          The processed input string, being returned.
@@ -4019,14 +4412,14 @@ class tslib_cObj {
                                $textstr.=$res.$parts[1];
                        } else {
                                $textstr.='http://'.$textpieces[$i];
-                       }                               
+                       }
                }
                return $textstr;
        }
 
        /**
         * Will find all strings prefixed with "mailto:" in the $data string and make them into a link, linking to the email address they point to.
-        * 
+        *
         * @param       string          The string in which to search for "mailto:"
         * @param       array           Configuration for makeLinks, see link
         * @return      string          The processed input string, being returned.
@@ -4041,19 +4434,17 @@ class tslib_cObj {
                $textstr = $textpieces[0];
                $initP = '?id='.$GLOBALS['TSFE']->id.'&type='.$GLOBALS['TSFE']->type;
                for($i=1; $i<$pieces; $i++)     {
-                       $len=strcspn($textpieces[$i],chr(32).chr(9).chr(13).chr(10));
+                       $len = strcspn($textpieces[$i],chr(32).chr(9).chr(13).chr(10));
                        if (trim(substr($textstr,-1))=='' && $len)      {
-                               $lastChar=substr($textpieces[$i],$len-1,1);
+                               $lastChar = substr($textpieces[$i],$len-1,1);
                                if (!ereg('[A-Za-z0-9]',$lastChar)) {$len--;}
 
-                               $parts[0]=substr($textpieces[$i],0,$len);
-                               $parts[1]=substr($textpieces[$i],$len);
-                               $linktxt=ereg_replace('\?.*','',$parts[0]);
-                               if (!$GLOBALS['TSFE']->config['config']['jumpurl_enable'] || $GLOBALS['TSFE']->config['config']['jumpurl_mailto_disable'])      {
-                                       $res = '<a href="mailto:'.htmlspecialchars($parts[0]).'"'.$aTagParams.'>';
-                               } else {
-                                       $res = '<a href="'.htmlspecialchars($GLOBALS['TSFE']->absRefPrefix.$GLOBALS['TSFE']->config['mainScript'].$initP.'&jumpurl='.rawurlencode('mailto:'.$parts[0]).$GLOBALS['TSFE']->getMethodUrlIdToken).'"'.$aTagParams.'>';
-                               }
+                               $parts[0] = substr($textpieces[$i],0,$len);
+                               $parts[1] = substr($textpieces[$i],$len);
+                               $linktxt = ereg_replace('\?.*','',$parts[0]);
+                               list($mailToUrl,$linktxt) = $this->getMailTo($parts[0],$linktxt,$initP);
+                               $mailToUrl = $GLOBALS['TSFE']->spamProtectEmailAddresses === 'ascii'?$mailToUrl:htmlspecialchars($mailToUrl);
+                               $res = '<a href="'.$mailToUrl.'"'.$aTagParams.'>';
                                if ($conf['ATagBeforeWrap'])    {
                                        $res= $res.$this->wrap($linktxt, $conf['wrap']).'</a>';
                                } else {
@@ -4062,16 +4453,16 @@ class tslib_cObj {
                                $textstr.=$res.$parts[1];
                        } else {
                                $textstr.='mailto:'.$textpieces[$i];
-                       }                               
+                       }
                }
                return $textstr;
        }
 
        /**
-        * Creates and returns a TypoScript "imgResource". 
+        * Creates and returns a TypoScript "imgResource".
         * The value ($file) can either be a file reference (TypoScript resource) or the string "GIFBUILDER". In the first case a current image is returned, possibly scaled down or otherwise processed. In the latter case a GIFBUILDER image is returned; This means an image is made by TYPO3 from layers of elements as GIFBUILDER defines.
         * In the function IMG_RESOURCE() this function is called like $this->getImgResource($conf['file'],$conf['file.']);
-        * 
+        *
         * @param       string          A "imgResource" TypoScript data type. Either a TypoScript file resource or the string GIFBUILDER. See description above.
         * @param       array           TypoScript properties for the imgResource type
         * @return      array           Returns info-array. info[origFile] = original file.
@@ -4117,15 +4508,20 @@ class tslib_cObj {
                                                if (!isset($GLOBALS['TSFE']->tmpl->fileCache[$hash]))   {
                                                        $gifCreator = t3lib_div::makeInstance('tslib_gifbuilder');
                                                        $gifCreator->init();
+
+                                                       if ($GLOBALS['TSFE']->config['config']['meaningfulTempFilePrefix'])     {
+                                                               $gifCreator->filenamePrefix = $GLOBALS['TSFE']->fileNameASCIIPrefix(ereg_replace('\.[[:alnum:]]+$','',basename($theImage)),intval($GLOBALS['TSFE']->config['config']['meaningfulTempFilePrefix']),'_');
+                                                       }
+
                                                        if ($fileArray['sample'])       {
                                                                $gifCreator->scalecmd = '-sample';
                                                                $GLOBALS['TT']->setTSlogMessage('Sample option: Images are scaled with -sample.');
                                                        }
                                                        if ($fileArray['alternativeTempPath'] && t3lib_div::inList($GLOBALS['TYPO3_CONF_VARS']['FE']['allowedTempPaths'],$fileArray['alternativeTempPath']))    {
-                                                               $gifCreator->tempPath = $fileArray['alternativeTempPath'];      
+                                                               $gifCreator->tempPath = $fileArray['alternativeTempPath'];
                                                                $GLOBALS['TT']->setTSlogMessage('Set alternativeTempPath: '.$fileArray['alternativeTempPath']);
                                                        }
-                                                       
+
                                                        if (!trim($fileArray['ext'])){$fileArray['ext']='web';}
                                                        $options = Array();
                                                        if ($fileArray['maxW']) {$options['maxW']=$fileArray['maxW'];}
@@ -4159,7 +4555,7 @@ class tslib_cObj {
                                                                                        $tempScale=array();
                                                                                        $command = '-geometry '.$tempFileInfo[0].'x'.$tempFileInfo[1].'!';
                                                                                        $tmpStr = $gifCreator->randomName();
-                                                                                       
+
                                                                                                //      m_mask
                                                                                        $tempScale['m_mask']=$tmpStr.'_mask.'.$temp_ext;
                                                                                        $gifCreator->imageMagickExec($m_mask[3],$tempScale['m_mask'],$command.$negate);
@@ -4173,7 +4569,7 @@ class tslib_cObj {
                                                                                                $gifCreator->imageMagickExec($m_bottomImg[3],$tempScale['m_bottomImg'],$command);
                                                                                                $tempScale['m_bottomImg_mask']=$tmpStr.'_bottomImg_mask.'.$temp_ext;
                                                                                                $gifCreator->imageMagickExec($m_bottomImg_mask[3],$tempScale['m_bottomImg_mask'],$command.$negate);
-       
+
                                                                                                        // BEGIN combining:
                                                                                                        // The image onto the background
                                                                                                $gifCreator->combineExec($tempScale['m_bgImg'],$tempScale['m_bottomImg'],$tempScale['m_bottomImg_mask'],$tempScale['m_bgImg']);
@@ -4201,7 +4597,7 @@ class tslib_cObj {
                                                }
                                                return $GLOBALS['TSFE']->tmpl->fileCache[$hash];
                                        }
-                                       
+
                                break;
                        }
                }
@@ -4231,24 +4627,24 @@ class tslib_cObj {
 
 
 
-       
-       
-       
-       
-       
-       
+
+
+
+
+
+
        /***********************************************
         *
         * Data retrieval etc.
         *
         ***********************************************/
 
-       
+
        /**
         * Returns the value for the field from $this->data. If "//" is found in the $field value that token will split the field values apart and the first field having a non-blank value will be returned.
-        * 
+        *
         * @param       string          The fieldname, eg. "title" or "navtitle // title" (in the latter case the value of $this->data[navtitle] is returned if not blank, otherwise $this->data[title] will be)
-        * @return      string          
+        * @return      string
         */
        function getFieldVal($field)    {
                if (!strstr($field,'//'))       {
@@ -4263,7 +4659,7 @@ class tslib_cObj {
 
        /**
         * Implements the TypoScript data type "getText". This takes a string with parameters and based on those a value from somewhere in the system is returned.
-        * 
+        *
         * @param       string          The parameter string, eg. "field : title" or "field : navtitle // field : title" (in the latter case and example of how the value is FIRST splitted by "//" is shown)
         * @param       mixed           Alternative field array; If you set this to an array this variable will be used to look up values for the "field" key. Otherwise the current page record in $GLOBALS['TSFE']->page is used.
         * @return      string          The value fetched
@@ -4283,63 +4679,106 @@ class tslib_cObj {
                        if ((string)$key!='')   {
                                switch(strtolower(trim($parts[0])))     {
                                        case 'gpvar':
-                                               $retVal= t3lib_div::GPvar($key);
+                                               list($firstKey, $rest) = explode('|', $key, 2);
+                                               if (strlen(trim($firstKey)))    {
+                                                       $retVal = t3lib_div::_GP(trim($firstKey));
+                                                               // Look for deeper levels:
+                                                       if (strlen(trim($rest)))        {
+                                                               $retVal = is_array($retVal) ? $this->getGlobal($rest, $retVal) : '';
+                                                       }
+                                                               // Check that output is not an array:
+                                                       if (is_array($retVal))  $retVal = '';
+                                               }
                                        break;
                                        case 'tsfe':
-                                               $retVal= $GLOBALS['TSFE']->$key;
+                                               $retVal = $GLOBALS['TSFE']->$key;
                                        break;
                                        case 'getenv':
-                                               $retVal= getenv($key);
+                                               $retVal = getenv($key);
+                                       break;
+                                       case 'getindpenv':
+                                               $retVal = t3lib_div::getIndpEnv($key);
                                        break;
                                        case 'field':
-                                               $retVal= $fieldArray[$key];
+                                               $retVal = $fieldArray[$key];
                                        break;
                                        case 'parameters':
-                                               $retVal= $this->parameters[$key];
+                                               $retVal = $this->parameters[$key];
                                        break;
                                        case 'register':
-                                               $retVal= $GLOBALS['TSFE']->register[$key];
+                                               $retVal = $GLOBALS['TSFE']->register[$key];
                                        break;
                                        case 'global':
-                                               $retVal= $this->getGlobal($key);
+                                               $retVal = $this->getGlobal($key);
                                        break;
                                        case 'leveltitle':
                                                $nkey = $this->getKey($key,$GLOBALS['TSFE']->tmpl->rootLine);
-                                               $retVal= $this->rootLineValue($nkey,'title',stristr($key,'slide'));
+                                               $retVal = $this->rootLineValue($nkey,'title',stristr($key,'slide'));
                                        break;
                                        case 'levelmedia':
                                                $nkey = $this->getKey($key,$GLOBALS['TSFE']->tmpl->rootLine);
-                                               $retVal= $this->rootLineValue($nkey,'media',stristr($key,'slide'));
+                                               $retVal = $this->rootLineValue($nkey,'media',stristr($key,'slide'));
                                        break;
                                        case 'leveluid':
                                                $nkey = $this->getKey($key,$GLOBALS['TSFE']->tmpl->rootLine);
-                                               $retVal= $this->rootLineValue($nkey,'uid',stristr($key,'slide'));
+                                               $retVal = $this->rootLineValue($nkey,'uid',stristr($key,'slide'));
+                                       break;
+                                       case 'levelfield':
+                                               $keyP = t3lib_div::trimExplode(',',$key);
+                                               $nkey = $this->getKey($keyP[0],$GLOBALS['TSFE']->tmpl->rootLine);
+                                               $retVal = $this->rootLineValue($nkey,$keyP[1],strtolower($keyP[2])=='slide');
                                        break;
                                        case 'fullrootline':
-                                               $keyP=t3lib_div::trimExplode(',',$key);
+                                               $keyP = t3lib_div::trimExplode(',',$key);
                                                $fullKey = intval($keyP[0])-count($GLOBALS['TSFE']->tmpl->rootLine)+count($GLOBALS['TSFE']->rootLine);
                                                if ($fullKey>=0)        {
-                                                       $retVal= $this->rootLineValue($fullKey,$keyP[1],stristr($keyP[2],'slide'),$GLOBALS['TSFE']->rootLine);
+                                                       $retVal = $this->rootLineValue($fullKey,$keyP[1],stristr($keyP[2],'slide'),$GLOBALS['TSFE']->rootLine);
                                                }
                                        break;
                                        case 'date':
                                                if (!$key) {$key = 'd/m Y';}
-                                               $retVal= Date($key, time());
+                                               $retVal = date($key, time());
                                        break;
                                        case 'page':
-                                               $retVal= $GLOBALS['TSFE']->page[$key];
+                                               $retVal = $GLOBALS['TSFE']->page[$key];
                                        break;
                                        case 'current':
-                                               $retVal= $this->data[$this->currentValKey];
+                                               $retVal = $this->data[$this->currentValKey];
                                        break;
                                        case 'level':
-                                               $retVal= count($GLOBALS['TSFE']->tmpl->rootLine)-1;
+                                               $retVal = count($GLOBALS['TSFE']->tmpl->rootLine)-1;
                                        break;
                                        case 'db':
                                                $selectParts = t3lib_div::trimExplode(':',$key);
                                                $db_rec = $GLOBALS['TSFE']->sys_page->getRawRecord($selectParts[0],$selectParts[1]);
                                                if (is_array($db_rec) && $selectParts[2])       {$retVal = $db_rec[$selectParts[2]];}
                                        break;
+                                       case 'lll':
+                                               $retVal = $GLOBALS['TSFE']->sL('LLL:'.$key);
+                                       break;
+                                       case 'path':
+                                               $retVal = $GLOBALS['TSFE']->tmpl->getFileName($key);
+                                       break;
+                                       case 'cobj':
+                                               switch((string)$key)    {
+                                                       case 'parentRecordNumber':
+                                                               $retVal = $this->parentRecordNumber;
+                                                       break;
+                                               }
+                                       break;
+                                       case 'debug':
+                                               switch((string)$key)    {
+                                                       case 'rootLine':
+                                                               $retVal = t3lib_div::view_array($GLOBALS['TSFE']->tmpl->rootLine);
+                                                       break;
+                                                       case 'fullRootLine':
+                                                               $retVal = t3lib_div::view_array($GLOBALS['TSFE']->rootLine);
+                                                       break;
+                                                       case 'data':
+                                                               $retVal = t3lib_div::view_array($this->data);
+                                                       break;
+                                               }
+                                       break;
                                }
                        }
                }
@@ -4348,7 +4787,7 @@ class tslib_cObj {
 
        /**
         * Returns a value from the current rootline (site) from $GLOBALS['TSFE']->tmpl->rootLine;
-        * 
+        *
         * @param       string          Which level in the root line
         * @param       string          The field in the rootline record to return (a field from the pages table)
         * @param       boolean         If set, then we will traverse through the rootline from outer level towards the root level until the value found is true
@@ -4371,17 +4810,18 @@ class tslib_cObj {
 
        /**
         * Returns a value from the array, $GLOBALS where the input key, $val, is splitted by "|" first and each part points to a key in the $GLOBALS array.
-        * Example: $var = "HTTP_GET_VARS | id" will return the value $GLOBALS['HTTP_GET_VARS']['id'] value
-        * 
+        * Example: $var = "HTTP_SERVER_VARS | something" will return the value $GLOBALS['HTTP_SERVER_VARS']['something'] value
+        *
         * @param       string          Key, see description of functon
+        * @param       array           If you want another array than $GLOBALS used, then just put it in here!
         * @return      mixed           Value from $GLOBALS
         * @access private
         * @see getData()
         */
-       function getGlobal($var) {
-               $vars = explode('|',$var);
+       function getGlobal($var, $source=NULL) {
+               $vars = explode('|', $var);
                $c = count($vars);
-               $theVar = $GLOBALS[trim($vars[0])];
+               $theVar = isset($source) ? $source[trim($vars[0])] : $GLOBALS[trim($vars[0])];
                for ($a=1;$a<$c;$a++) {
                        if (!isset($theVar))    {break;}
                        $theVar = $theVar[trim($vars[$a])];
@@ -4396,7 +4836,7 @@ class tslib_cObj {
        /**
         * Processing of key values pointing to entries in $arr; Here negative values are converted to positive keys pointer to an entry in the array but from behind (based on the negative value).
         * Example: entrylevel = -1 means that entryLevel ends up pointing at the outermost-level, -2 means the level before the outermost...
-        * 
+        *
         * @param       integer         The integer to transform
         * @param       array           Array in which the key should be found.
         * @return      integer         The processed integer key value.
@@ -4411,27 +4851,24 @@ class tslib_cObj {
                        }
                        if ($key < 0)   {
                                $key=0;
-                       }               
+                       }
                }
                return $key;
        }
 
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
+
+
+
+
+
+
+
+
+
+
+
+
+
 
 
 
@@ -4444,14 +4881,14 @@ class tslib_cObj {
         *
         ***********************************************/
 
-       
+
        /**
         * Implements the "typolink" property of stdWrap (and others)
         * Basically the input string, $linktext, is (typically) wrapped in a <a>-tag linking to some page, email address, file or URL based on a parameter defined by the configuration array $conf.
         * This function is best used from internal functions as is. There are some API functions defined after this function which is more suited for general usage in external applications.
         * Generally the concept "typolink" should be used in your own applications as an API for making links to pages with parameters and more. The reason for this is that you will then automatically make links compatible with all the centralized functions for URL simulation and manipulation of parameters into hashes and more.
         * For many more details on the parameters and how they are intepreted, please see the link to TSref below.
-        * 
+        *
         * @param       string          The string (text) to link
         * @param       array           TypoScript configuration (see link below)
         * @return      string          A link-wrapped string.
@@ -4459,24 +4896,24 @@ class tslib_cObj {
         * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=321&cHash=59bd727a5e
         */
        function typoLink($linktxt, $conf)      {
-               $finalTagParts=array();
+               $finalTagParts = array();
                $finalTagParts['aTagParams'] = $GLOBALS['TSFE']->ATagParams.($conf['ATagParams']?' '.$conf['ATagParams']:'');
-               
+
                $link_param = trim($this->stdWrap($conf['parameter'],$conf['parameter.']));
                $sectionMark = trim($this->stdWrap($conf['section'],$conf['section.']));
                $sectionMark = $sectionMark ? '#'.$sectionMark : '';
                $initP = '?id='.$GLOBALS['TSFE']->id.'&type='.$GLOBALS['TSFE']->type;
-               $this->lastTypoLinkUrl='';
+               $this->lastTypoLinkUrl = '';
                $this->lastTypoLinkTarget = '';
                if ($link_param)        {
                        $link_paramA = t3lib_div::trimExplode(' ',$link_param,1);
                        $link_param = trim($link_paramA[0]);    // Link parameter value
                        $linkClass = trim($link_paramA[2]);             // Link class
                        $forceTarget = trim($link_paramA[1]);   // Target value
-                       if ($forceTarget=='-')  $forceTarget='';        // The '-' character means 'no target'. Necessary in order to specify a class as third parameter without setting the target!
+                       if ($forceTarget=='-')  $forceTarget = '';      // The '-' character means 'no target'. Necessary in order to specify a class as third parameter without setting the target!
                                // Check, if the target is coded as a JS open window link:
-                       $JSwindowParts=array();
-                       $JSwindowParams='';
+                       $JSwindowParts = array();
+                       $JSwindowParams = '';
                        $onClick = '';
                        if ($forceTarget && ereg('^([0-9]+)x([0-9]+)(:(.*)|.*)$',$forceTarget,$JSwindowParts))  {
                                        // Take all pre-configured and inserted parameters and compile parameter list, including width+height:
@@ -4493,25 +4930,18 @@ class tslib_cObj {
                                $JSwindowParams = implode(',',$JSwindow_paramsArr);
                                $forceTarget = '';      // Resetting the target since we will use onClick.
                        }
-                       
+
                                // Internal target:
                        $target = isset($conf['target']) ? $conf['target'] : $GLOBALS['TSFE']->intTarget;
                        if ($conf['target.'])   {$target=$this->stdWrap($target, $conf['target.']);}
-                       
+
+                               // Parse URL:
+                       $pU = parse_url($link_param);
+
                                // Detecting kind of link:
-                       if(strstr($link_param,'@'))     {               // If it's a mail address:
+                       if(strstr($link_param,'@') && !$pU['scheme'])   {               // If it's a mail address:
                                $link_param = eregi_replace('^mailto:','',$link_param);
-                               if ($linktxt=='') $linktxt = $link_param;
-                               if (!$GLOBALS['TSFE']->config['config']['jumpurl_enable'] || $GLOBALS['TSFE']->config['config']['jumpurl_mailto_disable'])      {
-                                       $this->lastTypoLinkUrl = 'mailto:'.$link_param;
-                                       if ($GLOBALS['TSFE']->spamProtectEmailAddresses)        {
-                                               $this->lastTypoLinkUrl = "javascript:linkTo_UnCryptMailto('".$GLOBALS['TSFE']->encryptEmail($this->lastTypoLinkUrl)."');";
-                                               $atLabel = trim($GLOBALS['TSFE']->config['config']['spamProtectEmailAddresses_atSubst']);
-                                               $linktxt=str_replace('@',$atLabel?$atLabel:'(at)',$linktxt);
-                                       }
-                               } else {
-                                       $this->lastTypoLinkUrl = $GLOBALS['TSFE']->absRefPrefix.$GLOBALS['TSFE']->config['mainScript'].$initP.'&jumpurl='.rawurlencode('mailto:'.$link_param).$GLOBALS['TSFE']->getMethodUrlIdToken;
-                               }
+                               list($this->lastTypoLinkUrl,$linktxt) = $this->getMailTo($link_param,$linktxt,$initP);
                                $finalTagParts['url']=$this->lastTypoLinkUrl;
                                $finalTagParts['TYPE']='mailto';
                        } else {
@@ -4521,17 +4951,20 @@ class tslib_cObj {
 
                                        // Detects if a file is found in site-root (or is a 'virtual' simulateStaticDocument file!) and if so it will be treated like a normal file.
                                list($rootFileDat) = explode('?',rawurldecode($link_param));
+                               $containsSlash = strstr($rootFileDat,'/');
                                $rFD_fI = pathinfo($rootFileDat);
-                               if (trim($rootFileDat) && !strstr($link_param,'/') && (@is_file(PATH_site.$rootFileDat) || t3lib_div::inList('php,html,htm',strtolower($rFD_fI['extension'])))) {       
-                                       $isLocalFile=1;
-                               } 
+                               if (trim($rootFileDat) && !$containsSlash && (@is_file(PATH_site.$rootFileDat) || t3lib_div::inList('php,html,htm',strtolower($rFD_fI['extension']))))  {
+                                       $isLocalFile = 1;
+                               } elseif ($containsSlash)       {
+                                       $isLocalFile = 2;               // Adding this so realurl directories are linked right (non-existing).
+                               }
 
-                               if(!$isLocalFile && $urlChar && (strstr($link_param,'//') || !$fileChar || $urlChar<$fileChar)) {       // url (external): If doubleSlash or if a '.' comes before a '/'.
+                               if($pU['scheme'] || ($isLocalFile!=1 && $urlChar && (!$containsSlash || $urlChar<$fileChar)))   {       // url (external): If doubleSlash or if a '.' comes before a '/'.
                                        $target = isset($conf['extTarget']) ? $conf['extTarget'] : $GLOBALS['TSFE']->extTarget;
                                        if ($conf['extTarget.'])        {$target = $this->stdWrap($target, $conf['extTarget.']);}
                                        if ($forceTarget)       {$target=$forceTarget;}
                                        if ($linktxt=='') $linktxt = $link_param;
-                                       if (!ereg('^[a-z]*://',trim(strtolower($link_param))))  {$scheme='http://';} else {$scheme='';}
+                                       if (!$pU['scheme'])     {$scheme='http://';} else {$scheme='';}
                                        if ($GLOBALS['TSFE']->config['config']['jumpurl_enable'])       {
                                                $this->lastTypoLinkUrl = $GLOBALS['TSFE']->absRefPrefix.$GLOBALS['TSFE']->config['mainScript'].$initP.'&jumpurl='.rawurlencode($scheme.$link_param).$GLOBALS['TSFE']->getMethodUrlIdToken;
                                        } else {
@@ -4541,8 +4974,8 @@ class tslib_cObj {
                                        $finalTagParts['url']=$this->lastTypoLinkUrl;
                                        $finalTagParts['targetParams'] = $target ? ' target="'.$target.'"' : '';
                                        $finalTagParts['TYPE']='url';
-                               } elseif ($fileChar || $isLocalFile)    {       // file (internal)
-                                       $splitLinkParam = explode('?',$link_param);
+                               } elseif ($containsSlash || $isLocalFile)       {       // file (internal)
+                                       $splitLinkParam = explode('?', $link_param);
                                        if (@file_exists(rawurldecode($splitLinkParam[0])) || $isLocalFile)     {
                                                if ($linktxt=='') $linktxt = rawurldecode($link_param);
                                                if ($GLOBALS['TSFE']->config['config']['jumpurl_enable'])       {
@@ -4553,14 +4986,14 @@ class tslib_cObj {
                                                if ($forceTarget)       {$target=$forceTarget;}
                                                $this->lastTypoLinkTarget = $target;
 
-                                               $finalTagParts['url']=$this->lastTypoLinkUrl;
+                                               $finalTagParts['url'] = $this->lastTypoLinkUrl;
                                                $finalTagParts['targetParams'] = $target ? ' target="'.$target.'"' : '';
-                                               $finalTagParts['TYPE']='file';
+                                               $finalTagParts['TYPE'] = 'file';
                                        } else {
                                                $GLOBALS['TT']->setTSlogMessage("typolink(): File '".$splitLinkParam[0]."' did not exist, so '".$linktxt."' was not linked.",1);
                                                return $linktxt;
                                        }
-                               } else {        // integer or alias (alias is without slashes or periods or commas, that is 'nospace,alphanum_x,lower,unique' according to tables.php!!)
+                               } else {        // integer or alias (alias is without slashes or periods or commas, that is 'nospace,alphanum_x,lower,unique' according to definition in $TCA!)
                                        if ($conf['no_cache.']) $conf['no_cache']=$this->stdWrap($conf['no_cache'], $conf['no_cache.']);
                                        $link_params_parts=explode('#',$link_param);
                                        $link_param = trim($link_params_parts[0]);              // Link-data del
@@ -4579,51 +5012,68 @@ class tslib_cObj {
                                        if (!t3lib_div::testInt($link_param))   {
                                                $link_param = $GLOBALS['TSFE']->sys_page->getPageIdFromAlias($link_param);
                                        }
-                                       $page = $GLOBALS['TSFE']->sys_page->getPage($link_param);
-                                       if ($page)      {
-                                                       // This checks if the linked id is in the rootline of this site.
+
+                                               // Looking up the page record to verify its existence:
+                                       $disableGroupAccessCheck = $GLOBALS['TSFE']->config['config']['typolinkLinkAccessRestrictedPages'] ? TRUE : FALSE;
+                                       $page = $GLOBALS['TSFE']->sys_page->getPage($link_param,$disableGroupAccessCheck);
+
+                                       if (count($page))       {
+                                                       // This checks if the linked id is in the rootline of this site and if not it will find the domain for that ID and prefix it:
                                                $tCR_domain='';
                                                if ($GLOBALS['TSFE']->config['config']['typolinkCheckRootline'])        {
-                                                       $tCR_rootline=$GLOBALS['TSFE']->sys_page->getRootLine($page['uid']);    // Gets rootline of linked-to page
-                                                       $tCR_flag=0;
-                                                       reset($tCR_rootline);
-                                                       while(list(,$tCR_data)=each($tCR_rootline))     {
-                                                                       if ($tCR_data['uid']==$GLOBALS['TSFE']->tmpl->rootLine[0]['uid'])       {
-                                                                               $tCR_flag = 1;  // OK, it was in rootline!
-                                                                               break;
-                                                                       }
+                                                       $tCR_rootline = $GLOBALS['TSFE']->sys_page->getRootLine($page['uid']);  // Gets rootline of linked-to page
+                                                       $tCR_flag = 0;
+                                                       foreach($tCR_rootline as $tCR_data)     {
+                                                               if ($tCR_data['uid']==$GLOBALS['TSFE']->tmpl->rootLine[0]['uid'])       {
+                                                                       $tCR_flag = 1;  // OK, it was in rootline!
+                                                                       break;
+                                                               }
                                                        }
                                                        if (!$tCR_flag) {
-                                                               reset($tCR_rootline);
-                                                               while(list(,$tCR_data)=each($tCR_rootline))     {
-                                                                       $query = 'SELECT * FROM sys_domain WHERE pid='.$tCR_data['uid'].' AND redirectTo=""'.
-                                                                               $this->enableFields('sys_domain').
-                                                                               ' ORDER BY sorting';
-                                                                       $res = mysql (TYPO3_db, $query);
-                                                                       echo mysql_error();
-                                                                       if ($row=mysql_fetch_assoc($res))       {
-                                                                               $tCR_domain=ereg_replace('\/$','',$row['domainName']);
+                                                               foreach($tCR_rootline as $tCR_data)     {
+                                                                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_domain', 'pid='.intval($tCR_data['uid']).' AND redirectTo=\'\''.$this->enableFields('sys_domain'), '', 'sorting');
+                                                                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                                                                               $tCR_domain = ereg_replace('\/$','',$row['domainName']);
                                                                                break;
                                                                        }
                                                                }
                                                        }
                                                }
-                                               $addQueryParams = trim($this->stdWrap($conf['additionalParams'],$conf['additionalParams.']));
-                                               if (substr($addQueryParams,0,1)!='&')           {
-                                                       $addQueryParams='';
-                                               } elseif ($conf['useCacheHash']) {      // cache hashing:
-                                                       $pA=$GLOBALS['TSFE']->cHashParams($addQueryParams.$GLOBALS['TSFE']->linkVars);  // Added '.$this->linkVars' dec 2003: The need for adding the linkVars is that they will be included in the link, but not the cHash. Thus the linkVars will always be the problem that prevents the cHash from working. I cannot see what negative implications in terms of incompatibilities this could bring, but for now I hope there are none. So here we go... (- kasper)
-                                                       $addQueryParams.='&cHash='.t3lib_div::shortMD5(serialize($pA));
+                                                       // MointPoints, look for closest MPvar:
+                                               $MPvarAcc = array();
+                                               if (!$GLOBALS['TSFE']->config['config']['MP_disableTypolinkClosestMPvalue'])    {
+                                                       $temp_MP = $this->getClosestMPvalueForPage($page['uid'],TRUE);
+                                                       if ($temp_MP)   $MPvarAcc['closest'] = $temp_MP;
                                                }
-                                                       // MointPoints:
-                                               if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] && $GLOBALS['TSFE']->MP)     {       
-                                                       if (!strcmp($GLOBALS['TSFE']->id,$page['uid'])) {       // same page as current.
-                                                               $addQueryParams.='&MP='.rawurlencode($GLOBALS['TSFE']->MP);
+                                                       // Look for overlay Mount Point:
+                                               $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($page['uid'], $page);
+                                               if (is_array($mount_info) && $mount_info['overlay'])    {
+                                                       $page = $GLOBALS['TSFE']->sys_page->getPage($mount_info['mount_pid'],$disableGroupAccessCheck);
+                                                       if (!count($page))      {
+                                                               $GLOBALS['TT']->setTSlogMessage("typolink(): Mount point '".$mount_info['mount_pid']."' was not available, so '".$linktxt."' was not linked.",1);
+                                                               return $linktxt;
                                                        }
+                                                       $MPvarAcc['re-map'] = $mount_info['MPvar'];
                                                }
 
+                                                       // Setting title if blank value to link:
                                                if ($linktxt=='') $linktxt = $page['title'];
-                                               if ($tCR_domain)        {               // If other domain, overwrite 
+
+                                                       // Query Params:
+                                               $addQueryParams = $conf['addQueryString'] ? '&'.t3lib_div::getIndpEnv('QUERY_STRING') : '';
+                                               $addQueryParams .= trim($this->stdWrap($conf['additionalParams'],$conf['additionalParams.']));
+                                               if (substr($addQueryParams,0,1)!='&')           {
+                                                       $addQueryParams = '';
+                                               } elseif ($conf['useCacheHash']) {      // cache hashing:
+                                                       $pA = t3lib_div::cHashParams($addQueryParams.$GLOBALS['TSFE']->linkVars);       // Added '.$this->linkVars' dec 2003: The need for adding the linkVars is that they will be included in the link, but not the cHash. Thus the linkVars will always be the problem that prevents the cHash from working. I cannot see what negative implications in terms of incompatibilities this could bring, but for now I hope there are none. So here we go... (- kasper)
+                                                       $addQueryParams.= '&cHash='.t3lib_div::shortMD5(serialize($pA));
+                                               }
+                                                       // Add "&MP" var:
+                                               if (count($MPvarAcc))   {
+                                                       $addQueryParams.= '&MP='.rawurlencode(implode(',',$MPvarAcc));
+                                               }
+                                                       // If other domain, overwrite
+                                               if ($tCR_domain)        {
                                                        $target = isset($conf['extTarget']) ? $conf['extTarget'] : $GLOBALS['TSFE']->extTarget;
                                                        if ($conf['extTarget.'])        {$target = $this->stdWrap($target, $conf['extTarget.']);}
                                                        if ($forceTarget)       {$target=$forceTarget;}