Fixed bug #13675: Performance improvement: Use array_walk() for t3lib_div::intExplode
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tceforms_inline.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2006-2009 Oliver Hader <oh@inpublica.de>
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * The Inline-Relational-Record-Editing (IRRE) functions as part of the TCEforms.
29 *
30 * $Id$
31 *
32 * @author Oliver Hader <oh@inpublica.de>
33 */
34 /**
35 * [CLASS/FUNCTION INDEX of SCRIPT]
36 *
37 *
38 *
39 * 88: class t3lib_TCEforms_inline
40 * 109: function init(&$tceForms)
41 * 127: function getSingleField_typeInline($table,$field,$row,&$PA)
42 *
43 * SECTION: Regular rendering of forms, fields, etc.
44 * 263: function renderForeignRecord($parentUid, $rec, $config = array())
45 * 319: function renderForeignRecordHeader($parentUid, $foreign_table,$rec,$config = array())
46 * 375: function renderForeignRecordHeaderControl($table,$row,$config = array())
47 * 506: function renderCombinationTable(&$rec, $appendFormFieldNames, $config = array())
48 * 560: function renderPossibleRecordsSelector($selItems, $conf, $uniqueIds=array())
49 * 627: function addJavaScript()
50 * 643: function addJavaScriptSortable($objectId)
51 *
52 * SECTION: Handling of AJAX calls
53 * 665: function createNewRecord($domObjectId, $foreignUid = 0)
54 * 755: function getJSON($jsonArray)
55 * 770: function getNewRecordLink($objectPrefix, $conf = array())
56 *
57 * SECTION: Get data from database and handle relations
58 * 807: function getRelatedRecords($table,$field,$row,&$PA,$config)
59 * 839: function getPossibleRecords($table,$field,$row,$conf,$checkForConfField='foreign_selector')
60 * 885: function getUniqueIds($records, $conf=array())
61 * 905: function getRecord($pid, $table, $uid, $cmd='')
62 * 929: function getNewRecord($pid, $table)
63 *
64 * SECTION: Structure stack for handling inline objects/levels
65 * 951: function pushStructure($table, $uid, $field = '', $config = array())
66 * 967: function popStructure()
67 * 984: function updateStructureNames()
68 * 1000: function getStructureItemName($levelData)
69 * 1015: function getStructureLevel($level)
70 * 1032: function getStructurePath($structureDepth = -1)
71 * 1057: function parseStructureString($string, $loadConfig = false)
72 *
73 * SECTION: Helper functions
74 * 1098: function checkConfiguration(&$config)
75 * 1123: function checkAccess($cmd, $table, $theUid)
76 * 1185: function compareStructureConfiguration($compare)
77 * 1199: function normalizeUid($string)
78 * 1213: function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array())
79 * 1242: function isInlineChildAndLabelField($table, $field)
80 * 1258: function getStructureDepth()
81 * 1295: function arrayCompareComplex($subjectArray, $searchArray, $type = '')
82 * 1349: function isAssociativeArray($object)
83 * 1364: function getPossibleRecordsFlat($possibleRecords)
84 * 1383: function skipField($table, $field, $row, $config)
85 *
86 * TOTAL FUNCTIONS: 35
87 * (This index is automatically created/updated by the extension "extdeveval")
88 *
89 */
90
91
92 class t3lib_TCEforms_inline {
93 const Structure_Separator = '-';
94 const Disposal_AttributeName = 'Disposal_AttributeName';
95 const Disposal_AttributeId = 'Disposal_AttributeId';
96
97 /**
98 * Reference to the calling TCEforms instance
99 *
100 * @var t3lib_TCEforms
101 */
102 var $fObj;
103 var $backPath; // Reference to $fObj->backPath
104
105 var $isAjaxCall = false; // Indicates if a field is rendered upon an AJAX call
106 var $inlineStructure = array(); // the structure/hierarchy where working in, e.g. cascading inline tables
107 var $inlineFirstPid; // the first call of an inline type appeared on this page (pid of record)
108 var $inlineNames = array(); // keys: form, object -> hold the name/id for each of them
109 var $inlineData = array(); // inline data array used for JSON output
110 var $inlineView = array(); // expanded/collapsed states for the current BE user
111 var $inlineCount = 0; // count the number of inline types used
112 var $inlineStyles = array();
113
114 var $prependNaming = 'data'; // how the $this->fObj->prependFormFieldNames should be set ('data' is default)
115 var $prependFormFieldNames; // reference to $this->fObj->prependFormFieldNames
116 var $prependCmdFieldNames; // reference to $this->fObj->prependCmdFieldNames
117
118 protected $hookObjects = array(); // array containing instances of hook classes called once for IRRE objects
119
120
121 /**
122 * Intialize an instance of t3lib_TCEforms_inline
123 *
124 * @param t3lib_TCEforms $tceForms: Reference to an TCEforms instance
125 * @return void
126 */
127 function init(&$tceForms) {
128 $this->fObj = $tceForms;
129 $this->backPath =& $tceForms->backPath;
130 $this->prependFormFieldNames =& $this->fObj->prependFormFieldNames;
131 $this->prependCmdFieldNames =& $this->fObj->prependCmdFieldNames;
132 $this->inlineStyles['margin-right'] = '5';
133 $this->initHookObjects();
134 }
135
136
137 /**
138 * Initialized the hook objects for this class.
139 * Each hook object has to implement the interface t3lib_tceformsInlineHook.
140 *
141 * @return void
142 */
143 protected function initHookObjects() {
144 $this->hookObjects = array();
145 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'])) {
146 $tceformsInlineHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'];
147 if (is_array($tceformsInlineHook)) {
148 foreach($tceformsInlineHook as $classData) {
149 $processObject = t3lib_div::getUserObj($classData);
150
151 if(!($processObject instanceof t3lib_tceformsInlineHook)) {
152 throw new UnexpectedValueException('$processObject must implement interface t3lib_tceformsInlineHook', 1202072000);
153 }
154
155 $processObject->init($this);
156 $this->hookObjects[] = $processObject;
157 }
158 }
159 }
160 }
161
162
163 /**
164 * Generation of TCEform elements of the type "inline"
165 * This will render inline-relational-record sets. Relations.
166 *
167 * @param string $table: The table name of the record
168 * @param string $field: The field name which this element is supposed to edit
169 * @param array $row: The record data array where the value(s) for the field can be found
170 * @param array $PA: An array with additional configuration options.
171 * @return string The HTML code for the TCEform field
172 */
173 function getSingleField_typeInline($table,$field,$row,&$PA) {
174 // check the TCA configuration - if false is returned, something was wrong
175 if ($this->checkConfiguration($PA['fieldConf']['config']) === false) {
176 return false;
177 }
178
179 // count the number of processed inline elements
180 $this->inlineCount++;
181
182 // Init:
183 $config = $PA['fieldConf']['config'];
184 $foreign_table = $config['foreign_table'];
185 t3lib_div::loadTCA($foreign_table);
186
187 if (t3lib_BEfunc::isTableLocalizable($table)) {
188 $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
189 }
190 $minitems = t3lib_div::intInRange($config['minitems'],0);
191 $maxitems = t3lib_div::intInRange($config['maxitems'],0);
192 if (!$maxitems) $maxitems=100000;
193
194 // Register the required number of elements:
195 $this->fObj->requiredElements[$PA['itemFormElName']] = array($minitems,$maxitems,'imgName'=>$table.'_'.$row['uid'].'_'.$field);
196
197 // remember the page id (pid of record) where inline editing started first
198 // we need that pid for ajax calls, so that they would know where the action takes place on the page structure
199 if (!isset($this->inlineFirstPid)) {
200 // if this record is not new, try to fetch the inlineView states
201 // @TODO: Add checking/cleaning for unused tables, records, etc. to save space in uc-field
202 if (t3lib_div::testInt($row['uid'])) {
203 $inlineView = unserialize($GLOBALS['BE_USER']->uc['inlineView']);
204 $this->inlineView = $inlineView[$table][$row['uid']];
205 }
206 // If the parent is a page, use the uid(!) of the (new?) page as pid for the child records:
207 if ($table == 'pages') {
208 $this->inlineFirstPid = $row['uid'];
209 // If pid is negative, fetch the previous record and take its pid:
210 } elseif ($row['pid'] < 0) {
211 $prevRec = t3lib_BEfunc::getRecord($table, abs($row['pid']));
212 $this->inlineFirstPid = $prevRec['pid'];
213 // Take the pid as it is:
214 } else {
215 $this->inlineFirstPid = $row['pid'];
216 }
217 }
218 // add the current inline job to the structure stack
219 $this->pushStructure($table, $row['uid'], $field, $config);
220 // e.g. data[<table>][<uid>][<field>]
221 $nameForm = $this->inlineNames['form'];
222 // e.g. data-<pid>-<table1>-<uid1>-<field1>-<table2>-<uid2>-<field2>
223 $nameObject = $this->inlineNames['object'];
224 // get the records related to this inline record
225 $relatedRecords = $this->getRelatedRecords($table,$field,$row,$PA,$config);
226 // set the first and last record to the config array
227 $relatedRecordsUids = array_keys($relatedRecords['records']);
228 $config['inline']['first'] = reset($relatedRecordsUids);
229 $config['inline']['last'] = end($relatedRecordsUids);
230
231 // Tell the browser what we have (using JSON later):
232 $top = $this->getStructureLevel(0);
233 $this->inlineData['config'][$nameObject] = array(
234 'table' => $foreign_table,
235 'md5' => md5($nameObject),
236 );
237 $this->inlineData['config'][$nameObject. self::Structure_Separator . $foreign_table] = array(
238 'min' => $minitems,
239 'max' => $maxitems,
240 'sortable' => $config['appearance']['useSortable'],
241 'top' => array(
242 'table' => $top['table'],
243 'uid' => $top['uid'],
244 ),
245 );
246 // Set a hint for nested IRRE and tab elements:
247 $this->inlineData['nested'][$nameObject] = $this->fObj->getDynNestedStack(false, $this->isAjaxCall);
248
249 // if relations are required to be unique, get the uids that have already been used on the foreign side of the relation
250 if ($config['foreign_unique']) {
251 // If uniqueness *and* selector are set, they should point to the same field - so, get the configuration of one:
252 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_unique']);
253 // Get the used unique ids:
254 $uniqueIds = $this->getUniqueIds($relatedRecords['records'], $config, $selConfig['type']=='groupdb');
255 $possibleRecords = $this->getPossibleRecords($table,$field,$row,$config,'foreign_unique');
256 $uniqueMax = $config['appearance']['useCombination'] || $possibleRecords === false ? -1 : count($possibleRecords);
257 $this->inlineData['unique'][$nameObject. self::Structure_Separator . $foreign_table] = array(
258 'max' => $uniqueMax,
259 'used' => $uniqueIds,
260 'type' => $selConfig['type'],
261 'table' => $config['foreign_table'],
262 'elTable' => $selConfig['table'], // element/record table (one step down in hierarchy)
263 'field' => $config['foreign_unique'],
264 'selector' => $selConfig['selector'],
265 'possible' => $this->getPossibleRecordsFlat($possibleRecords),
266 );
267 }
268
269 // if it's required to select from possible child records (reusable children), add a selector box
270 if ($config['foreign_selector']) {
271 // if not already set by the foreign_unique, set the possibleRecords here and the uniqueIds to an empty array
272 if (!$config['foreign_unique']) {
273 $possibleRecords = $this->getPossibleRecords($table,$field,$row,$config);
274 $uniqueIds = array();
275 }
276 $selectorBox = $this->renderPossibleRecordsSelector($possibleRecords,$config,$uniqueIds);
277 $item .= $selectorBox;
278 }
279
280 // wrap all inline fields of a record with a <div> (like a container)
281 $item .= '<div id="'.$nameObject.'">';
282
283 // define how to show the "Create new record" link - if there are more than maxitems, hide it
284 if ($relatedRecords['count'] >= $maxitems || ($uniqueMax > 0 && $relatedRecords['count'] >= $uniqueMax)) {
285 $config['inline']['inlineNewButtonStyle'] = 'display: none;';
286 }
287
288 // Render the level links (create new record, localize all, synchronize):
289 if ($config['appearance']['levelLinksPosition']!='none') {
290 $levelLinks = $this->getLevelInteractionLink('newRecord', $nameObject . self::Structure_Separator . $foreign_table, $config);
291 if ($language>0) {
292 // Add the "Localize all records" link before all child records:
293 if (isset($config['appearance']['showAllLocalizationLink']) && $config['appearance']['showAllLocalizationLink']) {
294 $levelLinks.= $this->getLevelInteractionLink('localize', $nameObject . self::Structure_Separator . $foreign_table, $config);
295 }
296 // Add the "Synchronize with default language" link before all child records:
297 if (isset($config['appearance']['showSynchronizationLink']) && $config['appearance']['showSynchronizationLink']) {
298 $levelLinks.= $this->getLevelInteractionLink('synchronize', $nameObject . self::Structure_Separator . $foreign_table, $config);
299 }
300 }
301 }
302 // Add the level links before all child records:
303 if (in_array($config['appearance']['levelLinksPosition'], array('both', 'top'))) {
304 $item.= $levelLinks;
305 }
306
307 $item .= '<div id="'.$nameObject.'_records">';
308 $relationList = array();
309 if (count($relatedRecords['records'])) {
310 foreach ($relatedRecords['records'] as $rec) {
311 $item .= $this->renderForeignRecord($row['uid'],$rec,$config);
312 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
313 $relationList[] = $rec['uid'];
314 }
315 }
316 }
317 $item .= '</div>';
318
319 // Add the level links after all child records:
320 if (in_array($config['appearance']['levelLinksPosition'], array('both', 'bottom'))) {
321 $item.= $levelLinks;
322 }
323
324 // add Drag&Drop functions for sorting to TCEforms::$additionalJS_post
325 if (count($relationList) > 1 && $config['appearance']['useSortable'])
326 $this->addJavaScriptSortable($nameObject.'_records');
327 // publish the uids of the child records in the given order to the browser
328 $item .= '<input type="hidden" name="'.$nameForm.'" value="'.implode(',', $relationList).'" class="inlineRecord" />';
329 // close the wrap for all inline fields (container)
330 $item .= '</div>';
331
332 // on finishing this section, remove the last item from the structure stack
333 $this->popStructure();
334
335 // if this was the first call to the inline type, restore the values
336 if (!$this->getStructureDepth()) {
337 unset($this->inlineFirstPid);
338 }
339
340 return $item;
341 }
342
343
344 /*******************************************************
345 *
346 * Regular rendering of forms, fields, etc.
347 *
348 *******************************************************/
349
350
351 /**
352 * Render the form-fields of a related (foreign) record.
353 *
354 * @param string $parentUid: The uid of the parent (embedding) record (uid or NEW...)
355 * @param array $rec: The table record of the child/embedded table (normaly post-processed by t3lib_transferData)
356 * @param array $config: content of $PA['fieldConf']['config']
357 * @return string The HTML code for this "foreign record"
358 */
359 function renderForeignRecord($parentUid, $rec, $config = array()) {
360 $foreign_table = $config['foreign_table'];
361 $foreign_field = $config['foreign_field'];
362 $foreign_selector = $config['foreign_selector'];
363
364 // Register default localization content:
365 $parent = $this->getStructureLevel(-1);
366 if (isset($parent['localizationMode']) && $parent['localizationMode']!=false) {
367 $this->fObj->registerDefaultLanguageData($foreign_table, $rec);
368 }
369 // Send a mapping information to the browser via JSON:
370 // e.g. data[<curTable>][<curId>][<curField>] => data-<pid>-<parentTable>-<parentId>-<parentField>-<curTable>-<curId>-<curField>
371 $this->inlineData['map'][$this->inlineNames['form']] = $this->inlineNames['object'];
372
373 // Set this variable if we handle a brand new unsaved record:
374 $isNewRecord = t3lib_div::testInt($rec['uid']) ? false : true;
375 // Set this variable if the record is virtual and only show with header and not editable fields:
376 $isVirtualRecord = (isset($rec['__virtual']) && $rec['__virtual']);
377 // If there is a selector field, normalize it:
378 if ($foreign_selector) {
379 $rec[$foreign_selector] = $this->normalizeUid($rec[$foreign_selector]);
380 }
381
382 if (!$this->checkAccess(($isNewRecord ? 'new' : 'edit'), $foreign_table, $rec['uid'])) {
383 return false;
384 }
385
386 // Get the current naming scheme for DOM name/id attributes:
387 $nameObject = $this->inlineNames['object'];
388 $appendFormFieldNames = '['.$foreign_table.']['.$rec['uid'].']';
389 $objectId = $nameObject . self::Structure_Separator . $foreign_table . self::Structure_Separator . $rec['uid'];
390 // Put the current level also to the dynNestedStack of TCEforms:
391 $this->fObj->pushToDynNestedStack('inline', $objectId);
392
393 $header = $this->renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
394 if (!$isVirtualRecord) {
395 $combination = $this->renderCombinationTable($rec, $appendFormFieldNames, $config);
396 $fields = $this->renderMainFields($foreign_table, $rec);
397 $fields = $this->wrapFormsSection($fields);
398 // Get configuration:
399 $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
400
401 if ($isNewRecord) {
402 // show this record expanded or collapsed
403 $isExpanded = (!$collapseAll ? 1 : 0);
404 // get the top parent table
405 $top = $this->getStructureLevel(0);
406 $ucFieldName = 'uc[inlineView]['.$top['table'].']['.$top['uid'].']'.$appendFormFieldNames;
407 // set additional fields for processing for saving
408 $fields .= '<input type="hidden" name="'.$this->prependFormFieldNames.$appendFormFieldNames.'[pid]" value="'.$rec['pid'].'"/>';
409 $fields .= '<input type="hidden" name="'.$ucFieldName.'" value="'.$isExpanded.'" />';
410 } else {
411 // show this record expanded or collapsed
412 $isExpanded = (!$collapseAll && $this->getExpandedCollapsedState($foreign_table, $rec['uid']));
413 // set additional field for processing for saving
414 $fields .= '<input type="hidden" name="'.$this->prependCmdFieldNames.$appendFormFieldNames.'[delete]" value="1" disabled="disabled" />';
415 }
416
417 // if this record should be shown collapsed
418 if (!$isExpanded) {
419 $appearanceStyleFields = ' style="display: none;"';
420 }
421 }
422
423 // set the record container with data for output
424 $out = '<div id="' . $objectId . '_header">' . $header . '</div>';
425 $out .= '<div id="' . $objectId . '_fields"' . $appearanceStyleFields . '>' . $fields.$combination . '</div>';
426 // wrap the header, fields and combination part of a child record with a div container
427 $classMSIE = ($this->fObj->clientInfo['BROWSER']=='msie' && $this->fObj->clientInfo['VERSION'] < 8 ? 'MSIE' : '');
428 $class = 'inlineDiv' . $classMSIE . ($isNewRecord ? ' inlineIsNewRecord' : '');
429 $out = '<div id="' . $objectId . '_div" class="'.$class.'">' . $out . '</div>';
430
431 // Remove the current level also from the dynNestedStack of TCEforms:
432 $this->fObj->popFromDynNestedStack();
433
434 return $out;
435 }
436
437
438 /**
439 * Wrapper for TCEforms::getMainFields().
440 *
441 * @param string $table: The table name
442 * @param array $row: The record to be rendered
443 * @return string The rendered form
444 */
445 protected function renderMainFields($table, $row) {
446 // The current render depth of t3lib_TCEforms:
447 $depth = $this->fObj->renderDepth;
448 // If there is some information about already rendered palettes of our parent, store this info:
449 if (isset($this->fObj->palettesRendered[$depth][$table])) {
450 $palettesRendered = $this->fObj->palettesRendered[$depth][$table];
451 }
452 // Render the form:
453 $content = $this->fObj->getMainFields($table, $row, $depth);
454 // If there was some info about rendered palettes stored, write it back for our parent:
455 if (isset($palettesRendered)) {
456 $this->fObj->palettesRendered[$depth][$table] = $palettesRendered;
457 }
458 return $content;
459 }
460
461
462 /**
463 * Renders the HTML header for a foreign record, such as the title, toggle-function, drag'n'drop, etc.
464 * Later on the command-icons are inserted here.
465 *
466 * @param string $parentUid: The uid of the parent (embedding) record (uid or NEW...)
467 * @param string $foreign_table: The foreign_table we create a header for
468 * @param array $rec: The current record of that foreign_table
469 * @param array $config: content of $PA['fieldConf']['config']
470 * @param boolean $isVirtualRecord:
471 * @return string The HTML code of the header
472 */
473 function renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord=false) {
474 // Init:
475 $objectId = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table . self::Structure_Separator . $rec['uid'];
476 $expandSingle = $config['appearance']['expandSingle'] ? 1 : 0;
477 $onClick = "return inline.expandCollapseRecord('" . htmlspecialchars($objectId) . "', $expandSingle)";
478
479 // Pre-Processing:
480 $isOnSymmetricSide = t3lib_loadDBGroup::isOnSymmetricSide($parentUid, $config, $rec);
481 $hasForeignLabel = !$isOnSymmetricSide && $config['foreign_label'] ? true : false;
482 $hasSymmetricLabel = $isOnSymmetricSide && $config['symmetric_label'] ? true : false;
483 // Get the record title/label for a record:
484 // render using a self-defined user function
485 if ($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc']) {
486 $params = array(
487 'table' => $foreign_table,
488 'row' => $rec,
489 'title' => '',
490 'isOnSymmetricSide' => $isOnSymmetricSide,
491 'parent' => array(
492 'uid' => $parentUid,
493 'config' => $config,
494 ),
495 );
496 $null = null; // callUserFunction requires a third parameter, but we don't want to give $this as reference!
497 t3lib_div::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'], $params, $null);
498 $recTitle = $params['title'];
499 // render the special alternative title
500 } elseif ($hasForeignLabel || $hasSymmetricLabel) {
501 $titleCol = $hasForeignLabel ? $config['foreign_label'] : $config['symmetric_label'];
502 $foreignConfig = $this->getPossibleRecordsSelectorConfig($config, $titleCol);
503 // Render title for everything else than group/db:
504 if ($foreignConfig['type'] != 'groupdb') {
505 $recTitle = t3lib_BEfunc::getProcessedValueExtra($foreign_table, $titleCol, $rec[$titleCol], 0, 0, false);
506 // Render title for group/db:
507 } else {
508 // $recTitle could be something like: "tx_table_123|...",
509 $valueParts = t3lib_div::trimExplode('|', $rec[$titleCol]);
510 $itemParts = t3lib_div::revExplode('_', $valueParts[0], 2);
511 $recTemp = t3lib_befunc::getRecordWSOL($itemParts[0], $itemParts[1]);
512 $recTitle = t3lib_BEfunc::getRecordTitle($itemParts[0], $recTemp, false);
513 }
514 $recTitle = t3lib_BEfunc::getRecordTitlePrep($recTitle);
515 if (!strcmp(trim($recTitle),'')) {
516 $recTitle = t3lib_BEfunc::getNoRecordTitle(true);
517 }
518 // render the standard
519 } else {
520 $recTitle = t3lib_BEfunc::getRecordTitle($foreign_table, $rec, true);
521 }
522
523 $altText = t3lib_BEfunc::getRecordIconAltText($rec, $foreign_table);
524 $iconImg = t3lib_iconWorks::getIconImage($foreign_table, $rec, $this->backPath, 'title="'.htmlspecialchars($altText).'" class="absmiddle"');
525 $label = '<span id="' . $objectId . '_label">' . $recTitle . '</span>';
526 if (!$isVirtualRecord) {
527 $iconImg = $this->wrapWithAnchor($iconImg, '#', array('onclick' => $onClick));
528 $label = $this->wrapWithAnchor($label, '#', array('onclick' => $onClick, 'style' => 'display: block;'));
529 }
530
531 $ctrl = $this->renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
532
533 // @TODO: Check the table wrapping and the CSS definitions
534 $header =
535 '<table cellspacing="0" cellpadding="0" border="0" width="100%" style="margin-right: '.$this->inlineStyles['margin-right'].'px;"'.
536 ($this->fObj->borderStyle[2] ? ' background="'.htmlspecialchars($this->backPath.$this->fObj->borderStyle[2]).'"':'').
537 ($this->fObj->borderStyle[3] ? ' class="'.htmlspecialchars($this->fObj->borderStyle[3]).'"':'').'>' .
538 '<tr class="class-main12"><td width="18">'.$iconImg.'</td><td align="left"><b>'.$label.'</b></td><td align="right">'.$ctrl.'</td></tr></table>';
539
540 return $header;
541 }
542
543
544 /**
545 * Render the control-icons for a record header (create new, sorting, delete, disable/enable).
546 * Most of the parts are copy&paste from class.db_list_extra.inc and modified for the JavaScript calls here
547 *
548 * @param string $parentUid: The uid of the parent (embedding) record (uid or NEW...)
549 * @param string $foreign_table: The table (foreign_table) we create control-icons for
550 * @param array $rec: The current record of that foreign_table
551 * @param array $config: (modified) TCA configuration of the field
552 * @return string The HTML code with the control-icons
553 */
554 function renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config=array(), $isVirtualRecord=false) {
555 // Initialize:
556 $cells = array();
557 $isNewItem = substr($rec['uid'], 0, 3) == 'NEW';
558
559 $tcaTableCtrl =& $GLOBALS['TCA'][$foreign_table]['ctrl'];
560 $tcaTableCols =& $GLOBALS['TCA'][$foreign_table]['columns'];
561
562 $isPagesTable = $foreign_table == 'pages' ? true : false;
563 $isOnSymmetricSide = t3lib_loadDBGroup::isOnSymmetricSide($parentUid, $config, $rec);
564 $enableManualSorting = $tcaTableCtrl['sortby'] || $config['MM'] || (!$isOnSymmetricSide && $config['foreign_sortby']) || ($isOnSymmetricSide && $config['symmetric_sortby']) ? true : false;
565
566 $nameObject = $this->inlineNames['object'];
567 $nameObjectFt = $nameObject . self::Structure_Separator . $foreign_table;
568 $nameObjectFtId = $nameObjectFt . self::Structure_Separator . $rec['uid'];
569
570 $calcPerms = $GLOBALS['BE_USER']->calcPerms(
571 t3lib_BEfunc::readPageAccess($rec['pid'], $GLOBALS['BE_USER']->getPagePermsClause(1))
572 );
573
574 // If the listed table is 'pages' we have to request the permission settings for each page:
575 if ($isPagesTable) {
576 $localCalcPerms = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages',$rec['uid']));
577 }
578
579 // This expresses the edit permissions for this particular element:
580 $permsEdit = ($isPagesTable && ($localCalcPerms&2)) || (!$isPagesTable && ($calcPerms&16));
581
582 // Controls: Defines which controls should be shown
583 $enabledControls = $config['appearance']['enabledControls'];
584 // Hook: Can disable/enable single controls for specific child records:
585 foreach ($this->hookObjects as $hookObj) {
586 $hookObj->renderForeignRecordHeaderControl_preProcess($parentUid, $foreign_table, $rec, $config, $isVirtual, $enabledControls);
587 }
588
589 // Icon to visualize that a required field is nested in this inline level:
590 $cells['required'] = '<img name="'.$nameObjectFtId.'_req" src="clear.gif" width="10" height="10" hspace="4" vspace="3" alt="" />';
591
592 if (isset($rec['__create'])) {
593 $cells['localize.isLocalizable'] = '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/localize_green.gif','width="16" height="16"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localize.isLocalizable', 1).'" alt="" />';
594 } elseif (isset($rec['__remove'])) {
595 $cells['localize.wasRemovedInOriginal'] = '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/localize_red.gif','width="16" height="16"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localize.wasRemovedInOriginal', 1).'" alt="" />';
596 }
597
598 // "Info": (All records)
599 if ($enabledControls['info'] && !$isNewItem) {
600 $cells['info']='<a href="#" onclick="'.htmlspecialchars('top.launchView(\''.$foreign_table.'\', \''.$rec['uid'].'\'); return false;').'">'.
601 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/zoom2.gif','width="12" height="12"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:showInfo',1).'" alt="" />'.
602 '</a>';
603 }
604 // If the table is NOT a read-only table, then show these links:
605 if (!$tcaTableCtrl['readOnly'] && !$isVirtualRecord) {
606
607 // "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):
608 if ($enabledControls['new'] && ($enableManualSorting || $tcaTableCtrl['useColumnsForDefaultValues'])) {
609 if (
610 (!$isPagesTable && ($calcPerms&16)) || // For NON-pages, must have permission to edit content on this parent page
611 ($isPagesTable && ($calcPerms&8)) // For pages, must have permission to create new pages here.
612 ) {
613 $onClick = "return inline.createNewRecord('".$nameObjectFt."','".$rec['uid']."')";
614 $class = ' class="inlineNewButton '.$this->inlineData['config'][$nameObject]['md5'].'"';
615 if ($config['inline']['inlineNewButtonStyle']) {
616 $style = ' style="'.$config['inline']['inlineNewButtonStyle'].'"';
617 }
618 $cells['new']='<a href="#" onclick="'.htmlspecialchars($onClick).'"'.$class.$style.'>'.
619 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/new_'.($isPagesTable?'page':'el').'.gif','width="'.($isPagesTable?13:11).'" height="12"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:new'.($isPagesTable?'Page':'Record'),1).'" alt="" />'.
620 '</a>';
621 }
622 }
623
624 // Drag&Drop Sorting: Sortable handler for script.aculo.us
625 if ($enabledControls['dragdrop'] && $permsEdit && $enableManualSorting && $config['appearance']['useSortable']) {
626 $cells['dragdrop'] = '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/move.gif','width="16" height="16" hspace="2"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.move',1).'" alt="" style="cursor: move;" class="sortableHandle" />';
627 }
628
629 // "Up/Down" links
630 if ($enabledControls['sort'] && $permsEdit && $enableManualSorting) {
631 $onClick = "return inline.changeSorting('".$nameObjectFtId."', '1')"; // Up
632 $style = $config['inline']['first'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
633 $cells['sort.up']='<a href="#" onclick="'.htmlspecialchars($onClick).'" class="sortingUp" '.$style.'>'.
634 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/button_up.gif','width="11" height="10"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:moveUp',1).'" alt="" />'.
635 '</a>';
636
637 $onClick = "return inline.changeSorting('".$nameObjectFtId."', '-1')"; // Down
638 $style = $config['inline']['last'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
639 $cells['sort.down']='<a href="#" onclick="'.htmlspecialchars($onClick).'" class="sortingDown" '.$style.'>'.
640 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/button_down.gif','width="11" height="10"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:moveDown',1).'" alt="" />'.
641 '</a>';
642 }
643
644 // "Hide/Unhide" links:
645 $hiddenField = $tcaTableCtrl['enablecolumns']['disabled'];
646 if ($enabledControls['hide'] && $permsEdit && $hiddenField && $tcaTableCols[$hiddenField] && (!$tcaTableCols[$hiddenField]['exclude'] || $GLOBALS['BE_USER']->check('non_exclude_fields',$foreign_table.':'.$hiddenField))) {
647 $onClick = "return inline.enableDisableRecord('".$nameObjectFtId."')";
648 if ($rec[$hiddenField]) {
649 $cells['hide.unhide']='<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
650 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/button_unhide.gif','width="11" height="10"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:unHide'.($isPagesTable?'Page':''),1).'" alt="" id="'.$nameObjectFtId.'_disabled" />'.
651 '</a>';
652 } else {
653 $cells['hide.hide']='<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
654 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/button_hide.gif','width="11" height="10"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:hide'.($isPagesTable?'Page':''),1).'" alt="" id="'.$nameObjectFtId.'_disabled" />'.
655 '</a>';
656 }
657 }
658
659 // "Delete" link:
660 if ($enabledControls['delete'] && ($isPagesTable && $localCalcPerms&4 || !$isPagesTable && $calcPerms&16)) {
661 $onClick = "inline.deleteRecord('".$nameObjectFtId."');";
662 $cells['delete']='<a href="#" onclick="'.htmlspecialchars('if (confirm('.$GLOBALS['LANG']->JScharCode($GLOBALS['LANG']->getLL('deleteWarning')).')) { '.$onClick.' } return false;').'">'.
663 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/garbage.gif','width="11" height="12"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:delete',1).'" alt="" />'.
664 '</a>';
665 }
666 // If this is a virtual record offer a minimized set of icons for user interaction:
667 } elseif ($isVirtualRecord) {
668 if ($enabledControls['localize'] && isset($rec['__create'])) {
669 $onClick = "inline.synchronizeLocalizeRecords('".$nameObjectFt."', ".$rec['uid'].");";
670 $cells['localize'] = '<a href="#" onclick="'.htmlspecialchars($onClick).'">' .
671 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/localize_el.gif','width="16" height="16"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localize', 1).'" alt="" />' .
672 '</a>';
673 }
674 }
675
676 // If the record is edit-locked by another user, we will show a little warning sign:
677 if ($lockInfo=t3lib_BEfunc::isRecordLocked($foreign_table,$rec['uid'])) {
678 $cells['locked']='<a href="#" onclick="'.htmlspecialchars('alert('.$GLOBALS['LANG']->JScharCode($lockInfo['msg']).');return false;').'">'.
679 '<img'.t3lib_iconWorks::skinImg('','gfx/recordlock_warning3.gif','width="17" height="12"').' title="'.htmlspecialchars($lockInfo['msg']).'" alt="" />'.
680 '</a>';
681 }
682
683 // Hook: Post-processing of single controls for specific child records:
684 foreach ($this->hookObjects as $hookObj) {
685 $hookObj->renderForeignRecordHeaderControl_postProcess($parentUid, $foreign_table, $rec, $config, $isVirtual, $cells);
686 }
687 // Compile items into a DIV-element:
688 return '
689 <!-- CONTROL PANEL: '.$foreign_table.':'.$rec['uid'].' -->
690 <div class="typo3-DBctrl">'.implode('', $cells).'</div>';
691 }
692
693
694 /**
695 * Render a table with TCEforms, that occurs on a intermediate table but should be editable directly,
696 * so two tables are combined (the intermediate table with attributes and the sub-embedded table).
697 * -> This is a direct embedding over two levels!
698 *
699 * @param array $rec: The table record of the child/embedded table (normaly post-processed by t3lib_transferData)
700 * @param string $appendFormFieldNames: The [<table>][<uid>] of the parent record (the intermediate table)
701 * @param array $config: content of $PA['fieldConf']['config']
702 * @return string A HTML string with <table> tag around.
703 */
704 function renderCombinationTable(&$rec, $appendFormFieldNames, $config = array()) {
705 $foreign_table = $config['foreign_table'];
706 $foreign_selector = $config['foreign_selector'];
707
708 if ($foreign_selector && $config['appearance']['useCombination']) {
709 $comboConfig = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector]['config'];
710 $comboRecord = array();
711
712 // If record does already exist, load it:
713 if ($rec[$foreign_selector] && t3lib_div::testInt($rec[$foreign_selector])) {
714 $comboRecord = $this->getRecord(
715 $this->inlineFirstPid,
716 $comboConfig['foreign_table'],
717 $rec[$foreign_selector]
718 );
719 $isNewRecord = false;
720 // It is a new record, create a new record virtually:
721 } else {
722 $comboRecord = $this->getNewRecord(
723 $this->inlineFirstPid,
724 $comboConfig['foreign_table']
725 );
726 $isNewRecord = true;
727 }
728
729 // get the TCEforms interpretation of the TCA of the child table
730 $out = $this->renderMainFields($comboConfig['foreign_table'], $comboRecord);
731 $out = $this->wrapFormsSection($out, array(), array('class' => 'wrapperAttention'));
732
733 // if this is a new record, add a pid value to store this record and the pointer value for the intermediate table
734 if ($isNewRecord) {
735 $comboFormFieldName = $this->prependFormFieldNames.'['.$comboConfig['foreign_table'].']['.$comboRecord['uid'].'][pid]';
736 $out .= '<input type="hidden" name="'.$comboFormFieldName.'" value="'.$comboRecord['pid'].'" />';
737 }
738
739 // if the foreign_selector field is also responsible for uniqueness, tell the browser the uid of the "other" side of the relation
740 if ($isNewRecord || $config['foreign_unique'] == $foreign_selector) {
741 $parentFormFieldName = $this->prependFormFieldNames.$appendFormFieldNames.'['.$foreign_selector.']';
742 $out .= '<input type="hidden" name="'.$parentFormFieldName.'" value="'.$comboRecord['uid'].'" />';
743 }
744 }
745
746 return $out;
747 }
748
749
750 /**
751 * Get a selector as used for the select type, to select from all available
752 * records and to create a relation to the embedding record (e.g. like MM).
753 *
754 * @param array $selItems: Array of all possible records
755 * @param array $conf: TCA configuration of the parent(!) field
756 * @param array $uniqueIds: The uids that have already been used and should be unique
757 * @return string A HTML <select> box with all possible records
758 */
759 function renderPossibleRecordsSelector($selItems, $conf, $uniqueIds=array()) {
760 $foreign_table = $conf['foreign_table'];
761 $foreign_selector = $conf['foreign_selector'];
762
763 $selConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_selector);
764 $config = $selConfig['PA']['fieldConf']['config'];
765
766 if ($selConfig['type'] == 'select') {
767 $item = $this->renderPossibleRecordsSelectorTypeSelect($selItems, $conf, $selConfig['PA'], $uniqueIds);
768 } elseif ($selConfig['type'] == 'groupdb') {
769 $item = $this->renderPossibleRecordsSelectorTypeGroupDB($conf, $selConfig['PA']);
770 }
771
772 return $item;
773 }
774
775
776 /**
777 * Get a selector as used for the select type, to select from all available
778 * records and to create a relation to the embedding record (e.g. like MM).
779 *
780 * @param array $selItems: Array of all possible records
781 * @param array $conf: TCA configuration of the parent(!) field
782 * @param array $PA: An array with additional configuration options
783 * @param array $uniqueIds: The uids that have already been used and should be unique
784 * @return string A HTML <select> box with all possible records
785 */
786 function renderPossibleRecordsSelectorTypeSelect($selItems, $conf, &$PA, $uniqueIds=array()) {
787 $foreign_table = $conf['foreign_table'];
788 $foreign_selector = $conf['foreign_selector'];
789
790 $PA = array();
791 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector];
792 $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
793 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table,array(),$foreign_selector);
794 $config = $PA['fieldConf']['config'];
795
796 if(!$disabled) {
797 // Create option tags:
798 $opt = array();
799 $styleAttrValue = '';
800 foreach($selItems as $p) {
801 if ($config['iconsInOptionTags']) {
802 $styleAttrValue = $this->fObj->optionTagStyle($p[2]);
803 }
804 if (!in_array($p[1], $uniqueIds)) {
805 $opt[]= '<option value="'.htmlspecialchars($p[1]).'"'.
806 ' style="'.(in_array($p[1], $uniqueIds) ? '' : '').
807 ($styleAttrValue ? ' style="'.htmlspecialchars($styleAttrValue) : '').'">'.
808 htmlspecialchars($p[0]).'</option>';
809 }
810 }
811
812 // Put together the selector box:
813 $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="'.htmlspecialchars($config['itemListStyle']).'"' : ' style="'.$this->fObj->defaultMultipleSelectorStyle.'"';
814 $size = intval($conf['size']);
815 $size = $conf['autoSizeMax'] ? t3lib_div::intInRange(count($itemArray)+1,t3lib_div::intInRange($size,1),$conf['autoSizeMax']) : $size;
816 $onChange = "return inline.importNewRecord('" . $this->inlineNames['object']. self::Structure_Separator . $conf['foreign_table'] . "')";
817 $item = '
818 <select id="'.$this->inlineNames['object'] . self::Structure_Separator . $conf['foreign_table'] . '_selector"'.
819 $this->fObj->insertDefStyle('select').
820 ($size ? ' size="'.$size.'"' : '').
821 ' onchange="'.htmlspecialchars($onChange).'"'.
822 $PA['onFocus'].
823 $selector_itemListStyle.
824 ($conf['foreign_unique'] ? ' isunique="isunique"' : '').'>
825 '.implode('
826 ',$opt).'
827 </select>';
828
829 // add a "Create new relation" link for adding new relations
830 // this is neccessary, if the size of the selector is "1" or if
831 // there is only one record item in the select-box, that is selected by default
832 // the selector-box creates a new relation on using a onChange event (see some line above)
833 $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation',1);
834 $item .=
835 '<a href="#" onclick="'.htmlspecialchars($onChange).'" align="abstop">'.
836 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/edit2.gif','width="11" height="12"').' align="absmiddle" '.t3lib_BEfunc::titleAltAttrib($createNewRelationText).' /> '.$createNewRelationText.
837 '</a>';
838 // wrap the selector and add a spacer to the bottom
839 $item = '<div style="margin-bottom: 20px;">'.$item.'</div>';
840 }
841
842 return $item;
843 }
844
845
846 /**
847 * Generate a link that opens an element browser in a new window.
848 * For group/db there is no way o use a "selector" like a <select>|</select>-box.
849 *
850 * @param array $conf: TCA configuration of the parent(!) field
851 * @param array $PA: An array with additional configuration options
852 * @return string A HTML link that opens an element browser in a new window
853 */
854 function renderPossibleRecordsSelectorTypeGroupDB($conf, &$PA) {
855 $foreign_table = $conf['foreign_table'];
856
857 $config = $PA['fieldConf']['config'];
858 $allowed = $config['allowed'];
859 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table;
860
861 $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation',1);
862 $onClick = "setFormValueOpenBrowser('db','".('|||'.$allowed.'|'.$objectPrefix.'|inline.checkUniqueElement||inline.importElement')."'); return false;";
863 $item =
864 '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
865 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/insert3.gif','width="14" height="14"').' align="absmiddle" '.t3lib_BEfunc::titleAltAttrib($createNewRelationText).' /> '.$createNewRelationText.
866 '</a>';
867
868 return $item;
869 }
870
871
872 /**
873 * Creates the HTML code of a general link to be used on a level of inline children.
874 * The possible keys for the parameter $type are 'newRecord', 'localize' and 'synchronize'.
875 *
876 * @param string $type: The link type, values are 'newRecord', 'localize' and 'synchronize'.
877 * @param string $objectPrefix: The "path" to the child record to create (e.g. 'data-parentPageId-partenTable-parentUid-parentField-childTable]')
878 * @param array $conf: TCA configuration of the parent(!) field
879 * @return string The HTML code of the new link, wrapped in a div
880 */
881 protected function getLevelInteractionLink($type, $objectPrefix, $conf=array()) {
882 $nameObject = $this->inlineNames['object'];
883 $attributes = array();
884 switch($type) {
885 case 'newRecord':
886 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:cm.createnew', 1);
887 $iconFile = 'gfx/new_el.gif';
888 // $iconAddon = 'width="11" height="12"';
889 $className = 'typo3-newRecordLink';
890 $attributes['class'] = 'inlineNewButton '.$this->inlineData['config'][$nameObject]['md5'];
891 $attributes['onclick'] = "return inline.createNewRecord('$objectPrefix')";
892 if (isset($conf['inline']['inlineNewButtonStyle']) && $conf['inline']['inlineNewButtonStyle']) {
893 $attributes['style'] = $conf['inline']['inlineNewButtonStyle'];
894 }
895 if (isset($conf['appearance']['newRecordLinkAddTitle']) && $conf['appearance']['newRecordLinkAddTitle']) {
896 $titleAddon = ' '.$GLOBALS['LANG']->sL($GLOBALS['TCA'][$conf['foreign_table']]['ctrl']['title'], 1);
897 }
898 break;
899 case 'localize':
900 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localizeAllRecords', 1);
901 $iconFile = 'gfx/localize_el.gif';
902 $className = 'typo3-localizationLink';
903 $attributes['onclick'] = "return inline.synchronizeLocalizeRecords('$objectPrefix', 'localize')";
904 break;
905 case 'synchronize':
906 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:synchronizeWithOriginalLanguage', 1);
907 $iconFile = 'gfx/synchronize_el.gif';
908 $className = 'typo3-synchronizationLink';
909 $attributes['class'] = 'inlineNewButton '.$this->inlineData['config'][$nameObject]['md5'];
910 $attributes['onclick'] = "return inline.synchronizeLocalizeRecords('$objectPrefix', 'synchronize')";
911 break;
912 }
913 // Create the link:
914 $icon = ($iconFile ? '<img'.t3lib_iconWorks::skinImg($this->backPath, $iconFile, $iconAddon).' alt="'.htmlspecialchars($title.$titleAddon).'" />' : '');
915 $link = $this->wrapWithAnchor($icon.$title.$titleAddon, '#', $attributes);
916 return '<div'.($className ? ' class="'.$className.'"' : '').'>'.$link.'</div>';
917 }
918
919
920 /**
921 * Creates a link/button to create new records
922 *
923 * @param string $objectPrefix: The "path" to the child record to create (e.g. 'data-parentPageId-partenTable-parentUid-parentField-childTable')
924 * @param array $conf: TCA configuration of the parent(!) field
925 * @return string The HTML code for the new record link
926 * @deprecated since TYPO3 4.2.0-beta1, this function will be removed in TYPO3 4.5.
927 */
928 function getNewRecordLink($objectPrefix, $conf = array()) {
929 t3lib_div::logDeprecatedFunction();
930
931 return $this->getLevelInteractionLink('newRecord', $objectPrefix, $conf);
932 }
933
934
935 /**
936 * Add Sortable functionality using script.acolo.us "Sortable".
937 *
938 * @param string $objectId: The container id of the object - elements inside will be sortable
939 * @return void
940 */
941 function addJavaScriptSortable($objectId) {
942 $this->fObj->additionalJS_post[] = '
943 inline.createDragAndDropSorting("'.$objectId.'");
944 ';
945 }
946
947
948 /*******************************************************
949 *
950 * Handling of AJAX calls
951 *
952 *******************************************************/
953
954
955 /**
956 * General processor for AJAX requests concerning IRRE.
957 * (called by typo3/ajax.php)
958 *
959 * @param array $params: additional parameters (not used here)
960 * @param TYPO3AJAX $ajaxObj: the TYPO3AJAX object of this request
961 * @return void
962 */
963 public function processAjaxRequest($params, $ajaxObj) {
964 $ajaxArguments = t3lib_div::_GP('ajax');
965 $ajaxIdParts = explode('::', $GLOBALS['ajaxID'], 2);
966
967 if (isset($ajaxArguments) && is_array($ajaxArguments) && count($ajaxArguments)) {
968 $ajaxMethod = $ajaxIdParts[1];
969 switch ($ajaxMethod) {
970 case 'createNewRecord':
971 case 'synchronizeLocalizeRecords':
972 $this->isAjaxCall = true;
973 // Construct runtime environment for Inline Relational Record Editing:
974 $this->processAjaxRequestConstruct($ajaxArguments);
975 // Parse the DOM identifier (string), add the levels to the structure stack (array) and load the TCA config:
976 $this->parseStructureString($ajaxArguments[0], true);
977 // Render content:
978 $ajaxObj->setContentFormat('jsonbody');
979 $ajaxObj->setContent(
980 call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments)
981 );
982 break;
983 case 'setExpandedCollapsedState':
984 $ajaxObj->setContentFormat('jsonbody');
985 call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments);
986 break;
987 }
988 }
989 }
990
991
992 /**
993 * Construct runtime environment for Inline Relational Record Editing.
994 * - creates an anoymous SC_alt_doc in $GLOBALS['SOBE']
995 * - creates a t3lib_TCEforms in $GLOBALS['SOBE']->tceforms
996 * - sets ourself as reference to $GLOBALS['SOBE']->tceforms->inline
997 * - sets $GLOBALS['SOBE']->tceforms->RTEcounter to the current situation on client-side
998 *
999 * @param array &$ajaxArguments: The arguments to be processed by the AJAX request
1000 * @return void
1001 */
1002 protected function processAjaxRequestConstruct(&$ajaxArguments) {
1003 global $SOBE, $BE_USER, $TYPO3_CONF_VARS;
1004
1005 require_once(PATH_typo3.'template.php');
1006
1007 $GLOBALS['LANG']->includeLLFile('EXT:lang/locallang_alt_doc.xml');
1008
1009 // Create a new anonymous object:
1010 $SOBE = new stdClass();
1011 $SOBE->MOD_MENU = array(
1012 'showPalettes' => '',
1013 'showDescriptions' => '',
1014 'disableRTE' => ''
1015 );
1016 // Setting virtual document name
1017 $SOBE->MCONF['name']='xMOD_alt_doc.php';
1018 // CLEANSE SETTINGS
1019 $SOBE->MOD_SETTINGS = t3lib_BEfunc::getModuleData(
1020 $SOBE->MOD_MENU,
1021 t3lib_div::_GP('SET'),
1022 $SOBE->MCONF['name']
1023 );
1024 // Create an instance of the document template object
1025 $SOBE->doc = t3lib_div::makeInstance('template');
1026 $SOBE->doc->backPath = $GLOBALS['BACK_PATH'];
1027 // Initialize TCEforms (rendering the forms)
1028 $SOBE->tceforms = t3lib_div::makeInstance('t3lib_TCEforms');
1029 $SOBE->tceforms->inline = $this;
1030 $SOBE->tceforms->RTEcounter = intval(array_shift($ajaxArguments));
1031 $SOBE->tceforms->initDefaultBEMode();
1032 $SOBE->tceforms->palettesCollapsed = !$SOBE->MOD_SETTINGS['showPalettes'];
1033 $SOBE->tceforms->disableRTE = $SOBE->MOD_SETTINGS['disableRTE'];
1034 $SOBE->tceforms->enableClickMenu = TRUE;
1035 $SOBE->tceforms->enableTabMenu = TRUE;
1036 // Clipboard is initialized:
1037 $SOBE->tceforms->clipObj = t3lib_div::makeInstance('t3lib_clipboard'); // Start clipboard
1038 $SOBE->tceforms->clipObj->initializeClipboard(); // Initialize - reads the clipboard content from the user session
1039 // Setting external variables:
1040 if ($BE_USER->uc['edit_showFieldHelp']!='text' && $SOBE->MOD_SETTINGS['showDescriptions']) {
1041 $SOBE->tceforms->edit_showFieldHelp = 'text';
1042 }
1043 }
1044
1045
1046 /**
1047 * Determines and sets several script calls to a JSON array, that would have been executed if processed in non-AJAX mode.
1048 *
1049 * @param array &$jsonArray: Reference of the array to be used for JSON
1050 * @param array $config: The configuration of the IRRE field of the parent record
1051 * @return void
1052 */
1053 protected function getCommonScriptCalls(&$jsonArray, $config) {
1054 // Add data that would have been added at the top of a regular TCEforms call:
1055 if ($headTags = $this->getHeadTags()) {
1056 $jsonArray['headData'] = $headTags;
1057 }
1058 // Add the JavaScript data that would have been added at the bottom of a regular TCEforms call:
1059 $jsonArray['scriptCall'][] = $this->fObj->JSbottom($this->fObj->formName, true);
1060 // If script.aculo.us Sortable is used, update the Observer to know the record:
1061 if ($config['appearance']['useSortable']) {
1062 $jsonArray['scriptCall'][] = "inline.createDragAndDropSorting('".$this->inlineNames['object']."_records');";
1063 }
1064 // if TCEforms has some JavaScript code to be executed, just do it
1065 if ($this->fObj->extJSCODE) {
1066 $jsonArray['scriptCall'][] = $this->fObj->extJSCODE;
1067 }
1068 }
1069
1070
1071 /**
1072 * Initialize environment for AJAX calls
1073 *
1074 * @param string $method: Name of the method to be called
1075 * @param array $arguments: Arguments to be delivered to the method
1076 * @return void
1077 * @deprecated since TYPO3 4.2.0-alpha3, this function will be removed in TYPO3 4.5.
1078 */
1079 function initForAJAX($method, &$arguments) {
1080 t3lib_div::logDeprecatedFunction();
1081
1082 // Set t3lib_TCEforms::$RTEcounter to the given value:
1083 if ($method == 'createNewRecord') {
1084 $this->fObj->RTEcounter = intval(array_shift($arguments));
1085 }
1086 }
1087
1088
1089 /**
1090 * Generates an error message that transferred as JSON for AJAX calls
1091 *
1092 * @param string $message: The error message to be shown
1093 * @return array The error message in a JSON array
1094 */
1095 protected function getErrorMessageForAJAX($message) {
1096 $jsonArray = array(
1097 'data' => $message,
1098 'scriptCall' => array(
1099 'alert("' . $message . '");'
1100 )
1101 );
1102 return $jsonArray;
1103 }
1104
1105
1106 /**
1107 * Handle AJAX calls to show a new inline-record of the given table.
1108 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1109 *
1110 * @param string $domObjectId: The calling object in hierarchy, that requested a new record.
1111 * @param string $foreignUid: If set, the new record should be inserted after that one.
1112 * @return array An array to be used for JSON
1113 */
1114 function createNewRecord($domObjectId, $foreignUid = 0) {
1115 // the current table - for this table we should add/import records
1116 $current = $this->inlineStructure['unstable'];
1117 // the parent table - this table embeds the current table
1118 $parent = $this->getStructureLevel(-1);
1119 // get TCA 'config' of the parent table
1120 if (!$this->checkConfiguration($parent['config'])) {
1121 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1122 }
1123 $config = $parent['config'];
1124
1125 $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
1126 $expandSingle = (isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle']);
1127
1128 // Put the current level also to the dynNestedStack of TCEforms:
1129 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1130
1131 // dynamically create a new record using t3lib_transferData
1132 if (!$foreignUid || !t3lib_div::testInt($foreignUid) || $config['foreign_selector']) {
1133 $record = $this->getNewRecord($this->inlineFirstPid, $current['table']);
1134 // Set language of new child record to the language of the parent record:
1135 if ($config['localizationMode']=='select') {
1136 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1137 $parentLanguageField = $GLOBALS['TCA'][$parent['table']]['ctrl']['languageField'];
1138 $childLanguageField = $GLOBALS['TCA'][$current['table']]['ctrl']['languageField'];
1139 if ($parentRecord[$languageField]>0) {
1140 $record[$childLanguageField] = $parentRecord[$languageField];
1141 }
1142 }
1143
1144 // dynamically import an existing record (this could be a call from a select box)
1145 } else {
1146 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $foreignUid);
1147 }
1148
1149 // now there is a foreign_selector, so there is a new record on the intermediate table, but
1150 // this intermediate table holds a field, which is responsible for the foreign_selector, so
1151 // we have to set this field to the uid we get - or if none, to a new uid
1152 if ($config['foreign_selector'] && $foreignUid) {
1153 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_selector']);
1154 // For a selector of type group/db, prepend the tablename (<tablename>_<uid>):
1155 $record[$config['foreign_selector']] = $selConfig['type'] != 'groupdb' ? '' : $selConfig['table'].'_';
1156 $record[$config['foreign_selector']] .= $foreignUid;
1157 }
1158
1159 // the HTML-object-id's prefix of the dynamically created record
1160 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1161 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1162
1163 // render the foreign record that should passed back to browser
1164 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1165 if($item === false) {
1166 return $this->getErrorMessageForAJAX('Access denied');
1167 }
1168
1169 // Encode TCEforms AJAX response with utf-8:
1170 $item = $GLOBALS['LANG']->csConvObj->utf8_encode($item, $GLOBALS['LANG']->charSet);
1171
1172 if (!$current['uid']) {
1173 $jsonArray = array(
1174 'data' => $item,
1175 'scriptCall' => array(
1176 "inline.domAddNewRecord('bottom','".$this->inlineNames['object']."_records','$objectPrefix',json.data);",
1177 "inline.memorizeAddRecord('$objectPrefix','".$record['uid']."',null,'$foreignUid');"
1178 )
1179 );
1180
1181 // append the HTML data after an existing record in the container
1182 } else {
1183 $jsonArray = array(
1184 'data' => $item,
1185 'scriptCall' => array(
1186 "inline.domAddNewRecord('after','".$domObjectId.'_div'."','$objectPrefix',json.data);",
1187 "inline.memorizeAddRecord('$objectPrefix','".$record['uid']."','".$current['uid']."','$foreignUid');"
1188 )
1189 );
1190 }
1191 $this->getCommonScriptCalls($jsonArray, $config);
1192 // Collapse all other records if requested:
1193 if (!$collapseAll && $expandSingle) {
1194 $jsonArray['scriptCall'][] = "inline.collapseAllRecords('$objectId', '$objectPrefix', '".$record['uid']."');";
1195 }
1196 // tell the browser to scroll to the newly created record
1197 $jsonArray['scriptCall'][] = "Element.scrollTo('".$objectId."_div');";
1198 // fade out and fade in the new record in the browser view to catch the user's eye
1199 $jsonArray['scriptCall'][] = "inline.fadeOutFadeIn('".$objectId."_div');";
1200
1201 // Remove the current level also from the dynNestedStack of TCEforms:
1202 $this->fObj->popFromDynNestedStack();
1203
1204 // Return the JSON array:
1205 return $jsonArray;
1206 }
1207
1208
1209 /**
1210 * Handle AJAX calls to localize all records of a parent, localize a single record or to synchronize with the original language parent.
1211 *
1212 * @param string $domObjectId: The calling object in hierarchy, that requested a new record.
1213 * @param mixed $type: Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (integer)
1214 * @return array An array to be used for JSON
1215 */
1216 protected function synchronizeLocalizeRecords($domObjectId, $type) {
1217 $jsonArray = false;
1218 if (t3lib_div::inList('localize,synchronize', $type) || t3lib_div::testInt($type)) {
1219 // The current level:
1220 $current = $this->inlineStructure['unstable'];
1221 // The parent level:
1222 $parent = $this->getStructureLevel(-1);
1223 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1224
1225 $cmd = array();
1226 $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'].','.$type;
1227
1228 /* @var t3lib_TCEmain */
1229 $tce = t3lib_div::makeInstance('t3lib_TCEmain');
1230 $tce->stripslashes_values = false;
1231 $tce->start(array(), $cmd);
1232 $tce->process_cmdmap();
1233 $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parent['field']];
1234 unset($tce);
1235
1236 $jsonArray = $this->getExecuteChangesJsonArray($parentRecord[$parent['field']], $newItemList);
1237 $this->getCommonScriptCalls($jsonArray, $parent['config']);
1238 }
1239 return $jsonArray;
1240 }
1241
1242
1243 /**
1244 * Generates a JSON array which executes the changes and thus updates the forms view.
1245 *
1246 * @param string $oldItemList: List of related child reocrds before changes were made (old)
1247 * @param string $newItemList: List of related child records after changes where made (new)
1248 * @return array An array to be used for JSON
1249 */
1250 protected function getExecuteChangesJsonArray($oldItemList, $newItemList) {
1251 $parent = $this->getStructureLevel(-1);
1252 $current = $this->inlineStructure['unstable'];
1253
1254 $jsonArray = array('scriptCall' => array());
1255 $jsonArrayScriptCall =& $jsonArray['scriptCall'];
1256
1257 $nameObject = $this->inlineNames['object'];
1258 $nameObjectForeignTable = $nameObject . self::Structure_Separator . $current['table'];
1259 // Get the name of the field pointing to the original record:
1260 $transOrigPointerField = $GLOBALS['TCA'][$current['table']]['ctrl']['transOrigPointerField'];
1261 // Get the name of the field used as foreign selector (if any):
1262 $foreignSelector = (isset($parent['config']['foreign_selector']) && $parent['config']['foreign_selector'] ? $parent['config']['foreign_selector'] : false);
1263 // Convert lists to array with uids of child records:
1264 $oldItems = $this->getRelatedRecordsUidArray($oldItemList);
1265 $newItems = $this->getRelatedRecordsUidArray($newItemList);
1266 // Determine the items that were localized or localized:
1267 $removedItems = array_diff($oldItems, $newItems);
1268 $localizedItems = array_diff($newItems, $oldItems);
1269 // Set the items that should be removed in the forms view:
1270 foreach ($removedItems as $item) {
1271 $jsonArrayScriptCall[] = "inline.deleteRecord('".$nameObjectForeignTable . self::Structure_Separator . $item . "', {forceDirectRemoval: true});";
1272 }
1273 // Set the items that should be added in the forms view:
1274 foreach ($localizedItems as $item) {
1275 $row = $this->getRecord($this->inlineFirstPid, $current['table'], $item);
1276 $selectedValue = ($foreignSelector ? "'".$row[$foreignSelector]."'" : 'null');
1277 $data.= $this->renderForeignRecord($parent['uid'], $row, $parent['config']);
1278 $jsonArrayScriptCall[] = "inline.memorizeAddRecord('$nameObjectForeignTable', '".$item."', null, $selectedValue);";
1279 // Remove possible virtual records in the form which showed that a child records could be localized:
1280 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]) {
1281 $jsonArrayScriptCall[] = "inline.fadeAndRemove('" . $nameObjectForeignTable . self::Structure_Separator . $row[$transOrigPointerField] . '_div' . "');";
1282 }
1283 }
1284 if ($data) {
1285 $data = $GLOBALS['LANG']->csConvObj->utf8_encode($data, $GLOBALS['LANG']->charSet);
1286 $jsonArray['data'] = $data;
1287 array_unshift(
1288 $jsonArrayScriptCall,
1289 "inline.domAddNewRecord('bottom', '".$nameObject."_records', '$nameObjectForeignTable', json.data);"
1290 );
1291 }
1292
1293 return $jsonArray;
1294 }
1295
1296
1297 /**
1298 * Save the expanded/collapsed state of a child record in the BE_USER->uc.
1299 *
1300 * @param string $domObjectId: The calling object in hierarchy, that requested a new record.
1301 * @param string $expand: Whether this record is expanded.
1302 * @param string $collapse: Whether this record is collapsed.
1303 * @return void
1304 */
1305 function setExpandedCollapsedState($domObjectId, $expand, $collapse) {
1306 // parse the DOM identifier (string), add the levels to the structure stack (array), but don't load TCA config
1307 $this->parseStructureString($domObjectId, false);
1308 // the current table - for this table we should add/import records
1309 $current = $this->inlineStructure['unstable'];
1310 // the top parent table - this table embeds the current table
1311 $top = $this->getStructureLevel(0);
1312
1313 // only do some action if the top record and the current record were saved before
1314 if (t3lib_div::testInt($top['uid'])) {
1315 $inlineView = (array)unserialize($GLOBALS['BE_USER']->uc['inlineView']);
1316 $inlineViewCurrent =& $inlineView[$top['table']][$top['uid']];
1317
1318 $expandUids = t3lib_div::trimExplode(',', $expand);
1319 $collapseUids = t3lib_div::trimExplode(',', $collapse);
1320
1321 // set records to be expanded
1322 foreach ($expandUids as $uid) {
1323 $inlineViewCurrent[$current['table']][] = $uid;
1324 }
1325 // set records to be collapsed
1326 foreach ($collapseUids as $uid) {
1327 $inlineViewCurrent[$current['table']] = $this->removeFromArray($uid, $inlineViewCurrent[$current['table']]);
1328 }
1329
1330 // save states back to database
1331 if (is_array($inlineViewCurrent[$current['table']])) {
1332 $inlineViewCurrent = array_unique($inlineViewCurrent);
1333 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
1334 $GLOBALS['BE_USER']->writeUC();
1335 }
1336 }
1337 }
1338
1339
1340 /*******************************************************
1341 *
1342 * Get data from database and handle relations
1343 *
1344 *******************************************************/
1345
1346
1347 /**
1348 * Get the related records of the embedding item, this could be 1:n, m:n.
1349 * Returns an associative array with the keys records and count. 'count' contains only real existing records on the current parent record.
1350 *
1351 * @param string $table: The table name of the record
1352 * @param string $field: The field name which this element is supposed to edit
1353 * @param array $row: The record data array where the value(s) for the field can be found
1354 * @param array $PA: An array with additional configuration options.
1355 * @param array $config: (Redundant) content of $PA['fieldConf']['config'] (for convenience)
1356 * @return array The records related to the parent item as associative array.
1357 */
1358 function getRelatedRecords($table, $field, $row, &$PA, $config) {
1359 $records = array();
1360 $pid = $row['pid'];
1361 $elements = $PA['itemFormElValue'];
1362 $foreignTable = $config['foreign_table'];
1363
1364 $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $config);
1365
1366 if ($localizationMode!=false) {
1367 $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
1368 $transOrigPointer = intval($row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
1369 if ($language>0 && $transOrigPointer) {
1370 // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
1371 if ($localizationMode=='keep') {
1372 $transOrigRec = $this->getRecord(0, $table, $transOrigPointer);
1373 $elements = $transOrigRec[$field];
1374 $pid = $transOrigRec['pid'];
1375 // Localization in modes 'select', 'all' or 'sync' offer a dynamic localization and synchronization with the original language record:
1376 } elseif ($localizationMode=='select') {
1377 $transOrigRec = $this->getRecord(0, $table, $transOrigPointer);
1378 $pid = $transOrigRec['pid'];
1379 $recordsOriginal = $this->getRelatedRecordsArray($pid, $foreignTable, $transOrigRec[$field]);
1380 }
1381 }
1382 }
1383
1384 $records = $this->getRelatedRecordsArray($pid, $foreignTable, $elements);
1385 $relatedRecords = array('records' => $records, 'count' => count($records));
1386
1387 // Merge original language with current localization and show differences:
1388 if (is_array($recordsOriginal)) {
1389 $options = array(
1390 'showPossible' => (isset($config['appearance']['showPossibleLocalizationRecords']) && $config['appearance']['showPossibleLocalizationRecords']),
1391 'showRemoved' => (isset($config['appearance']['showRemovedLocalizationRecords']) && $config['appearance']['showRemovedLocalizationRecords']),
1392 );
1393 if ($options['showPossible'] || $options['showRemoved']) {
1394 $relatedRecords['records'] = $this->getLocalizationDifferences($foreignTable, $options, $recordsOriginal, $records);
1395 }
1396 }
1397
1398 return $relatedRecords;
1399 }
1400
1401
1402 /**
1403 * Gets the related records of the embedding item, this could be 1:n, m:n.
1404 *
1405 * @param integer $pid: The pid of the parent record
1406 * @param string $table: The table name of the record
1407 * @param string $itemList: The list of related child records
1408 * @return array The records related to the parent item
1409 */
1410 protected function getRelatedRecordsArray($pid, $table, $itemList) {
1411 $records = array();
1412 $itemArray = $this->getRelatedRecordsUidArray($itemList);
1413 // Perform modification of the selected items array:
1414 foreach($itemArray as $uid) {
1415 // Get the records for this uid using t3lib_transferdata:
1416 if ($record = $this->getRecord($pid, $table, $uid)) {
1417 $records[$uid] = $record;
1418 }
1419 }
1420 return $records;
1421 }
1422
1423
1424 /**
1425 * Gets an array with the uids of related records out of a list of items.
1426 * This list could contain more information than required. This methods just
1427 * extracts the uids.
1428 *
1429 * @param string $itemList: The list of related child records
1430 * @return array An array with uids
1431 */
1432 protected function getRelatedRecordsUidArray($itemList) {
1433 $itemArray = t3lib_div::trimExplode(',', $itemList, 1);
1434 // Perform modification of the selected items array:
1435 foreach($itemArray as $key => &$value) {
1436 $parts = explode('|', $value, 2);
1437 $value = $parts[0];
1438 }
1439 return $itemArray;
1440 }
1441
1442
1443 /**
1444 * Gets the difference between current localized structure and the original language structure.
1445 * If there are records which once were localized but don't exist in the original version anymore, the record row is marked with '__remove'.
1446 * If there are records which can be localized and exist only in the original version, the record row is marked with '__create' and '__virtual'.
1447 *
1448 * @param string $table: The table name of the parent records
1449 * @param array $options: Options defining what kind of records to display
1450 * @param array $recordsOriginal: The uids of the child records of the original language
1451 * @param array $recordsLocalization: The uids of the child records of the current localization
1452 * @return array Merged array of uids of the child records of both versions
1453 */
1454 protected function getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization) {
1455 $records = array();
1456 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1457 // Compare original to localized version of the records:
1458 foreach ($recordsLocalization as $uid => $row) {
1459 // If the record points to a original translation which doesn't exist anymore, it could be removed:
1460 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]>0) {
1461 $transOrigPointer = $row[$transOrigPointerField];
1462 if (isset($recordsOriginal[$transOrigPointer])) {
1463 unset($recordsOriginal[$transOrigPointer]);
1464 } elseif ($options['showRemoved']) {
1465 $row['__remove'] = true;
1466 }
1467 }
1468 $records[$uid] = $row;
1469 }
1470 // Process the remaining records in the original unlocalized parent:
1471 if ($options['showPossible']) {
1472 foreach ($recordsOriginal as $uid => $row) {
1473 $row['__create'] = true;
1474 $row['__virtual'] = true;
1475 $records[$uid] = $row;
1476 }
1477 }
1478 return $records;
1479 }
1480
1481
1482 /**
1483 * Get possible records.
1484 * Copied from TCEform and modified.
1485 *
1486 * @param string The table name of the record
1487 * @param string The field name which this element is supposed to edit
1488 * @param array The record data array where the value(s) for the field can be found
1489 * @param array An array with additional configuration options.
1490 * @param string $checkForConfField: For which field in the foreign_table the possible records should be fetched
1491 * @return mixed Array of possible record items; false if type is "group/db", then everything could be "possible"
1492 */
1493 function getPossibleRecords($table,$field,$row,$conf,$checkForConfField='foreign_selector') {
1494 // ctrl configuration from TCA:
1495 $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
1496 // Field configuration from TCA:
1497 $foreign_table = $conf['foreign_table'];
1498 $foreign_check = $conf[$checkForConfField];
1499
1500 $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
1501 $PA = $foreignConfig['PA'];
1502 $config = $PA['fieldConf']['config'];
1503
1504 if ($foreignConfig['type'] == 'select') {
1505 // Getting the selector box items from the system
1506 $selItems = $this->fObj->addSelectOptionsToItemArray(
1507 $this->fObj->initItemArray($PA['fieldConf']),
1508 $PA['fieldConf'],
1509 $this->fObj->setTSconfig($table, $row),
1510 $field
1511 );
1512 // Possibly filter some items:
1513 $keepItemsFunc = create_function('$value', 'return $value[1];');
1514 $selItems = t3lib_div::keepItemsInArray($selItems, $PA['fieldTSConfig']['keepItems'], $keepItemsFunc);
1515 // Possibly add some items:
1516 $selItems = $this->fObj->addItems($selItems, $PA['fieldTSConfig']['addItems.']);
1517 if (isset($config['itemsProcFunc']) && $config['itemsProcFunc']) {
1518 $selItems = $this->fObj->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
1519 }
1520
1521 // Possibly remove some items:
1522 $removeItems = t3lib_div::trimExplode(',',$PA['fieldTSConfig']['removeItems'],1);
1523 foreach($selItems as $tk => $p) {
1524
1525 // Checking languages and authMode:
1526 $languageDeny = $tcaTableCtrl['languageField'] && !strcmp($tcaTableCtrl['languageField'], $field) && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
1527 $authModeDeny = $config['form_type']=='select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table,$field,$p[1],$config['authMode']);
1528 if (in_array($p[1],$removeItems) || $languageDeny || $authModeDeny) {
1529 unset($selItems[$tk]);
1530 } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
1531 $selItems[$tk][0]=$this->fObj->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]);
1532 }
1533
1534 // Removing doktypes with no access:
1535 if ($table.'.'.$field == 'pages.doktype') {
1536 if (!($GLOBALS['BE_USER']->isAdmin() || t3lib_div::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'],$p[1]))) {
1537 unset($selItems[$tk]);
1538 }
1539 }
1540 }
1541 } else {
1542 $selItems = false;
1543 }
1544
1545 return $selItems;
1546 }
1547
1548 /**
1549 * Gets the uids of a select/selector that should be unique an have already been used.
1550 *
1551 * @param array $records: All inline records on this level
1552 * @param array $conf: The TCA field configuration of the inline field to be rendered
1553 * @param boolean $splitValue: for usage with group/db, values come like "tx_table_123|Title%20abc", but we need "tx_table" and "123"
1554 * @return array The uids, that have been used already and should be used unique
1555 */
1556 function getUniqueIds($records, $conf=array(), $splitValue=false) {
1557 $uniqueIds = array();
1558
1559 if (isset($conf['foreign_unique']) && $conf['foreign_unique'] && count($records)) {
1560 foreach ($records as $rec) {
1561 // Skip virtual records (e.g. shown in localization mode):
1562 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
1563 $value = $rec[$conf['foreign_unique']];
1564 // Split the value and extract the table and uid:
1565 if ($splitValue) {
1566 $valueParts = t3lib_div::trimExplode('|', $value);
1567 $itemParts = explode('_', $valueParts[0]);
1568 $value = array(
1569 'uid' => array_pop($itemParts),
1570 'table' => implode('_', $itemParts)
1571 );
1572 }
1573 $uniqueIds[$rec['uid']] = $value;
1574 }
1575 }
1576 }
1577
1578 return $uniqueIds;
1579 }
1580
1581
1582 /**
1583 * Determines the corrected pid to be used for a new record.
1584 * The pid to be used can be defined by a Page TSconfig.
1585 *
1586 * @param string $table: The table name
1587 * @param integer $parentPid: The pid of the parent record
1588 * @return integer The corrected pid to be used for a new record
1589 */
1590 protected function getNewRecordPid($table, $parentPid=null) {
1591 $newRecordPid = $this->inlineFirstPid;
1592 $pageTS = t3lib_beFunc::getPagesTSconfig($parentPid, true);
1593 if (isset($pageTS['TCAdefaults.'][$table.'.']['pid']) && t3lib_div::testInt($pageTS['TCAdefaults.'][$table.'.']['pid'])) {
1594 $newRecordPid = $pageTS['TCAdefaults.'][$table.'.']['pid'];
1595 } elseif (isset($parentPid) && t3lib_div::testInt($parentPid)) {
1596 $newRecordPid = $parentPid;
1597 }
1598 return $newRecordPid;
1599 }
1600
1601
1602 /**
1603 * Get a single record row for a TCA table from the database.
1604 * t3lib_transferData is used for "upgrading" the values, especially the relations.
1605 *
1606 * @param integer $pid: The pid of the page the record should be stored (only relevant for NEW records)
1607 * @param string $table: The table to fetch data from (= foreign_table)
1608 * @param string $uid: The uid of the record to fetch, or the pid if a new record should be created
1609 * @param string $cmd: The command to perform, empty or 'new'
1610 * @return array A record row from the database post-processed by t3lib_transferData
1611 */
1612 function getRecord($pid, $table, $uid, $cmd='') {
1613 $trData = t3lib_div::makeInstance('t3lib_transferData');
1614 $trData->addRawData = TRUE;
1615 $trData->lockRecords=1;
1616 $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1617 // if a new record should be created
1618 $trData->fetchRecord($table, $uid, ($cmd === 'new' ? 'new' : ''));
1619 reset($trData->regTableItems_data);
1620 $rec = current($trData->regTableItems_data);
1621
1622 return $rec;
1623 }
1624
1625
1626 /**
1627 * Wrapper. Calls getRecord in case of a new record should be created.
1628 *
1629 * @param integer $pid: The pid of the page the record should be stored (only relevant for NEW records)
1630 * @param string $table: The table to fetch data from (= foreign_table)
1631 * @return array A record row from the database post-processed by t3lib_transferData
1632 */
1633 function getNewRecord($pid, $table) {
1634 $rec = $this->getRecord($pid, $table, $pid, 'new');
1635 $rec['uid'] = uniqid('NEW');
1636 $rec['pid'] = $this->getNewRecordPid($table, $pid);
1637 return $rec;
1638 }
1639
1640
1641 /*******************************************************
1642 *
1643 * Structure stack for handling inline objects/levels
1644 *
1645 *******************************************************/
1646
1647
1648 /**
1649 * Add a new level on top of the structure stack. Other functions can access the
1650 * stack and determine, if there's possibly a endless loop.
1651 *
1652 * @param string $table: The table name of the record
1653 * @param string $uid: The uid of the record that embeds the inline data
1654 * @param string $field: The field name which this element is supposed to edit
1655 * @param array $config: The TCA-configuration of the inline field
1656 * @return void
1657 */
1658 function pushStructure($table, $uid, $field = '', $config = array()) {
1659 $this->inlineStructure['stable'][] = array(
1660 'table' => $table,
1661 'uid' => $uid,
1662 'field' => $field,
1663 'config' => $config,
1664 'localizationMode' => t3lib_BEfunc::getInlineLocalizationMode($table, $config),
1665 );
1666 $this->updateStructureNames();
1667 }
1668
1669
1670 /**
1671 * Remove the item on top of the structure stack and return it.
1672 *
1673 * @return array The top item of the structure stack - array(<table>,<uid>,<field>,<config>)
1674 */
1675 function popStructure() {
1676 if (count($this->inlineStructure['stable'])) {
1677 $popItem = array_pop($this->inlineStructure['stable']);
1678 $this->updateStructureNames();
1679 }
1680 return $popItem;
1681 }
1682
1683
1684 /**
1685 * For common use of DOM object-ids and form field names of a several inline-level,
1686 * these names/identifiers are preprocessed and set to $this->inlineNames.
1687 * This function is automatically called if a level is pushed to or removed from the
1688 * inline structure stack.
1689 *
1690 * @return void
1691 */
1692 function updateStructureNames() {
1693 $current = $this->getStructureLevel(-1);
1694 // if there are still more inline levels available
1695 if ($current !== false) {
1696 $this->inlineNames = array(
1697 'form' => $this->prependFormFieldNames . $this->getStructureItemName($current, self::Disposal_AttributeName),
1698 'object' => $this->prependNaming . self::Structure_Separator . $this->inlineFirstPid . self::Structure_Separator . $this->getStructurePath(),
1699 );
1700 // if there are no more inline levels available
1701 } else {
1702 $this->inlineNames = array();
1703 }
1704 }
1705
1706
1707 /**
1708 * Create a name/id for usage in HTML output of a level of the structure stack to be used in form names.
1709 *
1710 * @param array $levelData: Array of a level of the structure stack (containing the keys table, uid and field)
1711 * @param string $disposal: How the structure name is used (e.g. as <div id="..."> or <input name="..." />)
1712 * @return string The name/id of that level, to be used for HTML output
1713 */
1714 function getStructureItemName($levelData, $disposal = self::Disposal_AttributeId) {
1715 if (is_array($levelData)) {
1716 $parts = array($levelData['table'], $levelData['uid']);
1717 if (isset($levelData['field'])) {
1718 $parts[] = $levelData['field'];
1719 }
1720
1721 // Use in name attributes:
1722 if ($disposal === self::Disposal_AttributeName) {
1723 $name = '[' . implode('][', $parts) . ']';
1724 // Use in id attributes:
1725 } else {
1726 $name = implode(self::Structure_Separator, $parts);
1727 }
1728 }
1729 return $name;
1730 }
1731
1732
1733 /**
1734 * Get a level from the stack and return the data.
1735 * If the $level value is negative, this function works top-down,
1736 * if the $level value is positive, this function works bottom-up.
1737 *
1738 * @param integer $level: Which level to return
1739 * @return array The item of the stack at the requested level
1740 */
1741 function getStructureLevel($level) {
1742 $inlineStructureCount = count($this->inlineStructure['stable']);
1743 if ($level < 0) $level = $inlineStructureCount+$level;
1744 if ($level >= 0 && $level < $inlineStructureCount)
1745 return $this->inlineStructure['stable'][$level];
1746 else
1747 return false;
1748 }
1749
1750
1751 /**
1752 * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
1753 * An identifier looks like "<table>-<uid>-<field>".
1754 *
1755 * @param integer $structureDepth: How much levels to output, beginning from the top of the stack
1756 * @return string The path of identifiers
1757 */
1758 function getStructurePath($structureDepth = -1) {
1759 $structureLevels = array();
1760 $structureCount = count($this->inlineStructure['stable']);
1761
1762 if ($structureDepth < 0 || $structureDepth > $structureCount) {
1763 $structureDepth = $structureCount;
1764 }
1765
1766 for ($i = 1; $i <= $structureDepth; $i++) {
1767 array_unshift(
1768 $structureLevels,
1769 $this->getStructureItemName(
1770 $this->getStructureLevel(-$i),
1771 self::Disposal_AttributeId
1772 )
1773 );
1774 }
1775
1776 return implode(self::Structure_Separator, $structureLevels);
1777 }
1778
1779
1780 /**
1781 * Convert the DOM object-id of an inline container to an array.
1782 * The object-id could look like 'data-parentPageId-tx_mmftest_company-1-employees'.
1783 * The result is written to $this->inlineStructure.
1784 * There are two keys:
1785 * - 'stable': Containing full qualified identifiers (table, uid and field)
1786 * - 'unstable': Containting partly filled data (e.g. only table and possibly field)
1787 *
1788 * @param string $domObjectId: The DOM object-id
1789 * @param boolean $loadConfig: Load the TCA configuration for that level (default: true)
1790 * @return void
1791 */
1792 function parseStructureString($string, $loadConfig=true) {
1793 $unstable = array();
1794 $vector = array('table', 'uid', 'field');
1795 $pattern = '/^' . $this->prependNaming . self::Structure_Separator . '(.+?)' . self::Structure_Separator . '(.+)$/';
1796 if (preg_match($pattern, $string, $match)) {
1797 $this->inlineFirstPid = $match[1];
1798 $parts = explode(self::Structure_Separator, $match[2]);
1799 $partsCnt = count($parts);
1800 for ($i = 0; $i < $partsCnt; $i++) {
1801 if ($i > 0 && $i % 3 == 0) {
1802 // load the TCA configuration of the table field and store it in the stack
1803 if ($loadConfig) {
1804 t3lib_div::loadTCA($unstable['table']);
1805 $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
1806 // Fetch TSconfig:
1807 $TSconfig = $this->fObj->setTSconfig(
1808 $unstable['table'],
1809 array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid),
1810 $unstable['field']
1811 );
1812 // Override TCA field config by TSconfig:
1813 if (!$TSconfig['disabled']) {
1814 $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
1815 }
1816 $unstable['localizationMode'] = t3lib_BEfunc::getInlineLocalizationMode($unstable['table'], $unstable['config']);
1817 }
1818 $this->inlineStructure['stable'][] = $unstable;
1819 $unstable = array();
1820 }
1821 $unstable[$vector[$i % 3]] = $parts[$i];
1822 }
1823 $this->updateStructureNames();
1824 if (count($unstable)) $this->inlineStructure['unstable'] = $unstable;
1825 }
1826 }
1827
1828
1829 /*******************************************************
1830 *
1831 * Helper functions
1832 *
1833 *******************************************************/
1834
1835
1836 /**
1837 * Does some checks on the TCA configuration of the inline field to render.
1838 *
1839 * @param array $config: Reference to the TCA field configuration
1840 * @param string $table: The table name of the record
1841 * @param string $field: The field name which this element is supposed to edit
1842 * @param array $row: The record data array of the parent
1843 * @return boolean If critical configuration errors were found, false is returned
1844 */
1845 function checkConfiguration(&$config) {
1846 $foreign_table = $config['foreign_table'];
1847
1848 // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
1849 if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
1850 return false;
1851 }
1852 // Init appearance if not set:
1853 if (!isset($config['appearance']) || !is_array($config['appearance'])) {
1854 $config['appearance'] = array();
1855 }
1856 // 'newRecordLinkPosition' is deprecated since TYPO3 4.2.0-beta1, this is for backward compatibility:
1857 if (!isset($config['appearance']['levelLinksPosition']) && isset($config['appearance']['newRecordLinkPosition']) && $config['appearance']['newRecordLinkPosition']) {
1858 t3lib_div::deprecationLog('TCA contains a deprecated definition using "newRecordLinkPosition"');
1859 $config['appearance']['levelLinksPosition'] = $config['appearance']['newRecordLinkPosition'];
1860 }
1861 // Set the position/appearance of the "Create new record" link:
1862 if (isset($config['foreign_selector']) && $config['foreign_selector'] && (!isset($config['appearance']['useCombination']) || !$config['appearance']['useCombination'])) {
1863 $config['appearance']['levelLinksPosition'] = 'none';
1864 } elseif (!isset($config['appearance']['levelLinksPosition']) || !in_array($config['appearance']['levelLinksPosition'], array('top', 'bottom', 'both', 'none'))) {
1865 $config['appearance']['levelLinksPosition'] = 'top';
1866 }
1867 // Defines which controls should be shown in header of each record:
1868 $enabledControls = array(
1869 'info' => true,
1870 'new' => true,
1871 'dragdrop' => true,
1872 'sort' => true,
1873 'hide' => true,
1874 'delete' => true,
1875 'localize' => true,
1876 );
1877 if (isset($config['appearance']['enabledControls']) && is_array($config['appearance']['enabledControls'])) {
1878 $config['appearance']['enabledControls'] = array_merge($enabledControls, $config['appearance']['enabledControls']);
1879 } else {
1880 $config['appearance']['enabledControls'] = $enabledControls;
1881 }
1882
1883 return true;
1884 }
1885
1886
1887 /**
1888 * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
1889 * as well as the table access rights of the user.
1890 *
1891 * @param string $cmd: The command that sould be performed ('new' or 'edit')
1892 * @param string $table: The table to check access for
1893 * @param string $theUid: The record uid of the table
1894 * @return boolean Returns true is the user has access, or false if not
1895 */
1896 function checkAccess($cmd, $table, $theUid) {
1897 // 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...)
1898 // First, resetting flags.
1899 $hasAccess = 0;
1900 $deniedAccessReason = '';
1901
1902 // Admin users always have acces:
1903 if ($GLOBALS['BE_USER']->isAdmin()) {
1904 return true;
1905 }
1906 // If the command is to create a NEW record...:
1907 if ($cmd=='new') {
1908 // If the pid is numerical, check if it's possible to write to this page:
1909 if (t3lib_div::testInt($this->inlineFirstPid)) {
1910 $calcPRec = t3lib_BEfunc::getRecord('pages', $this->inlineFirstPid);
1911 if(!is_array($calcPRec)) {
1912 return false;
1913 }
1914 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec); // Permissions for the parent page
1915 if ($table=='pages') { // If pages:
1916 $hasAccess = $CALC_PERMS&8 ? 1 : 0; // Are we allowed to create new subpages?
1917 } else {
1918 $hasAccess = $CALC_PERMS&16 ? 1 : 0; // Are we allowed to edit content on this page?
1919 }
1920 // If the pid is a NEW... value, the access will be checked on creating the page:
1921 // (if the page with the same NEW... value could be created in TCEmain, this child record can neither)
1922 } else {
1923 $hasAccess = 1;
1924 }
1925 } else { // Edit:
1926 $calcPRec = t3lib_BEfunc::getRecord($table,$theUid);
1927 t3lib_BEfunc::fixVersioningPid($table,$calcPRec);
1928 if (is_array($calcPRec)) {
1929 if ($table=='pages') { // If pages:
1930 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
1931 $hasAccess = $CALC_PERMS&2 ? 1 : 0;
1932 } else {
1933 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages',$calcPRec['pid'])); // Fetching pid-record first.
1934 $hasAccess = $CALC_PERMS&16 ? 1 : 0;
1935 }
1936
1937 // Check internals regarding access:
1938 if ($hasAccess) {
1939 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
1940 }
1941 }
1942 }
1943
1944 if(!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
1945 $hasAccess = 0;
1946 }
1947
1948 if(!$hasAccess) {
1949 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
1950 if($deniedAccessReason) {
1951 debug($deniedAccessReason);
1952 }
1953 }
1954
1955 return $hasAccess ? true : false;
1956 }
1957
1958
1959 /**
1960 * Check the keys and values in the $compare array against the ['config'] part of the top level of the stack.
1961 * A boolean value is return depending on how the comparison was successful.
1962 *
1963 * @param array $compare: keys and values to compare to the ['config'] part of the top level of the stack
1964 * @return boolean Whether the comparison was successful
1965 * @see arrayCompareComplex
1966 */
1967 function compareStructureConfiguration($compare) {
1968 $level = $this->getStructureLevel(-1);
1969 $result = $this->arrayCompareComplex($level, $compare);
1970
1971 return $result;
1972 }
1973
1974
1975 /**
1976 * Normalize a relation "uid" published by transferData, like "1|Company%201"
1977 *
1978 * @param string $string: A transferData reference string, containing the uid
1979 * @return string The normalized uid
1980 */
1981 function normalizeUid($string) {
1982 $parts = explode('|', $string);
1983 return $parts[0];
1984 }
1985
1986
1987 /**
1988 * Wrap the HTML code of a section with a table tag.
1989 *
1990 * @param string $section: The HTML code to be wrapped
1991 * @param array $styleAttrs: Attributes for the style argument in the table tag
1992 * @param array $tableAttrs: Attributes for the table tag (like width, border, etc.)
1993 * @return string The wrapped HTML code
1994 */
1995 function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
1996 if (!$styleAttrs['margin-right']) $styleAttrs['margin-right'] = $this->inlineStyles['margin-right'].'px';
1997
1998 foreach ($styleAttrs as $key => $value) $style .= ($style?' ':'').$key.': '.htmlspecialchars($value).'; ';
1999 if ($style) $style = ' style="'.$style.'"';
2000
2001 if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) $tableAttrs['background'] = $this->backPath.$this->borderStyle[2];
2002 if (!$tableAttrs['cellspacing']) $tableAttrs['cellspacing'] = '0';
2003 if (!$tableAttrs['cellpadding']) $tableAttrs['cellpadding'] = '0';
2004 if (!$tableAttrs['border']) $tableAttrs['border'] = '0';
2005 if (!$tableAttrs['width']) $tableAttrs['width'] = '100%';
2006 if (!$tableAttrs['class'] && $this->borderStyle[3]) $tableAttrs['class'] = $this->borderStyle[3];
2007
2008 foreach ($tableAttrs as $key => $value) $table .= ($table?' ':'').$key.'="'.htmlspecialchars($value).'"';
2009
2010 $out = '<table '.$table.$style.'>'.$section.'</table>';
2011 return $out;
2012 }
2013
2014
2015 /**
2016 * Checks if the $table is the child of a inline type AND the $field is the label field of this table.
2017 * This function is used to dynamically update the label while editing. This has no effect on labels,
2018 * that were processed by a TCEmain-hook on saving.
2019 *
2020 * @param string $table: The table to check
2021 * @param string $field: The field on this table to check
2022 * @return boolean is inline child and field is responsible for the label
2023 */
2024 function isInlineChildAndLabelField($table, $field) {
2025 $level = $this->getStructureLevel(-1);
2026 if ($level['config']['foreign_label'])
2027 $label = $level['config']['foreign_label'];
2028 else
2029 $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
2030 return $level['config']['foreign_table'] === $table && $label == $field ? true : false;
2031 }
2032
2033
2034 /**
2035 * Get the depth of the stable structure stack.
2036 * (count($this->inlineStructure['stable'])
2037 *
2038 * @return integer The depth of the structure stack
2039 */
2040 function getStructureDepth() {
2041 return count($this->inlineStructure['stable']);
2042 }
2043
2044
2045 /**
2046 * Handles complex comparison requests on an array.
2047 * A request could look like the following:
2048 *
2049 * $searchArray = array(
2050 * '%AND' => array(
2051 * 'key1' => 'value1',
2052 * 'key2' => 'value2',
2053 * '%OR' => array(
2054 * 'subarray' => array(
2055 * 'subkey' => 'subvalue'
2056 * ),
2057 * 'key3' => 'value3',
2058 * 'key4' => 'value4'
2059 * )
2060 * )
2061 * );
2062 *
2063 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
2064 * overwriting the sub-array. It could be neccessary, if you use complex comparisons.
2065 *
2066 * The example above means, key1 *AND* key2 (and their values) have to match with
2067 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
2068 * condition.
2069 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
2070 * function recurses down one level in that sub-array.
2071 *
2072 * @param array $subjectArray: The array to search in
2073 * @param array $searchArray: The array with keys and values to search for
2074 * @param string $type: Use '%AND' or '%OR' for comparision
2075 * @return boolean The result of the comparison
2076 */
2077 function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
2078 $localMatches = 0;
2079 $localEntries = 0;
2080
2081 if (is_array($searchArray) && count($searchArray)) {
2082 // if no type was passed, try to determine
2083 if (!$type) {
2084 reset($searchArray);
2085 $type = key($searchArray);
2086 $searchArray = current($searchArray);
2087 }
2088
2089 // we use '%AND' and '%OR' in uppercase
2090 $type = strtoupper($type);
2091
2092 // split regular elements from sub elements
2093 foreach ($searchArray as $key => $value) {
2094 $localEntries++;
2095
2096 // process a sub-group of OR-conditions
2097 if ($key == '%OR') {
2098 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
2099 // process a sub-group of AND-conditions
2100 } elseif ($key == '%AND') {
2101 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
2102 // a part of an associative array should be compared, so step down in the array hierarchy
2103 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
2104 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
2105 // it is a normal array that is only used for grouping and indexing
2106 } elseif (is_array($value)) {
2107 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
2108 // directly compare a value
2109 } else {
2110 if (isset($subjectArray[$key]) && isset($value)) {
2111 // Boolean match:
2112 if (is_bool($value)) {
2113 $localMatches += (!($subjectArray[$key] xor $value) ? 1 : 0);
2114 // Value match for numbers:
2115 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
2116 $localMatches += ($subjectArray[$key] == $value ? 1 : 0);
2117 // Value and type match:
2118 } else {
2119 $localMatches += ($subjectArray[$key] === $value ? 1 : 0);
2120 }
2121 }
2122 }
2123
2124 // if one or more matches are required ('OR'), return true after the first successful match
2125 if ($type == '%OR' && $localMatches > 0) return true;
2126 // if all matches are required ('AND') and we have no result after the first run, return false
2127 if ($type == '%AND' && $localMatches == 0) return false;
2128 }
2129 }
2130
2131 // return the result for '%AND' (if nothing was checked, true is returned)
2132 return $localEntries == $localMatches ? true : false;
2133 }
2134
2135
2136 /**
2137 * Checks whether an object is an associative array.
2138 *
2139 * @param mixed $object: The object to be checked
2140 * @return boolean Returns true, if the object is an associative array
2141 */
2142 function isAssociativeArray($object) {
2143 return is_array($object) && count($object) && (array_keys($object) !== range(0, sizeof($object) - 1))
2144 ? true
2145 : false;
2146 }
2147
2148
2149 /**
2150 * Remove an element from an array.
2151 *
2152 * @param mixed $needle: The element to be removed.
2153 * @param array $haystack: The array the element should be removed from.
2154 * @param mixed $strict: Search elements strictly.
2155 * @return array The array $haystack without the $needle
2156 */
2157 function removeFromArray($needle, $haystack, $strict=null) {
2158 $pos = array_search($needle, $haystack, $strict);
2159 if ($pos !== false) unset($haystack[$pos]);
2160 return $haystack;
2161 }
2162
2163
2164 /**
2165 * Makes a flat array from the $possibleRecords array.
2166 * The key of the flat array is the value of the record,
2167 * the value of the flat array is the label of the record.
2168 *
2169 * @param array $possibleRecords: The possibleRecords array (for select fields)
2170 * @return mixed A flat array with key=uid, value=label; if $possibleRecords isn't an array, false is returned.
2171 */
2172 function getPossibleRecordsFlat($possibleRecords) {
2173 $flat = false;
2174 if (is_array($possibleRecords)) {
2175 $flat = array();
2176 foreach ($possibleRecords as $record) $flat[$record[1]] = $record[0];
2177 }
2178 return $flat;
2179 }
2180
2181
2182 /**
2183 * Determine the configuration and the type of a record selector.
2184 *
2185 * @param array $conf: TCA configuration of the parent(!) field
2186 * @return array Associative array with the keys 'PA' and 'type', both are false if the selector was not valid.
2187 */
2188 function getPossibleRecordsSelectorConfig($conf, $field = '') {
2189 $foreign_table = $conf['foreign_table'];
2190 $foreign_selector = $conf['foreign_selector'];
2191
2192 $PA = false;
2193 $type = false;
2194 $table = false;
2195 $selector = false;
2196
2197 if ($field) {
2198 $PA = array();
2199 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
2200 $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
2201 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table,array(),$field);
2202 $config = $PA['fieldConf']['config'];
2203 // Determine type of Selector:
2204 $type = $this->getPossibleRecordsSelectorType($config);
2205 // Return table on this level:
2206 $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
2207 // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
2208 if ($foreign_selector && $foreign_selector == $field && $type) {
2209 $selector = $type;
2210 }
2211 }
2212
2213 return array(
2214 'PA' => $PA,
2215 'type' => $type,
2216 'table' => $table,
2217 'selector' => $selector,
2218 );
2219 }
2220
2221
2222 /**
2223 * Determine the type of a record selector, e.g. select or group/db.
2224 *
2225 * @param array $config: TCE configuration of the selector
2226 * @return mixed The type of the selector, 'select' or 'groupdb' - false not valid
2227 */
2228 function getPossibleRecordsSelectorType($config) {
2229 $type = false;
2230 if ($config['type'] == 'select') {
2231 $type = 'select';
2232 } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
2233 $type = 'groupdb';
2234 }
2235 return $type;
2236 }
2237
2238
2239 /**
2240 * Check, if a field should be skipped, that was defined to be handled as foreign_field or foreign_sortby of
2241 * the parent record of the "inline"-type - if so, we have to skip this field - the rendering is done via "inline" as hidden field
2242 *
2243 * @param string $table: The table name
2244 * @param string $field: The field name
2245 * @param array $row: The record row from the database
2246 * @param array $config: TCA configuration of the field
2247 * @return boolean Determines whether the field should be skipped.
2248 */
2249 function skipField($table, $field, $row, $config) {
2250 $skipThisField = false;
2251
2252 if ($this->getStructureDepth()) {
2253 $searchArray = array(
2254 '%OR' => array(
2255 'config' => array(
2256 0 => array(
2257 '%AND' => array(
2258 'foreign_table' => $table,
2259 '%OR' => array(
2260 '%AND' => array(
2261 'appearance' => array('useCombination' => true),
2262 'foreign_selector' => $field,
2263 ),
2264 'MM' => $config['MM']
2265 ),
2266 ),
2267 ),
2268 1 => array(
2269 '%AND' => array(
2270 'foreign_table' => $config['foreign_table'],
2271 'foreign_selector' => $config['foreign_field'],
2272 ),
2273 ),
2274 ),
2275 ),
2276 );
2277
2278 // get the parent record from structure stack
2279 $level = $this->getStructureLevel(-1);
2280
2281 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
2282 if (t3lib_loadDBGroup::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
2283 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
2284 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
2285 // Hide fields, that are set automatically:
2286 } else {
2287 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
2288 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
2289 }
2290
2291 $skipThisField = $this->compareStructureConfiguration($searchArray, true);
2292 }
2293
2294 return $skipThisField;
2295 }
2296
2297
2298 /**
2299 * Creates recursively a JSON literal from a mulidimensional associative array.
2300 * Uses Services_JSON (http://mike.teczno.com/JSON/doc/)
2301 *
2302 * @param array $jsonArray: The array (or part of) to be transformed to JSON
2303 * @return string If $level>0: part of JSON literal; if $level==0: whole JSON literal wrapped with <script> tags
2304 * @deprecated Since TYPO3 4.2: Moved to t3lib_div::array2json, will be removed in TYPO3 4.4
2305 */
2306 function getJSON($jsonArray) {
2307 t3lib_div::logDeprecatedFunction();
2308
2309 return json_encode($jsonArray);
2310 }
2311
2312
2313 /**
2314 * Checks if a uid of a child table is in the inline view settings.
2315 *
2316 * @param string $table: Name of the child table
2317 * @param integer $uid: uid of the the child record
2318 * @return boolean true=expand, false=collapse
2319 */
2320 function getExpandedCollapsedState($table, $uid) {
2321 if (isset($this->inlineView[$table]) && is_array($this->inlineView[$table])) {
2322 if (in_array($uid, $this->inlineView[$table]) !== false) {
2323 return true;
2324 }
2325 }
2326 return false;
2327 }
2328
2329
2330 /**
2331 * Update expanded/collapsed states on new inline records if any.
2332 *
2333 * @param array $uc: The uc array to be processed and saved (by reference)
2334 * @param t3lib_TCEmain $tce: Instance of TCEmain that saved data before
2335 * @return void
2336 */
2337 function updateInlineView(&$uc, $tce) {
2338 if (isset($uc['inlineView']) && is_array($uc['inlineView'])) {
2339 $inlineView = (array)unserialize($GLOBALS['BE_USER']->uc['inlineView']);
2340
2341 foreach ($uc['inlineView'] as $topTable => $topRecords) {
2342 foreach ($topRecords as $topUid => $childElements) {
2343 foreach ($childElements as $childTable => $childRecords) {
2344 $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
2345 if (count($uids)) {
2346 $newExpandedChildren = array();
2347 foreach ($childRecords as $childUid => $state) {
2348 if ($state && in_array($childUid, $uids)) {
2349 $newChildUid = $tce->substNEWwithIDs[$childUid];
2350 $newExpandedChildren[] = $newChildUid;
2351 }
2352 }
2353 // Add new expanded child records to UC (if any):
2354 if (count($newExpandedChildren)) {
2355 $inlineViewCurrent =& $inlineView[$topTable][$topUid][$childTable];
2356 if (is_array($inlineViewCurrent)) {
2357 $inlineViewCurrent = array_unique(array_merge($inlineViewCurrent, $newExpandedChildren));
2358 } else {
2359 $inlineViewCurrent = $newExpandedChildren;
2360 }
2361 }
2362 }
2363 }
2364 }
2365 }
2366
2367 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
2368 $GLOBALS['BE_USER']->writeUC();
2369 }
2370 }
2371
2372
2373 /**
2374 * Returns the the margin in pixels, that is used for each new inline level.
2375 *
2376 * @return integer A pixel value for the margin of each new inline level.
2377 */
2378 function getLevelMargin() {
2379 $margin = ($this->inlineStyles['margin-right']+1)*2;
2380 return $margin;
2381 }
2382
2383 /**
2384 * Parses the HTML tags that would have been inserted to the <head> of a HTML document and returns the found tags as multidimensional array.
2385 *
2386 * @return array The parsed tags with their attributes and innerHTML parts
2387 */
2388 protected function getHeadTags() {
2389 $headTags = array();
2390 $headDataRaw = $this->fObj->JStop();
2391
2392 if ($headDataRaw) {
2393 // Create instance of the HTML parser:
2394 $parseObj = t3lib_div::makeInstance('t3lib_parsehtml');
2395 // Removes script wraps:
2396 $headDataRaw = str_replace(array('/*<![CDATA[*/', '/*]]>*/'), '', $headDataRaw);
2397 // Removes leading spaces of a multiline string:
2398 $headDataRaw = trim(preg_replace('/(^|\r|\n)( |\t)+/', '$1', $headDataRaw));
2399 // Get script and link tags:
2400 $tags = array_merge(
2401 $parseObj->getAllParts($parseObj->splitTags('link', $headDataRaw)),
2402 $parseObj->getAllParts($parseObj->splitIntoBlock('script', $headDataRaw))
2403 );
2404
2405 foreach ($tags as $tagData) {
2406 $tagAttributes = $parseObj->get_tag_attributes($parseObj->getFirstTag($tagData), true);
2407 $headTags[] = array(
2408 'name' => $parseObj->getFirstTagName($tagData),
2409 'attributes' => $tagAttributes[0],
2410 'innerHTML' => $parseObj->removeFirstAndLastTag($tagData),
2411 );
2412 }
2413 }
2414
2415 return $headTags;
2416 }
2417
2418
2419 /**
2420 * Wraps a text with an anchor and returns the HTML representation.
2421 *
2422 * @param string $text: The text to be wrapped by an anchor
2423 * @param string $link: The link to be used in the anchor
2424 * @param array $attributes: Array of attributes to be used in the anchor
2425 * @return string The wrapped texted as HTML representation
2426 */
2427 protected function wrapWithAnchor($text, $link, $attributes=array()) {
2428 $link = trim($link);
2429 $result = '<a href="'.($link ? $link : '#').'"';
2430 foreach ($attributes as $key => $value) {
2431 $result.= ' '.$key.'="'.htmlspecialchars(trim($value)).'"';
2432 }
2433 $result.= '>'.$text.'</a>';
2434 return $result;
2435 }
2436 }
2437
2438
2439 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms_inline.php']) {
2440 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms_inline.php']);
2441 }
2442
2443 ?>