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