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