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