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