21d3ac6cab55cf85d8bf92777799baff2e4a6db2
[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 // Return if field should not be rendered in translated records
96 || $isOverlay && empty($parameterArray['fieldConf']['l10n_display']) && $parameterArray['fieldConf']['l10n_mode'] === 'exclude'
97 // @todo: localizationMode still needs handling!
98 || $isOverlay && $this->data['localizationMode'] && $this->data['localizationMode'] !== $parameterArray['fieldConf']['l10n_cat']
99 || $this->inlineFieldShouldBeSkipped()
100 ) {
101 return $resultArray;
102 }
103
104 $parameterArray['fieldTSConfig'] = [];
105 if (isset($this->data['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.'])
106 && is_array($this->data['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.'])
107 ) {
108 $parameterArray['fieldTSConfig'] = $this->data['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.'];
109 }
110 if ($parameterArray['fieldTSConfig']['disabled']) {
111 return $resultArray;
112 }
113
114 // Override fieldConf by fieldTSconfig:
115 $parameterArray['fieldConf']['config'] = FormEngineUtility::overrideFieldConf($parameterArray['fieldConf']['config'], $parameterArray['fieldTSConfig']);
116 $parameterArray['itemFormElName'] = 'data[' . $table . '][' . $row['uid'] . '][' . $fieldName . ']';
117 $parameterArray['itemFormElID'] = 'data_' . $table . '_' . $row['uid'] . '_' . $fieldName;
118 $newElementBaseName = $this->data['elementBaseName'] . '[' . $table . '][' . $row['uid'] . '][' . $fieldName . ']';
119
120 // The value to show in the form field.
121 $parameterArray['itemFormElValue'] = $row[$fieldName];
122 // Set field to read-only if configured for translated records to show default language content as readonly
123 if ($parameterArray['fieldConf']['l10n_display']
124 && GeneralUtility::inList($parameterArray['fieldConf']['l10n_display'], 'defaultAsReadonly')
125 && $isOverlay
126 ) {
127 $parameterArray['fieldConf']['config']['readOnly'] = true;
128 $parameterArray['itemFormElValue'] = $this->data['defaultLanguageRow'][$fieldName];
129 }
130
131 if (strpos($this->data['processedTca']['ctrl']['type'], ':') === false) {
132 $typeField = $this->data['processedTca']['ctrl']['type'];
133 } else {
134 $typeField = substr($this->data['processedTca']['ctrl']['type'], 0, strpos($this->data['processedTca']['ctrl']['type'], ':'));
135 }
136 // Create a JavaScript code line which will ask the user to save/update the form due to changing the element.
137 // This is used for eg. "type" fields and others configured with "requestUpdate"
138 if (!empty($this->data['processedTca']['ctrl']['type'])
139 && $fieldName === $typeField
140 || !empty($this->data['processedTca']['ctrl']['requestUpdate'])
141 && GeneralUtility::inList(str_replace(' ', '', $this->data['processedTca']['ctrl']['requestUpdate']), $fieldName)
142 ) {
143 if ($backendUser->jsConfirmation(JsConfirmation::TYPE_CHANGE)) {
144 $alertMsgOnChange = 'top.TYPO3.Modal.confirm(TYPO3.lang["FormEngine.refreshRequiredTitle"], TYPO3.lang["FormEngine.refreshRequiredContent"]).on("button.clicked", function(e) { if (e.target.name == "ok" && TBE_EDITOR.checkSubmit(-1)) { TBE_EDITOR.submitForm() } top.TYPO3.Modal.dismiss(); });';
145 } else {
146 $alertMsgOnChange = 'if (TBE_EDITOR.checkSubmit(-1)){ TBE_EDITOR.submitForm() };';
147 }
148 } else {
149 $alertMsgOnChange = '';
150 }
151
152 // JavaScript code for event handlers:
153 $parameterArray['fieldChangeFunc'] = [];
154 $parameterArray['fieldChangeFunc']['TBE_EDITOR_fieldChanged'] = 'TBE_EDITOR.fieldChanged(' . GeneralUtility::quoteJSvalue($table) . ',' . GeneralUtility::quoteJSvalue($row['uid']) . ',' . GeneralUtility::quoteJSvalue($fieldName) . ',' . GeneralUtility::quoteJSvalue($parameterArray['itemFormElName']) . ');';
155 if ($alertMsgOnChange) {
156 $parameterArray['fieldChangeFunc']['alert'] = $alertMsgOnChange;
157 }
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 $disabled = '';
273 $fallbackValue = 0;
274 if (strlen(BackendUtility::getRecordTitlePrep($placeholder, 20)) > 0) {
275 $overrideLabel = sprintf($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override'), BackendUtility::getRecordTitlePrep($placeholder, 20));
276 } else {
277 $fallbackValue = 1;
278 $checked = ' checked="checked"';
279 $disabled = ' disabled="disabled"';
280 $overrideLabel = sprintf($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.placeholder.override_not_available'), BackendUtility::getRecordTitlePrep($placeholder, 20));
281 }
282
283 $resultArray['additionalJavaScriptPost'][] = 'typo3form.fieldTogglePlaceholder('
284 . GeneralUtility::quoteJSvalue($parameterArray['itemFormElName']) . ', ' . ($checked ? 'false' : 'true') . ');';
285
286 // Renders an input or textarea field depending on type of "parent"
287 $options = [];
288 $options['databaseRow'] = [];
289 $options['table'] = '';
290 $options['parameterArray'] = $parameterArray;
291 $options['parameterArray']['itemFormElValue'] = GeneralUtility::fixed_lgd_cs($placeholder, 30);
292 $options['renderType'] = 'none';
293 $noneElementResult = $this->nodeFactory->create($options)->render();
294 $noneElementHtml = $noneElementResult['html'];
295
296 $placeholderWrap = [];
297 $placeholderWrap[] = '<div class="' . implode(' ', $fieldItemClasses) . '">';
298 $placeholderWrap[] = '<div class="t3-form-field-disable"></div>';
299 $placeholderWrap[] = '<div class="checkbox">';
300 $placeholderWrap[] = '<label>';
301 $placeholderWrap[] = '<input type="hidden"' . $nullControlNameAttribute . ' value="' . $fallbackValue . '" />';
302 $placeholderWrap[] = '<input type="checkbox"' . $nullControlNameAttribute . ' value="1" id="tce-forms-textfield-use-override-' . $fieldName . '-' . $row['uid'] . '" onchange="' . htmlspecialchars($onChange) . '"' . $checked . $disabled . ' />';
303 $placeholderWrap[] = $overrideLabel;
304 $placeholderWrap[] = '</label>';
305 $placeholderWrap[] = '</div>';
306 $placeholderWrap[] = '<div class="t3js-formengine-placeholder-placeholder">';
307 $placeholderWrap[] = $noneElementHtml;
308 $placeholderWrap[] = '</div>';
309 $placeholderWrap[] = '<div class="t3js-formengine-placeholder-formfield">';
310 $placeholderWrap[] = $html;
311 $placeholderWrap[] = '</div>';
312 $placeholderWrap[] = '</div>';
313
314 $html = implode(LF, $placeholderWrap);
315 } elseif ($parameterArray['fieldConf']['config']['type'] !== 'user' || empty($parameterArray['fieldConf']['config']['noTableWrapping'])) {
316 // Add a casual wrap if the field is not of type user with no wrap requested.
317 $standardWrap = [];
318 $standardWrap[] = '<div class="' . implode(' ', $fieldItemClasses) . '">';
319 $standardWrap[] = '<div class="t3-form-field-disable"></div>';
320 $standardWrap[] = $html;
321 $standardWrap[] = '</div>';
322
323 $html = implode(LF, $standardWrap);
324 }
325
326 $resultArray['html'] = $html;
327 return $resultArray;
328 }
329
330 /**
331 * Renders the display of default language record content around current field.
332 * Will render content if any is found in the internal array.
333 *
334 * @param string $table Table name of the record being edited
335 * @param string $field Field name represented by $item
336 * @param array $row Record array of the record being edited
337 * @param string $item HTML of the form field. This is what we add the content to.
338 * @return string Item string returned again, possibly with the original value added to.
339 */
340 protected function renderDefaultLanguageContent($table, $field, $row, $item)
341 {
342 if (is_array($this->data['defaultLanguageRow'])) {
343 $defaultLanguageValue = BackendUtility::getProcessedValue(
344 $table,
345 $field,
346 $this->data['defaultLanguageRow'][$field],
347 0,
348 true,
349 false,
350 $this->data['defaultLanguageRow']['uid'],
351 true,
352 $this->data['defaultLanguageRow']['pid']
353 );
354 $fieldConfig = $this->data['processedTca']['columns'][$field];
355 // Don't show content if it's for IRRE child records:
356 if ($fieldConfig['config']['type'] !== 'inline' && $fieldConfig['config']['type'] !== 'flex') {
357 /** @var IconFactory $iconFactory */
358 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
359 if ($defaultLanguageValue !== '') {
360 $item .= '<div class="t3-form-original-language" title="' . htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:localizeMergeIfNotBlank')) . '">'
361 . $iconFactory->getIcon($this->data['systemLanguageRows'][0]['flagIconIdentifier'], Icon::SIZE_SMALL)->render()
362 . $this->getMergeBehaviourIcon($fieldConfig['l10n_mode'])
363 . $this->previewFieldValue($defaultLanguageValue, $fieldConfig, $field) . '</div>';
364 }
365 $additionalPreviewLanguages = $this->data['additionalLanguageRows'];
366 foreach ($additionalPreviewLanguages as $previewLanguage) {
367 $defaultLanguageValue = BackendUtility::getProcessedValue(
368 $table,
369 $field,
370 $previewLanguage[$field],
371 0,
372 true
373 );
374 if ($defaultLanguageValue !== '') {
375 $item .= '<div class="t3-form-original-language" title="' . htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:localizeMergeIfNotBlank')) . '">'
376 . $iconFactory->getIcon($this->data['systemLanguageRows'][$previewLanguage['sys_language_uid']]['flagIconIdentifier'], Icon::SIZE_SMALL)->render()
377 . $this->getMergeBehaviourIcon($fieldConfig['l10n_mode'])
378 . $this->previewFieldValue($defaultLanguageValue, $fieldConfig, $field) . '</div>';
379 }
380 }
381 }
382 }
383 return $item;
384 }
385
386 /**
387 * Renders an icon to indicate the way the translation and the original is merged (if this is relevant).
388 *
389 * If a field is defined as 'mergeIfNotBlank' this is useful information for an editor. He/she can leave the field blank and
390 * the original value will be used. Without this hint editors are likely to copy the contents even if it is not necessary.
391 *
392 * @param string $l10nMode Localization mode from TCA
393 * @return string
394 */
395 protected function getMergeBehaviourIcon($l10nMode)
396 {
397 $icon = '';
398 if ($l10nMode === 'mergeIfNotBlank') {
399 /** @var IconFactory $iconFactory */
400 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
401 $icon = $iconFactory->getIcon('actions-edit-merge-localization', Icon::SIZE_SMALL)->render();
402 }
403 return $icon;
404 }
405
406 /**
407 * Renders the diff-view of default language record content compared with what the record was originally translated from.
408 * Will render content if any is found in the internal array
409 *
410 * @param string $table Table name of the record being edited
411 * @param string $field Field name represented by $item
412 * @param array $row Record array of the record being edited
413 * @param string $item HTML of the form field. This is what we add the content to.
414 * @return string Item string returned again, possibly with the original value added to.
415 */
416 protected function renderDefaultLanguageDiff($table, $field, $row, $item)
417 {
418 if (is_array($this->data['defaultLanguageDiffRow'][$table . ':' . $row['uid']])) {
419 // Initialize:
420 $dLVal = [
421 'old' => $this->data['defaultLanguageDiffRow'][$table . ':' . $row['uid']],
422 'new' => $this->data['defaultLanguageRow']
423 ];
424 // There must be diff-data:
425 if (isset($dLVal['old'][$field])) {
426 if ((string)$dLVal['old'][$field] !== (string)$dLVal['new'][$field]) {
427 // Create diff-result:
428 /** @var DiffUtility $diffUtility */
429 $diffUtility = GeneralUtility::makeInstance(DiffUtility::class);
430 $diffres = $diffUtility->makeDiffDisplay(
431 BackendUtility::getProcessedValue($table, $field, $dLVal['old'][$field], 0, 1),
432 BackendUtility::getProcessedValue($table, $field, $dLVal['new'][$field], 0, 1)
433 );
434 $item .= '
435 <div class="t3-form-original-language-diff">
436 <div class="t3-form-original-language-diffheader">'
437 . htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.changeInOrig'))
438 . '</div>
439 <div class="t3-form-original-language-diffcontent">
440 <div class="diff">
441 <div class="diff-item">
442 <div class="diff-item-result diff-item-result-inline">' . $diffres . '</div>
443 </div>
444 </div>
445 </div>
446 </div>
447 ';
448 }
449 }
450 }
451 return $item;
452 }
453
454 /**
455 * Checks if the $table is the child of an inline type AND the $field is the label field of this table.
456 * This function is used to dynamically update the label while editing. This has no effect on labels,
457 * that were processed by a FormEngine-hook on saving.
458 *
459 * @param string $table The table to check
460 * @param string $field The field on this table to check
461 * @return bool Is inline child and field is responsible for the label
462 */
463 protected function isInlineChildAndLabelField($table, $field)
464 {
465 /** @var InlineStackProcessor $inlineStackProcessor */
466 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
467 $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);
468 $level = $inlineStackProcessor->getStructureLevel(-1);
469 if ($level['config']['foreign_label']) {
470 $label = $level['config']['foreign_label'];
471 } else {
472 $label = $this->data['processedTca']['ctrl']['label'];
473 }
474 return $level['config']['foreign_table'] === $table && $label === $field;
475 }
476
477 /**
478 * Rendering of inline fields should be skipped under certain circumstances
479 *
480 * @return bool TRUE if field should be skipped based on inline configuration
481 */
482 protected function inlineFieldShouldBeSkipped()
483 {
484 $table = $this->data['tableName'];
485 $fieldName = $this->data['fieldName'];
486 $fieldConfig = $this->data['processedTca']['columns'][$fieldName]['config'];
487
488 /** @var InlineStackProcessor $inlineStackProcessor */
489 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
490 $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);
491 $structureDepth = $inlineStackProcessor->getStructureDepth();
492
493 $skipThisField = false;
494 if ($structureDepth > 0) {
495 $searchArray = [
496 '%OR' => [
497 'config' => [
498 0 => [
499 '%AND' => [
500 'foreign_table' => $table,
501 '%OR' => [
502 '%AND' => [
503 'appearance' => ['useCombination' => true],
504 'foreign_selector' => $fieldName
505 ],
506 'MM' => $fieldConfig['MM']
507 ]
508 ]
509 ],
510 1 => [
511 '%AND' => [
512 'foreign_table' => $fieldConfig['foreign_table'],
513 'foreign_selector' => $fieldConfig['foreign_field']
514 ]
515 ]
516 ]
517 ]
518 ];
519 // Get the parent record from structure stack
520 $level = $inlineStackProcessor->getStructureLevel(-1);
521 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
522 if ($this->data['isOnSymmetricSide']) {
523 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $fieldName;
524 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $fieldName;
525 } else {
526 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $fieldName;
527 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $fieldName;
528 }
529 $skipThisField = $this->arrayCompareComplex($level, $searchArray);
530 }
531 return $skipThisField;
532 }
533
534 /**
535 * Handles complex comparison requests on an array.
536 * A request could look like the following:
537 *
538 * $searchArray = array(
539 * '%AND' => array(
540 * 'key1' => 'value1',
541 * 'key2' => 'value2',
542 * '%OR' => array(
543 * 'subarray' => array(
544 * 'subkey' => 'subvalue'
545 * ),
546 * 'key3' => 'value3',
547 * 'key4' => 'value4'
548 * )
549 * )
550 * );
551 *
552 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
553 * overwriting the sub-array. It could be necessary, if you use complex comparisons.
554 *
555 * The example above means, key1 *AND* key2 (and their values) have to match with
556 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
557 * condition.
558 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
559 * function recurses down one level in that sub-array.
560 *
561 * @param array $subjectArray The array to search in
562 * @param array $searchArray The array with keys and values to search for
563 * @param string $type Use '%AND' or '%OR' for comparison
564 * @return bool The result of the comparison
565 */
566 protected function arrayCompareComplex($subjectArray, $searchArray, $type = '')
567 {
568 $localMatches = 0;
569 $localEntries = 0;
570 if (is_array($searchArray) && !empty($searchArray)) {
571 // If no type was passed, try to determine
572 if (!$type) {
573 reset($searchArray);
574 $type = key($searchArray);
575 $searchArray = current($searchArray);
576 }
577 // We use '%AND' and '%OR' in uppercase
578 $type = strtoupper($type);
579 // Split regular elements from sub elements
580 foreach ($searchArray as $key => $value) {
581 $localEntries++;
582 // Process a sub-group of OR-conditions
583 if ($key === '%OR') {
584 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
585 } elseif ($key === '%AND') {
586 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
587 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
588 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
589 } elseif (is_array($value)) {
590 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
591 } else {
592 if (isset($subjectArray[$key]) && isset($value)) {
593 // Boolean match:
594 if (is_bool($value)) {
595 $localMatches += !($subjectArray[$key] xor $value) ? 1 : 0;
596 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
597 $localMatches += $subjectArray[$key] == $value ? 1 : 0;
598 } else {
599 $localMatches += $subjectArray[$key] === $value ? 1 : 0;
600 }
601 }
602 }
603 // If one or more matches are required ('OR'), return TRUE after the first successful match
604 if ($type === '%OR' && $localMatches > 0) {
605 return true;
606 }
607 // If all matches are required ('AND') and we have no result after the first run, return FALSE
608 if ($type === '%AND' && $localMatches == 0) {
609 return false;
610 }
611 }
612 }
613 // Return the result for '%AND' (if nothing was checked, TRUE is returned)
614 return $localEntries === $localMatches;
615 }
616
617 /**
618 * Checks whether an object is an associative array.
619 *
620 * @param mixed $object The object to be checked
621 * @return bool Returns TRUE, if the object is an associative array
622 */
623 protected function isAssociativeArray($object)
624 {
625 return is_array($object) && !empty($object) && array_keys($object) !== range(0, sizeof($object) - 1);
626 }
627
628 /**
629 * @return BackendUserAuthentication
630 */
631 protected function getBackendUserAuthentication()
632 {
633 return $GLOBALS['BE_USER'];
634 }
635
636 /**
637 * @return LanguageService
638 */
639 protected function getLanguageService()
640 {
641 return $GLOBALS['LANG'];
642 }
643 }