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