16b1fee7ee0625c782af551995395a3c2b2b9376
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Container / SingleFieldContainer.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form\Container;
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\Form\InlineStackProcessor;
18 use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
19 use TYPO3\CMS\Backend\Utility\BackendUtility;
20 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
21 use TYPO3\CMS\Core\Imaging\Icon;
22 use TYPO3\CMS\Core\Imaging\IconFactory;
23 use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
24 use TYPO3\CMS\Core\Utility\DiffUtility;
25 use TYPO3\CMS\Core\Utility\GeneralUtility;
26 use TYPO3\CMS\Core\Utility\MathUtility;
27 use TYPO3\CMS\Lang\LanguageService;
28
29 /**
30 * Container around a "single field".
31 *
32 * This container is the last one in the chain before processing is handed over to single element classes.
33 * If a single field is of type flex or inline, it however creates FlexFormEntryContainer or InlineControlContainer.
34 *
35 * The container does various checks and processing for a given single fields, for example it resolves
36 * display conditions and the HTML to compare different languages.
37 */
38 class SingleFieldContainer extends AbstractContainer
39 {
40 /**
41 * Entry method
42 *
43 * @return array As defined in initializeResultArray() of AbstractNode
44 */
45 public function render()
46 {
47 $backendUser = $this->getBackendUserAuthentication();
48 $languageService = $this->getLanguageService();
49 $resultArray = $this->initializeResultArray();
50
51 $table = $this->data['tableName'];
52 $row = $this->data['databaseRow'];
53 $fieldName = $this->data['fieldName'];
54
55 // @todo: it should be safe at this point, this array exists ...
56 if (!is_array($this->data['processedTca']['columns'][$fieldName])) {
57 return $resultArray;
58 }
59
60 $parameterArray = [];
61 $parameterArray['fieldConf'] = $this->data['processedTca']['columns'][$fieldName];
62
63 $isOverlay = false;
64
65 // This field decides whether the current record is an overlay (as opposed to being a standalone record)
66 // Based on this decision we need to trigger field exclusion or special rendering (like readOnly)
67 if (isset($this->data['processedTca']['ctrl']['transOrigPointerField'])
68 && is_array($this->data['processedTca']['columns'][$this->data['processedTca']['ctrl']['transOrigPointerField']])
69 ) {
70 $parentValue = $row[$this->data['processedTca']['ctrl']['transOrigPointerField']];
71 if (MathUtility::canBeInterpretedAsInteger($parentValue)) {
72 $isOverlay = (bool)$parentValue;
73 } elseif (is_array($parentValue)) {
74 // This case may apply if the value has been converted to an array by the select data provider
75 $isOverlay = !empty($parentValue) ? (bool)$parentValue[0] : false;
76 } elseif (is_string($parentValue) && $parentValue !== '') {
77 // This case may apply if a group definition is used in TCA and the group provider builds a weird string
78 $recordsReferencedInField = GeneralUtility::trimExplode(',', $parentValue);
79 // Pick the first record because if you set multiple records you're in trouble anyways
80 $recordIdentifierParts = GeneralUtility::trimExplode('|', $recordsReferencedInField[0]);
81 list(, $refUid) = BackendUtility::splitTable_Uid($recordIdentifierParts[0]);
82 $isOverlay = MathUtility::canBeInterpretedAsInteger($refUid) ? (bool)$refUid : false;
83 } else {
84 throw new \InvalidArgumentException('The given value for the original language field '
85 . $this->data['processedTca']['ctrl']['transOrigPointerField']
86 . ' of table ' . $table . ' contains an invalid value.', 1470742770);
87 }
88 }
89
90 // A couple of early returns in case the field should not be rendered
91 // Check if this field is configured and editable according to exclude fields and other configuration
92 if (// Return if BE-user has no access rights to this field, @todo: another user access rights check!
93 $parameterArray['fieldConf']['exclude'] && !$backendUser->check('non_exclude_fields', $table . ':' . $fieldName)
94 || $parameterArray['fieldConf']['config']['type'] === 'passthrough'
95 // @todo: Drop option "showIfRTE" ?
96 || !$backendUser->isRTE() && $parameterArray['fieldConf']['config']['showIfRTE']
97 // Return if field should not be rendered in translated records
98 || $isOverlay && empty($parameterArray['fieldConf']['l10n_display']) && $parameterArray['fieldConf']['l10n_mode'] === 'exclude'
99 // @todo: localizationMode still needs handling!
100 || $isOverlay && $this->data['localizationMode'] && $this->data['localizationMode'] !== $parameterArray['fieldConf']['l10n_cat']
101 || $this->inlineFieldShouldBeSkipped()
102 ) {
103 return $resultArray;
104 }
105
106 $parameterArray['fieldTSConfig'] = [];
107 if (isset($this->data['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.'])
108 && is_array($this->data['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.'])
109 ) {
110 $parameterArray['fieldTSConfig'] = $this->data['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.'];
111 }
112 if ($parameterArray['fieldTSConfig']['disabled']) {
113 return $resultArray;
114 }
115
116 // Override fieldConf by fieldTSconfig:
117 $parameterArray['fieldConf']['config'] = FormEngineUtility::overrideFieldConf($parameterArray['fieldConf']['config'], $parameterArray['fieldTSConfig']);
118 $parameterArray['itemFormElName'] = 'data[' . $table . '][' . $row['uid'] . '][' . $fieldName . ']';
119 $parameterArray['itemFormElID'] = 'data_' . $table . '_' . $row['uid'] . '_' . $fieldName;
120 $newElementBaseName = $this->data['elementBaseName'] . '[' . $table . '][' . $row['uid'] . '][' . $fieldName . ']';
121
122 // The value to show in the form field.
123 $parameterArray['itemFormElValue'] = $row[$fieldName];
124 // Set field to read-only if configured for translated records to show default language content as readonly
125 if ($parameterArray['fieldConf']['l10n_display']
126 && GeneralUtility::inList($parameterArray['fieldConf']['l10n_display'], 'defaultAsReadonly')
127 && $isOverlay
128 ) {
129 $parameterArray['fieldConf']['config']['readOnly'] = true;
130 $parameterArray['itemFormElValue'] = $this->data['defaultLanguageRow'][$fieldName];
131 }
132
133 if (strpos($this->data['processedTca']['ctrl']['type'], ':') === false) {
134 $typeField = $this->data['processedTca']['ctrl']['type'];
135 } else {
136 $typeField = substr($this->data['processedTca']['ctrl']['type'], 0, strpos($this->data['processedTca']['ctrl']['type'], ':'));
137 }
138 // Create a JavaScript code line which will ask the user to save/update the form due to changing the element.
139 // This is used for eg. "type" fields and others configured with "requestUpdate"
140 if (!empty($this->data['processedTca']['ctrl']['type'])
141 && $fieldName === $typeField
142 || !empty($this->data['processedTca']['ctrl']['requestUpdate'])
143 && GeneralUtility::inList(str_replace(' ', '', $this->data['processedTca']['ctrl']['requestUpdate']), $fieldName)
144 ) {
145 if ($backendUser->jsConfirmation(JsConfirmation::TYPE_CHANGE)) {
146 $alertMsgOnChange = 'top.TYPO3.Modal.confirm(TBE_EDITOR.labels.refreshRequired.title, TBE_EDITOR.labels.refreshRequired.content).on("button.clicked", function(e) { if (e.target.name == "ok" && TBE_EDITOR.checkSubmit(-1)) { TBE_EDITOR.submitForm() } top.TYPO3.Modal.dismiss(); });';
147 } else {
148 $alertMsgOnChange = 'if (TBE_EDITOR.checkSubmit(-1)){ TBE_EDITOR.submitForm() };';
149 }
150 } else {
151 $alertMsgOnChange = '';
152 }
153
154 // JavaScript code for event handlers:
155 $parameterArray['fieldChangeFunc'] = [];
156 $parameterArray['fieldChangeFunc']['TBE_EDITOR_fieldChanged'] = 'TBE_EDITOR.fieldChanged(' . GeneralUtility::quoteJSvalue($table) . ',' . GeneralUtility::quoteJSvalue($row['uid']) . ',' . GeneralUtility::quoteJSvalue($fieldName) . ',' . GeneralUtility::quoteJSvalue($parameterArray['itemFormElName']) . ');';
157 $parameterArray['fieldChangeFunc']['alert'] = $alertMsgOnChange;
158
159 // If this is the child of an inline type and it is the field creating the label
160 if ($this->isInlineChildAndLabelField($table, $fieldName)) {
161 /** @var InlineStackProcessor $inlineStackProcessor */
162 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
163 $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);
164 $inlineDomObjectId = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
165 $inlineObjectId = implode(
166 '-',
167 [
168 $inlineDomObjectId,
169 $table,
170 $row['uid']
171 ]
172 );
173 $parameterArray['fieldChangeFunc']['inline'] = 'inline.handleChangedField(' . GeneralUtility::quoteJSvalue($parameterArray['itemFormElName']) . ',' . GeneralUtility::quoteJSvalue($inlineObjectId) . ');';
174 }
175
176 // Based on the type of the item, call a render function on a child element
177 $options = $this->data;
178 $options['parameterArray'] = $parameterArray;
179 $options['elementBaseName'] = $newElementBaseName;
180 if (!empty($parameterArray['fieldConf']['config']['renderType'])) {
181 $options['renderType'] = $parameterArray['fieldConf']['config']['renderType'];
182 } else {
183 // Fallback to type if no renderType is given
184 $options['renderType'] = $parameterArray['fieldConf']['config']['type'];
185 }
186 $resultArray = $this->nodeFactory->create($options)->render();
187
188 // If output is empty stop further processing.
189 // This means there was internal processing only and we don't need to add additional information
190 if (empty($resultArray['html'])) {
191 return $resultArray;
192 }
193
194 $html = $resultArray['html'];
195
196 // @todo: the language handling, the null and the placeholder stuff should be embedded in the single
197 // @todo: element classes. Basically, this method should return here and have the element classes
198 // @todo: decide on language stuff and other wraps already.
199
200 // Add language + diff
201 $renderLanguageDiff = true;
202 if ($parameterArray['fieldConf']['l10n_display'] && (GeneralUtility::inList($parameterArray['fieldConf']['l10n_display'], 'hideDiff')
203 || GeneralUtility::inList($parameterArray['fieldConf']['l10n_display'], 'defaultAsReadonly'))
204 ) {
205 $renderLanguageDiff = false;
206 }
207 if ($renderLanguageDiff) {
208 $html = $this->renderDefaultLanguageContent($table, $fieldName, $row, $html);
209 $html = $this->renderDefaultLanguageDiff($table, $fieldName, $row, $html);
210 }
211
212 $fieldItemClasses = [
213 't3js-formengine-field-item'
214 ];
215
216 // NULL value and placeholder handling
217 $nullControlNameAttribute = ' name="' . htmlspecialchars('control[active][' . $table . '][' . $row['uid'] . '][' . $fieldName . ']') . '"';
218 if (!empty($parameterArray['fieldConf']['config']['eval']) && GeneralUtility::inList($parameterArray['fieldConf']['config']['eval'], 'null')
219 && (empty($parameterArray['fieldConf']['config']['mode']) || $parameterArray['fieldConf']['config']['mode'] !== 'useOrOverridePlaceholder')
220 ) {
221 // This field has eval=null set, but has no useOverridePlaceholder defined.
222 // Goal is to have a field that can distinct between NULL and empty string in the database.
223 // A checkbox and an additional hidden field will be created, both with the same name
224 // and prefixed with "control[active]". If the checkbox is set (value 1), the value from the casual
225 // input field will be written to the database. If the checkbox is not set, the hidden field
226 // transfers value=0 to DataHandler, the value of the input field will then be reset to NULL by the
227 // DataHandler at an early point in processing, so NULL will be written to DB as field value.
228
229 // If the value of the field *is* NULL at the moment, an additional class is set
230 // @todo: This does not work well at the moment, but is kept for now. see input_14 of ext:styleguide as example
231 $checked = ' checked="checked"';
232 if ($this->data['databaseRow'][$fieldName] === null) {
233 $fieldItemClasses[] = 'disabled';
234 $checked = '';
235 }
236
237 $formElementName = 'data[' . $table . '][' . $row['uid'] . '][' . $fieldName . ']';
238 $onChange = htmlspecialchars(
239 'typo3form.fieldSetNull(' . GeneralUtility::quoteJSvalue($formElementName) . ', !this.checked)'
240 );
241
242 $nullValueWrap = [];
243 $nullValueWrap[] = '<div class="' . implode(' ', $fieldItemClasses) . '">';
244 $nullValueWrap[] = '<div class="t3-form-field-disable"></div>';
245 $nullValueWrap[] = '<div class="checkbox t3-form-field-eval-null-checkbox">';
246 $nullValueWrap[] = '<label>';
247 $nullValueWrap[] = '<input type="hidden"' . $nullControlNameAttribute . ' value="0" />';
248 $nullValueWrap[] = '<input type="checkbox"' . $nullControlNameAttribute . ' value="1" onchange="' . $onChange . '"' . $checked . ' /> &nbsp;';
249 $nullValueWrap[] = '</label>';
250 $nullValueWrap[] = '</div>';
251 $nullValueWrap[] = $html;
252 $nullValueWrap[] = '</div>';
253
254 $html = implode(LF, $nullValueWrap);
255 } elseif (isset($parameterArray['fieldConf']['config']['mode']) && $parameterArray['fieldConf']['config']['mode'] === 'useOrOverridePlaceholder') {
256 // This field has useOverridePlaceholder set.
257 // Here, a value from a deeper DB structure can be "fetched up" as value, and can also be overridden by a
258 // local value. This is used in FAL, where eg. the "title" field can have the default value from sys_file_metadata,
259 // the title field of sys_file_reference is then set to NULL. Or the "override" checkbox is set, and a string
260 // or an empty string is then written to the field of sys_file_reference.
261 // The situation is similar to the NULL handling above, but additionally a "default" value should be shown.
262 // To achieve this, again a hidden control[hidden] field is added together with a checkbox with the same name
263 // to transfer the information whether the default value should be used or not: Checkbox checked transfers 1 as
264 // value in control[active], meaning the overridden value should be used.
265 // Additionally to the casual input field, a second field is added containing the "placeholder" value. This
266 // field has no name attribute and is not transferred at all. Those two are then hidden / shown depending
267 // on the state of the above checkbox in via JS.
268
269 $placeholder = empty($parameterArray['fieldConf']['config']['placeholder']) ? '' : $parameterArray['fieldConf']['config']['placeholder'];
270 $onChange = 'typo3form.fieldTogglePlaceholder(' . GeneralUtility::quoteJSvalue($parameterArray['itemFormElName']) . ', !this.checked)';
271 $checked = $parameterArray['itemFormElValue'] === null ? '' : ' checked="checked"';
272
273 $resultArray['additionalJavaScriptPost'][] = 'typo3form.fieldTogglePlaceholder('
274 . GeneralUtility::quoteJSvalue($parameterArray['itemFormElName']) . ', ' . ($checked ? 'false' : 'true') . ');';
275
276 // Renders an input or textarea field depending on type of "parent"
277 $options = [];
278 $options['databaseRow'] = [];
279 $options['table'] = '';
280 $options['parameterArray'] = $parameterArray;
281 $options['parameterArray']['itemFormElValue'] = GeneralUtility::fixed_lgd_cs($placeholder, 30);
282 $options['renderType'] = 'none';
283 $noneElementResult = $this->nodeFactory->create($options)->render();
284 $noneElementHtml = $noneElementResult['html'];
285
286 $placeholderWrap = [];
287 $placeholderWrap[] = '<div class="' . implode(' ', $fieldItemClasses) . '">';
288 $placeholderWrap[] = '<div class="t3-form-field-disable"></div>';
289 $placeholderWrap[] = '<div class="checkbox">';
290 $placeholderWrap[] = '<label>';
291 $placeholderWrap[] = '<input type="hidden"' . $nullControlNameAttribute . ' value="0" />';
292 $placeholderWrap[] = '<input type="checkbox"' . $nullControlNameAttribute . ' value="1" id="tce-forms-textfield-use-override-' . $fieldName . '-' . $row['uid'] . '" onchange="' . htmlspecialchars($onChange) . '"' . $checked . ' />';
293 $placeholderWrap[] = sprintf($languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.placeholder.override'), BackendUtility::getRecordTitlePrep($placeholder, 20));
294 $placeholderWrap[] = '</label>';
295 $placeholderWrap[] = '</div>';
296 $placeholderWrap[] = '<div class="t3js-formengine-placeholder-placeholder">';
297 $placeholderWrap[] = $noneElementHtml;
298 $placeholderWrap[] = '</div>';
299 $placeholderWrap[] = '<div class="t3js-formengine-placeholder-formfield">';
300 $placeholderWrap[] = $html;
301 $placeholderWrap[] = '</div>';
302 $placeholderWrap[] = '</div>';
303
304 $html = implode(LF, $placeholderWrap);
305 } elseif ($parameterArray['fieldConf']['config']['type'] !== 'user' || empty($parameterArray['fieldConf']['config']['noTableWrapping'])) {
306 // Add a casual wrap if the field is not of type user with no wrap requested.
307 $standardWrap = [];
308 $standardWrap[] = '<div class="' . implode(' ', $fieldItemClasses) . '">';
309 $standardWrap[] = '<div class="t3-form-field-disable"></div>';
310 $standardWrap[] = $html;
311 $standardWrap[] = '</div>';
312
313 $html = implode(LF, $standardWrap);
314 }
315
316 $resultArray['html'] = $html;
317 return $resultArray;
318 }
319
320 /**
321 * Renders the display of default language record content around current field.
322 * Will render content if any is found in the internal array.
323 *
324 * @param string $table Table name of the record being edited
325 * @param string $field Field name represented by $item
326 * @param array $row Record array of the record being edited
327 * @param string $item HTML of the form field. This is what we add the content to.
328 * @return string Item string returned again, possibly with the original value added to.
329 */
330 protected function renderDefaultLanguageContent($table, $field, $row, $item)
331 {
332 if (is_array($this->data['defaultLanguageRow'])) {
333 $defaultLanguageValue = BackendUtility::getProcessedValue(
334 $table,
335 $field,
336 $this->data['defaultLanguageRow'][$field],
337 0,
338 true,
339 false,
340 $this->data['defaultLanguageRow']['uid'],
341 true,
342 $this->data['defaultLanguageRow']['pid']
343 );
344 $fieldConfig = $this->data['processedTca']['columns'][$field];
345 // Don't show content if it's for IRRE child records:
346 if ($fieldConfig['config']['type'] !== 'inline') {
347 /** @var IconFactory $iconFactory */
348 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
349 if ($defaultLanguageValue !== '') {
350 $item .= '<div class="t3-form-original-language" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_misc.xlf:localizeMergeIfNotBlank', true) . '">'
351 . $iconFactory->getIcon($this->data['systemLanguageRows'][0]['flagIconIdentifier'], Icon::SIZE_SMALL)->render()
352 . $this->getMergeBehaviourIcon($fieldConfig['l10n_mode'])
353 . $this->previewFieldValue($defaultLanguageValue, $fieldConfig, $field) . '</div>';
354 }
355 $additionalPreviewLanguages = $this->data['additionalLanguageRows'];
356 foreach ($additionalPreviewLanguages as $previewLanguage) {
357 $defaultLanguageValue = BackendUtility::getProcessedValue(
358 $table,
359 $field,
360 $previewLanguage[$field],
361 0,
362 true
363 );
364 if ($defaultLanguageValue !== '') {
365 $item .= '<div class="t3-form-original-language" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_misc.xlf:localizeMergeIfNotBlank', true) . '">'
366 . $iconFactory->getIcon($this->data['systemLanguageRows'][$previewLanguage['sys_language_uid']]['flagIconIdentifier'], Icon::SIZE_SMALL)->render()
367 . $this->getMergeBehaviourIcon($fieldConfig['l10n_mode'])
368 . $this->previewFieldValue($defaultLanguageValue, $fieldConfig, $field) . '</div>';
369 }
370 }
371 }
372 }
373 return $item;
374 }
375
376 /**
377 * Renders an icon to indicate the way the translation and the original is merged (if this is relevant).
378 *
379 * If a field is defined as 'mergeIfNotBlank' this is useful information for an editor. He/she can leave the field blank and
380 * the original value will be used. Without this hint editors are likely to copy the contents even if it is not necessary.
381 *
382 * @param string $l10nMode Localization mode from TCA
383 * @return string
384 */
385 protected function getMergeBehaviourIcon($l10nMode)
386 {
387 $icon = '';
388 if ($l10nMode === 'mergeIfNotBlank') {
389 /** @var IconFactory $iconFactory */
390 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
391 $icon = $iconFactory->getIcon('actions-edit-merge-localization', Icon::SIZE_SMALL)->render();
392 }
393 return $icon;
394 }
395
396 /**
397 * Renders the diff-view of default language record content compared with what the record was originally translated from.
398 * Will render content if any is found in the internal array
399 *
400 * @param string $table Table name of the record being edited
401 * @param string $field Field name represented by $item
402 * @param array $row Record array of the record being edited
403 * @param string $item HTML of the form field. This is what we add the content to.
404 * @return string Item string returned again, possibly with the original value added to.
405 */
406 protected function renderDefaultLanguageDiff($table, $field, $row, $item)
407 {
408 if (is_array($this->data['defaultLanguageDiffRow'][$table . ':' . $row['uid']])) {
409 // Initialize:
410 $dLVal = [
411 'old' => $this->data['defaultLanguageDiffRow'][$table . ':' . $row['uid']],
412 'new' => $this->data['defaultLanguageRow']
413 ];
414 // There must be diff-data:
415 if (isset($dLVal['old'][$field])) {
416 if ((string)$dLVal['old'][$field] !== (string)$dLVal['new'][$field]) {
417 // Create diff-result:
418 /** @var DiffUtility $diffUtility */
419 $diffUtility = GeneralUtility::makeInstance(DiffUtility::class);
420 $diffres = $diffUtility->makeDiffDisplay(
421 BackendUtility::getProcessedValue($table, $field, $dLVal['old'][$field], 0, 1),
422 BackendUtility::getProcessedValue($table, $field, $dLVal['new'][$field], 0, 1)
423 );
424 $item .= '
425 <div class="t3-form-original-language-diff">
426 <div class="t3-form-original-language-diffheader">'
427 . htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.changeInOrig'))
428 . '</div>
429 <div class="t3-form-original-language-diffcontent">
430 <div class="diff">
431 <div class="diff-item">
432 <div class="diff-item-result diff-item-result-inline">' . $diffres . '</div>
433 </div>
434 </div>
435 </div>
436 </div>
437 ';
438 }
439 }
440 }
441 return $item;
442 }
443
444 /**
445 * Checks if the $table is the child of an inline type AND the $field is the label field of this table.
446 * This function is used to dynamically update the label while editing. This has no effect on labels,
447 * that were processed by a FormEngine-hook on saving.
448 *
449 * @param string $table The table to check
450 * @param string $field The field on this table to check
451 * @return bool Is inline child and field is responsible for the label
452 */
453 protected function isInlineChildAndLabelField($table, $field)
454 {
455 /** @var InlineStackProcessor $inlineStackProcessor */
456 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
457 $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);
458 $level = $inlineStackProcessor->getStructureLevel(-1);
459 if ($level['config']['foreign_label']) {
460 $label = $level['config']['foreign_label'];
461 } else {
462 $label = $this->data['processedTca']['ctrl']['label'];
463 }
464 return $level['config']['foreign_table'] === $table && $label === $field;
465 }
466
467 /**
468 * Rendering of inline fields should be skipped under certain circumstances
469 *
470 * @return bool TRUE if field should be skipped based on inline configuration
471 */
472 protected function inlineFieldShouldBeSkipped()
473 {
474 $table = $this->data['tableName'];
475 $row = $this->data['databaseRow'];
476 $fieldName = $this->data['fieldName'];
477 $fieldConfig = $this->data['processedTca']['columns'][$fieldName]['config'];
478
479 /** @var InlineStackProcessor $inlineStackProcessor */
480 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
481 $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);
482 $structureDepth = $inlineStackProcessor->getStructureDepth();
483
484 $skipThisField = false;
485 if ($structureDepth > 0) {
486 $searchArray = [
487 '%OR' => [
488 'config' => [
489 0 => [
490 '%AND' => [
491 'foreign_table' => $table,
492 '%OR' => [
493 '%AND' => [
494 'appearance' => ['useCombination' => true],
495 'foreign_selector' => $fieldName
496 ],
497 'MM' => $fieldConfig['MM']
498 ]
499 ]
500 ],
501 1 => [
502 '%AND' => [
503 'foreign_table' => $fieldConfig['foreign_table'],
504 'foreign_selector' => $fieldConfig['foreign_field']
505 ]
506 ]
507 ]
508 ]
509 ];
510 // Get the parent record from structure stack
511 $level = $inlineStackProcessor->getStructureLevel(-1);
512 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
513 if ($this->data['isOnSymmetricSide']) {
514 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $fieldName;
515 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $fieldName;
516 } else {
517 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $fieldName;
518 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $fieldName;
519 }
520 $skipThisField = $this->arrayCompareComplex($level, $searchArray);
521 }
522 return $skipThisField;
523 }
524
525 /**
526 * Handles complex comparison requests on an array.
527 * A request could look like the following:
528 *
529 * $searchArray = array(
530 * '%AND' => array(
531 * 'key1' => 'value1',
532 * 'key2' => 'value2',
533 * '%OR' => array(
534 * 'subarray' => array(
535 * 'subkey' => 'subvalue'
536 * ),
537 * 'key3' => 'value3',
538 * 'key4' => 'value4'
539 * )
540 * )
541 * );
542 *
543 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
544 * overwriting the sub-array. It could be necessary, if you use complex comparisons.
545 *
546 * The example above means, key1 *AND* key2 (and their values) have to match with
547 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
548 * condition.
549 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
550 * function recurses down one level in that sub-array.
551 *
552 * @param array $subjectArray The array to search in
553 * @param array $searchArray The array with keys and values to search for
554 * @param string $type Use '%AND' or '%OR' for comparison
555 * @return bool The result of the comparison
556 */
557 protected function arrayCompareComplex($subjectArray, $searchArray, $type = '')
558 {
559 $localMatches = 0;
560 $localEntries = 0;
561 if (is_array($searchArray) && !empty($searchArray)) {
562 // If no type was passed, try to determine
563 if (!$type) {
564 reset($searchArray);
565 $type = key($searchArray);
566 $searchArray = current($searchArray);
567 }
568 // We use '%AND' and '%OR' in uppercase
569 $type = strtoupper($type);
570 // Split regular elements from sub elements
571 foreach ($searchArray as $key => $value) {
572 $localEntries++;
573 // Process a sub-group of OR-conditions
574 if ($key === '%OR') {
575 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
576 } elseif ($key === '%AND') {
577 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
578 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
579 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
580 } elseif (is_array($value)) {
581 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
582 } else {
583 if (isset($subjectArray[$key]) && isset($value)) {
584 // Boolean match:
585 if (is_bool($value)) {
586 $localMatches += !($subjectArray[$key] xor $value) ? 1 : 0;
587 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
588 $localMatches += $subjectArray[$key] == $value ? 1 : 0;
589 } else {
590 $localMatches += $subjectArray[$key] === $value ? 1 : 0;
591 }
592 }
593 }
594 // If one or more matches are required ('OR'), return TRUE after the first successful match
595 if ($type === '%OR' && $localMatches > 0) {
596 return true;
597 }
598 // If all matches are required ('AND') and we have no result after the first run, return FALSE
599 if ($type === '%AND' && $localMatches == 0) {
600 return false;
601 }
602 }
603 }
604 // Return the result for '%AND' (if nothing was checked, TRUE is returned)
605 return $localEntries === $localMatches;
606 }
607
608 /**
609 * Checks whether an object is an associative array.
610 *
611 * @param mixed $object The object to be checked
612 * @return bool Returns TRUE, if the object is an associative array
613 */
614 protected function isAssociativeArray($object)
615 {
616 return is_array($object) && !empty($object) && array_keys($object) !== range(0, sizeof($object) - 1);
617 }
618
619 /**
620 * @return BackendUserAuthentication
621 */
622 protected function getBackendUserAuthentication()
623 {
624 return $GLOBALS['BE_USER'];
625 }
626
627 /**
628 * @return LanguageService
629 */
630 protected function getLanguageService()
631 {
632 return $GLOBALS['LANG'];
633 }
634 }