[BUGFIX] Determine translations from transOrigPointerField instead of languageField
[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['defaultLanguageData'][$table . ':' . $row['uid']][$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 1,
324 false,
325 $this->data['defaultLanguageRow']['uid']
326 );
327 $fieldConfig = $this->data['processedTca']['columns'][$field];
328 // Don't show content if it's for IRRE child records:
329 if ($fieldConfig['config']['type'] !== 'inline') {
330 /** @var IconFactory $iconFactory */
331 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
332 if ($defaultLanguageValue !== '') {
333 $item .= '<div class="t3-form-original-language" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_misc.xlf:localizeMergeIfNotBlank', true) . '">'
334 . $iconFactory->getIcon($this->data['systemLanguageRows'][0]['flagIconIdentifier'], Icon::SIZE_SMALL)->render()
335 . $this->getMergeBehaviourIcon($fieldConfig['l10n_mode'])
336 . $this->previewFieldValue($defaultLanguageValue, $fieldConfig, $field) . '</div>';
337 }
338 $additionalPreviewLanguages = $this->data['additionalLanguageRows'];
339 foreach ($additionalPreviewLanguages as $previewLanguage) {
340 $defaultLanguageValue = BackendUtility::getProcessedValue(
341 $table,
342 $field,
343 $previewLanguage[$field],
344 0,
345 true
346 );
347 if ($defaultLanguageValue !== '') {
348 $item .= '<div class="t3-form-original-language" title="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_misc.xlf:localizeMergeIfNotBlank', true) . '">'
349 . $iconFactory->getIcon($this->data['systemLanguageRows'][$previewLanguage['sys_language_uid']]['flagIconIdentifier'], Icon::SIZE_SMALL)->render()
350 . $this->getMergeBehaviourIcon($fieldConfig['l10n_mode'])
351 . $this->previewFieldValue($defaultLanguageValue, $fieldConfig, $field) . '</div>';
352 }
353 }
354 }
355 }
356 return $item;
357 }
358
359 /**
360 * Renders an icon to indicate the way the translation and the original is merged (if this is relevant).
361 *
362 * If a field is defined as 'mergeIfNotBlank' this is useful information for an editor. He/she can leave the field blank and
363 * the original value will be used. Without this hint editors are likely to copy the contents even if it is not necessary.
364 *
365 * @param string $l10nMode Localization mode from TCA
366 * @return string
367 */
368 protected function getMergeBehaviourIcon($l10nMode)
369 {
370 $icon = '';
371 if ($l10nMode === 'mergeIfNotBlank') {
372 /** @var IconFactory $iconFactory */
373 $iconFactory = GeneralUtility::makeInstance(IconFactory::class);
374 $icon = $iconFactory->getIcon('actions-edit-merge-localization', Icon::SIZE_SMALL)->render();
375 }
376 return $icon;
377 }
378
379 /**
380 * Renders the diff-view of default language record content compared with what the record was originally translated from.
381 * Will render content if any is found in the internal array
382 *
383 * @param string $table Table name of the record being edited
384 * @param string $field Field name represented by $item
385 * @param array $row Record array of the record being edited
386 * @param string $item HTML of the form field. This is what we add the content to.
387 * @return string Item string returned again, possibly with the original value added to.
388 */
389 protected function renderDefaultLanguageDiff($table, $field, $row, $item)
390 {
391 if (is_array($this->data['defaultLanguageDataDiff'][$table . ':' . $row['uid']])) {
392 // Initialize:
393 $dLVal = array(
394 'old' => $this->data['defaultLanguageDataDiff'][$table . ':' . $row['uid']],
395 'new' => $this->data['defaultLanguageData'][$table . ':' . $row['uid']]
396 );
397 // There must be diff-data:
398 if (isset($dLVal['old'][$field])) {
399 if ((string)$dLVal['old'][$field] !== (string)$dLVal['new'][$field]) {
400 // Create diff-result:
401 $diffUtility = GeneralUtility::makeInstance(DiffUtility::class);
402 $diffres = $diffUtility->makeDiffDisplay(
403 BackendUtility::getProcessedValue($table, $field, $dLVal['old'][$field], 0, 1),
404 BackendUtility::getProcessedValue($table, $field, $dLVal['new'][$field], 0, 1)
405 );
406 $item .= '<div class="t3-form-original-language-diff">
407 <div class="t3-form-original-language-diffheader">' .
408 htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/locallang_core.xlf:labels.changeInOrig')) .
409 '</div>
410 <div class="t3-form-original-language-diffcontent">' . $diffres . '</div>
411 </div>';
412 }
413 }
414 }
415 return $item;
416 }
417
418 /**
419 * Checks if the $table is the child of an inline type AND the $field is the label field of this table.
420 * This function is used to dynamically update the label while editing. This has no effect on labels,
421 * that were processed by a FormEngine-hook on saving.
422 *
423 * @param string $table The table to check
424 * @param string $field The field on this table to check
425 * @return bool Is inline child and field is responsible for the label
426 */
427 protected function isInlineChildAndLabelField($table, $field)
428 {
429 /** @var InlineStackProcessor $inlineStackProcessor */
430 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
431 $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);
432 $level = $inlineStackProcessor->getStructureLevel(-1);
433 if ($level['config']['foreign_label']) {
434 $label = $level['config']['foreign_label'];
435 } else {
436 $label = $this->data['processedTca']['ctrl']['label'];
437 }
438 return $level['config']['foreign_table'] === $table && $label === $field;
439 }
440
441 /**
442 * Rendering of inline fields should be skipped under certain circumstances
443 *
444 * @return bool TRUE if field should be skipped based on inline configuration
445 */
446 protected function inlineFieldShouldBeSkipped()
447 {
448 $table = $this->data['tableName'];
449 $row = $this->data['databaseRow'];
450 $fieldName = $this->data['fieldName'];
451 $fieldConfig = $this->data['processedTca']['columns'][$fieldName]['config'];
452
453 /** @var InlineStackProcessor $inlineStackProcessor */
454 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
455 $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);
456 $structureDepth = $inlineStackProcessor->getStructureDepth();
457
458 $skipThisField = false;
459 if ($structureDepth > 0) {
460 $searchArray = array(
461 '%OR' => array(
462 'config' => array(
463 0 => array(
464 '%AND' => array(
465 'foreign_table' => $table,
466 '%OR' => array(
467 '%AND' => array(
468 'appearance' => array('useCombination' => true),
469 'foreign_selector' => $fieldName
470 ),
471 'MM' => $fieldConfig['MM']
472 )
473 )
474 ),
475 1 => array(
476 '%AND' => array(
477 'foreign_table' => $fieldConfig['foreign_table'],
478 'foreign_selector' => $fieldConfig['foreign_field']
479 )
480 )
481 )
482 )
483 );
484 // Get the parent record from structure stack
485 $level = $inlineStackProcessor->getStructureLevel(-1);
486 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
487 if (RelationHandler::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
488 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $fieldName;
489 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $fieldName;
490 } else {
491 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $fieldName;
492 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $fieldName;
493 }
494 $skipThisField = $this->arrayCompareComplex($level, $searchArray);
495 }
496 return $skipThisField;
497 }
498
499 /**
500 * Handles complex comparison requests on an array.
501 * A request could look like the following:
502 *
503 * $searchArray = array(
504 * '%AND' => array(
505 * 'key1' => 'value1',
506 * 'key2' => 'value2',
507 * '%OR' => array(
508 * 'subarray' => array(
509 * 'subkey' => 'subvalue'
510 * ),
511 * 'key3' => 'value3',
512 * 'key4' => 'value4'
513 * )
514 * )
515 * );
516 *
517 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
518 * overwriting the sub-array. It could be necessary, if you use complex comparisons.
519 *
520 * The example above means, key1 *AND* key2 (and their values) have to match with
521 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
522 * condition.
523 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
524 * function recurses down one level in that sub-array.
525 *
526 * @param array $subjectArray The array to search in
527 * @param array $searchArray The array with keys and values to search for
528 * @param string $type Use '%AND' or '%OR' for comparison
529 * @return bool The result of the comparison
530 */
531 protected function arrayCompareComplex($subjectArray, $searchArray, $type = '')
532 {
533 $localMatches = 0;
534 $localEntries = 0;
535 if (is_array($searchArray) && !empty($searchArray)) {
536 // If no type was passed, try to determine
537 if (!$type) {
538 reset($searchArray);
539 $type = key($searchArray);
540 $searchArray = current($searchArray);
541 }
542 // We use '%AND' and '%OR' in uppercase
543 $type = strtoupper($type);
544 // Split regular elements from sub elements
545 foreach ($searchArray as $key => $value) {
546 $localEntries++;
547 // Process a sub-group of OR-conditions
548 if ($key === '%OR') {
549 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
550 } elseif ($key === '%AND') {
551 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
552 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
553 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
554 } elseif (is_array($value)) {
555 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
556 } else {
557 if (isset($subjectArray[$key]) && isset($value)) {
558 // Boolean match:
559 if (is_bool($value)) {
560 $localMatches += !($subjectArray[$key] xor $value) ? 1 : 0;
561 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
562 $localMatches += $subjectArray[$key] == $value ? 1 : 0;
563 } else {
564 $localMatches += $subjectArray[$key] === $value ? 1 : 0;
565 }
566 }
567 }
568 // If one or more matches are required ('OR'), return TRUE after the first successful match
569 if ($type === '%OR' && $localMatches > 0) {
570 return true;
571 }
572 // If all matches are required ('AND') and we have no result after the first run, return FALSE
573 if ($type === '%AND' && $localMatches == 0) {
574 return false;
575 }
576 }
577 }
578 // Return the result for '%AND' (if nothing was checked, TRUE is returned)
579 return $localEntries === $localMatches;
580 }
581
582 /**
583 * Checks whether an object is an associative array.
584 *
585 * @param mixed $object The object to be checked
586 * @return bool Returns TRUE, if the object is an associative array
587 */
588 protected function isAssociativeArray($object)
589 {
590 return is_array($object) && !empty($object) && array_keys($object) !== range(0, sizeof($object) - 1);
591 }
592
593 /**
594 * @return BackendUserAuthentication
595 */
596 protected function getBackendUserAuthentication()
597 {
598 return $GLOBALS['BE_USER'];
599 }
600
601 /**
602 * @return LanguageService
603 */
604 protected function getLanguageService()
605 {
606 return $GLOBALS['LANG'];
607 }
608 }