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