Small things
[Packages/TYPO3.CMS.git] / typo3 / sysext / cms / tslib / class.tslib_content.php
index 4bba4ab..713ec7d 100755 (executable)
@@ -1,22 +1,22 @@
 <?php
 /***************************************************************
 *  Copyright notice
-*  
-*  (c) 1999-2004 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]
  *
  *
  *
- *  243: class tslib_cObj 
- *  340:     function start($data,$table='')   
- *  355:     function setParent($data,$currentRecord)  
+ *  250: class tslib_cObj
+ *  344:     function start($data,$table='')
+ *  359:     function setParent($data,$currentRecord)
  *
  *              SECTION: CONTENT_OBJ:
- *  380:     function getCurrentVal()  
- *  391:     function setCurrentVal($value)    
- *  404:     function cObjGet($setup,$addKey='')       
- *  428:     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)
- *  567:     function HTML($conf)      
- *  578:     function TEXT($conf)      
- *  589:     function CLEARGIF($conf)  
- *  608:     function COBJ_ARRAY($conf,$ext='')        
- *  644:     function USER($conf,$ext='')      
- *  671:     function FILE($conf)      
- *  687:     function IMAGE($conf)     
- *  706:     function IMG_RESOURCE($conf)      
- *  718:     function IMGTEXT($conf) 
- * 1097:     function CONTENT($conf)   
- * 1148:     function RECORDS($conf)   
- * 1215:     function HMENU($conf)     
- * 1247:     function CTABLE ($conf)   
- * 1285:     function OTABLE ($conf)   
- * 1300:     function COLUMNS ($conf)  
- * 1379:     function HRULER ($conf)   
- * 1403:     function CASEFUNC ($conf)
- * 1428:     function LOAD_REGISTER($conf,$name)       
- * 1468:     function FORM($conf,$formData='')    
- * 1843:     function SEARCHRESULT($conf)      
- * 2002:     function PHP_SCRIPT($conf,$ext='')        
- * 2045:     function TEMPLATE($conf)  
- * 2189:     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:
- * 2278:     function netprintApplication_offsiteLinkWrap($str,$imgConf,$conf) 
- * 2319:     function getFieldDefaultValue($noValueInsert, $fieldName, $defaultVal) 
- * 2337:     function cImage($file,$conf) 
- * 2364:     function imageLinkWrap($string,$imageFile,$conf) 
- * 2428:     function fileResource($fName)     
- * 2451:     function lastChanged($tstamp)     
- * 2468:     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
- * 2513:     function getSubpart($content, $marker)    
- * 2542:     function substituteSubpart($content,$marker,$subpartContent,$recursive=1) 
- * 2584:     function substituteMarker($content,$marker,$markContent)  
- * 2604:     function substituteMarkerArrayCached($content,$markContentArray=array(),$subpartContentArray=array(),$wrappedSubpartContentArray=array()) 
- * 2702:     function substituteMarkerArray($content,$markContentArray,$wrap='',$uppercase=0)  
- * 2723:     function substituteMarkerInObject(&$tree, $markContentArray) 
- * 2746:     function fillInMarkerArray($markContentArray, $row, $fieldList='', $nl2br=TRUE, $prefix='FIELD_', $HSC=FALSE)     
+ * 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
- * 2809:     function stdWrap($content,$conf)  
- * 2956:     function numRows($conf)   
- * 2977:     function listNum($content,$listNum,$char) 
- * 2997:     function checkIf($conf)   
- * 3060:     function filelist($data)  
- * 3139:     function clean_directory($theDir) 
- * 3157:     function HTMLparser_TSbridge($theValue, $conf)    
- * 3171:     function dataWrap($content,$wrap) 
- * 3184:     function insertData($str) 
- * 3214:     function prefixComment($str,$conf,$content)       
- * 3238:     function substring($content,$options)     
- * 3256:     function crop($content,$options)  
- * 3282:     function textStyle($theValue, $conf) 
- * 3349:     function tableStyle($theValue, $conf) 
- * 3390:     function addParams($content,$conf) 
- * 3433:     function filelink($theValue, $conf)       
- * 3500:     function locDataJU($jumpUrl,$conf)        
- * 3531:     function calc($val)       
- * 3560:     function calcIntExplode($delim, $string)  
- * 3580:     function splitObj($value, $conf)  
- * 3636:     function parseFunc($theValue, $conf, $ref='') 
- * 3742:     function _parseFunc ($theValue, $conf) 
- * 3944:     function encaps_lineSplit($theValue, $conf)       
- * 4027:     function http_makelinks($data,$conf)      
- * 4094:     function mailto_makelinks($data,$conf)    
- * 4139:     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.
- * 4311:     function getFieldVal($field)      
- * 4331:     function getData($string,$fieldArray)     
- * 4446:     function rootLineValue($key,$field,$slideBack=0,$altRootLine='')  
- * 4467:     function getGlobal($var) 
- * 4492:     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)
- * 4544:     function typoLink($linktxt, $conf)        
- * 4787:     function typoLink_URL($conf)      
- * 4805:     function getTypoLink($label,$params,$urlParameters=array(),$target='')    
- * 4835:     function getTypoLink_URL($params,$urlParameters=array(),$target='')       
- * 4847:     function typolinkWrap($conf)      
- * 4860:     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
- * 4904:     function wrap($content,$wrap,$char='|')   
- * 4920:     function noTrimWrap($content,$wrap)       
- * 4934:     function wrapSpace($content, $wrap)       
- * 4960:     function callUserFunction($funcName,$conf,$content)       
- * 5001:     function processParams($params)   
- * 5019:     function keywords($content)       
- * 5036:     function caseshift($theValue, $case)      
- * 5059:     function HTMLcaseshift($theValue, $case)  
- * 5088:     function bytes($sizeInBytes,$labels)      
- * 5099:     function calcAge($seconds,$labels)        
- * 5130:     function sendNotifyEmail($msg, $recipients, $cc, $email_from, $email_fromName='', $replyTo='')    
- * 5157:     function URLqMark($url,$params)   
- * 5173:     function checkEmail($email)       
- * 5185:     function clearTSProperties($TSArr,$propList)      
- * 5204:     function mergeTSRef($confArr,$prop)       
- * 5227:     function joinTSarrays($conf,$old_conf)    
- * 5250:     function gifBuilderTextBox($gifbuilderConf, $conf, $text) 
- * 5306:     function linebreaks($string,$chars,$maxLines=0)   
- * 5337:     function getUpdateJS($dataArray, $formName, $arrPrefix, $fieldList)       
+ * 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
- * 5406:     function DBgetDelete($table, $uid, $doExec=FALSE) 
- * 5438:     function DBgetUpdate($table, $uid, $dataArr, $fieldList, $doExec=FALSE)   
- * 5480:     function DBgetInsert($table, $pid, $dataArr, $fieldList, $doExec=FALSE)   
- * 5517:     function DBmayFEUserEdit($table,$row, $feUserRow, $allowedGroups='',$feEditSelf=0)        
- * 5557:     function DBmayFEUserEditSelect($table,$feUserRow,$allowedGroups='',$feEditSelf=0) 
- * 5597:     function enableFields($table,$show_hidden=0)      
- * 5620:     function getTreeList($id,$depth,$begin=0,$dontCheckEnableFields=0,$addSelectFields='',$moreWhereClauses='')       
- * 5653:     function whereSelectFromList($field,$value)       
- * 5671:     function exec_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')   
- * 5698:     function exec_mm_query_uidList($select,$local_table_uidlist,$mm_table,$foreign_table='',$whereClause='',$groupBy='',$orderBy='',$limit='')        
- * 5719:     function searchWhere($sw,$searchFieldList,$searchTable='')        
- * 5752:     function exec_getQuery($table, $conf)     
- * 5770:     function getQuery($table, $conf, $returnQueryArray=FALSE) 
- * 5849:     function getWhere($table,$conf, $returnQueryArray=FALSE)  
- * 5935:     function checkPidArray($listArr)  
- * 5958:     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
- * 6014:     function editPanel($content, $conf, $currentRecord='', $dataArr=array())  
- * 6179:     function editIcons($content,$params, $conf=array(), $currentRecord='', $dataArr=array(),$addUrlParamStr='')       
- * 6243:     function editPanelLinkWrap($string,$formName,$cmd,$currentRecord='',$confirm='')  
- * 6281:     function editPanelLinkWrap_doWrap($string,$url,$currentRecord)    
- * 6308:     function editPanelPreviewBorder($table,$row,$content,$thick)      
- * 6325:     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)
  *
  *
- * 6356: class tslib_frameset 
- * 6366:     function make($setup)     
- * 6403:     function frameParams($setup, $typeNum)    
- * 6446:     function framesetParams($setup)   
+ * 6806: class tslib_frameset
+ * 6816:     function make($setup)
+ * 6853:     function frameParams($setup, $typeNum)
+ * 6896:     function framesetParams($setup)
  *
  *
- * 6479: class tslib_tableOffset       
- * 6491:     function start($content,$offset)  
+ * 6929: class tslib_tableOffset
+ * 6941:     function start($content,$offset)
  *
  *
- * 6569: class tslib_controlTable      
- * 6604:     function start($offset,$cMargins) 
+ * 7019: class tslib_controlTable
+ * 7054:     function start($offset,$cMargins)
  *
- * TOTAL FUNCTIONS: 126
+ * 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');
+}
 
 
 
@@ -235,19 +242,15 @@ require_once (PATH_t3lib."class.t3lib_parsehtml.php");
  * 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()
@@ -284,7 +287,7 @@ class tslib_cObj {
                28 => Array('params'=>'-quality 20', 'ext'=>'jpg')
        );
 
-       /** 
+       /**
         * ImageMagick parameters for image effects
         *
         * @see IMGTEXT()
@@ -300,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
@@ -327,7 +330,8 @@ 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.
@@ -355,8 +359,8 @@ class tslib_cObj {
        function setParent($data,$currentRecord)        {
                $this->parentRecord=array('data'=>$data, 'currentRecord'=>$currentRecord);
        }
-       
-       
+
+
 
 
 
@@ -449,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);
@@ -592,8 +603,8 @@ 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="" title="" />', $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.']);
        }
 
@@ -612,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'
@@ -648,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:
@@ -669,7 +680,7 @@ class tslib_cObj {
         * @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']);
                }
@@ -722,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.
@@ -748,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.']));
@@ -770,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;
@@ -788,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;
                        }
@@ -831,14 +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);
 
-                       $altP = $this->getAltParam($conf);
-                       
                                // EqualHeight
                        $equalHeight = intval($this->stdWrap($conf['equalH'],$conf['equalH.']));
                        if ($equalHeight)       {       // Initiate gifbuilder object in order to get dimensions AND calculate the imageWidth's
@@ -863,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;
@@ -878,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']);
@@ -893,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)];
@@ -901,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];
                                        }
@@ -925,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;
 
@@ -936,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.
@@ -964,11 +994,11 @@ 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;
@@ -989,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="" title="" /></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="" title="" /></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="" title="" />';
+                                                       $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;
                                                }
@@ -1018,7 +1048,7 @@ class tslib_cObj {
                                                        }
 
                                                        $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.']);}
@@ -1054,10 +1084,10 @@ 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;
@@ -1081,7 +1111,7 @@ class tslib_cObj {
                if ($conf['stdWrap.']) {
                        $output = $this->stdWrap($output, $conf['stdWrap.']);
                }
-               
+
                return $output;
        }
 
@@ -1095,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_')        {
@@ -1106,33 +1136,71 @@ class tslib_cObj {
                        $renderObjKey = $conf['renderObj'] ? 'renderObj' : '';
                        $renderObjConf = $conf['renderObj.'];
 
-                       $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;
-                               while ($row = $GLOBALS['TYPO3_DB']->sql_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;
        }
 
@@ -1146,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.']);
@@ -1160,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);
@@ -1181,25 +1249,36 @@ 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++;
-                                       $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-->';}
+
+                               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']);
        }
 
@@ -1213,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;
@@ -1225,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();
                        }
@@ -1379,9 +1458,10 @@ 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>';
+
+               $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>'; }
@@ -1408,7 +1488,7 @@ class tslib_cObj {
                        $theValue = $this->cObjGetSingle($name,$conf[$key.'.'], $key);
                        if ($conf['stdWrap.'])  {
                                $theValue = $this->stdWrap($theValue,$conf['stdWrap.']);
-                       }                       
+                       }
                        return $theValue;
                }
        }
@@ -1475,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']);
@@ -1501,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,'#/')) {
@@ -1553,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']);
@@ -1567,18 +1660,31 @@ 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':
                                                $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':
@@ -1588,26 +1694,28 @@ class tslib_cObj {
                                                $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':
                                                $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':
                                                        // 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':
@@ -1618,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++)    {
@@ -1643,9 +1751,9 @@ 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':
@@ -1669,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;
@@ -1695,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.' />',
+                                               } 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'];
                                                }
@@ -1728,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;
                                }
                        }
                }
@@ -1745,44 +1904,45 @@ 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']))       {
+                       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.
@@ -1793,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(
@@ -1825,7 +1992,7 @@ class tslib_cObj {
                if ($conf['arrayReturnMode'])   {
                        $content['validateForm']=$validateForm;
                        $content['formname']=$formname;
-                       return $content;        
+                       return $content;
                } else {
                        return implode('',$content);
                }
@@ -1843,7 +2010,7 @@ class tslib_cObj {
                        $search = t3lib_div::makeInstance('tslib_search');
                        $search->register_and_explode_search_string(t3lib_div::_GP('sword'));
                        $search->register_tables_and_columns(t3lib_div::_GP('scols'),$conf['allowedCols']);
-                               // depth                
+                               // depth
                        $depth=100;
                                // the startId is found
                        $theStartId=0;
@@ -1878,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
                                                        }
                                                }
                                        }
@@ -1888,17 +2055,23 @@ 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);
-                       
-                       $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';
-                       $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->queryParts);
 
                                // count...
                        if (t3lib_div::testInt(t3lib_div::_GP('scount')))       {
@@ -1914,24 +2087,24 @@ class tslib_cObj {
                        } else {
                                $theRange = 20;
                        }
-                       
+
                                // Order By:
                        if (!$conf['noOrderBy'])        {
                                $search->queryParts['ORDERBY'] = 'pages.lastUpdated, pages.tstamp';
                        }
-                       
+
                        $search->queryParts['LIMIT'] = $spointer.','.$theRange;
-                       
+
                                // search...
                        $search->execute_query();
                        if ($GLOBALS['TYPO3_DB']->sql_num_rows($search->result))        {
                                $GLOBALS['TSFE']->register['SWORD_PARAMS'] = $search->get_searchwords();
-                       
+
                                $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,'');
+                               $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::_GP('sword')).
@@ -1943,7 +2116,7 @@ class tslib_cObj {
                                $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>';
@@ -1958,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 = $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');
                                }
@@ -2045,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
@@ -2070,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.'])) {
@@ -2107,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.'])) {
@@ -2149,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);
@@ -2164,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);
@@ -2210,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))   {
@@ -2227,9 +2408,9 @@ 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>';
                                }
                        }
                }
@@ -2239,15 +2420,16 @@ class tslib_cObj {
                }
 
                return $content;
-       }       
+       }
+
+
+
+
+
+
 
 
 
-       
-       
-       
-       
-       
 
 
 
@@ -2256,13 +2438,42 @@ 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"
@@ -2315,7 +2526,7 @@ 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::_GP($fieldName);
@@ -2338,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...
+
+                       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].'"  border="'.intval($conf['border']).'"'.($conf['params']?' '.$conf['params']:'').($altParam).' />';
+
+                       $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']) {
@@ -2348,6 +2565,17 @@ 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.
@@ -2373,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.'])      {
@@ -2388,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');
@@ -2412,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="" title="" />';
+                               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);
                        }
@@ -2475,21 +2704,32 @@ class tslib_cObj {
 
        /**
         * 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 = $this->stdWrap($conf['altText'],$conf['altText.']);
+               $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)).'"';
 
-               $titleText = $this->stdWrap($conf['titleText'],$conf['titleText.']);
+                       // "title":
                if ($titleText) {
-                       $altParam .= ' title="'.htmlspecialchars(strip_tags($titleText)).'"';
+                       $altParam.= ' title="'.htmlspecialchars(strip_tags($titleText)).'"';
                } else {
-                       $altParam .= ' title="'.htmlspecialchars(strip_tags($altText)).'"';
+                       $altParam.= ' title="'.htmlspecialchars(strip_tags($altText)).'"';
                }
+
+                       // "longDesc" URL
+               if ($longDesc)  {
+                       $altParam.= ' longdesc="'.htmlspecialchars($longDesc).'"';
+               }
+
                return $altParam;
        }
 
@@ -2503,8 +2743,8 @@ class tslib_cObj {
 
 
 
-       
-       
+
+
 
 
 
@@ -2532,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);
                }
        }
@@ -2562,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);
@@ -2578,7 +2818,7 @@ class tslib_cObj {
                        } else {
                                $substContent=$subpartContent;
                        }
-       
+
                        if ($recursive && strpos($after, $marker))      {
                                return $before.$substContent.$this->substituteSubpart($after,$marker,$subpartContent);
                        } else {
@@ -2643,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))       {
@@ -2668,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
@@ -2682,7 +2922,7 @@ class tslib_cObj {
                        }
                }
 
-                       // Substitution/Merging: 
+                       // Substitution/Merging:
                        // Merging content types together, resetting
                $valueArr = array_merge($markContentArray,$subpartContentArray,$wrappedSubpartContentArray);
 
@@ -2700,7 +2940,7 @@ class tslib_cObj {
                        }
                }
                $content.=$storeArr['c'][count($storeArr['k'])];
-               
+
                $GLOBALS['TT']->pull();
                return $content;
        }
@@ -2797,7 +3037,7 @@ class tslib_cObj {
 
 
 
-       
+
 
 
 
@@ -2810,7 +3050,7 @@ 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")
@@ -2829,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;}
                        }
@@ -2853,18 +3093,22 @@ 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['csConv'])    { $content=$GLOBALS['TSFE']->csConv($content,$conf['csConv']); }
                                if ($conf['parseFunc.'] || $conf['parseFunc']) {$content=$this->parseFunc($content,$conf['parseFunc.'],$conf['parseFunc']);}
@@ -2874,22 +3118,30 @@ class tslib_cObj {
                                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.']);}
@@ -2906,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.']));}
@@ -2928,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.']);}
@@ -2936,23 +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');
                                }
                        }
                }
@@ -3139,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);
                                }
                        }
                }
@@ -3161,7 +3423,7 @@ 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.
         *
@@ -3206,18 +3468,18 @@ 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;
                } while($pointer<$totalLen);
                return $newVal;
        }
-       
+
        /**
         * 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.
@@ -3230,8 +3492,8 @@ class tslib_cObj {
         */
        function prefixComment($str,$conf,$content)     {
                $parts = explode('|',$str);
-               
-               $output = 
+
+               $output =
                        chr(10).str_pad('',$parts[0],chr(9)).
                        '<!-- '.htmlspecialchars($this->insertData($parts[1])).' [begin] -->'.
                        chr(10).str_pad('',$parts[0]+1,chr(9)).
@@ -3255,9 +3517,9 @@ 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]);
                }
        }
 
@@ -3265,21 +3527,26 @@ class tslib_cObj {
         * 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;
                                }
                        }
                }
@@ -3287,6 +3554,51 @@ 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
@@ -3296,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';
@@ -3308,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';
@@ -3320,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)    {
@@ -3348,7 +3660,7 @@ 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;
        }
@@ -3363,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';
@@ -3375,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');
@@ -3389,12 +3701,12 @@ 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"
         *
@@ -3406,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']);
@@ -3429,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);
                }
@@ -3458,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="" title="" />';
+                                               $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="" title="" />';
+                                       $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.']);
@@ -3499,7 +3813,7 @@ 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.']);
                }
        }
@@ -3528,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']
@@ -3596,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);
@@ -3651,7 +3965,7 @@ class tslib_cObj {
         * @see _parseFunc()
         */
        function parseFunc($theValue, $conf, $ref='') {
-       
+
                        // Fetch / merge reference, if any
                if ($ref)       {
                        $temp_conf = array(
@@ -3667,7 +3981,7 @@ class tslib_cObj {
                        $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:
@@ -3691,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]);
@@ -3725,7 +4043,7 @@ class tslib_cObj {
                                                                                if (is_array($stdWrap)) {
                                                                                        $colParts[$kkk] = $this->stdWrap($colParts[$kkk],$stdWrap);
                                                                                }
-                                                                               
+
                                                                                $colParts[$kkk]=$tag.$colParts[$kkk].'</'.$tagName.'>';
                                                                        }
                                                                }
@@ -3734,7 +4052,7 @@ class tslib_cObj {
                                                }
                                                $parts[$k] = implode('',$rowParts);
                                        }
-                                       
+
                                        if (is_array($cfg['stdWrap.'])) {
                                                $parts[$k] = $this->stdWrap($parts[$k],$cfg['stdWrap.']);
                                        }
@@ -3783,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]);
@@ -3820,7 +4138,7 @@ class tslib_cObj {
                                                                }
                                                        }
                                                }
-                                               
+
                                                        // stdWrap
                                                if (is_array($conf['plainTextStdWrap.']))       {$data = $this->stdWrap($data,$conf['plainTextStdWrap.']);}
                                                        // userFunc
@@ -3831,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 = '';
@@ -3914,7 +4232,7 @@ class tslib_cObj {
                                                        unset($contentAccum[$contentAccumP-1]);
                                                        $contentAccumP-=2;
                                                }
-                                               
+
                                                unset($currentTag);
                                                $treated=1;
                                        }
@@ -3964,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);
@@ -4016,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 {
@@ -4094,7 +4412,7 @@ class tslib_cObj {
                                $textstr.=$res.$parts[1];
                        } else {
                                $textstr.='http://'.$textpieces[$i];
-                       }                               
+                       }
                }
                return $textstr;
        }
@@ -4116,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 {
@@ -4137,7 +4453,7 @@ class tslib_cObj {
                                $textstr.=$res.$parts[1];
                        } else {
                                $textstr.='mailto:'.$textpieces[$i];
-                       }                               
+                       }
                }
                return $textstr;
        }
@@ -4192,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'];}
@@ -4234,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);
@@ -4248,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']);
@@ -4276,7 +4597,7 @@ class tslib_cObj {
                                                }
                                                return $GLOBALS['TSFE']->tmpl->fileCache[$hash];
                                        }
-                                       
+
                                break;
                        }
                }
@@ -4306,19 +4627,19 @@ 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.
         *
@@ -4358,62 +4679,74 @@ class tslib_cObj {
                        if ((string)$key!='')   {
                                switch(strtolower(trim($parts[0])))     {
                                        case 'gpvar':
-                                               $retVal= t3lib_div::_GP($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);
+                                               $keyP = t3lib_div::trimExplode(',',$key);
                                                $nkey = $this->getKey($keyP[0],$GLOBALS['TSFE']->tmpl->rootLine);
-                                               $retVal= $this->rootLineValue($nkey,$keyP[1],strtolower($keyP[2])=='slide');
+                                               $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);
@@ -4421,7 +4754,10 @@ class tslib_cObj {
                                                if (is_array($db_rec) && $selectParts[2])       {$retVal = $db_rec[$selectParts[2]];}
                                        break;
                                        case 'lll':
-                                               $retVal= $GLOBALS['TSFE']->sL('LLL:'.$key);
+                                               $retVal = $GLOBALS['TSFE']->sL('LLL:'.$key);
+                                       break;
+                                       case 'path':
+                                               $retVal = $GLOBALS['TSFE']->tmpl->getFileName($key);
                                        break;
                                        case 'cobj':
                                                switch((string)$key)    {
@@ -4477,14 +4813,15 @@ class tslib_cObj {
         * 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])];
@@ -4514,24 +4851,24 @@ class tslib_cObj {
                        }
                        if ($key < 0)   {
                                $key=0;
-                       }               
+                       }
                }
                return $key;
        }
 
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
+
+
+
+
+
+
+
+
+
+
+
+
+
 
 
 
@@ -4544,7 +4881,7 @@ 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.
@@ -4559,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:
@@ -4593,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 {
@@ -4621,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 {
@@ -4641,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'])       {
@@ -4653,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
@@ -4679,24 +5012,26 @@ 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))     {
-                                                                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_domain', 'pid='.intval($tCR_data['uid']).' AND redirectTo=""'.$this->enableFields('sys_domain'), '', 'sorting');
+                                                               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;
@@ -4704,22 +5039,41 @@ class tslib_cObj {
                                                                }
                                                        }
                                                }
-                                               $addQueryParams = trim($this->stdWrap($conf['additionalParams'],$conf['additionalParams.']));
+                                                       // 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;
+                                               }
+                                                       // 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'];
+
+                                                       // 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 = $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)
+                                                       $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));
                                                }
-                                                       // 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);
-                                                       }
+                                                       // Add "&MP" var:
+                                               if (count($MPvarAcc))   {
+                                                       $addQueryParams.= '&MP='.rawurlencode(implode(',',$MPvarAcc));
                                                }
-
-                                               if ($linktxt=='') $linktxt = $page['title'];
-                                               if ($tCR_domain)        {               // If other domain, overwrite 
+                                                       // 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;}
@@ -4727,7 +5081,7 @@ class tslib_cObj {
                                                        $this->lastTypoLinkUrl = $this->URLqMark('http://'.$tCR_domain.'/?id='.$page['uid'],$addQueryParams).$sectionMark;
                                                } else {        // Internal link:
                                                        if ($forceTarget)       {$target=$forceTarget;}
-                                                       $LD=$GLOBALS['TSFE']->tmpl->linkData($page,$target,$conf['no_cache'],'','',$addQueryParams,$theTypeP);
+                                                       $LD = $GLOBALS['TSFE']->tmpl->linkData($page,$target,$conf['no_cache'],'','',$addQueryParams,$theTypeP);
                                                        $this->lastTypoLinkUrl = $this->URLqMark($LD['totalURL'],'').$sectionMark;
                                                }
 
@@ -4738,7 +5092,7 @@ class tslib_cObj {
                                                if ($sectionMark && !trim($addQueryParams) && $page['uid']==$GLOBALS['TSFE']->id)       {
                                                        list(,$URLparams) = explode('?',$this->lastTypoLinkUrl);
                                                        list($URLparams) = explode('#',$URLparams);
-                                                       parse_str ($URLparams.$LD['orig_type'], $URLparamsArray); 
+                                                       parse_str ($URLparams.$LD['orig_type'], $URLparamsArray);
                                                        if (intval($URLparamsArray['type'])==$GLOBALS['TSFE']->type)    {       // type nums must match as well as page ids
                                                                unset($URLparamsArray['id']);
                                                                unset($URLparamsArray['type']);
@@ -4747,6 +5101,20 @@ class tslib_cObj {
                                                                }
                                                        }
                                                }
+
+                                                       // If link is to a access restricted page which should be redirected, then find new URL:
+                                               if ($GLOBALS['TSFE']->config['config']['typolinkLinkAccessRestrictedPages'] &&
+                                                               $GLOBALS['TSFE']->config['config']['typolinkLinkAccessRestrictedPages']!=='NONE' &&
+                                                               !$GLOBALS['TSFE']->checkPageGroupAccess($page)) {
+                                                                       $thePage = $GLOBALS['TSFE']->sys_page->getPage($GLOBALS['TSFE']->config['config']['typolinkLinkAccessRestrictedPages']);
+
+                                                                       $addParams = $GLOBALS['TSFE']->config['config']['typolinkLinkAccessRestrictedPages_addParams'];
+                                                                       $addParams = str_replace('###RETURN_URL###',rawurlencode($this->lastTypoLinkUrl),$addParams);
+                                                                       $addParams = str_replace('###PAGE_ID###',$page['uid'],$addParams);
+                                                                       $LD = $GLOBALS['TSFE']->tmpl->linkData($thePage,$target,'','','',$addParams,$theTypeP);
+                                                                       $this->lastTypoLinkUrl = $this->URLqMark($LD['totalURL'],'');
+                                               }
+
                                                        // Rendering the tag.
                                                $finalTagParts['url']=$this->lastTypoLinkUrl;
                                                $finalTagParts['targetParams']=$targetPart;
@@ -4755,34 +5123,38 @@ class tslib_cObj {
                                                $GLOBALS['TT']->setTSlogMessage("typolink(): Page id '".$link_param."' was not found, so '".$linktxt."' was not linked.",1);
                                                return $linktxt;
                                        }
-                               }               
+                               }
                        }
-                       
+
                        if ($JSwindowParams)    {
-                               $onClick="vHWin=window.open('".$finalTagParts['url']."','FEopenLink','".$JSwindowParams."');vHWin.focus();return false;";
+                               $onClick="vHWin=window.open('".$GLOBALS['TSFE']->baseUrlWrap($finalTagParts['url'])."','FEopenLink','".$JSwindowParams."');vHWin.focus();return false;";
                                $res = '<a href="#" onclick="'.htmlspecialchars($onClick).'"'.($linkClass?' class="'.$linkClass.'"':'').$finalTagParts['aTagParams'].'>';
                        } else {
-                               $res = '<a href="'.htmlspecialchars($finalTagParts['url']).'"'.$finalTagParts['targetParams'].($linkClass?' class="'.$linkClass.'"':'').$finalTagParts['aTagParams'].'>';
+                               if ($GLOBALS['TSFE']->spamProtectEmailAddresses === 'ascii' && $finalTagParts['TYPE'] === 'mailto') {
+                                       $res = '<a href="'.$finalTagParts['url'].'"'.$finalTagParts['targetParams'].($linkClass?' class="'.$linkClass.'"':'').$finalTagParts['aTagParams'].'>';
+                               } else {
+                                       $res = '<a href="'.htmlspecialchars($finalTagParts['url']).'"'.$finalTagParts['targetParams'].($linkClass?' class="'.$linkClass.'"':'').$finalTagParts['aTagParams'].'>';
+                               }
                        }
-                       
+
                                // Call user function:
                        if ($conf['userFunc'])  {
                                $finalTagParts['TAG']=$res;
                                $res = $this->callUserFunction($conf['userFunc'],$conf['userFunc.'],$finalTagParts);
                        }
-                       
+
                                // If flag "returnLastTypoLinkUrl" set, then just return the latest URL made:
-                       if ($conf['returnLast'])        {       
+                       if ($conf['returnLast'])        {
                                switch($conf['returnLast'])     {
                                        case 'url':
-                                               return $this->lastTypoLinkUrl; 
+                                               return $this->lastTypoLinkUrl;
                                        break;
                                        case 'target':
-                                               return $this->lastTypoLinkTarget; 
+                                               return $this->lastTypoLinkTarget;
                                        break;
                                }
                        }
-                       
+
                        if ($conf['ATagBeforeWrap'])    {
                                return $res.$this->wrap($linktxt, $conf['wrap']).'</a>';
                        } else {
@@ -4813,7 +5185,7 @@ class tslib_cObj {
         * Optionally you can supply $urlParameters which is an array with key/value pairs that are rawurlencoded and appended to the resulting url.
         *
         * @param       string          Text string being wrapped by the link.
-        * @param       string          Link parameter; eg. "123" for page id, "kasper@typo3.com" for email address, "http://...." for URL, "fileadmin/blabla.txt" for file.
+        * @param       string          Link parameter; eg. "123" for page id, "kasperYYYY@typo3.com" for email address, "http://...." for URL, "fileadmin/blabla.txt" for file.
         * @param       array           An array with key/value pairs representing URL parameters to set. Values NOT URL-encoded yet.
         * @param       string          Specific target set, if any. (Default is using the current)
         * @return      string          The wrapped $label-text string
@@ -4828,10 +5200,7 @@ class tslib_cObj {
                }
                if (is_array($urlParameters))   {
                        if (count($urlParameters))      {
-                               reset($urlParameters);
-                               while(list($k,$v)=each($urlParameters)) {
-                                       $conf['additionalParams'].='&'.$k.'='.rawurlencode($v);
-                               }
+                               $conf['additionalParams'].= t3lib_div::implodeArrayForUrl('',$urlParameters);
                        }
                } else {
                        $conf['additionalParams'].=$urlParameters;
@@ -4843,7 +5212,7 @@ class tslib_cObj {
        /**
         * Returns the URL of a "typolink" create from the input parameter string, url-parameters and target
         *
-        * @param       string          Link parameter; eg. "123" for page id, "kasper@typo3.com" for email address, "http://...." for URL, "fileadmin/blabla.txt" for file.
+        * @param       string          Link parameter; eg. "123" for page id, "kasperYYYY@typo3.com" for email address, "http://...." for URL, "fileadmin/blabla.txt" for file.
         * @param       array           An array with key/value pairs representing URL parameters to set. Values NOT URL-encoded yet.
         * @param       string          Specific target set, if any. (Default is using the current)
         * @return      string          The URL
@@ -4878,11 +5247,92 @@ class tslib_cObj {
                return $this->getTypoLink_URL($id?$id:$GLOBALS['TSFE']->id,$urlParameters,$GLOBALS['TSFE']->sPre);
        }
 
+       /**
+        * Returns the &MP variable value for a page id.
+        * The function will do its best to find a MP value that will keep the page id inside the current Mount Point rootline if any.
+        *
+        * @param       integer         page id
+        * @param       boolean         If true, the MPvalue is returned raw. Normally it is encoded as &MP=... variable
+        * @return      string          MP value, prefixed with &MP= (depending on $raw)
+        * @see typolink()
+        */
+       function getClosestMPvalueForPage($pageId, $raw=FALSE)  {
+                       // MointPoints:
+               if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] && $GLOBALS['TSFE']->MP)     {
+
+                       if (!strcmp($GLOBALS['TSFE']->id, $pageId))     {       // same page as current.
+                               $MP = $GLOBALS['TSFE']->MP;
+                       } else { // ... otherwise find closest meeting point:
+                               $tCR_rootline = $GLOBALS['TSFE']->sys_page->getRootLine($pageId, '', TRUE);     // Gets rootline of linked-to page
+                               $inverseTmplRootline = array_reverse($GLOBALS['TSFE']->tmpl->rootLine);
+
+                               $rl_mpArray = array();
+                               $startMPaccu = FALSE;
+
+                                       // Traverse root line of link uid and inside of that the REAL root line of current position.
+                               foreach($tCR_rootline as $tCR_data)     {
+                                       foreach($inverseTmplRootline as $rlKey => $invTmplRLRec)        {
+
+                                                       // Accumulate MP data:
+                                               if ($startMPaccu && $invTmplRLRec['_MP_PARAM']) {
+                                                       $rl_mpArray[] = $invTmplRLRec['_MP_PARAM'];
+                                               }
+
+                                                       // If two PIDs matches and this is NOT the site root, start accumulation of MP data (on the next level):
+                                                       // (The check for site root is done so links to branches outsite the site but sharing the site roots PID is NOT detected as within the branch!)
+                                               if ($tCR_data['pid']==$invTmplRLRec['pid'] && count($inverseTmplRootline)!=$rlKey+1)    {
+                                                       $startMPaccu = TRUE;
+                                               }
+                                       }
+                                       if ($startMPaccu)       break;  // Good enough...
+                               }
+
+                               if (count($rl_mpArray)) {
+                                       $MP = implode(',', array_reverse($rl_mpArray));
+                               }
+                       }
+               }
 
+               return !$raw  ? ($MP ? '&MP='.rawurlencode($MP) : '') : $MP;
+       }
 
+       /**
+        * Creates a href attibute for given $mailAddress.
+        * The function uses spamProtectEmailAddresses and Jumpurl functionality for encoding the mailto statement.
+        * If spamProtectEmailAddresses is disabled, it'll just return a string like "mailto:user@example.tld".
+        *
+        * @param       string          Email address
+        * @param       string          $initP: Initial link parameters, only used if Jumpurl functionality is enabled. Example: ?id=5&type=0
+        * @return      string          Returns a numerical array with two elements: 1) $mailToUrl, string ready to be inserted into the href attribute of the <a> tag, b) $linktxt: The string between starting and ending <a> tag.
+        */
+       function getMailTo($mailAddress,$linktxt,$initP='?') {
+               if(!strcmp($linktxt,''))        { $linktxt = $mailAddress; }
 
+               $mailToUrl = 'mailto:'.$mailAddress;
 
+               if (!$GLOBALS['TSFE']->config['config']['jumpurl_enable'] || $GLOBALS['TSFE']->config['config']['jumpurl_mailto_disable']) {
+                       if ($GLOBALS['TSFE']->spamProtectEmailAddresses) {
+                               if ($GLOBALS['TSFE']->spamProtectEmailAddresses === 'ascii')    {
+                                       $mailToUrl = $GLOBALS['TSFE']->encryptEmail($mailToUrl);
+                               } else {
+                                       $mailToUrl = "javascript:linkTo_UnCryptMailto('".$GLOBALS['TSFE']->encryptEmail($mailToUrl)."');";
+                               }
+                               if ($GLOBALS['TSFE']->config['config']['spamProtectEmailAddresses_atSubst']) {
+                                       $atLabel = trim($GLOBALS['TSFE']->config['config']['spamProtectEmailAddresses_atSubst']);
+                               }
+                               $linktxt = str_replace('@',$atLabel?$atLabel:'(at)',$linktxt);
 
+                               if ($GLOBALS['TSFE']->config['config']['spamProtectEmailAddresses_lastDotSubst']) {
+                                       $lastDotLabel = trim($GLOBALS['TSFE']->config['config']['spamProtectEmailAddresses_lastDotSubst']);
+                                       $lastDotLabel = $lastDotLabel ? $lastDotLabel : '(dot)';
+                                       $linktxt = preg_replace('/\.([^\.]+)$/', $lastDotLabel.'$1', $linktxt);
+                               }
+                       }
+               } else {
+                       $mailToUrl = $GLOBALS['TSFE']->absRefPrefix.$GLOBALS['TSFE']->config['mainScript'].$initP.'&jumpurl='.rawurlencode($mailToUrl).$GLOBALS['TSFE']->getMethodUrlIdToken;
+               }
+               return array($mailToUrl,$linktxt);
+       }
 
 
 
@@ -4906,7 +5356,7 @@ class tslib_cObj {
         * Miscellaneous functions, stand alone
         *
         ***********************************************/
-       
+
        /**
         * Wrapping a string.
         * Implements the TypoScript "wrap" property.
@@ -4955,10 +5405,10 @@ class tslib_cObj {
                        $wrapBefore = intval($wrapArray[0]);
                        $wrapAfter = intval($wrapArray[1]);
                        if ($wrapBefore)        {
-                               $result = '<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$wrapBefore.'" border="0" class="spacer-gif" alt="" title="" /><br />'.$result;
+                               $result = '<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$wrapBefore.'"'.$this->getBorderAttr(' border="0"').' class="spacer-gif" alt="" title="" /><br />'.$result;
                        }
                        if ($wrapAfter) {
-                               $result.='<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$wrapAfter.'" border="0" class="spacer-gif" alt="" title="" /><br />';
+                               $result.='<img src="'.$GLOBALS['TSFE']->absRefPrefix.'clear.gif" width="1" height="'.$wrapAfter.'"'.$this->getBorderAttr(' border="0"').' class="spacer-gif" alt="" title="" /><br />';
                        }
                }
                return $result;
@@ -4976,7 +5426,7 @@ class tslib_cObj {
         */
        function callUserFunction($funcName,$conf,$content)     {
                $pre = $GLOBALS['TSFE']->TYPO3_CONF_VARS['FE']['userFuncClassPrefix'];
-               if ($pre && 
+               if ($pre &&
                        !t3lib_div::isFirstPartOfStr(trim($funcName),$pre) &&
                        !t3lib_div::isFirstPartOfStr(trim($funcName),'tx_')
                        )       {
@@ -5039,7 +5489,7 @@ class tslib_cObj {
                while(list($k,$v)=each($listArr))       {
                        $listArr[$k]=trim($v);
                }
-               return implode($listArr,',');
+               return implode(',',$listArr);
        }
 
        /**
@@ -5054,12 +5504,14 @@ class tslib_cObj {
                $case = strtolower($case);
                switch($case)   {
                        case 'upper':
-                               $theValue = strtoupper($theValue);
-                               $theValue = strtr($theValue, $this->caseConvStrings[0], $this->caseConvStrings[1]);
+                               $theValue = $GLOBALS['TSFE']->csConvObj->conv_case($GLOBALS['TSFE']->renderCharset,$theValue,'toUpper');
+                               #$theValue = strtoupper($theValue);
+                               #$theValue = strtr($theValue, $this->caseConvStrings[0], $this->caseConvStrings[1]);
                        break;
                        case 'lower':
-                               $theValue = strtolower($theValue);
-                               $theValue = strtr($theValue, $this->caseConvStrings[1], $this->caseConvStrings[0]);
+                               $theValue = $GLOBALS['TSFE']->csConvObj->conv_case($GLOBALS['TSFE']->renderCharset,$theValue,'toLower');
+                               #$theValue = strtolower($theValue);
+                               #$theValue = strtr($theValue, $this->caseConvStrings[1], $this->caseConvStrings[0]);
                        break;
                }
                return $theValue;
@@ -5074,18 +5526,18 @@ class tslib_cObj {
         * @see caseshift()
         */
        function HTMLcaseshift($theValue, $case)        {
-               $inside=0;
-               $newVal='';
-               $pointer=0;
+               $inside = 0;
+               $newVal = '';
+               $pointer = 0;
                $totalLen = strlen($theValue);
                do      {
                        if (!$inside)   {
                                $len = strcspn(substr($theValue,$pointer),'<');
-                               $newVal.=$this->caseshift(substr($theValue,$pointer,$len),$case);
+                               $newVal.= $this->caseshift(substr($theValue,$pointer,$len),$case);
                                $inside = 1;
                        } else {
                                $len = strcspn(substr($theValue,$pointer),'>')+1;
-                               $newVal.=substr($theValue,$pointer,$len);
+                               $newVal.= substr($theValue,$pointer,$len);
                                $inside = 0;
                        }
                        $pointer+=$len;
@@ -5119,7 +5571,7 @@ class tslib_cObj {
                } else {
                        $labels=str_replace('"','',$labels);
                }
-               
+
                $labelArr = explode('|',$labels);
                if ($seconds<3600)      {
                        $seconds = round ($seconds/60).$labelArr[0];
@@ -5132,7 +5584,7 @@ class tslib_cObj {
                }
                return $seconds;
        }
-       
+
        /**
         * Sending a notification email using $GLOBALS['TSFE']->plainMailEncoded()
         *
@@ -5150,18 +5602,18 @@ class tslib_cObj {
                if ($email_from)        {$headers[]='From: '.$email_fromName.' <'.$email_from.'>';}
                if ($replyTo)           {$headers[]='Reply-To: '.$replyTo;}
 
-               $recipients=implode(t3lib_div::trimExplode(',',$recipients,1),',');
-               
+               $recipients=implode(',',t3lib_div::trimExplode(',',$recipients,1));
+
                $emailContent = trim($msg);
                if ($emailContent)      {
                        $parts = split(chr(10),$emailContent,2);                // First line is subject
                        $subject=trim($parts[0]);
                        $plain_message=trim($parts[1]);
-                       
-                       if ($recipients)        $GLOBALS['TSFE']->plainMailEncoded($recipients, $subject, $plain_message, implode($headers,chr(10)));
-                       if ($cc)        $GLOBALS['TSFE']->plainMailEncoded($cc, $subject, $plain_message, implode($headers,chr(10)));
+
+                       if ($recipients)        $GLOBALS['TSFE']->plainMailEncoded($recipients, $subject, $plain_message, implode(chr(10),$headers));
+                       if ($cc)        $GLOBALS['TSFE']->plainMailEncoded($cc, $subject, $plain_message, implode(chr(10),$headers));
                        return true;
-               }               
+               }
        }
 
        /**
@@ -5270,7 +5722,7 @@ class tslib_cObj {
                $Valign = strtolower(trim($conf['Valign']));
                $tmplObjNumber = intval($conf['tmplObjNumber']);
                $maxLines = intval($conf['maxLines']);
-               
+
                if ($tmplObjNumber && $gifbuilderConf[$tmplObjNumber]=='TEXT')  {
                        $textArr = $this->linebreaks($text,$chars,$maxLines);
                        $angle = intval($gifbuilderConf[$tmplObjNumber.'.']['angle']);
@@ -5362,42 +5814,42 @@ class tslib_cObj {
                                        $JSPart.="
        updateForm('".$formName."','".$arrPrefix."[".$fKey."][]',unescape('".rawurlencode($Nvalue)."'))";
                                }
-                       
+
                        } else {
                                $JSPart.="
        updateForm('".$formName."','".$arrPrefix."[".$fKey."]',unescape('".rawurlencode($value)."'))";
                        }
                }
-               $JSPart='<script type="text/javascript">  
+               $JSPart='<script type="text/javascript">
        /*<![CDATA[*/ '.$JSPart.'
        /*]]>*/
 </script>
-';     
+';
                $GLOBALS['TSFE']->additionalHeaderData['JSincludeFormupdate']='<script type="text/javascript" src="'.$GLOBALS['TSFE']->absRefPrefix.'t3lib/jsfunc.updateform.js"></script>';
                return $JSPart;
        }
 
-       
-       
-       
-       
-       
 
 
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
-       
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 
 
 
@@ -5457,7 +5909,7 @@ class tslib_cObj {
                $uid=intval($uid);
 
                if ($uid)       {
-                       $fieldList = implode(t3lib_div::trimExplode(',',$fieldList,1),',');
+                       $fieldList = implode(',',t3lib_div::trimExplode(',',$fieldList,1));
                        $updateFields=array();
 
                        foreach($dataArr as $f => $v)   {
@@ -5465,11 +5917,11 @@ class tslib_cObj {
                                        $updateFields[$f] = $v;
                                }
                        }
-                       
+
                        if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'])  {
                                $updateFields[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = time();
                        }
-                       
+
                        if (count($updateFields))       {
                                if ($doExec)    {
                                        return $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
@@ -5501,18 +5953,18 @@ class tslib_cObj {
                if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id'])       {$field=$GLOBALS['TCA'][$table]['ctrl']['cruser_id']; $dataArr[$field]=0; $extraList.=','.$field;}
                if ($GLOBALS['TCA'][$table]['ctrl']['fe_cruser_id'])    {$field=$GLOBALS['TCA'][$table]['ctrl']['fe_cruser_id']; $dataArr[$field]=intval($GLOBALS['TSFE']->fe_user->user['uid']); $extraList.=','.$field;}
                if ($GLOBALS['TCA'][$table]['ctrl']['fe_crgroup_id'])   {$field=$GLOBALS['TCA'][$table]['ctrl']['fe_crgroup_id']; list($dataArr[$field])=explode(',',$GLOBALS['TSFE']->fe_user->user['usergroup']); $dataArr[$field]=intval($dataArr[$field]); $extraList.=','.$field;}
-               
+
                unset($dataArr['uid']); // uid can never be set
                if ($pid>=0)    { $dataArr['pid'] = $pid; }             // Set pid < 0 and the dataarr-pid will be used!
-               $fieldList = implode(t3lib_div::trimExplode(',',$fieldList.','.$extraList,1),',');
-               
+               $fieldList = implode(',',t3lib_div::trimExplode(',',$fieldList.','.$extraList,1));
+
                $insertFields = array();
                foreach($dataArr as $f => $v)   {
                        if (t3lib_div::inList($fieldList,$f))   {
                                $insertFields[$f] = $v;
                        }
                }
-               
+
                if ($doExec)    {
                        return $GLOBALS['TYPO3_DB']->exec_INSERTquery($table, $insertFields);
                } else {
@@ -5532,7 +5984,7 @@ class tslib_cObj {
         * @see user_feAdmin
         */
        function DBmayFEUserEdit($table,$row, $feUserRow, $allowedGroups='',$feEditSelf=0)      {
-               $groupList = $allowedGroups ? implode(array_intersect(t3lib_div::trimExplode(',',$feUserRow['usergroup'],1),t3lib_div::trimExplode(',',$allowedGroups,1)),',') : $feUserRow['usergroup'];
+               $groupList = $allowedGroups ? implode(',',array_intersect(t3lib_div::trimExplode(',',$feUserRow['usergroup'],1),t3lib_div::trimExplode(',',$allowedGroups,1))) : $feUserRow['usergroup'];
                $ok=0;
                        // points to the field that allows further editing from frontend if not set. If set the record is locked.
                if (!$GLOBALS['TCA'][$table]['ctrl']['fe_admin_lock'] || !$row[$GLOBALS['TCA'][$table]['ctrl']['fe_admin_lock']])       {
@@ -5573,7 +6025,7 @@ class tslib_cObj {
         */
        function DBmayFEUserEditSelect($table,$feUserRow,$allowedGroups='',$feEditSelf=0)       {
                        // Returns where-definition that selects user-editable records.
-               $groupList = $allowedGroups ? implode(array_intersect(t3lib_div::trimExplode(',',$feUserRow['usergroup'],1),t3lib_div::trimExplode(',',$allowedGroups,1)),',') : $feUserRow['usergroup'];
+               $groupList = $allowedGroups ? implode(',',array_intersect(t3lib_div::trimExplode(',',$feUserRow['usergroup'],1),t3lib_div::trimExplode(',',$allowedGroups,1))) : $feUserRow['usergroup'];
                $OR_arr=array();
                        // points to the field (integer) that holds the fe_users-id of the creator fe_user
                if ($GLOBALS['TCA'][$table]['ctrl']['fe_cruser_id'])    {
@@ -5590,12 +6042,12 @@ class tslib_cObj {
                if ($feEditSelf && $table=='fe_users')  {
                        $OR_arr[]='uid='.intval($feUserRow['uid']);
                }
-               
+
                $whereDef=' AND 1=0';
                if (count($OR_arr))     {
-                       $whereDef=' AND ('.implode($OR_arr,' OR ').')';
+                       $whereDef=' AND ('.implode(' OR ',$OR_arr).')';
                        if ($GLOBALS['TCA'][$table]['ctrl']['fe_admin_lock'])   {
-                               $whereDef.=' AND NOT '.$GLOBALS['TCA'][$table]['ctrl']['fe_admin_lock'];
+                               $whereDef.=' AND '.$GLOBALS['TCA'][$table]['ctrl']['fe_admin_lock'].'=0';
                        }
                }
                return $whereDef;
@@ -5608,7 +6060,7 @@ class tslib_cObj {
         *
         * @param       string          The table for which to get the where clause
         * @param       boolean         If set, then you want NOT to filter out hidden records. Otherwise hidden record are filtered based on the current preview settings.
-        * @return      string          The part of the where clause on the form " AND NOT [fieldname] AND ...". Eg. " AND NOT hidden AND starttime < 123345567"
+        * @return      string          The part of the where clause on the form " AND [fieldname]=0 AND ...". Eg. " AND hidden=0 AND starttime < 123345567"
         * @see t3lib_pageSelect::enableFields()
         */
        function enableFields($table,$show_hidden=0)    {
@@ -5616,45 +6068,119 @@ class tslib_cObj {
        }
 
        /**
-        * Generates a list of Page-uid's from $id. List does not include $id itself
-        *  The only pages WHICH PREVENTS DECENDING in a branch are
+        * Generates a list of Page-uid's from $id. List does not include $id itself (unless the id specified is negative in which case it does!)
+        * The only pages WHICH PREVENTS DECENDING in a branch are
         *    - deleted pages,
         *    - pages in a recycler or of the Backend User Section type
         *    - pages that has the extendToSubpages set, WHERE start/endtime, hidden and fe_users would hide the records.
-        *  Apart from that, pages with enable-fields excluding them, will also be removed. HOWEVER $dontCheckEnableFields set will allow enableFields-excluded pages to be included anyway - including extendToSubpages sections!
-        *
-        *  Returns the list with a comma in the end (if any pages selected!) - which means the input page id can comfortably be appended to the output string if you need it to.
+        * Apart from that, pages with enable-fields excluding them, will also be removed. HOWEVER $dontCheckEnableFields set will allow enableFields-excluded pages to be included anyway - including extendToSubpages sections!
+        * Mount Pages are also descended but notice that these ID numbers are not useful for links unless the correct MPvar is set.
         *
-        * @param       integer         The id of the start page from which point in the page tree to decend.
+        * @param       integer         The id of the start page from which point in the page tree to decend. IF NEGATIVE the id itself is included in the end of the list (only if $begin is 0) AND the output does NOT contain a last comma. Recommended since it will resolve the input ID for mount pages correctly and also check if the start ID actually exists!
         * @param       integer         The number of levels to decend. If you want to decend infinitely, just set this to 100 or so. Should be at least "1" since zero will just make the function return (no decend...)
         * @param       integer         $begin is an optional integer that determines at which level in the tree to start collecting uid's. Zero means 'start right away', 1 = 'next level and out'
         * @param       boolean         See function description
         * @param       string          Additional fields to select. Syntax: ",[fieldname],[fieldname],..."
         * @param       string          Additional where clauses. Syntax: " AND [fieldname]=[value] AND ..."
-        * @return      string          A list of page ID integer values for the decended levels.
+        * @param       array           Array of IDs from previous recursions. In order to prevent infinite loops with mount pages.
+        * @param       integer         Internal: Zero for the first recursion, incremented for each recursive call.
+        * @return      string          Returns the list with a comma in the end (if any pages selected and not if $id is negative and $id is added itself) - which means the input page id can comfortably be appended to the output string if you need it to.
         * @see tslib_fe::checkEnableFields(), tslib_fe::checkPagerecordForIncludeSection()
         */
-       function getTreeList($id,$depth,$begin=0,$dontCheckEnableFields=0,$addSelectFields='',$moreWhereClauses='')     {
-               $depth=intval($depth);
-               $begin=intval($begin);
-               $id=intval($id);
-               $theList='';
-               $allFields = 'uid,hidden,starttime,endtime,fe_group,extendToSubpages,doktype,php_tree_stop'.$addSelectFields;
-               if ($id && $depth>0)    {
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($allFields, 'pages', 'pid='.intval($id).' AND NOT deleted AND doktype!=255 AND doktype!=6'.$moreWhereClauses, '' ,'sorting');
-                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))      {
-                               if ($dontCheckEnableFields || $GLOBALS['TSFE']->checkPagerecordForIncludeSection($row)) {
-                                       if ($begin<=0)  {
-                                               if ($dontCheckEnableFields || $GLOBALS['TSFE']->checkEnableFields($row))        {
-                                                       $theList.=$row['uid'].',';
+       function getTreeList($id,$depth,$begin=0,$dontCheckEnableFields=FALSE,$addSelectFields='',$moreWhereClauses='', $prevId_array=array(), $recursionLevel=0)       {
+
+                       // Init vars:
+               $allFields = 'uid,hidden,starttime,endtime,fe_group,extendToSubpages,doktype,php_tree_stop,mount_pid,mount_pid_ol,t3ver_state'.$addSelectFields;
+               $depth = intval($depth);
+               $begin = intval($begin);
+               $id = intval($id);
+               $theList = '';
+               $addId = 0;
+
+               if ($id)        {
+
+                               // First level, check id (second level, this is done BEFORE the recursive call)
+                       if (!$recursionLevel)   {
+                                       // If Id less than zero it means we should add the real id to list:
+                               if ($id < 0)    {
+                                       $addId = $id = abs($id);
+                               }
+                                       // Check start page:
+                               if ($GLOBALS['TSFE']->sys_page->getRawRecord('pages',$id,'uid'))        {
+
+                                               // Find mount point if any:
+                                       $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($id);
+                                       if (is_array($mount_info))      {
+                                               $id = $mount_info['mount_pid'];
+                                                       // In Overlay mode, use the mounted page uid as added ID!:
+                                               if ($addId && $mount_info['overlay'])   {
+                                                       $addId = $id;
                                                }
                                        }
-                                       if ($depth>1 && !$row['php_tree_stop']) {
-                                               $theList.=tslib_cObj::getTreeList($row['uid'], $depth-1, $begin-1, $dontCheckEnableFields, $addSelectFields, $moreWhereClauses);
+                               } else return '';       // Return blank if the start page was NOT found at all!
+                       }
+
+                               // Add this ID to the array of IDs
+                       if ($begin<=0)  {
+                               $prevId_array[] = $id;
+                       }
+
+                               // Select sublevel:
+                       if ($depth>0)   {
+                               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($allFields, 'pages', 'pid='.intval($id).' AND deleted=0'.$moreWhereClauses, '' ,'sorting');
+                               while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))      {
+                                       $GLOBALS['TSFE']->sys_page->versionOL('pages',$row);
+
+                                       if ($row['doktype']==255 || $row['doktype']==6 || $row['t3ver_state']==1)       { unset($row); }        // Doing this after the overlay to make sure changes in the overlay are respected.
+
+                                       if (is_array($row))     {
+                                                       // Find mount point if any:
+                                               $next_id = $row['uid'];
+                                               $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($next_id, $row);
+                                                       // Overlay mode:
+                                               if (is_array($mount_info) && $mount_info['overlay'])    {
+                                                       $next_id = $mount_info['mount_pid'];
+                                                       $res2 = $GLOBALS['TYPO3_DB']->exec_SELECTquery($allFields, 'pages', 'uid='.intval($next_id).' AND deleted=0'.$moreWhereClauses, '' ,'sorting');
+                                                       $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res2);
+                                                       $GLOBALS['TSFE']->sys_page->versionOL('pages',$row);
+
+                                                       if ($row['doktype']==255 || $row['doktype']==6 || $row['t3ver_state']==1)       { unset($row); }        // Doing this after the overlay to make sure changes in the overlay are respected.
+                                               }
+                                                       // Add record:
+                                               if (is_array($row) && ($dontCheckEnableFields || $GLOBALS['TSFE']->checkPagerecordForIncludeSection($row)))     {
+                                                               // Add ID to list:
+                                                       if ($begin<=0)  {
+                                                               if ($dontCheckEnableFields || $GLOBALS['TSFE']->checkEnableFields($row))        {
+                                                                       $theList.= $next_id.',';
+                                                               }
+                                                       }
+                                                               // Next level:
+                                                       if ($depth>1 && !$row['php_tree_stop']) {
+                                                                       // Normal mode:
+                                                               if (is_array($mount_info) && !$mount_info['overlay'])   {
+                                                                       $next_id = $mount_info['mount_pid'];
+                                                               }
+                                                                       // Call recursively, if the id is not in prevID_array:
+                                                               if (!in_array($next_id,$prevId_array))  {
+                                                                       $theList.= tslib_cObj::getTreeList($next_id, $depth-1, $begin-1, $dontCheckEnableFields, $addSelectFields, $moreWhereClauses, $prevId_array, $recursionLevel+1);
+                                                               }
+                                                       }
+                                               }
                                        }
                                }
                        }
                }
+                       // If first run, check if the ID should be returned:
+               if (!$recursionLevel)   {
+                       if ($addId)     {
+                               if ($begin>0)   {
+                                       $theList.= 0;
+                               } else {
+                                       $theList.= $addId;
+                               }
+                       }
+               }
+                       // Return list:
                return $theList;
        }
 
@@ -5672,7 +6198,7 @@ class tslib_cObj {
        }
 
        /**
-        * Executes a SELECT query for joining three tables according the the MM-relation standards used for tables configured in $TCA. That means MM-joins where the join table has the fields "uid_local" and "uid_foreign"
+        * Executes a SELECT query for joining three tables according to the MM-relation standards used for tables configured in $TCA. That means MM-joins where the join table has the fields "uid_local" and "uid_foreign"
         *
         * @param       string          List of fields to select
         * @param       string          The local table
@@ -5687,7 +6213,7 @@ class tslib_cObj {
         */
        function exec_mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='') {
                return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
-                                       $select, 
+                                       $select,
                                        $local_table.','.$mm_table.($foreign_table?','.$foreign_table:''),
                                        $local_table.'.uid='.$mm_table.'.uid_local'.($foreign_table?' AND '.$foreign_table.'.uid='.$mm_table.'.uid_foreign':'').
                                                $whereClause,   // whereClauseMightContainGroupOrderBy
@@ -5698,7 +6224,7 @@ class tslib_cObj {
        }
 
        /**
-        * Executes a SELECT query for joining two tables according the the MM-relation standards used for tables configured in $TCA. That means MM-joins where the join table has the fields "uid_local" and "uid_foreign"
+        * Executes a SELECT query for joining two tables according to the MM-relation standards used for tables configured in $TCA. That means MM-joins where the join table has the fields "uid_local" and "uid_foreign"
         * The two tables joined is the join table ($mm_table) and the foreign table ($foreign_table) - so the "local table" is not included but instead you can supply a list of UID integers from the local table to match in the join-table.
         *
         * @param       string          List of fields to select
@@ -5714,8 +6240,8 @@ class tslib_cObj {
         */
        function exec_mm_query_uidList($select,$local_table_uidlist,$mm_table,$foreign_table='',$whereClause='',$groupBy='',$orderBy='',$limit='')      {
                return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
-                                       $select, 
-                                       $mm_table.($foreign_table?','.$foreign_table:''), 
+                                       $select,
+                                       $mm_table.($foreign_table?','.$foreign_table:''),
                                        $mm_table.'.uid_local IN ('.$local_table_uidlist.')'.($foreign_table?' AND '.$foreign_table.'.uid='.$mm_table.'.uid_foreign':'').
                                                $whereClause,   // whereClauseMightContainGroupOrderBy
                                        $groupBy,
@@ -5746,11 +6272,11 @@ class tslib_cObj {
                                if (strlen($val)>=2)    {
                                        reset($searchFields);
                                        while(list(,$field)=each($searchFields))        {
-                                               $where_p[]=$prefixTableName.$field.' LIKE "%'.$GLOBALS['TYPO3_DB']->quoteStr($val, $searchTable).'%"';
+                                               $where_p[] = $prefixTableName.$field.' LIKE \'%'.$GLOBALS['TYPO3_DB']->quoteStr($val, $searchTable).'%\'';
                                        }
                                }
                                if (count($where_p))    {
-                                       $where.=' AND ('.implode($where_p,' OR ').')';
+                                       $where.=' AND ('.implode(' OR ',$where_p).')';
                                }
                        }
                }
@@ -5771,7 +6297,7 @@ class tslib_cObj {
 
                return $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryParts);
        }
-       
+
        /**
         * Creates and returns a SELECT query for records from $table and with conditions based on the configuration in the $conf array
         * Implements the "select" function in TypoScript
@@ -5799,7 +6325,7 @@ class tslib_cObj {
                        // Setting LIMIT:
                if ($conf['max'] || $conf['begin']) {
                        $error=0;
-                               
+
                                // Finding the total number of records, if used:
                        if (strstr(strtolower($conf['begin'].$conf['max']),'total'))    {
                                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $queryParts['WHERE'], $queryParts['GROUPBY']);
@@ -5817,7 +6343,7 @@ class tslib_cObj {
                                if ($conf['begin'] && !$conf['max'])    {
                                        $conf['max'] = 100000;
                                }
-                               
+
                                if ($conf['begin'] && $conf['max'])     {
                                        $queryParts['LIMIT'] = $conf['begin'].','.$conf['max'];
                                } elseif (!$conf['begin'] && $conf['max'])      {
@@ -5841,11 +6367,11 @@ class tslib_cObj {
                                // Compile and return query:
                        $queryParts['FROM'] = trim($table.' '.$joinPart);
                        $query = $GLOBALS['TYPO3_DB']->SELECTquery(
-                                               $queryParts['SELECT'], 
-                                               $queryParts['FROM'], 
-                                               $queryParts['WHERE'], 
-                                               $queryParts['GROUPBY'], 
-                                               $queryParts['ORDERBY'], 
+                                               $queryParts['SELECT'],
+                                               $queryParts['FROM'],
+                                               $queryParts['WHERE'],
+                                               $queryParts['GROUPBY'],
+                                               $queryParts['ORDERBY'],
                                                $queryParts['LIMIT']
                                        );
                        return $returnQueryArray ? $queryParts : $query;
@@ -5864,7 +6390,8 @@ class tslib_cObj {
         * @see getQuery()
         */
        function getWhere($table,$conf, $returnQueryArray=FALSE)        {
-                       
+               global $TCA;
+
                        // Init:
                $query = '';
                $pid_uid_flag=0;
@@ -5888,10 +6415,10 @@ class tslib_cObj {
                }
                if (trim($conf['pidInList']))   {
                        $listArr = t3lib_div::intExplode(',',str_replace('this',$GLOBALS['TSFE']->contentPid,$conf['pidInList']));      // str_replace instead of ereg_replace 020800
-                               // removes all pages which are not visible for the user!                        
+                               // removes all pages which are not visible for the user!
                        $listArr = $this->checkPidArray($listArr);
                        if (count($listArr))    {
-                           $query.=' AND '.$table.'.pid IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($listArr)).')';
+                               $query.=' AND '.$table.'.pid IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($listArr)).')';
                                $pid_uid_flag++;
                        } else {
                                $pid_uid_flag=0;                // If not uid and not pid then uid is set to 0 - which results in nothing!!
@@ -5903,10 +6430,17 @@ class tslib_cObj {
                if ($where = trim($conf['where']))      {
                        $query.=' AND '.$where;
                }
+
                if ($conf['languageField'])     {
-                       $query.=' AND '.$conf['languageField'].'='.intval($GLOBALS['TSFE']->sys_language_uid);
+                       if ($GLOBALS['TSFE']->sys_language_contentOL && $TCA[$table] && $TCA[$table]['ctrl']['languageField'] && $TCA[$table]['ctrl']['transOrigPointerField']) {
+                                       // Sys language content is set to zero/-1 - and it is expected that whatever routine processes the output will OVERLAY the records with localized versions!
+                               $sys_language_content = '0,-1';
+                       } else {
+                               $sys_language_content = intval($GLOBALS['TSFE']->sys_language_content);
+                       }
+                       $query.=' AND '.$conf['languageField'].' IN ('.$sys_language_content.')';
                }
-               
+
                $andWhere = trim($this->stdWrap($conf['andWhere'],$conf['andWhere.']));
                if ($andWhere)  {
                        $query.=' AND '.$andWhere;
@@ -5914,17 +6448,18 @@ class tslib_cObj {
 
                        // enablefields
                if ($table=='pages')    {
-                       $query.=' '.$GLOBALS['TSFE']->sys_page->where_hid_del;
+                       $query.=' '.$GLOBALS['TSFE']->sys_page->where_hid_del.
+                                               $GLOBALS['TSFE']->sys_page->where_groupAccess;
                } else {
                        $query.=$this->enableFields($table);
                }
-               
+
                        // MAKE WHERE:
                if ($query)     {
                        $queryParts['WHERE'] = trim(substr($query,4));  // Stripping of " AND"...
                        $query = 'WHERE '.$queryParts['WHERE'];
                }
-               
+
                        // GROUP BY
                if (trim($conf['groupBy']))     {
                        $queryParts['GROUPBY'] = trim($conf['groupBy']);
@@ -5952,14 +6487,14 @@ class tslib_cObj {
        function checkPidArray($listArr)        {
                $outArr = Array();
                if (is_array($listArr) && count($listArr))      {
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid IN ('.implode($listArr,',').')'.$this->enableFields('pages').' AND doktype NOT IN ('.$this->checkPid_badDoktypeList.')');
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid IN ('.implode(',',$listArr).')'.$this->enableFields('pages').' AND doktype NOT IN ('.$this->checkPid_badDoktypeList.')');
                        if ($error = $GLOBALS['TYPO3_DB']->sql_error()) {
                                $GLOBALS['TT']->setTSlogMessage($error.': '.$query,3);
                        } else {
                                while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))       {
                                        $outArr[] = $row['uid'];
                                }
-                       }                       
+                       }
                }
                return $outArr;
        }
@@ -5974,7 +6509,7 @@ class tslib_cObj {
         */
        function checkPid($uid) {
                $uid = intval($uid);
-               if (!isset($this->checkPid_cache[$uid]))        {       
+               if (!isset($this->checkPid_cache[$uid]))        {
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid='.intval($uid).$this->enableFields('pages').' AND doktype NOT IN ('.$this->checkPid_badDoktypeList.')');
                        if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))   {
                                $this->checkPid_cache[$uid] = 1;
@@ -6033,23 +6568,23 @@ class tslib_cObj {
 
                        // If no backend user, return immediately
                if (!$GLOBALS['TSFE']->beUserLogin)             {return $content;}
-               
+
                        // If a backend user is logged in, then go on...
                if ($conf['newRecordFromTable'])        {
                        $currentRecord = $conf['newRecordFromTable'].':NEW';
                        $conf['allow']='new';
                }
-               
+
                if (!$currentRecord)    $currentRecord=$this->currentRecord;
                if (!count($dataArr))   $dataArr=$this->data;
                list($table,$uid) = explode(':',$currentRecord);
                $mayEdit=0;
-               
+
                if (!$conf['onlyCurrentPid'] || $dataArr['pid']==$GLOBALS['TSFE']->id)  {
                                // Permissions:
                        $types = t3lib_div::trimExplode(',',strtolower($conf['allow']),1);
                        $allow = array_flip($types);
-                       
+
                        $perms = $GLOBALS['BE_USER']->calcPerms($GLOBALS['TSFE']->page);
                        if ($table=='pages')    {
                                if (count($GLOBALS['TSFE']->config['rootLine'])==1)     {unset($allow['move']); unset($allow['hide']); unset($allow['delete']);}        // rootpage!
@@ -6066,8 +6601,8 @@ class tslib_cObj {
                                        $newUid = -1*$uid;
                                }
                        }
-               }               
-                               
+               }
+
                if ($GLOBALS['TSFE']->displayEditIcons && $table && $mayEdit)   {
                        $GLOBALS['TSFE']->set_no_cache();               // Special content is about to be shown, so the cache must be disabled.
                        $formName = 'TSFE_EDIT_FORM_'.substr($GLOBALS['TSFE']->uniqueHash(),0,4);
@@ -6082,7 +6617,7 @@ class tslib_cObj {
                        if (is_array($TSFE_EDIT) && $TSFE_EDIT['record']==$currentRecord && !$TSFE_EDIT['update_close'])        {
                                $theCmd =$TSFE_EDIT['cmd'];
                        }
-                       
+
                        switch($theCmd) {
                                case 'edit':
                   &nb