class.t3lib_tceforms_inline.php

Go to the documentation of this file.
00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 2006-2010 Oliver Hader <oh@inpublica.de>
00006 *  All rights reserved
00007 *
00008 *  This script is part of the TYPO3 project. The TYPO3 project is
00009 *  free software; you can redistribute it and/or modify
00010 *  it under the terms of the GNU General Public License as published by
00011 *  the Free Software Foundation; either version 2 of the License, or
00012 *  (at your option) any later version.
00013 *
00014 *  The GNU General Public License can be found at
00015 *  http://www.gnu.org/copyleft/gpl.html.
00016 *  A copy is found in the textfile GPL.txt and important notices to the license
00017 *  from the author is found in LICENSE.txt distributed with these scripts.
00018 *
00019 *
00020 *  This script is distributed in the hope that it will be useful,
00021 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023 *  GNU General Public License for more details.
00024 *
00025 *  This copyright notice MUST APPEAR in all copies of the script!
00026 ***************************************************************/
00027 /**
00028  * The Inline-Relational-Record-Editing (IRRE) functions as part of the TCEforms.
00029  *
00030  * $Id: class.t3lib_tceforms_inline.php 8655 2010-08-23 21:49:13Z steffenk $
00031  *
00032  * @author  Oliver Hader <oh@inpublica.de>
00033  */
00034 /**
00035  * [CLASS/FUNCTION INDEX of SCRIPT]
00036  *
00037  *
00038  *
00039  *   88: class t3lib_TCEforms_inline
00040  *  109:     function init(&$tceForms)
00041  *  127:     function getSingleField_typeInline($table,$field,$row,&$PA)
00042  *
00043  *              SECTION: Regular rendering of forms, fields, etc.
00044  *  263:     function renderForeignRecord($parentUid, $rec, $config = array())
00045  *  319:     function renderForeignRecordHeader($parentUid, $foreign_table,$rec,$config = array())
00046  *  375:     function renderForeignRecordHeaderControl($table,$row,$config = array())
00047  *  506:     function renderCombinationTable(&$rec, $appendFormFieldNames, $config = array())
00048  *  560:     function renderPossibleRecordsSelector($selItems, $conf, $uniqueIds=array())
00049  *  627:     function addJavaScript()
00050  *  643:     function addJavaScriptSortable($objectId)
00051  *
00052  *              SECTION: Handling of AJAX calls
00053  *  665:     function createNewRecord($domObjectId, $foreignUid = 0)
00054  *  755:     function getJSON($jsonArray)
00055  *  770:     function getNewRecordLink($objectPrefix, $conf = array())
00056  *
00057  *              SECTION: Get data from database and handle relations
00058  *  807:     function getRelatedRecords($table,$field,$row,&$PA,$config)
00059  *  839:     function getPossibleRecords($table,$field,$row,$conf,$checkForConfField='foreign_selector')
00060  *  885:     function getUniqueIds($records, $conf=array())
00061  *  905:     function getRecord($pid, $table, $uid, $cmd='')
00062  *  929:     function getNewRecord($pid, $table)
00063  *
00064  *              SECTION: Structure stack for handling inline objects/levels
00065  *  951:     function pushStructure($table, $uid, $field = '', $config = array())
00066  *  967:     function popStructure()
00067  *  984:     function updateStructureNames()
00068  * 1000:     function getStructureItemName($levelData)
00069  * 1015:     function getStructureLevel($level)
00070  * 1032:     function getStructurePath($structureDepth = -1)
00071  * 1057:     function parseStructureString($string, $loadConfig = false)
00072  *
00073  *              SECTION: Helper functions
00074  * 1098:     function checkConfiguration(&$config)
00075  * 1123:     function checkAccess($cmd, $table, $theUid)
00076  * 1185:     function compareStructureConfiguration($compare)
00077  * 1199:     function normalizeUid($string)
00078  * 1213:     function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array())
00079  * 1242:     function isInlineChildAndLabelField($table, $field)
00080  * 1258:     function getStructureDepth()
00081  * 1295:     function arrayCompareComplex($subjectArray, $searchArray, $type = '')
00082  * 1349:     function isAssociativeArray($object)
00083  * 1364:     function getPossibleRecordsFlat($possibleRecords)
00084  * 1383:     function skipField($table, $field, $row, $config)
00085  *
00086  * TOTAL FUNCTIONS: 35
00087  * (This index is automatically created/updated by the extension "extdeveval")
00088  *
00089  */
00090 
00091 
00092 class t3lib_TCEforms_inline {
00093     const Structure_Separator = '-';
00094     const Disposal_AttributeName = 'Disposal_AttributeName';
00095     const Disposal_AttributeId = 'Disposal_AttributeId';
00096 
00097     /**
00098      * Reference to the calling TCEforms instance
00099      *
00100      * @var t3lib_TCEforms
00101      */
00102     var $fObj;
00103     var $backPath;                          // Reference to $fObj->backPath
00104 
00105     var $isAjaxCall = false;                // Indicates if a field is rendered upon an AJAX call
00106     var $inlineStructure = array();         // the structure/hierarchy where working in, e.g. cascading inline tables
00107     var $inlineFirstPid;                    // the first call of an inline type appeared on this page (pid of record)
00108     var $inlineNames = array();             // keys: form, object -> hold the name/id for each of them
00109     var $inlineData = array();              // inline data array used for JSON output
00110     var $inlineView = array();              // expanded/collapsed states for the current BE user
00111     var $inlineCount = 0;                   // count the number of inline types used
00112     var $inlineStyles = array();
00113 
00114     var $prependNaming = 'data';            // how the $this->fObj->prependFormFieldNames should be set ('data' is default)
00115     var $prependFormFieldNames;             // reference to $this->fObj->prependFormFieldNames
00116     var $prependCmdFieldNames;              // reference to $this->fObj->prependCmdFieldNames
00117 
00118     protected $hookObjects = array();           // array containing instances of hook classes called once for IRRE objects
00119 
00120 
00121     /**
00122      * Intialize an instance of t3lib_TCEforms_inline
00123      *
00124      * @param   t3lib_TCEforms      $tceForms: Reference to an TCEforms instance
00125      * @return  void
00126      */
00127     function init(&$tceForms) {
00128         $this->fObj = $tceForms;
00129         $this->backPath =& $tceForms->backPath;
00130         $this->prependFormFieldNames =& $this->fObj->prependFormFieldNames;
00131         $this->prependCmdFieldNames =& $this->fObj->prependCmdFieldNames;
00132         $this->inlineStyles['margin-right'] = '5';
00133         $this->initHookObjects();
00134     }
00135 
00136 
00137     /**
00138      * Initialized the hook objects for this class.
00139      * Each hook object has to implement the interface t3lib_tceformsInlineHook.
00140      *
00141      * @return  void
00142      */
00143     protected function initHookObjects() {
00144         $this->hookObjects = array();
00145         if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'])) {
00146             $tceformsInlineHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'];
00147             if (is_array($tceformsInlineHook)) {
00148                 foreach($tceformsInlineHook as $classData) {
00149                     $processObject = t3lib_div::getUserObj($classData);
00150 
00151                     if(!($processObject instanceof t3lib_tceformsInlineHook)) {
00152                         throw new UnexpectedValueException('$processObject must implement interface t3lib_tceformsInlineHook', 1202072000);
00153                     }
00154 
00155                     $processObject->init($this);
00156                     $this->hookObjects[] = $processObject;
00157                 }
00158             }
00159         }
00160     }
00161 
00162 
00163     /**
00164      * Generation of TCEform elements of the type "inline"
00165      * This will render inline-relational-record sets. Relations.
00166      *
00167      * @param   string      $table: The table name of the record
00168      * @param   string      $field: The field name which this element is supposed to edit
00169      * @param   array       $row: The record data array where the value(s) for the field can be found
00170      * @param   array       $PA: An array with additional configuration options.
00171      * @return  string      The HTML code for the TCEform field
00172      */
00173     function getSingleField_typeInline($table,$field,$row,&$PA) {
00174             // check the TCA configuration - if false is returned, something was wrong
00175         if ($this->checkConfiguration($PA['fieldConf']['config']) === false) {
00176             return false;
00177         }
00178 
00179             // count the number of processed inline elements
00180         $this->inlineCount++;
00181 
00182             // Init:
00183         $config = $PA['fieldConf']['config'];
00184         $foreign_table = $config['foreign_table'];
00185         t3lib_div::loadTCA($foreign_table);
00186 
00187         if (t3lib_BEfunc::isTableLocalizable($table)) {
00188             $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
00189         }
00190         $minitems = t3lib_div::intInRange($config['minitems'],0);
00191         $maxitems = t3lib_div::intInRange($config['maxitems'],0);
00192         if (!$maxitems) $maxitems=100000;
00193 
00194             // Register the required number of elements:
00195         $this->fObj->requiredElements[$PA['itemFormElName']] = array($minitems,$maxitems,'imgName'=>$table.'_'.$row['uid'].'_'.$field);
00196 
00197             // remember the page id (pid of record) where inline editing started first
00198             // we need that pid for ajax calls, so that they would know where the action takes place on the page structure
00199         if (!isset($this->inlineFirstPid)) {
00200                 // if this record is not new, try to fetch the inlineView states
00201                 // @TODO: Add checking/cleaning for unused tables, records, etc. to save space in uc-field
00202             if (t3lib_div::testInt($row['uid'])) {
00203                 $inlineView = unserialize($GLOBALS['BE_USER']->uc['inlineView']);
00204                 $this->inlineView = $inlineView[$table][$row['uid']];
00205             }
00206                 // If the parent is a page, use the uid(!) of the (new?) page as pid for the child records:
00207             if ($table == 'pages') {
00208                 $this->inlineFirstPid = $row['uid'];
00209                 // If pid is negative, fetch the previous record and take its pid:
00210             } elseif ($row['pid'] < 0) {
00211                 $prevRec = t3lib_BEfunc::getRecord($table, abs($row['pid']));
00212                 $this->inlineFirstPid = $prevRec['pid'];
00213                 // Take the pid as it is:
00214             } else {
00215                 $this->inlineFirstPid = $row['pid'];
00216             }
00217         }
00218             // add the current inline job to the structure stack
00219         $this->pushStructure($table, $row['uid'], $field, $config);
00220             // e.g. data[<table>][<uid>][<field>]
00221         $nameForm = $this->inlineNames['form'];
00222             // e.g. data-<pid>-<table1>-<uid1>-<field1>-<table2>-<uid2>-<field2>
00223         $nameObject = $this->inlineNames['object'];
00224             // get the records related to this inline record
00225         $relatedRecords = $this->getRelatedRecords($table,$field,$row,$PA,$config);
00226             // set the first and last record to the config array
00227         $relatedRecordsUids = array_keys($relatedRecords['records']);
00228         $config['inline']['first'] = reset($relatedRecordsUids);
00229         $config['inline']['last'] = end($relatedRecordsUids);
00230 
00231             // Tell the browser what we have (using JSON later):
00232         $top = $this->getStructureLevel(0);
00233         $this->inlineData['config'][$nameObject] = array(
00234             'table' => $foreign_table,
00235             'md5' => md5($nameObject),
00236         );
00237         $this->inlineData['config'][$nameObject. self::Structure_Separator . $foreign_table] = array(
00238             'min' => $minitems,
00239             'max' => $maxitems,
00240             'sortable' => $config['appearance']['useSortable'],
00241             'top' => array(
00242                 'table' => $top['table'],
00243                 'uid'   => $top['uid'],
00244             ),
00245         );
00246             // Set a hint for nested IRRE and tab elements:
00247         $this->inlineData['nested'][$nameObject] = $this->fObj->getDynNestedStack(false, $this->isAjaxCall);
00248 
00249             // if relations are required to be unique, get the uids that have already been used on the foreign side of the relation
00250         if ($config['foreign_unique']) {
00251                 // If uniqueness *and* selector are set, they should point to the same field - so, get the configuration of one:
00252             $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_unique']);
00253                 // Get the used unique ids:
00254             $uniqueIds = $this->getUniqueIds($relatedRecords['records'], $config, $selConfig['type']=='groupdb');
00255             $possibleRecords = $this->getPossibleRecords($table,$field,$row,$config,'foreign_unique');
00256             $uniqueMax = $config['appearance']['useCombination'] || $possibleRecords === false ? -1 : count($possibleRecords);
00257             $this->inlineData['unique'][$nameObject. self::Structure_Separator . $foreign_table] = array(
00258                 'max' => $uniqueMax,
00259                 'used' => $uniqueIds,
00260                 'type' => $selConfig['type'],
00261                 'table' => $config['foreign_table'],
00262                 'elTable' => $selConfig['table'], // element/record table (one step down in hierarchy)
00263                 'field' => $config['foreign_unique'],
00264                 'selector' => $selConfig['selector'],
00265                 'possible' => $this->getPossibleRecordsFlat($possibleRecords),
00266             );
00267         }
00268 
00269             // if it's required to select from possible child records (reusable children), add a selector box
00270         if ($config['foreign_selector']) {
00271                 // if not already set by the foreign_unique, set the possibleRecords here and the uniqueIds to an empty array
00272             if (!$config['foreign_unique']) {
00273                 $possibleRecords = $this->getPossibleRecords($table,$field,$row,$config);
00274                 $uniqueIds = array();
00275             }
00276             $selectorBox = $this->renderPossibleRecordsSelector($possibleRecords,$config,$uniqueIds);
00277             $item .= $selectorBox;
00278         }
00279 
00280             // wrap all inline fields of a record with a <div> (like a container)
00281         $item .= '<div id="'.$nameObject.'">';
00282 
00283             // define how to show the "Create new record" link - if there are more than maxitems, hide it
00284         if ($relatedRecords['count'] >= $maxitems || ($uniqueMax > 0 && $relatedRecords['count'] >= $uniqueMax)) {
00285             $config['inline']['inlineNewButtonStyle'] = 'display: none;';
00286         }
00287 
00288             // Render the level links (create new record, localize all, synchronize):
00289         if ($config['appearance']['levelLinksPosition']!='none') {
00290             $levelLinks = $this->getLevelInteractionLink('newRecord', $nameObject . self::Structure_Separator . $foreign_table, $config);
00291             if ($language>0) {
00292                     // Add the "Localize all records" link before all child records:
00293                 if (isset($config['appearance']['showAllLocalizationLink']) && $config['appearance']['showAllLocalizationLink']) {
00294                     $levelLinks.= $this->getLevelInteractionLink('localize', $nameObject . self::Structure_Separator . $foreign_table, $config);
00295                 }
00296                     // Add the "Synchronize with default language" link before all child records:
00297                 if (isset($config['appearance']['showSynchronizationLink']) && $config['appearance']['showSynchronizationLink']) {
00298                     $levelLinks.= $this->getLevelInteractionLink('synchronize', $nameObject . self::Structure_Separator . $foreign_table, $config);
00299                 }
00300             }
00301         }
00302             // Add the level links before all child records:
00303         if (in_array($config['appearance']['levelLinksPosition'], array('both', 'top'))) {
00304             $item.= $levelLinks;
00305         }
00306 
00307         $item .= '<div id="'.$nameObject.'_records">';
00308         $relationList = array();
00309         if (count($relatedRecords['records'])) {
00310             foreach ($relatedRecords['records'] as $rec) {
00311                 $item .= $this->renderForeignRecord($row['uid'],$rec,$config);
00312                 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
00313                     $relationList[] = $rec['uid'];
00314                 }
00315             }
00316         }
00317         $item .= '</div>';
00318 
00319             // Add the level links after all child records:
00320         if (in_array($config['appearance']['levelLinksPosition'], array('both', 'bottom'))) {
00321             $item.= $levelLinks;
00322         }
00323 
00324             // add Drag&Drop functions for sorting to TCEforms::$additionalJS_post
00325         if (count($relationList) > 1 && $config['appearance']['useSortable'])
00326             $this->addJavaScriptSortable($nameObject.'_records');
00327             // publish the uids of the child records in the given order to the browser
00328         $item .= '<input type="hidden" name="'.$nameForm.'" value="'.implode(',', $relationList).'" class="inlineRecord" />';
00329             // close the wrap for all inline fields (container)
00330         $item .= '</div>';
00331 
00332             // on finishing this section, remove the last item from the structure stack
00333         $this->popStructure();
00334 
00335             // if this was the first call to the inline type, restore the values
00336         if (!$this->getStructureDepth()) {
00337             unset($this->inlineFirstPid);
00338         }
00339 
00340         return $item;
00341     }
00342 
00343 
00344     /*******************************************************
00345      *
00346      * Regular rendering of forms, fields, etc.
00347      *
00348      *******************************************************/
00349 
00350 
00351     /**
00352      * Render the form-fields of a related (foreign) record.
00353      *
00354      * @param   string      $parentUid: The uid of the parent (embedding) record (uid or NEW...)
00355      * @param   array       $rec: The table record of the child/embedded table (normaly post-processed by t3lib_transferData)
00356      * @param   array       $config: content of $PA['fieldConf']['config']
00357      * @return  string      The HTML code for this "foreign record"
00358      */
00359     function renderForeignRecord($parentUid, $rec, $config = array()) {
00360         $foreign_table = $config['foreign_table'];
00361         $foreign_field = $config['foreign_field'];
00362         $foreign_selector = $config['foreign_selector'];
00363 
00364             // Register default localization content:
00365         $parent = $this->getStructureLevel(-1);
00366         if (isset($parent['localizationMode']) && $parent['localizationMode']!=false) {
00367             $this->fObj->registerDefaultLanguageData($foreign_table, $rec);
00368         }
00369             // Send a mapping information to the browser via JSON:
00370             // e.g. data[<curTable>][<curId>][<curField>] => data-<pid>-<parentTable>-<parentId>-<parentField>-<curTable>-<curId>-<curField>
00371         $this->inlineData['map'][$this->inlineNames['form']] = $this->inlineNames['object'];
00372 
00373             // Set this variable if we handle a brand new unsaved record:
00374         $isNewRecord = t3lib_div::testInt($rec['uid']) ? false : true;
00375             // Set this variable if the record is virtual and only show with header and not editable fields:
00376         $isVirtualRecord = (isset($rec['__virtual']) && $rec['__virtual']);
00377             // If there is a selector field, normalize it:
00378         if ($foreign_selector) {
00379             $rec[$foreign_selector] = $this->normalizeUid($rec[$foreign_selector]);
00380         }
00381 
00382         if (!$this->checkAccess(($isNewRecord ? 'new' : 'edit'), $foreign_table, $rec['uid'])) {
00383             return false;
00384         }
00385 
00386             // Get the current naming scheme for DOM name/id attributes:
00387         $nameObject = $this->inlineNames['object'];
00388         $appendFormFieldNames = '['.$foreign_table.']['.$rec['uid'].']';
00389         $objectId = $nameObject . self::Structure_Separator . $foreign_table . self::Structure_Separator . $rec['uid'];
00390             // Put the current level also to the dynNestedStack of TCEforms:
00391         $this->fObj->pushToDynNestedStack('inline', $objectId);
00392 
00393         if (!$isVirtualRecord) {
00394                 // Get configuration:
00395             $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
00396             $ajaxLoad = (isset($config['appearance']['ajaxLoad']) && !$config['appearance']['ajaxLoad']) ? false : true;
00397 
00398             if ($isNewRecord) {
00399                     // show this record expanded or collapsed
00400                 $isExpanded = (!$collapseAll ? 1 : 0);
00401             } else {
00402                 $isExpanded = ($config['renderFieldsOnly'] || (!$collapseAll && $this->getExpandedCollapsedState($foreign_table, $rec['uid'])));
00403             }
00404                 // Render full content ONLY IF this is a AJAX-request, a new record, the record is not collapsed or AJAX-loading is explicitly turned off
00405             if ($isNewRecord || $isExpanded || !$ajaxLoad) {
00406                 $combination = $this->renderCombinationTable($rec, $appendFormFieldNames, $config);
00407                 $fields = $this->renderMainFields($foreign_table, $rec);
00408                 $fields = $this->wrapFormsSection($fields);
00409                     // Replace returnUrl in Wizard-Code, if this is an AJAX call
00410                 $ajaxArguments = t3lib_div::_GP('ajax');
00411                 if (isset($ajaxArguments[2]) && trim($ajaxArguments[2]) != '') {
00412                     $fields = str_replace('P[returnUrl]=%2F' . rawurlencode(TYPO3_mainDir) . '%2Fajax.php', 'P[returnUrl]=' . rawurlencode($ajaxArguments[2]), $fields);
00413                 }
00414             } else {
00415                 $combination = '';
00416                     // This string is the marker for the JS-function to check if the full content has already been loaded
00417                 $fields = '<!--notloaded-->';
00418             }
00419             if ($isNewRecord) {
00420                     // get the top parent table
00421                 $top = $this->getStructureLevel(0);
00422                 $ucFieldName = 'uc[inlineView]['.$top['table'].']['.$top['uid'].']'.$appendFormFieldNames;
00423                     // set additional fields for processing for saving
00424                 $fields .= '<input type="hidden" name="'.$this->prependFormFieldNames.$appendFormFieldNames.'[pid]" value="'.$rec['pid'].'"/>';
00425                 $fields .= '<input type="hidden" name="'.$ucFieldName.'" value="'.$isExpanded.'" />';
00426             } else {
00427                     // set additional field for processing for saving
00428                 $fields .= '<input type="hidden" name="'.$this->prependCmdFieldNames.$appendFormFieldNames.'[delete]" value="1" disabled="disabled" />';
00429             }
00430                 // if this record should be shown collapsed
00431             if (!$isExpanded) {
00432                 $appearanceStyleFields = ' style="display: none;"';
00433             }
00434         }
00435 
00436         if ($config['renderFieldsOnly']) {
00437             $out = $fields . $combination;
00438         } else {
00439             // set the record container with data for output
00440             $out = '<div class="t3-form-field-record-inline" id="' . $objectId . '_fields"' . $appearanceStyleFields . '>' . $fields . $combination . '</div>';
00441             $header = $this->renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
00442             $out = '<div class="t3-form-field-header-inline" id="' . $objectId . '_header">' . $header . '</div>' . $out;
00443                 // wrap the header, fields and combination part of a child record with a div container
00444             $classMSIE = ($this->fObj->clientInfo['BROWSER']=='msie' && $this->fObj->clientInfo['VERSION'] < 8 ? 'MSIE' : '');
00445             $class = 'inlineDiv' . $classMSIE . ($isNewRecord ? ' inlineIsNewRecord' : '');
00446             $out = '<div id="' . $objectId . '_div" class="t3-form-field-container-inline '.$class.'">' . $out . '</div>';
00447         }
00448             // Remove the current level also from the dynNestedStack of TCEforms:
00449         $this->fObj->popFromDynNestedStack();
00450 
00451         return $out;
00452     }
00453 
00454 
00455     /**
00456      * Wrapper for TCEforms::getMainFields().
00457      *
00458      * @param   string      $table: The table name
00459      * @param   array       $row: The record to be rendered
00460      * @return  string      The rendered form
00461      */
00462     protected function renderMainFields($table, $row) {
00463             // The current render depth of t3lib_TCEforms:
00464         $depth = $this->fObj->renderDepth;
00465             // If there is some information about already rendered palettes of our parent, store this info:
00466         if (isset($this->fObj->palettesRendered[$depth][$table])) {
00467             $palettesRendered = $this->fObj->palettesRendered[$depth][$table];
00468         }
00469             // Render the form:
00470         $content = $this->fObj->getMainFields($table, $row, $depth);
00471             // If there was some info about rendered palettes stored, write it back for our parent:
00472         if (isset($palettesRendered)) {
00473             $this->fObj->palettesRendered[$depth][$table] = $palettesRendered;
00474         }
00475         return $content;
00476     }
00477 
00478 
00479     /**
00480      * Renders the HTML header for a foreign record, such as the title, toggle-function, drag'n'drop, etc.
00481      * Later on the command-icons are inserted here.
00482      *
00483      * @param   string      $parentUid: The uid of the parent (embedding) record (uid or NEW...)
00484      * @param   string      $foreign_table: The foreign_table we create a header for
00485      * @param   array       $rec: The current record of that foreign_table
00486      * @param   array       $config: content of $PA['fieldConf']['config']
00487      * @param   boolean     $isVirtualRecord:
00488      * @return  string      The HTML code of the header
00489      */
00490     function renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord=false) {
00491             // Init:
00492         $objectId = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table . self::Structure_Separator . $rec['uid'];
00493         $expandSingle = $config['appearance']['expandSingle'] ? 1 : 0;
00494             // we need the returnUrl of the main script when loading the fields via AJAX-call (to correct wizard code, so include it as 3rd parameter)
00495         $onClick = "return inline.expandCollapseRecord('" . htmlspecialchars($objectId) . "', $expandSingle, '" . rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI')) . "')";
00496 
00497             // Pre-Processing:
00498         $isOnSymmetricSide = t3lib_loadDBGroup::isOnSymmetricSide($parentUid, $config, $rec);
00499         $hasForeignLabel = !$isOnSymmetricSide && $config['foreign_label'] ? true : false;
00500         $hasSymmetricLabel = $isOnSymmetricSide && $config['symmetric_label'] ? true : false;
00501             // Get the record title/label for a record:
00502             // render using a self-defined user function
00503         if ($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc']) {
00504             $params = array(
00505                 'table' => $foreign_table,
00506                 'row'   => $rec,
00507                 'title' => '',
00508                 'isOnSymmetricSide' => $isOnSymmetricSide,
00509                 'parent' => array(
00510                     'uid' => $parentUid,
00511                     'config' => $config,
00512                 ),
00513             );
00514             $null = null;   // callUserFunction requires a third parameter, but we don't want to give $this as reference!
00515             t3lib_div::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'], $params, $null);
00516             $recTitle = $params['title'];
00517             // render the special alternative title
00518         } elseif ($hasForeignLabel || $hasSymmetricLabel) {
00519             $titleCol = $hasForeignLabel ? $config['foreign_label'] : $config['symmetric_label'];
00520             $foreignConfig = $this->getPossibleRecordsSelectorConfig($config, $titleCol);
00521                 // Render title for everything else than group/db:
00522             if ($foreignConfig['type'] != 'groupdb') {
00523                 $recTitle = t3lib_BEfunc::getProcessedValueExtra($foreign_table, $titleCol, $rec[$titleCol], 0, 0, false);
00524                 // Render title for group/db:
00525             } else {
00526                     // $recTitle could be something like: "tx_table_123|...",
00527                 $valueParts = t3lib_div::trimExplode('|', $rec[$titleCol]);
00528                 $itemParts = t3lib_div::revExplode('_', $valueParts[0], 2);
00529                 $recTemp = t3lib_befunc::getRecordWSOL($itemParts[0], $itemParts[1]);
00530                 $recTitle = t3lib_BEfunc::getRecordTitle($itemParts[0], $recTemp, false);
00531             }
00532             $recTitle = t3lib_BEfunc::getRecordTitlePrep($recTitle);
00533             if (!strcmp(trim($recTitle),'')) {
00534                 $recTitle = t3lib_BEfunc::getNoRecordTitle(true);
00535             }
00536             // render the standard
00537         } else {
00538             $recTitle = t3lib_BEfunc::getRecordTitle($foreign_table, $rec, true);
00539         }
00540 
00541         $altText = t3lib_BEfunc::getRecordIconAltText($rec, $foreign_table);
00542         $iconImg = t3lib_iconWorks::getSpriteIconForRecord($foreign_table, $rec, array('title' => htmlspecialchars($altText), 'id' => $objectId . '_icon"'));
00543         $label = '<span id="' . $objectId . '_label">' . $recTitle . '</span>';
00544         if (!$isVirtualRecord) {
00545             $iconImg = $this->wrapWithAnchor($iconImg, '#', array('onclick' => $onClick));
00546             $label = $this->wrapWithAnchor($label, '#', array('onclick' => $onClick, 'style' => 'display: block;'));
00547         }
00548 
00549         $ctrl = $this->renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
00550 
00551             // @TODO: Check the table wrapping and the CSS definitions
00552         $header =
00553             '<table cellspacing="0" cellpadding="0" border="0" width="100%" style="margin-right: '.$this->inlineStyles['margin-right'].'px;"'.
00554             ($this->fObj->borderStyle[2] ? ' background="'.htmlspecialchars($this->backPath.$this->fObj->borderStyle[2]).'"':'').
00555             ($this->fObj->borderStyle[3] ? ' class="'.htmlspecialchars($this->fObj->borderStyle[3]).'"':'').'>' .
00556             '<tr class="class-main12"><td width="18" id="' . $objectId . '_iconcontainer">' . $iconImg . '</td><td align="left"><strong>' . $label . '</strong></td><td align="right">' . $ctrl . '</td></tr></table>';
00557 
00558         return $header;
00559     }
00560 
00561 
00562     /**
00563      * Render the control-icons for a record header (create new, sorting, delete, disable/enable).
00564      * Most of the parts are copy&paste from class.db_list_extra.inc and modified for the JavaScript calls here
00565      *
00566      * @param   string      $parentUid: The uid of the parent (embedding) record (uid or NEW...)
00567      * @param   string      $foreign_table: The table (foreign_table) we create control-icons for
00568      * @param   array       $rec: The current record of that foreign_table
00569      * @param   array       $config: (modified) TCA configuration of the field
00570      * @return  string      The HTML code with the control-icons
00571      */
00572     function renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config=array(), $isVirtualRecord=false) {
00573             // Initialize:
00574         $cells = array();
00575         $isNewItem = substr($rec['uid'], 0, 3) == 'NEW';
00576 
00577         $tcaTableCtrl =& $GLOBALS['TCA'][$foreign_table]['ctrl'];
00578         $tcaTableCols =& $GLOBALS['TCA'][$foreign_table]['columns'];
00579 
00580         $isPagesTable = $foreign_table == 'pages' ? true : false;
00581         $isOnSymmetricSide = t3lib_loadDBGroup::isOnSymmetricSide($parentUid, $config, $rec);
00582         $enableManualSorting = $tcaTableCtrl['sortby'] || $config['MM'] || (!$isOnSymmetricSide && $config['foreign_sortby']) || ($isOnSymmetricSide && $config['symmetric_sortby']) ? true : false;
00583 
00584         $nameObject = $this->inlineNames['object'];
00585         $nameObjectFt = $nameObject . self::Structure_Separator . $foreign_table;
00586         $nameObjectFtId = $nameObjectFt . self::Structure_Separator . $rec['uid'];
00587 
00588         $calcPerms = $GLOBALS['BE_USER']->calcPerms(
00589             t3lib_BEfunc::readPageAccess($rec['pid'], $GLOBALS['BE_USER']->getPagePermsClause(1))
00590         );
00591 
00592             // If the listed table is 'pages' we have to request the permission settings for each page:
00593         if ($isPagesTable)  {
00594             $localCalcPerms = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages',$rec['uid']));
00595         }
00596 
00597             // This expresses the edit permissions for this particular element:
00598         $permsEdit = ($isPagesTable && ($localCalcPerms&2)) || (!$isPagesTable && ($calcPerms&16));
00599 
00600             // Controls: Defines which controls should be shown
00601         $enabledControls = $config['appearance']['enabledControls'];
00602             // Hook: Can disable/enable single controls for specific child records:
00603         foreach ($this->hookObjects as $hookObj)    {
00604             $hookObj->renderForeignRecordHeaderControl_preProcess($parentUid, $foreign_table, $rec, $config, $isVirtual, $enabledControls);
00605         }
00606 
00607             // Icon to visualize that a required field is nested in this inline level:
00608         $cells['required'] = '<img name="'.$nameObjectFtId.'_req" src="clear.gif" width="10" height="10" hspace="4" vspace="3" alt="" />';
00609 
00610         if (isset($rec['__create'])) {
00611             $cells['localize.isLocalizable'] = t3lib_iconWorks::getSpriteIcon('actions-edit-localize-status-low', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localize.isLocalizable', TRUE)));
00612         } elseif (isset($rec['__remove'])) {
00613             $cells['localize.wasRemovedInOriginal'] = t3lib_iconWorks::getSpriteIcon('actions-edit-localize-status-high', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localize.wasRemovedInOriginal', 1)));
00614         }
00615 
00616             // "Info": (All records)
00617         if ($enabledControls['info'] && !$isNewItem) {
00618             $cells['info']='<a href="#" onclick="'.htmlspecialchars('top.launchView(\''.$foreign_table.'\', \''.$rec['uid'].'\'); return false;').'">'.
00619                 t3lib_iconWorks::getSpriteIcon('status-dialog-information', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:showInfo', TRUE))).
00620           '</a>';
00621         }
00622             // If the table is NOT a read-only table, then show these links:
00623         if (!$tcaTableCtrl['readOnly'] && !$isVirtualRecord)    {
00624 
00625                 // "New record after" link (ONLY if the records in the table are sorted by a "sortby"-row or if default values can depend on previous record):
00626             if ($enabledControls['new'] && ($enableManualSorting || $tcaTableCtrl['useColumnsForDefaultValues']))   {
00627                 if (
00628                     (!$isPagesTable && ($calcPerms&16)) ||  // For NON-pages, must have permission to edit content on this parent page
00629                     ($isPagesTable && ($calcPerms&8))       // For pages, must have permission to create new pages here.
00630                     )   {
00631                     $onClick = "return inline.createNewRecord('".$nameObjectFt."','".$rec['uid']."')";
00632                     $class = ' class="inlineNewButton '.$this->inlineData['config'][$nameObject]['md5'].'"';
00633                     if ($config['inline']['inlineNewButtonStyle']) {
00634                         $style = ' style="'.$config['inline']['inlineNewButtonStyle'].'"';
00635                     }
00636                     $cells['new']='<a href="#" onclick="'.htmlspecialchars($onClick).'"'.$class.$style.'>'.
00637                         t3lib_iconWorks::getSpriteIcon('actions-' . ($isPagesTable? 'page' :'document') . '-new',
00638                             array(
00639                                 'title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:new' . ($isPagesTable ? 'Page' : 'Record' ), 1)
00640                             )
00641                         ).
00642                         '</a>';
00643                 }
00644             }
00645 
00646                 // Drag&Drop Sorting: Sortable handler for script.aculo.us
00647             if ($enabledControls['dragdrop'] && $permsEdit && $enableManualSorting && $config['appearance']['useSortable']) {
00648                 $cells['dragdrop'] = t3lib_iconWorks::getSpriteIcon('actions-move-move', array('class' => 'sortableHandle', 'title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.move', TRUE)));
00649             }
00650 
00651                 // "Up/Down" links
00652             if ($enabledControls['sort'] && $permsEdit && $enableManualSorting) {
00653                 $onClick = "return inline.changeSorting('".$nameObjectFtId."', '1')";   // Up
00654                 $style = $config['inline']['first'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
00655                 $cells['sort.up']='<a href="#" onclick="'.htmlspecialchars($onClick).'" class="sortingUp" '.$style.'>'.
00656                         t3lib_iconWorks::getSpriteIcon('actions-move-up', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:moveUp', TRUE))).
00657                 '</a>';
00658 
00659                 $onClick = "return inline.changeSorting('".$nameObjectFtId."', '-1')";  // Down
00660                 $style = $config['inline']['last'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
00661                 $cells['sort.down']='<a href="#" onclick="'.htmlspecialchars($onClick).'" class="sortingDown" '.$style.'>'.
00662                         t3lib_iconWorks::getSpriteIcon('actions-move-down', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:moveDown', TRUE))).
00663                         '</a>';
00664             }
00665 
00666                 // "Hide/Unhide" links:
00667             $hiddenField = $tcaTableCtrl['enablecolumns']['disabled'];
00668             if ($enabledControls['hide'] && $permsEdit && $hiddenField && $tcaTableCols[$hiddenField] && (!$tcaTableCols[$hiddenField]['exclude'] || $GLOBALS['BE_USER']->check('non_exclude_fields',$foreign_table.':'.$hiddenField))) {
00669                 $onClick = "return inline.enableDisableRecord('".$nameObjectFtId."')";
00670                 if ($rec[$hiddenField]) {
00671                     $cells['hide.unhide']='<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
00672                         t3lib_iconWorks::getSpriteIcon(
00673                             'actions-edit-unhide',
00674                             array(
00675                                 'title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:unHide' . ($isPagesTable ? 'Page' : ''), 1),
00676                                 'id' => $nameObjectFtId . '_disabled'
00677                             )
00678                         ) .
00679                         '</a>';
00680                 } else {
00681                     $cells['hide.hide']='<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
00682                         t3lib_iconWorks::getSpriteIcon(
00683                             'actions-edit-hide',
00684                             array(
00685                                 'title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:hide' . ($isPagesTable ? 'Page' : ''), 1),
00686                                 'id' => $nameObjectFtId . '_disabled'
00687                             )
00688                         ) .
00689                         '</a>';
00690                 }
00691             }
00692 
00693                 // "Delete" link:
00694             if ($enabledControls['delete'] && ($isPagesTable && $localCalcPerms&4 || !$isPagesTable && $calcPerms&16)) {
00695                 $onClick = "inline.deleteRecord('".$nameObjectFtId."');";
00696                 $cells['delete']='<a href="#" onclick="'.htmlspecialchars('if (confirm('.$GLOBALS['LANG']->JScharCode($GLOBALS['LANG']->getLL('deleteWarning')).')) {   '.$onClick.' } return false;').'">'.
00697                         t3lib_iconWorks::getSpriteIcon('actions-edit-delete', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:delete', TRUE))) .
00698               '</a>';
00699             }
00700             // If this is a virtual record offer a minimized set of icons for user interaction:
00701         } elseif ($isVirtualRecord) {
00702             if ($enabledControls['localize'] && isset($rec['__create'])) {
00703                 $onClick = "inline.synchronizeLocalizeRecords('".$nameObjectFt."', ".$rec['uid'].");";
00704                 $cells['localize'] = '<a href="#" onclick="'.htmlspecialchars($onClick).'">' .
00705                     t3lib_iconWorks::getSpriteIcon('actions-document-localize', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localize', TRUE))) .
00706               '</a>';
00707             }
00708         }
00709 
00710             // If the record is edit-locked by another user, we will show a little warning sign:
00711         if ($lockInfo=t3lib_BEfunc::isRecordLocked($foreign_table,$rec['uid'])) {
00712             $cells['locked']='<a href="#" onclick="'.htmlspecialchars('alert('.$GLOBALS['LANG']->JScharCode($lockInfo['msg']).');return false;').'">'.
00713                     t3lib_iconWorks::getSpriteIcon('status-warning-in-use', array('title' => htmlspecialchars($lockInfo['msg']))) .
00714                     '</a>';
00715         }
00716 
00717             // Hook: Post-processing of single controls for specific child records:
00718         foreach ($this->hookObjects as $hookObj)    {
00719             $hookObj->renderForeignRecordHeaderControl_postProcess($parentUid, $foreign_table, $rec, $config, $isVirtual, $cells);
00720         }
00721             // Compile items into a DIV-element:
00722         return '
00723                                             <!-- CONTROL PANEL: '.$foreign_table.':'.$rec['uid'].' -->
00724                                             <div class="typo3-DBctrl">'.implode('', $cells).'</div>';
00725     }
00726 
00727 
00728     /**
00729      * Render a table with TCEforms, that occurs on a intermediate table but should be editable directly,
00730      * so two tables are combined (the intermediate table with attributes and the sub-embedded table).
00731      * -> This is a direct embedding over two levels!
00732      *
00733      * @param   array       $rec: The table record of the child/embedded table (normaly post-processed by t3lib_transferData)
00734      * @param   string      $appendFormFieldNames: The [<table>][<uid>] of the parent record (the intermediate table)
00735      * @param   array       $config: content of $PA['fieldConf']['config']
00736      * @return  string      A HTML string with <table> tag around.
00737      */
00738     function renderCombinationTable(&$rec, $appendFormFieldNames, $config = array()) {
00739         $foreign_table = $config['foreign_table'];
00740         $foreign_selector = $config['foreign_selector'];
00741 
00742         if ($foreign_selector && $config['appearance']['useCombination']) {
00743             $comboConfig = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector]['config'];
00744             $comboRecord = array();
00745 
00746                 // If record does already exist, load it:
00747             if ($rec[$foreign_selector] && t3lib_div::testInt($rec[$foreign_selector])) {
00748                 $comboRecord = $this->getRecord(
00749                     $this->inlineFirstPid,
00750                     $comboConfig['foreign_table'],
00751                     $rec[$foreign_selector]
00752                 );
00753                 $isNewRecord = false;
00754                 // It is a new record, create a new record virtually:
00755             } else {
00756                 $comboRecord = $this->getNewRecord(
00757                     $this->inlineFirstPid,
00758                     $comboConfig['foreign_table']
00759                 );
00760                 $isNewRecord = true;
00761             }
00762 
00763                 // get the TCEforms interpretation of the TCA of the child table
00764             $out = $this->renderMainFields($comboConfig['foreign_table'], $comboRecord);
00765             $out = $this->wrapFormsSection($out, array(), array('class' => 'wrapperAttention'));
00766 
00767                 // if this is a new record, add a pid value to store this record and the pointer value for the intermediate table
00768             if ($isNewRecord) {
00769                 $comboFormFieldName = $this->prependFormFieldNames.'['.$comboConfig['foreign_table'].']['.$comboRecord['uid'].'][pid]';
00770                 $out .= '<input type="hidden" name="'.$comboFormFieldName.'" value="'.$comboRecord['pid'].'" />';
00771             }
00772 
00773                 // if the foreign_selector field is also responsible for uniqueness, tell the browser the uid of the "other" side of the relation
00774             if ($isNewRecord || $config['foreign_unique'] == $foreign_selector) {
00775                 $parentFormFieldName = $this->prependFormFieldNames.$appendFormFieldNames.'['.$foreign_selector.']';
00776                 $out .= '<input type="hidden" name="'.$parentFormFieldName.'" value="'.$comboRecord['uid'].'" />';
00777             }
00778         }
00779 
00780         return $out;
00781     }
00782 
00783 
00784     /**
00785      * Get a selector as used for the select type, to select from all available
00786      * records and to create a relation to the embedding record (e.g. like MM).
00787      *
00788      * @param   array       $selItems: Array of all possible records
00789      * @param   array       $conf: TCA configuration of the parent(!) field
00790      * @param   array       $uniqueIds: The uids that have already been used and should be unique
00791      * @return  string      A HTML <select> box with all possible records
00792      */
00793     function renderPossibleRecordsSelector($selItems, $conf, $uniqueIds=array()) {
00794         $foreign_table = $conf['foreign_table'];
00795         $foreign_selector = $conf['foreign_selector'];
00796 
00797         $selConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_selector);
00798         $config = $selConfig['PA']['fieldConf']['config'];
00799 
00800         if ($selConfig['type'] == 'select') {
00801             $item = $this->renderPossibleRecordsSelectorTypeSelect($selItems, $conf, $selConfig['PA'], $uniqueIds);
00802         } elseif ($selConfig['type'] == 'groupdb') {
00803             $item = $this->renderPossibleRecordsSelectorTypeGroupDB($conf, $selConfig['PA']);
00804         }
00805 
00806         return $item;
00807     }
00808 
00809 
00810     /**
00811      * Get a selector as used for the select type, to select from all available
00812      * records and to create a relation to the embedding record (e.g. like MM).
00813      *
00814      * @param   array       $selItems: Array of all possible records
00815      * @param   array       $conf: TCA configuration of the parent(!) field
00816      * @param   array       $PA: An array with additional configuration options
00817      * @param   array       $uniqueIds: The uids that have already been used and should be unique
00818      * @return  string      A HTML <select> box with all possible records
00819      */
00820     function renderPossibleRecordsSelectorTypeSelect($selItems, $conf, &$PA, $uniqueIds=array()) {
00821         $foreign_table = $conf['foreign_table'];
00822         $foreign_selector = $conf['foreign_selector'];
00823 
00824         $PA = array();
00825         $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector];
00826         $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type'];   // Using "form_type" locally in this script
00827         $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table,array(),$foreign_selector);
00828         $config = $PA['fieldConf']['config'];
00829 
00830         if(!$disabled) {
00831                 // Create option tags:
00832             $opt = array();
00833             $styleAttrValue = '';
00834             foreach($selItems as $p)    {
00835                 if ($config['iconsInOptionTags'])   {
00836                     $styleAttrValue = $this->fObj->optionTagStyle($p[2]);
00837                 }
00838                 if (!in_array($p[1], $uniqueIds)) {
00839                     $opt[]= '<option value="'.htmlspecialchars($p[1]).'"'.
00840                                     ' style="'.(in_array($p[1], $uniqueIds) ? '' : '').
00841                                     ($styleAttrValue ? ' style="'.htmlspecialchars($styleAttrValue) : '').'">'.
00842                                     htmlspecialchars($p[0]).'</option>';
00843                 }
00844             }
00845 
00846                 // Put together the selector box:
00847             $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="'.htmlspecialchars($config['itemListStyle']).'"' : ' style="'.$this->fObj->defaultMultipleSelectorStyle.'"';
00848             $size = intval($conf['size']);
00849             $size = $conf['autoSizeMax'] ? t3lib_div::intInRange(count($itemArray)+1,t3lib_div::intInRange($size,1),$conf['autoSizeMax']) : $size;
00850             $onChange = "return inline.importNewRecord('" . $this->inlineNames['object']. self::Structure_Separator . $conf['foreign_table'] . "')";
00851             $item = '
00852                 <select id="'.$this->inlineNames['object'] . self::Structure_Separator . $conf['foreign_table'] . '_selector"'.
00853                             $this->fObj->insertDefStyle('select').
00854                             ($size ? ' size="'.$size.'"' : '').
00855                             ' onchange="'.htmlspecialchars($onChange).'"'.
00856                             $PA['onFocus'].
00857                             $selector_itemListStyle.
00858                             ($conf['foreign_unique'] ? ' isunique="isunique"' : '').'>
00859                     '.implode('
00860                     ',$opt).'
00861                 </select>';
00862 
00863                 // add a "Create new relation" link for adding new relations
00864                 // this is neccessary, if the size of the selector is "1" or if
00865                 // there is only one record item in the select-box, that is selected by default
00866                 // the selector-box creates a new relation on using a onChange event (see some line above)
00867             $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation',1);
00868             $item .=
00869                 '<a href="#" onclick="'.htmlspecialchars($onChange).'" align="abstop">'.
00870                     t3lib_iconWorks::getSpriteIcon('actions-document-new', array('title' => $createNewRelationText)) . $createNewRelationText .
00871                 '</a>';
00872                 // wrap the selector and add a spacer to the bottom
00873             $item = '<div style="margin-bottom: 20px;">'.$item.'</div>';
00874         }
00875 
00876         return $item;
00877     }
00878 
00879 
00880     /**
00881      * Generate a link that opens an element browser in a new window.
00882      * For group/db there is no way o use a "selector" like a <select>|</select>-box.
00883      *
00884      * @param   array       $conf: TCA configuration of the parent(!) field
00885      * @param   array       $PA: An array with additional configuration options
00886      * @return  string      A HTML link that opens an element browser in a new window
00887      */
00888     function renderPossibleRecordsSelectorTypeGroupDB($conf, &$PA) {
00889         $foreign_table = $conf['foreign_table'];
00890 
00891         $config = $PA['fieldConf']['config'];
00892         $allowed = $config['allowed'];
00893         $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table;
00894 
00895         $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation',1);
00896         $onClick = "setFormValueOpenBrowser('db','".('|||'.$allowed.'|'.$objectPrefix.'|inline.checkUniqueElement||inline.importElement')."'); return false;";
00897         $item =
00898             '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
00899                 t3lib_iconWorks::getSpriteIcon('actions-insert-record', array('title' => $createNewRelationText)). $createNewRelationText .
00900             '</a>';
00901 
00902         return $item;
00903     }
00904 
00905 
00906     /**
00907      * Creates the HTML code of a general link to be used on a level of inline children.
00908      * The possible keys for the parameter $type are 'newRecord', 'localize' and 'synchronize'.
00909      *
00910      * @param   string      $type: The link type, values are 'newRecord', 'localize' and 'synchronize'.
00911      * @param   string      $objectPrefix: The "path" to the child record to create (e.g. 'data-parentPageId-partenTable-parentUid-parentField-childTable]')
00912      * @param   array       $conf: TCA configuration of the parent(!) field
00913      * @return  string      The HTML code of the new link, wrapped in a div
00914      */
00915     protected function getLevelInteractionLink($type, $objectPrefix, $conf=array()) {
00916         $nameObject = $this->inlineNames['object'];
00917         $attributes = array();
00918         switch($type) {
00919             case 'newRecord':
00920                 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:cm.createnew', 1);
00921                 $icon = 'actions-document-new';
00922                 $className = 'typo3-newRecordLink';
00923                 $attributes['class'] = 'inlineNewButton '.$this->inlineData['config'][$nameObject]['md5'];
00924                 $attributes['onclick'] = "return inline.createNewRecord('$objectPrefix')";
00925                 if (isset($conf['inline']['inlineNewButtonStyle']) && $conf['inline']['inlineNewButtonStyle']) {
00926                     $attributes['style'] = $conf['inline']['inlineNewButtonStyle'];
00927                 }
00928                 if (isset($conf['appearance']['newRecordLinkAddTitle']) && $conf['appearance']['newRecordLinkAddTitle']) {
00929                     $titleAddon = ' '.$GLOBALS['LANG']->sL($GLOBALS['TCA'][$conf['foreign_table']]['ctrl']['title'], 1);
00930                 }
00931                 break;
00932             case 'localize':
00933                 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localizeAllRecords', 1);
00934                 $icon = 'actions-document-localize';
00935                 $className = 'typo3-localizationLink';
00936                 $attributes['onclick'] = "return inline.synchronizeLocalizeRecords('$objectPrefix', 'localize')";
00937                 break;
00938             case 'synchronize':
00939                 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:synchronizeWithOriginalLanguage', 1);
00940                 $icon = 'actions-document-synchronize';
00941                 $className = 'typo3-synchronizationLink';
00942                 $attributes['class'] = 'inlineNewButton '.$this->inlineData['config'][$nameObject]['md5'];
00943                 $attributes['onclick'] = "return inline.synchronizeLocalizeRecords('$objectPrefix', 'synchronize')";
00944                 break;
00945         }
00946             // Create the link:
00947         $icon = ($icon ? t3lib_iconWorks::getSpriteIcon($icon, array('title' => htmlspecialchars($title . $titleAddon))) : '');
00948         $link = $this->wrapWithAnchor($icon . $title . $titleAddon, '#', $attributes);
00949         return '<div' . ($className ? ' class="' . $className . '"' : '').'>' . $link . '</div>';
00950     }
00951 
00952 
00953     /**
00954      * Creates a link/button to create new records
00955      *
00956      * @param   string      $objectPrefix: The "path" to the child record to create (e.g. 'data-parentPageId-partenTable-parentUid-parentField-childTable')
00957      * @param   array       $conf: TCA configuration of the parent(!) field
00958      * @return  string      The HTML code for the new record link
00959      * @deprecated  since TYPO3 4.2.0-beta1, this function will be removed in TYPO3 4.5.
00960      */
00961     function getNewRecordLink($objectPrefix, $conf = array()) {
00962         t3lib_div::logDeprecatedFunction();
00963 
00964         return $this->getLevelInteractionLink('newRecord', $objectPrefix, $conf);
00965     }
00966 
00967 
00968     /**
00969      * Add Sortable functionality using script.acolo.us "Sortable".
00970      *
00971      * @param   string      $objectId: The container id of the object - elements inside will be sortable
00972      * @return  void
00973      */
00974     function addJavaScriptSortable($objectId) {
00975         $this->fObj->additionalJS_post[] = '
00976             inline.createDragAndDropSorting("'.$objectId.'");
00977         ';
00978     }
00979 
00980 
00981     /*******************************************************
00982      *
00983      * Handling of AJAX calls
00984      *
00985      *******************************************************/
00986 
00987 
00988     /**
00989      * General processor for AJAX requests concerning IRRE.
00990      * (called by typo3/ajax.php)
00991      *
00992      * @param   array       $params: additional parameters (not used here)
00993      * @param   TYPO3AJAX   $ajaxObj: the TYPO3AJAX object of this request
00994      * @return  void
00995      */
00996     public function processAjaxRequest($params, $ajaxObj) {
00997 
00998         $ajaxArguments = t3lib_div::_GP('ajax');
00999         $ajaxIdParts = explode('::', $GLOBALS['ajaxID'], 2);
01000 
01001         if (isset($ajaxArguments) && is_array($ajaxArguments) && count($ajaxArguments)) {
01002             $ajaxMethod = $ajaxIdParts[1];
01003             switch ($ajaxMethod) {
01004                 case 'createNewRecord':
01005                 case 'synchronizeLocalizeRecords':
01006                 case 'getRecordDetails':
01007                     $this->isAjaxCall = true;
01008                         // Construct runtime environment for Inline Relational Record Editing:
01009                     $this->processAjaxRequestConstruct($ajaxArguments);
01010                         // Parse the DOM identifier (string), add the levels to the structure stack (array) and load the TCA config:
01011                     $this->parseStructureString($ajaxArguments[0], true);
01012                         // Render content:
01013                     $ajaxObj->setContentFormat('jsonbody');
01014                     $ajaxObj->setContent(
01015                         call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments)
01016                     );
01017                     break;
01018                 case 'setExpandedCollapsedState':
01019                     $ajaxObj->setContentFormat('jsonbody');
01020                     call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments);
01021                     break;
01022             }
01023         }
01024     }
01025 
01026 
01027     /**
01028      * Construct runtime environment for Inline Relational Record Editing.
01029      * - creates an anoymous SC_alt_doc in $GLOBALS['SOBE']
01030      * - creates a t3lib_TCEforms in $GLOBALS['SOBE']->tceforms
01031      * - sets ourself as reference to $GLOBALS['SOBE']->tceforms->inline
01032      * - sets $GLOBALS['SOBE']->tceforms->RTEcounter to the current situation on client-side
01033      *
01034      * @param   array       &$ajaxArguments: The arguments to be processed by the AJAX request
01035      * @return  void
01036      */
01037     protected function processAjaxRequestConstruct(&$ajaxArguments) {
01038         global $SOBE, $BE_USER, $TYPO3_CONF_VARS;
01039 
01040         require_once(PATH_typo3.'template.php');
01041 
01042         $GLOBALS['LANG']->includeLLFile('EXT:lang/locallang_alt_doc.xml');
01043 
01044             // Create a new anonymous object:
01045         $SOBE = new stdClass();
01046         $SOBE->MOD_MENU = array(
01047             'showPalettes' => '',
01048             'showDescriptions' => '',
01049             'disableRTE' => ''
01050         );
01051             // Setting virtual document name
01052         $SOBE->MCONF['name']='xMOD_alt_doc.php';
01053             // CLEANSE SETTINGS
01054         $SOBE->MOD_SETTINGS = t3lib_BEfunc::getModuleData(
01055             $SOBE->MOD_MENU,
01056             t3lib_div::_GP('SET'),
01057             $SOBE->MCONF['name']
01058         );
01059             // Create an instance of the document template object
01060         $SOBE->doc = t3lib_div::makeInstance('template');
01061         $SOBE->doc->backPath = $GLOBALS['BACK_PATH'];
01062             // Initialize TCEforms (rendering the forms)
01063         $SOBE->tceforms = t3lib_div::makeInstance('t3lib_TCEforms');
01064         $SOBE->tceforms->inline = $this;
01065         $SOBE->tceforms->RTEcounter = intval(array_shift($ajaxArguments));
01066         $SOBE->tceforms->initDefaultBEMode();
01067         $SOBE->tceforms->palettesCollapsed = !$SOBE->MOD_SETTINGS['showPalettes'];
01068         $SOBE->tceforms->disableRTE = $SOBE->MOD_SETTINGS['disableRTE'];
01069         $SOBE->tceforms->enableClickMenu = TRUE;
01070         $SOBE->tceforms->enableTabMenu = TRUE;
01071             // Clipboard is initialized:
01072         $SOBE->tceforms->clipObj = t3lib_div::makeInstance('t3lib_clipboard');      // Start clipboard
01073         $SOBE->tceforms->clipObj->initializeClipboard();    // Initialize - reads the clipboard content from the user session
01074             // Setting external variables:
01075         if ($BE_USER->uc['edit_showFieldHelp']!='text' && $SOBE->MOD_SETTINGS['showDescriptions']) {
01076             $SOBE->tceforms->edit_showFieldHelp = 'text';
01077         }
01078     }
01079 
01080 
01081     /**
01082      * Determines and sets several script calls to a JSON array, that would have been executed if processed in non-AJAX mode.
01083      *
01084      * @param   array       &$jsonArray: Reference of the array to be used for JSON
01085      * @param   array       $config: The configuration of the IRRE field of the parent record
01086      * @return  void
01087      */
01088     protected function getCommonScriptCalls(&$jsonArray, $config) {
01089             // Add data that would have been added at the top of a regular TCEforms call:
01090         if ($headTags = $this->getHeadTags()) {
01091             $jsonArray['headData'] = $headTags;
01092         }
01093             // Add the JavaScript data that would have been added at the bottom of a regular TCEforms call:
01094         $jsonArray['scriptCall'][] = $this->fObj->JSbottom($this->fObj->formName, true);
01095             // If script.aculo.us Sortable is used, update the Observer to know the record:
01096         if ($config['appearance']['useSortable']) {
01097             $jsonArray['scriptCall'][] = "inline.createDragAndDropSorting('".$this->inlineNames['object']."_records');";
01098         }
01099             // if TCEforms has some JavaScript code to be executed, just do it
01100         if ($this->fObj->extJSCODE) {
01101             $jsonArray['scriptCall'][] = $this->fObj->extJSCODE;
01102         }
01103     }
01104 
01105 
01106     /**
01107      * Initialize environment for AJAX calls
01108      *
01109      * @param   string      $method: Name of the method to be called
01110      * @param   array       $arguments: Arguments to be delivered to the method
01111      * @return  void
01112      * @deprecated  since TYPO3 4.2.0-alpha3, this function will be removed in TYPO3 4.5.
01113      */
01114     function initForAJAX($method, &$arguments) {
01115         t3lib_div::logDeprecatedFunction();
01116 
01117             // Set t3lib_TCEforms::$RTEcounter to the given value:
01118         if ($method == 'createNewRecord') {
01119             $this->fObj->RTEcounter = intval(array_shift($arguments));
01120         }
01121     }
01122 
01123 
01124     /**
01125      * Generates an error message that transferred as JSON for AJAX calls
01126      *
01127      * @param   string      $message: The error message to be shown
01128      * @return  array       The error message in a JSON array
01129      */
01130     protected function getErrorMessageForAJAX($message) {
01131         $jsonArray = array(
01132             'data'  => $message,
01133             'scriptCall' => array(
01134                 'alert("' . $message . '");'
01135             )
01136         );
01137         return $jsonArray;
01138     }
01139 
01140 
01141     /**
01142      * Handle AJAX calls to show a new inline-record of the given table.
01143      * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
01144      *
01145      * @param   string      $domObjectId: The calling object in hierarchy, that requested a new record.
01146      * @param   string      $foreignUid: If set, the new record should be inserted after that one.
01147      * @return  array       An array to be used for JSON
01148      */
01149     function createNewRecord($domObjectId, $foreignUid = 0) {
01150             // the current table - for this table we should add/import records
01151         $current = $this->inlineStructure['unstable'];
01152             // the parent table - this table embeds the current table
01153         $parent = $this->getStructureLevel(-1);
01154             // get TCA 'config' of the parent table
01155         if (!$this->checkConfiguration($parent['config'])) {
01156             return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
01157         }
01158         $config = $parent['config'];
01159 
01160         $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
01161         $expandSingle = (isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle']);
01162 
01163             // Put the current level also to the dynNestedStack of TCEforms:
01164         $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
01165 
01166             // dynamically create a new record using t3lib_transferData
01167         if (!$foreignUid || !t3lib_div::testInt($foreignUid) || $config['foreign_selector']) {
01168             $record = $this->getNewRecord($this->inlineFirstPid, $current['table']);
01169                 // Set language of new child record to the language of the parent record:
01170             if ($config['localizationMode']=='select') {
01171                 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
01172                 $parentLanguageField = $GLOBALS['TCA'][$parent['table']]['ctrl']['languageField'];
01173                 $childLanguageField = $GLOBALS['TCA'][$current['table']]['ctrl']['languageField'];
01174                 if ($parentRecord[$languageField]>0) {
01175                     $record[$childLanguageField] = $parentRecord[$languageField];
01176                 }
01177             }
01178 
01179             // dynamically import an existing record (this could be a call from a select box)
01180         } else {
01181             $record = $this->getRecord($this->inlineFirstPid, $current['table'], $foreignUid);
01182         }
01183 
01184             // now there is a foreign_selector, so there is a new record on the intermediate table, but
01185             // this intermediate table holds a field, which is responsible for the foreign_selector, so
01186             // we have to set this field to the uid we get - or if none, to a new uid
01187         if ($config['foreign_selector'] && $foreignUid) {
01188             $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_selector']);
01189                 // For a selector of type group/db, prepend the tablename (<tablename>_<uid>):
01190             $record[$config['foreign_selector']] = $selConfig['type'] != 'groupdb' ? '' : $selConfig['table'].'_';
01191             $record[$config['foreign_selector']] .= $foreignUid;
01192         }
01193 
01194             // the HTML-object-id's prefix of the dynamically created record
01195         $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
01196         $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
01197 
01198             // render the foreign record that should passed back to browser
01199         $item = $this->renderForeignRecord($parent['uid'], $record, $config);
01200         if($item === false) {
01201             return $this->getErrorMessageForAJAX('Access denied');
01202         }
01203 
01204         if (!$current['uid']) {
01205             $jsonArray = array(
01206                 'data'  => $item,
01207                 'scriptCall' => array(
01208                     "inline.domAddNewRecord('bottom','".$this->inlineNames['object']."_records','$objectPrefix',json.data);",
01209                     "inline.memorizeAddRecord('$objectPrefix','".$record['uid']."',null,'$foreignUid');"
01210                 )
01211             );
01212 
01213             // append the HTML data after an existing record in the container
01214         } else {
01215             $jsonArray = array(
01216                 'data'  => $item,
01217                 'scriptCall' => array(
01218                     "inline.domAddNewRecord('after','".$domObjectId.'_div'."','$objectPrefix',json.data);",
01219                     "inline.memorizeAddRecord('$objectPrefix','".$record['uid']."','".$current['uid']."','$foreignUid');"
01220                 )
01221             );
01222         }
01223         $this->getCommonScriptCalls($jsonArray, $config);
01224             // Collapse all other records if requested:
01225         if (!$collapseAll && $expandSingle) {
01226             $jsonArray['scriptCall'][] = "inline.collapseAllRecords('$objectId', '$objectPrefix', '".$record['uid']."');";
01227         }
01228             // tell the browser to scroll to the newly created record
01229         $jsonArray['scriptCall'][] = "Element.scrollTo('".$objectId."_div');";
01230             // fade out and fade in the new record in the browser view to catch the user's eye
01231         $jsonArray['scriptCall'][] = "inline.fadeOutFadeIn('".$objectId."_div');";
01232 
01233             // Remove the current level also from the dynNestedStack of TCEforms:
01234         $this->fObj->popFromDynNestedStack();
01235 
01236             // Return the JSON array:
01237         return $jsonArray;
01238     }
01239 
01240 
01241     /**
01242      * Handle AJAX calls to localize all records of a parent, localize a single record or to synchronize with the original language parent.
01243      *
01244      * @param   string      $domObjectId: The calling object in hierarchy, that requested a new record.
01245      * @param   mixed       $type: Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (integer)
01246      * @return  array       An array to be used for JSON
01247      */
01248     protected function synchronizeLocalizeRecords($domObjectId, $type) {
01249         $jsonArray = false;
01250         if (t3lib_div::inList('localize,synchronize', $type) || t3lib_div::testInt($type)) {
01251                 // The current level:
01252             $current = $this->inlineStructure['unstable'];
01253                 // The parent level:
01254             $parent = $this->getStructureLevel(-1);
01255             $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
01256 
01257             $cmd = array();
01258             $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'].','.$type;
01259 
01260             /* @var t3lib_TCEmain */
01261             $tce = t3lib_div::makeInstance('t3lib_TCEmain');
01262             $tce->stripslashes_values = false;
01263             $tce->start(array(), $cmd);
01264             $tce->process_cmdmap();
01265             $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parent['field']];
01266             unset($tce);
01267 
01268             $jsonArray = $this->getExecuteChangesJsonArray($parentRecord[$parent['field']], $newItemList);
01269             $this->getCommonScriptCalls($jsonArray, $parent['config']);
01270         }
01271         return $jsonArray;
01272     }
01273 
01274     /**
01275      * Handle AJAX calls to dynamically load the form fields of a given record.
01276      * (basically a copy of "createNewRecord")
01277      * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
01278      *
01279      * @param   string      $domObjectId: The calling object in hierarchy, that requested a new record.
01280      * @return  array       An array to be used for JSON
01281      */
01282     function getRecordDetails($domObjectId) {
01283             // the current table - for this table we should add/import records
01284         $current = $this->inlineStructure['unstable'];
01285             // the parent table - this table embeds the current table
01286         $parent = $this->getStructureLevel(-1);
01287             // get TCA 'config' of the parent table
01288         if (!$this->checkConfiguration($parent['config'])) {
01289             return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
01290         }
01291         $config = $parent['config'];
01292             // set flag in config so that only the fields are rendered
01293         $config['renderFieldsOnly'] = true;
01294 
01295         $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
01296         $expandSingle = (isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle']);
01297 
01298             // Put the current level also to the dynNestedStack of TCEforms:
01299         $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
01300 
01301         $record = $this->getRecord($this->inlineFirstPid, $current['table'], $current['uid']);
01302 
01303             // the HTML-object-id's prefix of the dynamically created record
01304         $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
01305         $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
01306 
01307         $item = $this->renderForeignRecord($parent['uid'], $record, $config);
01308         if($item === false) {
01309             return $this->getErrorMessageForAJAX('Access denied');
01310         }
01311 
01312         $jsonArray = array(
01313             'data'  => $item,
01314             'scriptCall' => array(
01315                 'inline.domAddRecordDetails(\'' . $domObjectId . '\',\'' . $objectPrefix . '\',' . ($expandSingle ? '1' : '0') . ',json.data);',
01316             )
01317         );
01318 
01319         $this->getCommonScriptCalls($jsonArray, $config);
01320             // Collapse all other records if requested:
01321         if (!$collapseAll && $expandSingle) {
01322             $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\',\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
01323         }
01324 
01325             // Remove the current level also from the dynNestedStack of TCEforms:
01326         $this->fObj->popFromDynNestedStack();
01327 
01328             // Return the JSON array:
01329         return $jsonArray;
01330     }
01331 
01332 
01333     /**
01334      * Generates a JSON array which executes the changes and thus updates the forms view.
01335      *
01336      * @param   string      $oldItemList: List of related child reocrds before changes were made (old)
01337      * @param   string      $newItemList: List of related child records after changes where made (new)
01338      * @return  array       An array to be used for JSON
01339      */
01340     protected function getExecuteChangesJsonArray($oldItemList, $newItemList) {
01341         $parent = $this->getStructureLevel(-1);
01342         $current = $this->inlineStructure['unstable'];
01343 
01344         $jsonArray = array('scriptCall' => array());
01345         $jsonArrayScriptCall =& $jsonArray['scriptCall'];
01346 
01347         $nameObject = $this->inlineNames['object'];
01348         $nameObjectForeignTable = $nameObject . self::Structure_Separator . $current['table'];
01349             // Get the name of the field pointing to the original record:
01350         $transOrigPointerField = $GLOBALS['TCA'][$current['table']]['ctrl']['transOrigPointerField'];
01351             // Get the name of the field used as foreign selector (if any):
01352         $foreignSelector = (isset($parent['config']['foreign_selector']) && $parent['config']['foreign_selector'] ? $parent['config']['foreign_selector'] : false);
01353             // Convert lists to array with uids of child records:
01354         $oldItems = $this->getRelatedRecordsUidArray($oldItemList);
01355         $newItems = $this->getRelatedRecordsUidArray($newItemList);
01356             // Determine the items that were localized or localized:
01357         $removedItems = array_diff($oldItems, $newItems);
01358         $localizedItems = array_diff($newItems, $oldItems);
01359             // Set the items that should be removed in the forms view:
01360         foreach ($removedItems as $item) {
01361             $jsonArrayScriptCall[] = "inline.deleteRecord('".$nameObjectForeignTable . self::Structure_Separator . $item . "', {forceDirectRemoval: true});";
01362         }
01363             // Set the items that should be added in the forms view:
01364         foreach ($localizedItems as $item) {
01365             $row = $this->getRecord($this->inlineFirstPid, $current['table'], $item);
01366             $selectedValue = ($foreignSelector ? "'".$row[$foreignSelector]."'" : 'null');
01367             $data.= $this->renderForeignRecord($parent['uid'], $row, $parent['config']);
01368             $jsonArrayScriptCall[] = "inline.memorizeAddRecord('$nameObjectForeignTable', '".$item."', null, $selectedValue);";
01369                 // Remove possible virtual records in the form which showed that a child records could be localized:
01370             if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]) {
01371                 $jsonArrayScriptCall[] = "inline.fadeAndRemove('" . $nameObjectForeignTable . self::Structure_Separator . $row[$transOrigPointerField] . '_div' . "');";
01372             }
01373         }
01374         if ($data) {
01375             $data = $GLOBALS['LANG']->csConvObj->utf8_encode($data, $GLOBALS['LANG']->charSet);
01376             $jsonArray['data'] = $data;
01377             array_unshift(
01378                 $jsonArrayScriptCall,
01379                 "inline.domAddNewRecord('bottom', '".$nameObject."_records', '$nameObjectForeignTable', json.data);"
01380             );
01381         }
01382 
01383         return $jsonArray;
01384     }
01385 
01386 
01387     /**
01388      * Save the expanded/collapsed state of a child record in the BE_USER->uc.
01389      *
01390      * @param   string      $domObjectId: The calling object in hierarchy, that requested a new record.
01391      * @param   string      $expand: Whether this record is expanded.
01392      * @param   string      $collapse: Whether this record is collapsed.
01393      * @return  void
01394      */
01395     function setExpandedCollapsedState($domObjectId, $expand, $collapse) {
01396             // parse the DOM identifier (string), add the levels to the structure stack (array), but don't load TCA config
01397         $this->parseStructureString($domObjectId, false);
01398             // the current table - for this table we should add/import records
01399         $current = $this->inlineStructure['unstable'];
01400             // the top parent table - this table embeds the current table
01401         $top = $this->getStructureLevel(0);
01402 
01403             // only do some action if the top record and the current record were saved before
01404         if (t3lib_div::testInt($top['uid'])) {
01405             $inlineView = (array)unserialize($GLOBALS['BE_USER']->uc['inlineView']);
01406             $inlineViewCurrent =& $inlineView[$top['table']][$top['uid']];
01407 
01408             $expandUids = t3lib_div::trimExplode(',', $expand);
01409             $collapseUids = t3lib_div::trimExplode(',', $collapse);
01410 
01411                 // set records to be expanded
01412             foreach ($expandUids as $uid) {
01413                 $inlineViewCurrent[$current['table']][] = $uid;
01414             }
01415                 // set records to be collapsed
01416             foreach ($collapseUids as $uid) {
01417                 $inlineViewCurrent[$current['table']] = $this->removeFromArray($uid, $inlineViewCurrent[$current['table']]);
01418             }
01419 
01420                 // save states back to database
01421             if (is_array($inlineViewCurrent[$current['table']])) {
01422                 $inlineViewCurrent = array_unique($inlineViewCurrent);
01423                 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
01424                 $GLOBALS['BE_USER']->writeUC();
01425             }
01426         }
01427     }
01428 
01429 
01430     /*******************************************************
01431      *
01432      * Get data from database and handle relations
01433      *
01434      *******************************************************/
01435 
01436 
01437     /**
01438      * Get the related records of the embedding item, this could be 1:n, m:n.
01439      * Returns an associative array with the keys records and count. 'count' contains only real existing records on the current parent record.
01440      *
01441      * @param   string      $table: The table name of the record
01442      * @param   string      $field: The field name which this element is supposed to edit
01443      * @param   array       $row: The record data array where the value(s) for the field can be found
01444      * @param   array       $PA: An array with additional configuration options.
01445      * @param   array       $config: (Redundant) content of $PA['fieldConf']['config'] (for convenience)
01446      * @return  array       The records related to the parent item as associative array.
01447      */
01448     function getRelatedRecords($table, $field, $row, &$PA, $config) {
01449         $records = array();
01450         $pid = $row['pid'];
01451         $elements = $PA['itemFormElValue'];
01452         $foreignTable = $config['foreign_table'];
01453 
01454         $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $config);
01455 
01456         if ($localizationMode!=false) {
01457             $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
01458             $transOrigPointer = intval($row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
01459             if ($language>0 && $transOrigPointer) {
01460                     // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
01461                 if ($localizationMode=='keep') {
01462                     $transOrigRec = $this->getRecord(0, $table, $transOrigPointer);
01463                     $elements = $transOrigRec[$field];
01464                     $pid = $transOrigRec['pid'];
01465                     // Localization in modes 'select', 'all' or 'sync' offer a dynamic localization and synchronization with the original language record:
01466                 } elseif ($localizationMode=='select') {
01467                     $transOrigRec = $this->getRecord(0, $table, $transOrigPointer);
01468                     $pid = $transOrigRec['pid'];
01469                     $recordsOriginal = $this->getRelatedRecordsArray($pid, $foreignTable, $transOrigRec[$field]);
01470                 }
01471             }
01472         }
01473 
01474         $records = $this->getRelatedRecordsArray($pid, $foreignTable, $elements);
01475         $relatedRecords = array('records' => $records, 'count' => count($records));
01476 
01477             // Merge original language with current localization and show differences:
01478         if (is_array($recordsOriginal)) {
01479             $options = array(
01480                 'showPossible' => (isset($config['appearance']['showPossibleLocalizationRecords']) && $config['appearance']['showPossibleLocalizationRecords']),
01481                 'showRemoved' => (isset($config['appearance']['showRemovedLocalizationRecords']) && $config['appearance']['showRemovedLocalizationRecords']),
01482             );
01483             if ($options['showPossible'] || $options['showRemoved']) {
01484                 $relatedRecords['records'] = $this->getLocalizationDifferences($foreignTable, $options, $recordsOriginal, $records);
01485             }
01486         }
01487 
01488         return $relatedRecords;
01489     }
01490 
01491 
01492     /**
01493      * Gets the related records of the embedding item, this could be 1:n, m:n.
01494      *
01495      * @param   integer     $pid: The pid of the parent record
01496      * @param   string      $table: The table name of the record
01497      * @param   string      $itemList: The list of related child records
01498      * @return  array       The records related to the parent item
01499      */
01500     protected function getRelatedRecordsArray($pid, $table, $itemList) {
01501         $records = array();
01502         $itemArray = $this->getRelatedRecordsUidArray($itemList);
01503             // Perform modification of the selected items array:
01504         foreach($itemArray as $uid) {
01505                 // Get the records for this uid using t3lib_transferdata:
01506             if ($record = $this->getRecord($pid, $table, $uid)) {
01507                 $records[$uid] = $record;
01508             }
01509         }
01510         return $records;
01511     }
01512 
01513 
01514     /**
01515      * Gets an array with the uids of related records out of a list of items.
01516      * This list could contain more information than required. This methods just
01517      * extracts the uids.
01518      *
01519      * @param   string      $itemList: The list of related child records
01520      * @return  array       An array with uids
01521      */
01522     protected function getRelatedRecordsUidArray($itemList) {
01523         $itemArray = t3lib_div::trimExplode(',', $itemList, 1);
01524             // Perform modification of the selected items array:
01525         foreach($itemArray as $key => &$value) {
01526             $parts = explode('|', $value, 2);
01527             $value = $parts[0];
01528         }
01529         return $itemArray;
01530     }
01531 
01532 
01533     /**
01534      * Gets the difference between current localized structure and the original language structure.
01535      * If there are records which once were localized but don't exist in the original version anymore, the record row is marked with '__remove'.
01536      * If there are records which can be localized and exist only in the original version, the record row is marked with '__create' and '__virtual'.
01537      *
01538      * @param   string      $table: The table name of the parent records
01539      * @param   array       $options: Options defining what kind of records to display
01540      * @param   array       $recordsOriginal: The uids of the child records of the original language
01541      * @param   array       $recordsLocalization: The uids of the child records of the current localization
01542      * @return  array       Merged array of uids of the child records of both versions
01543      */
01544     protected function getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization) {
01545         $records = array();
01546         $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
01547             // Compare original to localized version of the records:
01548         foreach ($recordsLocalization as $uid => $row) {
01549                 // If the record points to a original translation which doesn't exist anymore, it could be removed:
01550             if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]>0) {
01551                 $transOrigPointer = $row[$transOrigPointerField];
01552                 if (isset($recordsOriginal[$transOrigPointer])) {
01553                     unset($recordsOriginal[$transOrigPointer]);
01554                 } elseif ($options['showRemoved']) {
01555                     $row['__remove'] = true;
01556                 }
01557             }
01558             $records[$uid] = $row;
01559         }
01560             // Process the remaining records in the original unlocalized parent:
01561         if ($options['showPossible']) {
01562             foreach ($recordsOriginal as $uid => $row) {
01563                 $row['__create'] = true;
01564                 $row['__virtual'] = true;
01565                 $records[$uid] = $row;
01566             }
01567         }
01568         return $records;
01569     }
01570 
01571 
01572     /**
01573      * Get possible records.
01574      * Copied from TCEform and modified.
01575      *
01576      * @param   string      The table name of the record
01577      * @param   string      The field name which this element is supposed to edit
01578      * @param   array       The record data array where the value(s) for the field can be found
01579      * @param   array       An array with additional configuration options.
01580      * @param   string      $checkForConfField: For which field in the foreign_table the possible records should be fetched
01581      * @return  mixed       Array of possible record items; false if type is "group/db", then everything could be "possible"
01582      */
01583     function getPossibleRecords($table,$field,$row,$conf,$checkForConfField='foreign_selector') {
01584             // ctrl configuration from TCA:
01585         $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
01586             // Field configuration from TCA:
01587         $foreign_table = $conf['foreign_table'];
01588         $foreign_check = $conf[$checkForConfField];
01589 
01590         $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
01591         $PA = $foreignConfig['PA'];
01592         $config = $PA['fieldConf']['config'];
01593 
01594         if ($foreignConfig['type'] == 'select') {
01595                 // Getting the selector box items from the system
01596             $selItems = $this->fObj->addSelectOptionsToItemArray(
01597                 $this->fObj->initItemArray($PA['fieldConf']),
01598                 $PA['fieldConf'],
01599                 $this->fObj->setTSconfig($table, $row),
01600                 $field
01601             );
01602                 // Possibly filter some items:
01603             $keepItemsFunc = create_function('$value', 'return $value[1];');
01604             $selItems = t3lib_div::keepItemsInArray($selItems, $PA['fieldTSConfig']['keepItems'], $keepItemsFunc);
01605                 // Possibly add some items:
01606             $selItems = $this->fObj->addItems($selItems, $PA['fieldTSConfig']['addItems.']);
01607             if (isset($config['itemsProcFunc']) && $config['itemsProcFunc']) {
01608                 $selItems = $this->fObj->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
01609             }
01610 
01611                 // Possibly remove some items:
01612             $removeItems = t3lib_div::trimExplode(',',$PA['fieldTSConfig']['removeItems'],1);
01613             foreach($selItems as $tk => $p) {
01614 
01615                     // Checking languages and authMode:
01616                 $languageDeny = $tcaTableCtrl['languageField'] && !strcmp($tcaTableCtrl['languageField'], $field) && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
01617                 $authModeDeny = $config['form_type']=='select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table,$field,$p[1],$config['authMode']);
01618                 if (in_array($p[1],$removeItems) || $languageDeny || $authModeDeny) {
01619                     unset($selItems[$tk]);
01620                 } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
01621                     $selItems[$tk][0]=$this->fObj->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]);
01622                 }
01623 
01624                     // Removing doktypes with no access:
01625                 if ($table.'.'.$field == 'pages.doktype')   {
01626                     if (!($GLOBALS['BE_USER']->isAdmin() || t3lib_div::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'],$p[1])))   {
01627                         unset($selItems[$tk]);
01628                     }
01629                 }
01630             }
01631         } else {
01632             $selItems = false;
01633         }
01634 
01635         return $selItems;
01636     }
01637 
01638     /**
01639      * Gets the uids of a select/selector that should be unique an have already been used.
01640      *
01641      * @param   array       $records: All inline records on this level
01642      * @param   array       $conf: The TCA field configuration of the inline field to be rendered
01643      * @param   boolean     $splitValue: for usage with group/db, values come like "tx_table_123|Title%20abc", but we need "tx_table" and "123"
01644      * @return  array       The uids, that have been used already and should be used unique
01645      */
01646     function getUniqueIds($records, $conf=array(), $splitValue=false) {
01647         $uniqueIds = array();
01648 
01649         if (isset($conf['foreign_unique']) && $conf['foreign_unique'] && count($records)) {
01650             foreach ($records as $rec) {
01651                     // Skip virtual records (e.g. shown in localization mode):
01652                 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
01653                     $value = $rec[$conf['foreign_unique']];
01654                         // Split the value and extract the table and uid:
01655                     if ($splitValue) {
01656                         $valueParts = t3lib_div::trimExplode('|', $value);
01657                         $itemParts = explode('_', $valueParts[0]);
01658                         $value = array(
01659                             'uid' => array_pop($itemParts),
01660                             'table' => implode('_', $itemParts)
01661                         );
01662                     }
01663                     $uniqueIds[$rec['uid']] = $value;
01664                 }
01665             }
01666         }
01667 
01668         return $uniqueIds;
01669     }
01670 
01671 
01672     /**
01673      * Determines the corrected pid to be used for a new record.
01674      * The pid to be used can be defined by a Page TSconfig.
01675      *
01676      * @param   string      $table: The table name
01677      * @param   integer     $parentPid: The pid of the parent record
01678      * @return  integer     The corrected pid to be used for a new record
01679      */
01680     protected function getNewRecordPid($table, $parentPid=null) {
01681         $newRecordPid = $this->inlineFirstPid;
01682         $pageTS = t3lib_beFunc::getPagesTSconfig($parentPid, true);
01683         if (isset($pageTS['TCAdefaults.'][$table.'.']['pid']) && t3lib_div::testInt($pageTS['TCAdefaults.'][$table.'.']['pid'])) {
01684             $newRecordPid = $pageTS['TCAdefaults.'][$table.'.']['pid'];
01685         } elseif (isset($parentPid) && t3lib_div::testInt($parentPid)) {
01686             $newRecordPid = $parentPid;
01687         }
01688         return $newRecordPid;
01689     }
01690 
01691 
01692     /**
01693      * Get a single record row for a TCA table from the database.
01694      * t3lib_transferData is used for "upgrading" the values, especially the relations.
01695      *
01696      * @param   integer     $pid: The pid of the page the record should be stored (only relevant for NEW records)
01697      * @param   string      $table: The table to fetch data from (= foreign_table)
01698      * @param   string      $uid: The uid of the record to fetch, or the pid if a new record should be created
01699      * @param   string      $cmd: The command to perform, empty or 'new'
01700      * @return  array       A record row from the database post-processed by t3lib_transferData
01701      */
01702     function getRecord($pid, $table, $uid, $cmd='') {
01703         $trData = t3lib_div::makeInstance('t3lib_transferData');
01704         $trData->addRawData = TRUE;
01705         $trData->lockRecords=1;
01706         $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
01707             // if a new record should be created
01708         $trData->fetchRecord($table, $uid, ($cmd === 'new' ? 'new' : ''));
01709         reset($trData->regTableItems_data);
01710         $rec = current($trData->regTableItems_data);
01711 
01712         return $rec;
01713     }
01714 
01715 
01716     /**
01717      * Wrapper. Calls getRecord in case of a new record should be created.
01718      *
01719      * @param   integer     $pid: The pid of the page the record should be stored (only relevant for NEW records)
01720      * @param   string      $table: The table to fetch data from (= foreign_table)
01721      * @return  array       A record row from the database post-processed by t3lib_transferData
01722      */
01723     function getNewRecord($pid, $table) {
01724         $rec = $this->getRecord($pid, $table, $pid, 'new');
01725         $rec['uid'] = uniqid('NEW');
01726         $rec['pid'] = $this->getNewRecordPid($table, $pid);
01727         return $rec;
01728     }
01729 
01730 
01731     /*******************************************************
01732      *
01733      * Structure stack for handling inline objects/levels
01734      *
01735      *******************************************************/
01736 
01737 
01738     /**
01739      * Add a new level on top of the structure stack. Other functions can access the
01740      * stack and determine, if there's possibly a endless loop.
01741      *
01742      * @param   string      $table: The table name of the record
01743      * @param   string      $uid: The uid of the record that embeds the inline data
01744      * @param   string      $field: The field name which this element is supposed to edit
01745      * @param   array       $config: The TCA-configuration of the inline field
01746      * @return  void
01747      */
01748     function pushStructure($table, $uid, $field = '', $config = array()) {
01749         $this->inlineStructure['stable'][] = array(
01750             'table' => $table,
01751             'uid' => $uid,
01752             'field' => $field,
01753             'config' => $config,
01754             'localizationMode' => t3lib_BEfunc::getInlineLocalizationMode($table, $config),
01755         );
01756         $this->updateStructureNames();
01757     }
01758 
01759 
01760     /**
01761      * Remove the item on top of the structure stack and return it.
01762      *
01763      * @return  array       The top item of the structure stack - array(<table>,<uid>,<field>,<config>)
01764      */
01765     function popStructure() {
01766         if (count($this->inlineStructure['stable'])) {
01767             $popItem = array_pop($this->inlineStructure['stable']);
01768             $this->updateStructureNames();
01769         }
01770         return $popItem;
01771     }
01772 
01773 
01774     /**
01775      * For common use of DOM object-ids and form field names of a several inline-level,
01776      * these names/identifiers are preprocessed and set to $this->inlineNames.
01777      * This function is automatically called if a level is pushed to or removed from the
01778      * inline structure stack.
01779      *
01780      * @return  void
01781      */
01782     function updateStructureNames() {
01783         $current = $this->getStructureLevel(-1);
01784             // if there are still more inline levels available
01785         if ($current !== false) {
01786             $this->inlineNames = array(
01787                 'form' => $this->prependFormFieldNames . $this->getStructureItemName($current, self::Disposal_AttributeName),
01788                 'object' => $this->prependNaming . self::Structure_Separator . $this->inlineFirstPid . self::Structure_Separator . $this->getStructurePath(),
01789             );
01790             // if there are no more inline levels available
01791         } else {
01792             $this->inlineNames = array();
01793         }
01794     }
01795 
01796 
01797     /**
01798      * Create a name/id for usage in HTML output of a level of the structure stack to be used in form names.
01799      *
01800      * @param   array       $levelData: Array of a level of the structure stack (containing the keys table, uid and field)
01801      * @param   string      $disposal: How the structure name is used (e.g. as <div id="..."> or <input name="..." />)
01802      * @return  string      The name/id of that level, to be used for HTML output
01803      */
01804     function getStructureItemName($levelData, $disposal = self::Disposal_AttributeId) {
01805         if (is_array($levelData)) {
01806             $parts = array($levelData['table'], $levelData['uid']);
01807             if (isset($levelData['field'])) {
01808                 $parts[] = $levelData['field'];
01809             }
01810 
01811                 // Use in name attributes:
01812             if ($disposal === self::Disposal_AttributeName) {
01813                 $name = '[' . implode('][', $parts) . ']';
01814                 // Use in id attributes:
01815             } else {
01816                 $name = implode(self::Structure_Separator, $parts);
01817             }
01818         }
01819         return $name;
01820     }
01821 
01822 
01823     /**
01824      * Get a level from the stack and return the data.
01825      * If the $level value is negative, this function works top-down,
01826      * if the $level value is positive, this function works bottom-up.
01827      *
01828      * @param   integer     $level: Which level to return
01829      * @return  array       The item of the stack at the requested level
01830      */
01831     function getStructureLevel($level) {
01832         $inlineStructureCount = count($this->inlineStructure['stable']);
01833         if ($level < 0) $level = $inlineStructureCount+$level;
01834         if ($level >= 0 && $level < $inlineStructureCount)
01835             return $this->inlineStructure['stable'][$level];
01836         else
01837             return false;
01838     }
01839 
01840 
01841     /**
01842      * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
01843      * An identifier looks like "<table>-<uid>-<field>".
01844      *
01845      * @param   integer     $structureDepth: How much levels to output, beginning from the top of the stack
01846      * @return  string      The path of identifiers
01847      */
01848     function getStructurePath($structureDepth = -1) {
01849         $structureLevels = array();
01850         $structureCount = count($this->inlineStructure['stable']);
01851 
01852         if ($structureDepth < 0 || $structureDepth > $structureCount) {
01853             $structureDepth = $structureCount;
01854         }
01855 
01856         for ($i = 1; $i <= $structureDepth; $i++) {
01857             array_unshift(
01858                 $structureLevels,
01859                 $this->getStructureItemName(
01860                     $this->getStructureLevel(-$i),
01861                     self::Disposal_AttributeId
01862                 )
01863             );
01864         }
01865 
01866         return implode(self::Structure_Separator, $structureLevels);
01867     }
01868 
01869 
01870     /**
01871      * Convert the DOM object-id of an inline container to an array.
01872      * The object-id could look like 'data-parentPageId-tx_mmftest_company-1-employees'.
01873      * The result is written to $this->inlineStructure.
01874      * There are two keys:
01875      *  - 'stable': Containing full qualified identifiers (table, uid and field)
01876      *  - 'unstable': Containting partly filled data (e.g. only table and possibly field)
01877      *
01878      * @param   string      $domObjectId: The DOM object-id
01879      * @param   boolean     $loadConfig: Load the TCA configuration for that level (default: true)
01880      * @return  void
01881      */
01882     function parseStructureString($string, $loadConfig=true) {
01883         $unstable = array();
01884         $vector = array('table', 'uid', 'field');
01885         $pattern = '/^' . $this->prependNaming . self::Structure_Separator . '(.+?)' . self::Structure_Separator . '(.+)$/';
01886         if (preg_match($pattern, $string, $match)) {
01887             $this->inlineFirstPid = $match[1];
01888             $parts = explode(self::Structure_Separator, $match[2]);
01889             $partsCnt = count($parts);
01890             for ($i = 0; $i < $partsCnt; $i++) {
01891                 if ($i > 0 && $i % 3 == 0) {
01892                         // load the TCA configuration of the table field and store it in the stack
01893                     if ($loadConfig) {
01894                         t3lib_div::loadTCA($unstable['table']);
01895                         $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
01896                             // Fetch TSconfig:
01897                         $TSconfig = $this->fObj->setTSconfig(
01898                             $unstable['table'],
01899                             array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid),
01900                             $unstable['field']
01901                         );
01902                             // Override TCA field config by TSconfig:
01903                         if (!$TSconfig['disabled']) {
01904                             $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
01905                         }
01906                         $unstable['localizationMode'] = t3lib_BEfunc::getInlineLocalizationMode($unstable['table'], $unstable['config']);
01907                     }
01908                     $this->inlineStructure['stable'][] = $unstable;
01909                     $unstable = array();
01910                 }
01911                 $unstable[$vector[$i % 3]] = $parts[$i];
01912             }
01913             $this->updateStructureNames();
01914             if (count($unstable)) $this->inlineStructure['unstable'] = $unstable;
01915         }
01916     }
01917 
01918 
01919     /*******************************************************
01920      *
01921      * Helper functions
01922      *
01923      *******************************************************/
01924 
01925 
01926     /**
01927      * Does some checks on the TCA configuration of the inline field to render.
01928      *
01929      * @param   array       $config: Reference to the TCA field configuration
01930      * @param   string      $table: The table name of the record
01931      * @param   string      $field: The field name which this element is supposed to edit
01932      * @param   array       $row: The record data array of the parent
01933      * @return  boolean     If critical configuration errors were found, false is returned
01934      */
01935     function checkConfiguration(&$config) {
01936         $foreign_table = $config['foreign_table'];
01937 
01938             // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
01939         if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
01940             return false;
01941         }
01942             // Init appearance if not set:
01943         if (!isset($config['appearance']) || !is_array($config['appearance'])) {
01944             $config['appearance'] = array();
01945         }
01946             // 'newRecordLinkPosition' is deprecated since TYPO3 4.2.0-beta1, this is for backward compatibility:
01947         if (!isset($config['appearance']['levelLinksPosition']) && isset($config['appearance']['newRecordLinkPosition']) && $config['appearance']['newRecordLinkPosition']) {
01948             t3lib_div::deprecationLog('TCA contains a deprecated definition using "newRecordLinkPosition"');
01949             $config['appearance']['levelLinksPosition'] = $config['appearance']['newRecordLinkPosition'];
01950         }
01951             // Set the position/appearance of the "Create new record" link:
01952         if (isset($config['foreign_selector']) && $config['foreign_selector'] && (!isset($config['appearance']['useCombination']) || !$config['appearance']['useCombination'])) {
01953             $config['appearance']['levelLinksPosition'] = 'none';
01954         } elseif (!isset($config['appearance']['levelLinksPosition']) || !in_array($config['appearance']['levelLinksPosition'], array('top', 'bottom', 'both', 'none'))) {
01955             $config['appearance']['levelLinksPosition'] = 'top';
01956         }
01957             // Defines which controls should be shown in header of each record:
01958         $enabledControls = array(
01959             'info'      => true,
01960             'new'       => true,
01961             'dragdrop'  => true,
01962             'sort'      => true,
01963             'hide'      => true,
01964             'delete'    => true,
01965             'localize'  => true,
01966         );
01967         if (isset($config['appearance']['enabledControls']) && is_array($config['appearance']['enabledControls'])) {
01968             $config['appearance']['enabledControls'] = array_merge($enabledControls, $config['appearance']['enabledControls']);
01969         } else {
01970             $config['appearance']['enabledControls'] = $enabledControls;
01971         }
01972 
01973         return true;
01974     }
01975 
01976 
01977     /**
01978      * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
01979      * as well as the table access rights of the user.
01980      *
01981      * @param   string      $cmd: The command that sould be performed ('new' or 'edit')
01982      * @param   string      $table: The table to check access for
01983      * @param   string      $theUid: The record uid of the table
01984      * @return  boolean     Returns true is the user has access, or false if not
01985      */
01986     function checkAccess($cmd, $table, $theUid) {
01987             // Checking if the user has permissions? (Only working as a precaution, because the final permission check is always down in TCE. But it's good to notify the user on beforehand...)
01988             // First, resetting flags.
01989         $hasAccess = 0;
01990         $deniedAccessReason = '';
01991 
01992             // Admin users always have acces:
01993         if ($GLOBALS['BE_USER']->isAdmin()) {
01994             return true;
01995         }
01996             // If the command is to create a NEW record...:
01997         if ($cmd=='new') {
01998                 // If the pid is numerical, check if it's possible to write to this page:
01999             if (t3lib_div::testInt($this->inlineFirstPid)) {
02000                 $calcPRec = t3lib_BEfunc::getRecord('pages', $this->inlineFirstPid);
02001                 if(!is_array($calcPRec)) {
02002                     return false;
02003                 }
02004                 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);    // Permissions for the parent page
02005                 if ($table=='pages')    {   // If pages:
02006                     $hasAccess = $CALC_PERMS&8 ? 1 : 0; // Are we allowed to create new subpages?
02007                 } else {
02008                     $hasAccess = $CALC_PERMS&16 ? 1 : 0; // Are we allowed to edit content on this page?
02009                 }
02010                 // If the pid is a NEW... value, the access will be checked on creating the page:
02011                 // (if the page with the same NEW... value could be created in TCEmain, this child record can neither)
02012             } else {
02013                 $hasAccess = 1;
02014             }
02015         } else {    // Edit:
02016             $calcPRec = t3lib_BEfunc::getRecord($table,$theUid);
02017             t3lib_BEfunc::fixVersioningPid($table,$calcPRec);
02018             if (is_array($calcPRec))    {
02019                 if ($table=='pages')    {   // If pages:
02020                     $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
02021                     $hasAccess = $CALC_PERMS&2 ? 1 : 0;
02022                 } else {
02023                     $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages',$calcPRec['pid']));    // Fetching pid-record first.
02024                     $hasAccess = $CALC_PERMS&16 ? 1 : 0;
02025                 }
02026 
02027                     // Check internals regarding access:
02028                 if ($hasAccess) {
02029                     $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
02030                 }
02031             }
02032         }
02033 
02034         if(!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
02035             $hasAccess = 0;
02036         }
02037 
02038         if(!$hasAccess) {
02039             $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
02040             if($deniedAccessReason) {
02041                 debug($deniedAccessReason);
02042             }
02043         }
02044 
02045         return $hasAccess ? true : false;
02046     }
02047 
02048 
02049     /**
02050      * Check the keys and values in the $compare array against the ['config'] part of the top level of the stack.
02051      * A boolean value is return depending on how the comparison was successful.
02052      *
02053      * @param   array       $compare: keys and values to compare to the ['config'] part of the top level of the stack
02054      * @return  boolean     Whether the comparison was successful
02055      * @see     arrayCompareComplex
02056      */
02057     function compareStructureConfiguration($compare) {
02058         $level = $this->getStructureLevel(-1);
02059         $result = $this->arrayCompareComplex($level, $compare);
02060 
02061         return $result;
02062     }
02063 
02064 
02065     /**
02066      * Normalize a relation "uid" published by transferData, like "1|Company%201"
02067      *
02068      * @param   string      $string: A transferData reference string, containing the uid
02069      * @return  string      The normalized uid
02070      */
02071     function normalizeUid($string) {
02072         $parts = explode('|', $string);
02073         return $parts[0];
02074     }
02075 
02076 
02077     /**
02078      * Wrap the HTML code of a section with a table tag.
02079      *
02080      * @param   string      $section: The HTML code to be wrapped
02081      * @param   array       $styleAttrs: Attributes for the style argument in the table tag
02082      * @param   array       $tableAttrs: Attributes for the table tag (like width, border, etc.)
02083      * @return  string      The wrapped HTML code
02084      */
02085     function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
02086         if (!$styleAttrs['margin-right']) $styleAttrs['margin-right'] = $this->inlineStyles['margin-right'].'px';
02087 
02088         foreach ($styleAttrs as $key => $value) $style .= ($style?' ':'').$key.': '.htmlspecialchars($value).'; ';
02089         if ($style) $style = ' style="'.$style.'"';
02090 
02091         if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) $tableAttrs['background'] = $this->backPath.$this->borderStyle[2];
02092         if (!$tableAttrs['cellspacing']) $tableAttrs['cellspacing'] = '0';
02093         if (!$tableAttrs['cellpadding']) $tableAttrs['cellpadding'] = '0';
02094         if (!$tableAttrs['border']) $tableAttrs['border'] = '0';
02095         if (!$tableAttrs['width']) $tableAttrs['width'] = '100%';
02096         if (!$tableAttrs['class'] && $this->borderStyle[3]) $tableAttrs['class'] = $this->borderStyle[3];
02097 
02098         foreach ($tableAttrs as $key => $value) $table .= ($table?' ':'').$key.'="'.htmlspecialchars($value).'"';
02099 
02100         $out = '<table '.$table.$style.'>'.$section.'</table>';
02101         return $out;
02102     }
02103 
02104 
02105     /**
02106      * Checks if the $table is the child of a inline type AND the $field is the label field of this table.
02107      * This function is used to dynamically update the label while editing. This has no effect on labels,
02108      * that were processed by a TCEmain-hook on saving.
02109      *
02110      * @param   string      $table: The table to check
02111      * @param   string      $field: The field on this table to check
02112      * @return  boolean     is inline child and field is responsible for the label
02113      */
02114     function isInlineChildAndLabelField($table, $field) {
02115         $level = $this->getStructureLevel(-1);
02116         if ($level['config']['foreign_label'])
02117             $label = $level['config']['foreign_label'];
02118         else
02119             $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
02120         return $level['config']['foreign_table'] === $table && $label == $field ? true : false;
02121     }
02122 
02123 
02124     /**
02125      * Get the depth of the stable structure stack.
02126      * (count($this->inlineStructure['stable'])
02127      *
02128      * @return  integer     The depth of the structure stack
02129      */
02130     function getStructureDepth() {
02131         return count($this->inlineStructure['stable']);
02132     }
02133 
02134 
02135     /**
02136      * Handles complex comparison requests on an array.
02137      * A request could look like the following:
02138      *
02139      * $searchArray = array(
02140      *      '%AND'  => array(
02141      *          'key1'  => 'value1',
02142      *          'key2'  => 'value2',
02143      *          '%OR'   => array(
02144      *              'subarray' => array(
02145      *                  'subkey' => 'subvalue'
02146      *              ),
02147      *              'key3'  => 'value3',
02148      *              'key4'  => 'value4'
02149      *          )
02150      *      )
02151      * );
02152      *
02153      * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
02154      * overwriting the sub-array. It could be neccessary, if you use complex comparisons.
02155      *
02156      * The example above means, key1 *AND* key2 (and their values) have to match with
02157      * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
02158      * condition.
02159      * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
02160      * function recurses down one level in that sub-array.
02161      *
02162      * @param   array       $subjectArray: The array to search in
02163      * @param   array       $searchArray: The array with keys and values to search for
02164      * @param   string      $type: Use '%AND' or '%OR' for comparision
02165      * @return  boolean     The result of the comparison
02166      */
02167     function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
02168         $localMatches = 0;
02169         $localEntries = 0;
02170 
02171         if (is_array($searchArray) && count($searchArray)) {
02172                 // if no type was passed, try to determine
02173             if (!$type) {
02174                 reset($searchArray);
02175                 $type = key($searchArray);
02176                 $searchArray = current($searchArray);
02177             }
02178 
02179                 // we use '%AND' and '%OR' in uppercase
02180             $type = strtoupper($type);
02181 
02182                 // split regular elements from sub elements
02183             foreach ($searchArray as $key => $value) {
02184                 $localEntries++;
02185 
02186                     // process a sub-group of OR-conditions
02187                 if ($key == '%OR') {
02188                     $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
02189                     // process a sub-group of AND-conditions
02190                 } elseif ($key == '%AND') {
02191                     $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
02192                     // a part of an associative array should be compared, so step down in the array hierarchy
02193                 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
02194                     $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
02195                     // it is a normal array that is only used for grouping and indexing
02196                 } elseif (is_array($value)) {
02197                     $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
02198                     // directly compare a value
02199                 } else {
02200                     if (isset($subjectArray[$key]) && isset($value)) {
02201                             // Boolean match:
02202                         if (is_bool($value)) {
02203                             $localMatches += (!($subjectArray[$key] xor $value) ? 1 : 0);
02204                             // Value match for numbers:
02205                         } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
02206                             $localMatches += ($subjectArray[$key] == $value ? 1 : 0);
02207                             // Value and type match:
02208                         } else {
02209                             $localMatches += ($subjectArray[$key] === $value ? 1 : 0);
02210                         }
02211                     }
02212                 }
02213 
02214                     // if one or more matches are required ('OR'), return true after the first successful match
02215                 if ($type == '%OR' && $localMatches > 0) return true;
02216                     // if all matches are required ('AND') and we have no result after the first run, return false
02217                 if ($type == '%AND' && $localMatches == 0) return false;
02218             }
02219         }
02220 
02221             // return the result for '%AND' (if nothing was checked, true is returned)
02222         return $localEntries == $localMatches ? true : false;
02223     }
02224 
02225 
02226     /**
02227      * Checks whether an object is an associative array.
02228      *
02229      * @param   mixed       $object: The object to be checked
02230      * @return  boolean     Returns true, if the object is an associative array
02231      */
02232     function isAssociativeArray($object) {
02233         return is_array($object) && count($object) && (array_keys($object) !== range(0, sizeof($object) - 1))
02234             ? true
02235             : false;
02236     }
02237 
02238 
02239     /**
02240      * Remove an element from an array.
02241      *
02242      * @param   mixed       $needle: The element to be removed.
02243      * @param   array       $haystack: The array the element should be removed from.
02244      * @param   mixed       $strict: Search elements strictly.
02245      * @return  array       The array $haystack without the $needle
02246      */
02247     function removeFromArray($needle, $haystack, $strict=null) {
02248         $pos = array_search($needle, $haystack, $strict);
02249         if ($pos !== false) unset($haystack[$pos]);
02250         return $haystack;
02251     }
02252 
02253 
02254     /**
02255      * Makes a flat array from the $possibleRecords array.
02256      * The key of the flat array is the value of the record,
02257      * the value of the flat array is the label of the record.
02258      *
02259      * @param   array       $possibleRecords: The possibleRecords array (for select fields)
02260      * @return  mixed       A flat array with key=uid, value=label; if $possibleRecords isn't an array, false is returned.
02261      */
02262     function getPossibleRecordsFlat($possibleRecords) {
02263         $flat = false;
02264         if (is_array($possibleRecords)) {
02265             $flat = array();
02266             foreach ($possibleRecords as $record) $flat[$record[1]] = $record[0];
02267         }
02268         return $flat;
02269     }
02270 
02271 
02272     /**
02273      * Determine the configuration and the type of a record selector.
02274      *
02275      * @param   array       $conf: TCA configuration of the parent(!) field
02276      * @return  array       Associative array with the keys 'PA' and 'type', both are false if the selector was not valid.
02277      */
02278     function getPossibleRecordsSelectorConfig($conf, $field = '') {
02279         $foreign_table = $conf['foreign_table'];
02280         $foreign_selector = $conf['foreign_selector'];
02281 
02282         $PA = false;
02283         $type = false;
02284         $table = false;
02285         $selector = false;
02286 
02287         if ($field) {
02288             $PA = array();
02289             $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
02290             $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type'];   // Using "form_type" locally in this script
02291             $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table,array(),$field);
02292             $config = $PA['fieldConf']['config'];
02293                 // Determine type of Selector:
02294             $type = $this->getPossibleRecordsSelectorType($config);
02295                 // Return table on this level:
02296             $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
02297                 // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
02298             if ($foreign_selector && $foreign_selector == $field && $type) {
02299                 $selector = $type;
02300             }
02301         }
02302 
02303         return array(
02304             'PA' => $PA,
02305             'type' => $type,
02306             'table' => $table,
02307             'selector' => $selector,
02308         );
02309     }
02310 
02311 
02312     /**
02313      * Determine the type of a record selector, e.g. select or group/db.
02314      *
02315      * @param   array       $config: TCE configuration of the selector
02316      * @return  mixed       The type of the selector, 'select' or 'groupdb' - false not valid
02317      */
02318     function getPossibleRecordsSelectorType($config) {
02319         $type = false;
02320         if ($config['type'] == 'select') {
02321             $type = 'select';
02322         } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
02323             $type = 'groupdb';
02324         }
02325         return $type;
02326     }
02327 
02328 
02329     /**
02330      * Check, if a field should be skipped, that was defined to be handled as foreign_field or foreign_sortby of
02331      * the parent record of the "inline"-type - if so, we have to skip this field - the rendering is done via "inline" as hidden field
02332      *
02333      * @param   string      $table: The table name
02334      * @param   string      $field: The field name
02335      * @param   array       $row: The record row from the database
02336      * @param   array       $config: TCA configuration of the field
02337      * @return  boolean     Determines whether the field should be skipped.
02338      */
02339     function skipField($table, $field, $row, $config) {
02340         $skipThisField = false;
02341 
02342         if ($this->getStructureDepth()) {
02343             $searchArray = array(
02344                 '%OR' => array(
02345                     'config' => array(
02346                         0 => array(
02347                             '%AND' => array(
02348                                 'foreign_table' => $table,
02349                                 '%OR' => array(
02350                                     '%AND' => array(
02351                                         'appearance' => array('useCombination' => true),
02352                                         'foreign_selector' => $field,
02353                                     ),
02354                                     'MM' => $config['MM']
02355                                 ),
02356                             ),
02357                         ),
02358                         1 => array(
02359                             '%AND' => array(
02360                                 'foreign_table' => $config['foreign_table'],
02361                                 'foreign_selector' => $config['foreign_field'],
02362                             ),
02363                         ),
02364                     ),
02365                 ),
02366             );
02367 
02368                 // get the parent record from structure stack
02369             $level = $this->getStructureLevel(-1);
02370 
02371                 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
02372             if (t3lib_loadDBGroup::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
02373                 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
02374                 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
02375                 // Hide fields, that are set automatically:
02376             } else {
02377                 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
02378                 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
02379             }
02380 
02381             $skipThisField = $this->compareStructureConfiguration($searchArray, true);
02382         }
02383 
02384         return $skipThisField;
02385     }
02386 
02387 
02388     /**
02389      * Creates recursively a JSON literal from a mulidimensional associative array.
02390      * Uses Services_JSON (http://mike.teczno.com/JSON/doc/)
02391      *
02392      * @param   array       $jsonArray: The array (or part of) to be transformed to JSON
02393      * @return  string      If $level>0: part of JSON literal; if $level==0: whole JSON literal wrapped with <script> tags
02394      * @deprecated          Since TYPO3 4.2: Moved to t3lib_div::array2json, will be removed in TYPO3 4.4
02395      */
02396     function getJSON($jsonArray) {
02397         t3lib_div::logDeprecatedFunction();
02398 
02399         return json_encode($jsonArray);
02400     }
02401 
02402 
02403     /**
02404      * Checks if a uid of a child table is in the inline view settings.
02405      *
02406      * @param   string      $table: Name of the child table
02407      * @param   integer     $uid: uid of the the child record
02408      * @return  boolean     true=expand, false=collapse
02409      */
02410     function getExpandedCollapsedState($table, $uid) {
02411         if (isset($this->inlineView[$table]) && is_array($this->inlineView[$table])) {
02412             if (in_array($uid, $this->inlineView[$table]) !== false) {
02413                 return true;
02414             }
02415         }
02416         return false;
02417     }
02418 
02419 
02420     /**
02421      * Update expanded/collapsed states on new inline records if any.
02422      *
02423      * @param   array       $uc: The uc array to be processed and saved (by reference)
02424      * @param   t3lib_TCEmain   $tce: Instance of TCEmain that saved data before
02425      * @return  void
02426      */
02427     function updateInlineView(&$uc, $tce) {
02428         if (isset($uc['inlineView']) && is_array($uc['inlineView'])) {
02429             $inlineView = (array)unserialize($GLOBALS['BE_USER']->uc['inlineView']);
02430 
02431             foreach ($uc['inlineView'] as $topTable => $topRecords) {
02432                 foreach ($topRecords as $topUid => $childElements) {
02433                     foreach ($childElements as $childTable => $childRecords) {
02434                         $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
02435                         if (count($uids)) {
02436                             $newExpandedChildren = array();
02437                             foreach ($childRecords as $childUid => $state) {
02438                                 if ($state && in_array($childUid, $uids)) {
02439                                     $newChildUid = $tce->substNEWwithIDs[$childUid];
02440                                     $newExpandedChildren[] = $newChildUid;
02441                                 }
02442                             }
02443                                 // Add new expanded child records to UC (if any):
02444                             if (count($newExpandedChildren)) {
02445                                 $inlineViewCurrent =& $inlineView[$topTable][$topUid][$childTable];
02446                                 if (is_array($inlineViewCurrent)) {
02447                                     $inlineViewCurrent = array_unique(array_merge($inlineViewCurrent, $newExpandedChildren));
02448                                 } else {
02449                                     $inlineViewCurrent = $newExpandedChildren;
02450                                 }
02451                             }
02452                         }
02453                     }
02454                 }
02455             }
02456 
02457             $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
02458             $GLOBALS['BE_USER']->writeUC();
02459         }
02460     }
02461 
02462 
02463     /**
02464      * Returns the the margin in pixels, that is used for each new inline level.
02465      *
02466      * @return  integer     A pixel value for the margin of each new inline level.
02467      */
02468     function getLevelMargin() {
02469         $margin = ($this->inlineStyles['margin-right']+1)*2;
02470         return $margin;
02471     }
02472 
02473     /**
02474      * Parses the HTML tags that would have been inserted to the <head> of a HTML document and returns the found tags as multidimensional array.
02475      *
02476      * @return  array       The parsed tags with their attributes and innerHTML parts
02477      */
02478     protected function getHeadTags() {
02479         $headTags = array();
02480         $headDataRaw = $this->fObj->JStop();
02481 
02482         if ($headDataRaw) {
02483                 // Create instance of the HTML parser:
02484             $parseObj = t3lib_div::makeInstance('t3lib_parsehtml');
02485                 // Removes script wraps:
02486             $headDataRaw = str_replace(array('/*<![CDATA[*/', '/*]]>*/'), '', $headDataRaw);
02487                 // Removes leading spaces of a multiline string:
02488             $headDataRaw = trim(preg_replace('/(^|\r|\n)( |\t)+/', '$1', $headDataRaw));
02489                 // Get script and link tags:
02490             $tags = array_merge(
02491                 $parseObj->getAllParts($parseObj->splitTags('link', $headDataRaw)),
02492                 $parseObj->getAllParts($parseObj->splitIntoBlock('script', $headDataRaw))
02493             );
02494 
02495             foreach ($tags as $tagData) {
02496                 $tagAttributes = $parseObj->get_tag_attributes($parseObj->getFirstTag($tagData), true);
02497                 $headTags[] = array(
02498                     'name' => $parseObj->getFirstTagName($tagData),
02499                     'attributes' => $tagAttributes[0],
02500                     'innerHTML' => $parseObj->removeFirstAndLastTag($tagData),
02501                 );
02502             }
02503         }
02504 
02505         return $headTags;
02506     }
02507 
02508 
02509     /**
02510      * Wraps a text with an anchor and returns the HTML representation.
02511      *
02512      * @param   string      $text: The text to be wrapped by an anchor
02513      * @param   string      $link: The link to be used in the anchor
02514      * @param   array       $attributes: Array of attributes to be used in the anchor
02515      * @return  string      The wrapped texted as HTML representation
02516      */
02517     protected function wrapWithAnchor($text, $link, $attributes=array()) {
02518         $link = trim($link);
02519         $result = '<a href="'.($link ? $link : '#').'"';
02520         foreach ($attributes as $key => $value) {
02521             $result.= ' '.$key.'="'.htmlspecialchars(trim($value)).'"';
02522         }
02523         $result.= '>'.$text.'</a>';
02524         return $result;
02525     }
02526 }
02527 
02528 
02529 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms_inline.php'])   {
02530     include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms_inline.php']);
02531 }
02532 
02533 ?>

Generated on Sat Sep 4 04:17:11 2010 for TYPO3 API by  doxygen 1.4.7