AbstractItemProvider.php 60.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
namespace TYPO3\CMS\Backend\Form\FormDataProvider;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

17
18
19
use TYPO3\CMS\Backend\Module\ModuleLoader;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
20
21
22
23
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Database\Query\QueryHelper;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
24
25
use TYPO3\CMS\Core\Database\RelationHandler;
use TYPO3\CMS\Core\Imaging\IconFactory;
26
use TYPO3\CMS\Core\Messaging\FlashMessage;
27
use TYPO3\CMS\Core\Messaging\FlashMessageQueue;
28
use TYPO3\CMS\Core\Messaging\FlashMessageService;
29
use TYPO3\CMS\Core\Utility\ArrayUtility;
30
use TYPO3\CMS\Core\Utility\GeneralUtility;
31
use TYPO3\CMS\Core\Utility\MathUtility;
32
33
34
35
36
37
use TYPO3\CMS\Lang\LanguageService;

/**
 * Contains methods used by Data providers that handle elements
 * with single items like select, radio and some more.
 */
38
39
40
41
42
43
44
45
46
47
48
49
50
51
abstract class AbstractItemProvider
{
    /**
     * Resolve "itemProcFunc" of elements.
     *
     * @param array $result Main result array
     * @param string $fieldName Field name to handle item list for
     * @param array $items Existing items array
     * @return array New list of item elements
     */
    protected function resolveItemProcessorFunction(array $result, $fieldName, array $items)
    {
        $table = $result['tableName'];
        $config = $result['processedTca']['columns'][$fieldName]['config'];
52

53
        $pageTsProcessorParameters = null;
54
55
        if (!empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['itemsProcFunc.'])) {
            $pageTsProcessorParameters = $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['itemsProcFunc.'];
56
57
58
59
60
61
62
63
64
65
        }
        $processorParameters = [
            // Function manipulates $items directly and return nothing
            'items' => &$items,
            'config' => $config,
            'TSconfig' => $pageTsProcessorParameters,
            'table' => $table,
            'row' => $result['databaseRow'],
            'field' => $fieldName,
        ];
66
67
68
        if (!empty($result['flexParentDatabaseRow'])) {
            $processorParameters['flexParentDatabaseRow'] = $result['flexParentDatabaseRow'];
        }
69

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
        try {
            GeneralUtility::callUserFunction($config['itemsProcFunc'], $processorParameters, $this);
        } catch (\Exception $exception) {
            // The itemsProcFunc method may throw an exception, create a flash message if so
            $languageService = $this->getLanguageService();
            $fieldLabel = $fieldName;
            if (!empty($result['processedTca']['columns'][$fieldName]['label'])) {
                $fieldLabel = $languageService->sL($result['processedTca']['columns'][$fieldName]['label']);
            }
            $message = sprintf(
                $languageService->sL('LLL:EXT:lang/locallang_core.xlf:error.items_proc_func_error'),
                $fieldLabel,
                $exception->getMessage()
            );
            /** @var FlashMessage $flashMessage */
            $flashMessage = GeneralUtility::makeInstance(
                FlashMessage::class,
                $message,
                '',
                FlashMessage::ERROR,
                true
            );
            /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
            $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
            $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
            $defaultFlashMessageQueue->enqueue($flashMessage);
        }
97

98
99
        return $items;
    }
100

101
102
103
104
    /**
     * PageTsConfig addItems:
     *
     * TCEFORMS.aTable.aField[.types][.aType].addItems.aValue = aLabel,
105
     * with type specific options merged by pageTsConfig already
106
     *
107
108
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
109
110
111
112
113
114
115
116
     * @param array $result result array
     * @param string $fieldName Current handle field name
     * @param array $items Incoming items
     * @return array Modified item array
     */
    protected function addItemsFromPageTsConfig(array $result, $fieldName, array $items)
    {
        $table = $result['tableName'];
117
118
        if (!empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['addItems.'])
            && is_array($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['addItems.'])
119
        ) {
120
            $addItemsArray = $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['addItems.'];
121
122
123
124
125
126
127
128
129
130
131
132
133
            foreach ($addItemsArray as $value => $label) {
                // If the value ends with a dot, it is a subelement like "34.icon = mylabel.png", skip it
                if (substr($value, -1) === '.') {
                    continue;
                }
                // Check if value "34 = mylabel" also has a "34.icon = myImage.png"
                $icon = null;
                if (isset($addItemsArray[$value . '.'])
                    && is_array($addItemsArray[$value . '.'])
                    && !empty($addItemsArray[$value . '.']['icon'])
                ) {
                    $icon = $addItemsArray[$value . '.']['icon'];
                }
134
                $items[] = [$label, $value, $icon];
135
136
137
138
            }
        }
        return $items;
    }
139

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    /**
     * TCA config "special" evaluation. Add them to $items
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result Result array
     * @param string $fieldName Current handle field name
     * @param array $items Incoming items
     * @return array Modified item array
     * @throws \UnexpectedValueException
     */
    protected function addItemsFromSpecial(array $result, $fieldName, array $items)
    {
        // Guard
        if (empty($result['processedTca']['columns'][$fieldName]['config']['special'])
            || !is_string($result['processedTca']['columns'][$fieldName]['config']['special'])
        ) {
            return $items;
        }

        $languageService = $this->getLanguageService();
        $iconFactory = GeneralUtility::makeInstance(IconFactory::class);

        $special = $result['processedTca']['columns'][$fieldName]['config']['special'];
164
        switch (true) {
165
            case $special === 'tables':
166
167
168
                foreach ($GLOBALS['TCA'] as $currentTable => $_) {
                    if (!empty($GLOBALS['TCA'][$currentTable]['ctrl']['adminOnly'])) {
                        // Hide "admin only" tables
169
170
                        continue;
                    }
171
172
173
174
175
176
177
178
179
180
                    $label = !empty($GLOBALS['TCA'][$currentTable]['ctrl']['title']) ? $GLOBALS['TCA'][$currentTable]['ctrl']['title'] : '';
                    $icon = $iconFactory->mapRecordTypeToIconIdentifier($currentTable, []);
                    $helpText = [];
                    $languageService->loadSingleTableDescription($currentTable);
                    // @todo: check if this actually works, currently help texts are missing
                    $helpTextArray = $GLOBALS['TCA_DESCR'][$currentTable]['columns'][''];
                    if (!empty($helpTextArray['description'])) {
                        $helpText['description'] = $helpTextArray['description'];
                    }
                    $items[] = [$label, $currentTable, $icon, $helpText];
181
                }
182
                break;
183
            case $special === 'pagetypes':
184
185
186
187
188
189
190
191
192
193
194
195
196
197
                if (isset($GLOBALS['TCA']['pages']['columns']['doktype']['config']['items'])
                    && is_array($GLOBALS['TCA']['pages']['columns']['doktype']['config']['items'])
                ) {
                    $specialItems = $GLOBALS['TCA']['pages']['columns']['doktype']['config']['items'];
                    foreach ($specialItems as $specialItem) {
                        if (!is_array($specialItem) || $specialItem[1] === '--div--') {
                            // Skip non arrays and divider items
                            continue;
                        }
                        $label = $specialItem[0];
                        $value = $specialItem[1];
                        $icon = $iconFactory->mapRecordTypeToIconIdentifier('pages', ['doktype' => $specialItem[1]]);
                        $items[] = [$label, $value, $icon];
                    }
198
                }
199
                break;
200
            case $special === 'exclude':
201
202
203
204
205
206
207
208
                $excludeArrays = $this->getExcludeFields();
                foreach ($excludeArrays as $excludeArray) {
                    // If the field comes from a FlexForm, the syntax is more complex
                    if ($excludeArray['origin'] === 'flexForm') {
                        // The field comes from a plugins FlexForm
                        // Add header if not yet set for plugin section
                        if (!isset($items[$excludeArray['sectionHeader']])) {
                            // there is no icon handling for plugins - we take the icon from the table
209
                            $icon = $iconFactory->mapRecordTypeToIconIdentifier($excludeArray['table'], []);
210
211
212
213
214
215
216
217
218
                            $items[$excludeArray['sectionHeader']] = [
                                $excludeArray['sectionHeader'],
                                '--div--',
                                $icon
                            ];
                        }
                    } else {
                        // Add header if not yet set for table
                        if (!isset($items[$excludeArray['table']])) {
219
                            $icon = $iconFactory->mapRecordTypeToIconIdentifier($excludeArray['table'], []);
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
                            $items[$excludeArray['table']] = [
                                $GLOBALS['TCA'][$excludeArray['table']]['ctrl']['title'],
                                '--div--',
                                $icon
                            ];
                        }
                    }
                    // Add help text
                    $helpText = [];
                    $languageService->loadSingleTableDescription($excludeArray['table']);
                    $helpTextArray = $GLOBALS['TCA_DESCR'][$excludeArray['table']]['columns'][$excludeArray['table']];
                    if (!empty($helpTextArray['description'])) {
                        $helpText['description'] = $helpTextArray['description'];
                    }
                    // Item configuration:
235
                    $items[] = [
236
237
238
239
                        rtrim($excludeArray['origin'] === 'flexForm' ? $excludeArray['fieldLabel'] : $languageService->sL($GLOBALS['TCA'][$excludeArray['table']]['columns'][$excludeArray['fieldName']]['label']), ':') . ' (' . $excludeArray['fieldName'] . ')',
                        $excludeArray['table'] . ':' . $excludeArray['fullField'] ,
                        'empty-empty',
                        $helpText
240
                    ];
241
                }
242
                break;
243
            case $special === 'explicitValues':
244
245
246
247
                $theTypes = $this->getExplicitAuthFieldValues();
                $icons = [
                    'ALLOW' => 'status-status-permission-granted',
                    'DENY' => 'status-status-permission-denied'
248
                ];
249
250
251
252
                // Traverse types:
                foreach ($theTypes as $tableFieldKey => $theTypeArrays) {
                    if (is_array($theTypeArrays['items'])) {
                        // Add header:
253
                        $items[] = [
254
255
                            $theTypeArrays['tableFieldLabel'],
                            '--div--',
256
                        ];
257
258
259
260
261
262
263
264
265
                        // Traverse options for this field:
                        foreach ($theTypeArrays['items'] as $itemValue => $itemContent) {
                            // Add item to be selected:
                            $items[] = [
                                '[' . $itemContent[2] . '] ' . $itemContent[1],
                                $tableFieldKey . ':' . preg_replace('/[:|,]/', '', $itemValue) . ':' . $itemContent[0],
                                $icons[$itemContent[0]]
                            ];
                        }
266
267
                    }
                }
268
                break;
269
            case $special === 'languages':
270
271
                foreach ($result['systemLanguageRows'] as $language) {
                    if ($language['uid'] !== -1) {
272
                        $items[] = [
273
274
275
                            0 => $language['title'] . ' [' . $language['uid'] . ']',
                            1 => $language['uid'],
                            2 => $language['flagIconIdentifier']
276
                        ];
277
278
279
                    }
                }
                break;
280
            case $special === 'custom':
281
282
283
284
285
                $customOptions = $GLOBALS['TYPO3_CONF_VARS']['BE']['customPermOptions'];
                if (is_array($customOptions)) {
                    foreach ($customOptions as $coKey => $coValue) {
                        if (is_array($coValue['items'])) {
                            // Add header:
286
                            $items[] = [
287
288
                                $languageService->sL($coValue['header']),
                                '--div--'
289
                            ];
290
291
292
293
294
295
296
297
298
299
300
301
302
303
                            // Traverse items:
                            foreach ($coValue['items'] as $itemKey => $itemCfg) {
                                $icon = 'empty-empty';
                                $helpText = [];
                                if (!empty($itemCfg[2])) {
                                    $helpText['description'] = $languageService->sL($itemCfg[2]);
                                }
                                $items[] = [
                                    $languageService->sL($itemCfg[0]),
                                    $coKey . ':' . preg_replace('/[:|,]/', '', $itemKey),
                                    $icon,
                                    $helpText
                                ];
                            }
304
305
306
                        }
                    }
                }
307
                break;
308
            case $special === 'modListGroup' || $special === 'modListUser':
309
                /** @var ModuleLoader $loadModules */
310
311
312
313
314
                $loadModules = GeneralUtility::makeInstance(ModuleLoader::class);
                $loadModules->load($GLOBALS['TBE_MODULES']);
                $modList = $special === 'modListUser' ? $loadModules->modListUser : $loadModules->modListGroup;
                if (is_array($modList)) {
                    foreach ($modList as $theMod) {
315
316
                        $moduleLabels = $loadModules->getLabelsForModule($theMod);
                        list($mainModule, $subModule) = explode('_', $theMod, 2);
317
                        // Icon:
318
                        if (!empty($subModule)) {
319
                            $icon = $loadModules->modules[$mainModule]['sub'][$subModule]['iconIdentifier'];
320
                        } else {
321
                            $icon = $loadModules->modules[$theMod]['iconIdentifier'];
322
                        }
323
324
                        // Add help text
                        $helpText = [
325
326
                            'title' => $languageService->sL($moduleLabels['shortdescription']),
                            'description' => $languageService->sL($moduleLabels['description'])
327
                        ];
328

329
                        $label = '';
330
331
332
333
                        // Add label for main module if this is a submodule
                        if (!empty($subModule)) {
                            $mainModuleLabels = $loadModules->getLabelsForModule($mainModule);
                            $label .= $languageService->sL($mainModuleLabels['title']) . '>';
334
                        }
335
336
                        // Add modules own label now
                        $label .= $languageService->sL($moduleLabels['title']);
337

338
                        // Item configuration
339
340
                        $items[] = [$label, $theMod, $icon, $helpText];
                    }
341
                }
342
343
344
345
346
347
                break;
            default:
                throw new \UnexpectedValueException(
                    'Unknown special value ' . $special . ' for field ' . $fieldName . ' of table ' . $result['tableName'],
                    1439298496
                );
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
        }
        return $items;
    }

    /**
     * TCA config "fileFolder" evaluation. Add them to $items
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result Result array
     * @param string $fieldName Current handle field name
     * @param array $items Incoming items
     * @return array Modified item array
     */
    protected function addItemsFromFolder(array $result, $fieldName, array $items)
    {
        if (empty($result['processedTca']['columns'][$fieldName]['config']['fileFolder'])
            || !is_string($result['processedTca']['columns'][$fieldName]['config']['fileFolder'])
        ) {
            return $items;
        }

        $fileFolder = $result['processedTca']['columns'][$fieldName]['config']['fileFolder'];
        $fileFolder = GeneralUtility::getFileAbsFileName($fileFolder);
        $fileFolder = rtrim($fileFolder, '/') . '/';

        if (@is_dir($fileFolder)) {
            $fileExtensionList = '';
            if (!empty($result['processedTca']['columns'][$fieldName]['config']['fileFolder_extList'])
                && is_string($result['processedTca']['columns'][$fieldName]['config']['fileFolder_extList'])
            ) {
                $fileExtensionList = $result['processedTca']['columns'][$fieldName]['config']['fileFolder_extList'];
            }
            $recursionLevels = isset($fieldValue['config']['fileFolder_recursions'])
                ? MathUtility::forceIntegerInRange($fieldValue['config']['fileFolder_recursions'], 0, 99)
                : 99;
            $fileArray = GeneralUtility::getAllFilesAndFoldersInPath([], $fileFolder, $fileExtensionList, 0, $recursionLevels);
            $fileArray = GeneralUtility::removePrefixPathFromList($fileArray, $fileFolder);
            foreach ($fileArray as $fileReference) {
                $fileInformation = pathinfo($fileReference);
                $icon = GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], strtolower($fileInformation['extension']))
389
                    ? $fileFolder . $fileReference
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
                    : '';
                $items[] = [
                    $fileReference,
                    $fileReference,
                    $icon
                ];
            }
        }

        return $items;
    }

    /**
     * TCA config "foreign_table" evaluation. Add them to $items
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result Result array
     * @param string $fieldName Current handle field name
     * @param array $items Incoming items
     * @return array Modified item array
411
     * @throws \UnexpectedValueException
412
413
414
415
416
417
418
419
420
421
422
423
424
     */
    protected function addItemsFromForeignTable(array $result, $fieldName, array $items)
    {
        // Guard
        if (empty($result['processedTca']['columns'][$fieldName]['config']['foreign_table'])
            || !is_string($result['processedTca']['columns'][$fieldName]['config']['foreign_table'])
        ) {
            return $items;
        }

        $languageService = $this->getLanguageService();

        $foreignTable = $result['processedTca']['columns'][$fieldName]['config']['foreign_table'];
425
426
427
428
429
430
431
432
433

        if (!is_array($GLOBALS['TCA'][$foreignTable])) {
            throw new \UnexpectedValueException(
                'Field ' . $fieldName . ' of table ' . $result['tableName'] . ' reference to foreign table '
                . $foreignTable . ', but this table is not defined in TCA',
                1439569743
            );
        }

434
435
        $queryBuilder = $this->buildForeignTableQueryBuilder($result, $fieldName);
        $queryResult = $queryBuilder->execute();
436
437

        // Early return on error with flash message
438
        $databaseError = $queryResult->errorInfo();
439
        if (!empty($databaseError)) {
440
            $msg = $databaseError . '. ';
441
442
443
444
445
446
447
448
449
            $msg .= $languageService->sL('LLL:EXT:lang/locallang_core.xlf:error.database_schema_mismatch');
            $msgTitle = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:error.database_schema_mismatch_title');
            /** @var $flashMessage FlashMessage */
            $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $msg, $msgTitle, FlashMessage::ERROR, true);
            /** @var $flashMessageService FlashMessageService */
            $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
            /** @var $defaultFlashMessageQueue FlashMessageQueue */
            $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
            $defaultFlashMessageQueue->enqueue($flashMessage);
450
            $queryResult->closeCursor();
451
452
453
454
455
456
457
458
459
460
461
            return $items;
        }

        $labelPrefix = '';
        if (!empty($result['processedTca']['columns'][$fieldName]['config']['foreign_table_prefix'])) {
            $labelPrefix = $result['processedTca']['columns'][$fieldName]['config']['foreign_table_prefix'];
            $labelPrefix = $languageService->sL($labelPrefix);
        }

        $iconFactory = GeneralUtility::makeInstance(IconFactory::class);

462
        while ($foreignRow = $queryResult->fetch()) {
463
464
            BackendUtility::workspaceOL($foreignTable, $foreignRow);
            if (is_array($foreignRow)) {
465
466
467
468
469
470
471
472
473
474
                // If the foreign table sets selicon_field, this field can contain an image
                // that represents this specific row.
                $iconFieldName = '';
                if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['selicon_field'])) {
                    $iconFieldName = $GLOBALS['TCA'][$foreignTable]['ctrl']['selicon_field'];
                }
                $iconPath = '';
                if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['selicon_field_path'])) {
                    $iconPath = $GLOBALS['TCA'][$foreignTable]['ctrl']['selicon_field_path'];
                }
475
                if ($iconFieldName && $iconPath && $foreignRow[$iconFieldName]) {
476
                    // Prepare the row icon if available
477
                    $iParts = GeneralUtility::trimExplode(',', $foreignRow[$iconFieldName], true);
478
                    $icon = $iconPath . '/' . trim($iParts[0]);
479
                } else {
480
                    // Else, determine icon based on record type, or a generic fallback
481
482
483
484
                    $icon = $iconFactory->mapRecordTypeToIconIdentifier($foreignTable, $foreignRow);
                }
                // Add the item
                $items[] = [
485
                    $labelPrefix . BackendUtility::getRecordTitle($foreignTable, $foreignRow),
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
                    $foreignRow['uid'],
                    $icon
                ];
            }
        }

        return $items;
    }

    /**
     * Remove items using "keepItems" pageTsConfig
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result Result array
     * @param string $fieldName Current handle field name
     * @param array $items Incoming items
     * @return array Modified item array
     */
    protected function removeItemsByKeepItemsPageTsConfig(array $result, $fieldName, array $items)
    {
        $table = $result['tableName'];
508
        if (!isset($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
509
510
511
512
513
            || !is_string($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
        ) {
            return $items;
        }

514
515
516
517
518
519
        // If keepItems is set but is an empty list all current items get removed
        if (empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
            && $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'] !== '0') {
            return [];
        }

520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
        return ArrayUtility::keepItemsInArray(
            $items,
            $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'],
            function ($value) {
                return $value[1];
            }
        );
    }

    /**
     * Remove items using "removeItems" pageTsConfig
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result Result array
     * @param string $fieldName Current handle field name
     * @param array $items Incoming items
     * @return array Modified item array
     */
    protected function removeItemsByRemoveItemsPageTsConfig(array $result, $fieldName, array $items)
    {
        $table = $result['tableName'];
        if (empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['removeItems'])
            || !is_string($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['removeItems'])
        ) {
            return $items;
        }

        $removeItems = GeneralUtility::trimExplode(
            ',',
            $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['removeItems'],
            true
        );
        foreach ($items as $key => $itemValues) {
            if (in_array($itemValues[1], $removeItems)) {
                unset($items[$key]);
            }
        }

        return $items;
    }

    /**
     * Remove items user restriction on language field
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result Result array
     * @param string $fieldName Current handle field name
     * @param array $items Incoming items
     * @return array Modified item array
     */
    protected function removeItemsByUserLanguageFieldRestriction(array $result, $fieldName, array $items)
    {
        // Guard clause returns if not a language field is handled
        if (empty($result['processedTca']['ctrl']['languageField'])
            || $result['processedTca']['ctrl']['languageField'] !== $fieldName
        ) {
            return $items;
        }

        $backendUser = $this->getBackendUser();
        foreach ($items as $key => $itemValues) {
            if (!$backendUser->checkLanguageAccess($itemValues[1])) {
                unset($items[$key]);
            }
        }

        return $items;
    }

    /**
     * Remove items by user restriction on authMode items
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result Result array
     * @param string $fieldName Current handle field name
     * @param array $items Incoming items
     * @return array Modified item array
     */
    protected function removeItemsByUserAuthMode(array $result, $fieldName, array $items)
    {
        // Guard clause returns early if no authMode field is configured
        if (!isset($result['processedTca']['columns'][$fieldName]['config']['authMode'])
            || !is_string($result['processedTca']['columns'][$fieldName]['config']['authMode'])
        ) {
            return $items;
        }

        $backendUser = $this->getBackendUser();
        $authMode = $result['processedTca']['columns'][$fieldName]['config']['authMode'];
        foreach ($items as $key => $itemValues) {
            // @todo: checkAuthMode() uses $GLOBAL access for "individual" authMode - get rid of this
            if (!$backendUser->checkAuthMode($result['tableName'], $fieldName, $itemValues[1], $authMode)) {
                unset($items[$key]);
            }
        }

        return $items;
    }

    /**
     * Remove items if doktype is handled for non admin users
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result Result array
     * @param string $fieldName Current handle field name
     * @param array $items Incoming items
     * @return array Modified item array
     */
    protected function removeItemsByDoktypeUserRestriction(array $result, $fieldName, array $items)
    {
        $table = $result['tableName'];
        $backendUser = $this->getBackendUser();
        // Guard clause returns if not correct table and field or if user is admin
        if ($table !== 'pages' && $table !== 'pages_language_overlay'
            || $fieldName !== 'doktype' || $backendUser->isAdmin()
        ) {
            return $items;
        }

        $allowedPageTypes = $backendUser->groupData['pagetypes_select'];
        foreach ($items as $key => $itemValues) {
            if (!GeneralUtility::inList($allowedPageTypes, $itemValues[1])) {
                unset($items[$key]);
            }
        }

        return $items;
    }

    /**
     * Returns an array with the exclude fields as defined in TCA and FlexForms
     * Used for listing the exclude fields in be_groups forms.
     *
     * @return array Array of arrays with excludeFields (fieldName, table:fieldName) from TCA
     *               and FlexForms (fieldName, table:extKey;sheetName;fieldName)
     */
    protected function getExcludeFields()
    {
        $languageService = $this->getLanguageService();
        $finalExcludeArray = [];

        // Fetch translations for table names
        $tableToTranslation = [];
        // All TCA keys
        foreach ($GLOBALS['TCA'] as $table => $conf) {
669
            $tableToTranslation[$table] = $languageService->sL($conf['ctrl']['title']);
670
671
672
673
674
675
676
677
678
679
680
681
682
683
        }
        // Sort by translations
        asort($tableToTranslation);
        foreach ($tableToTranslation as $table => $translatedTable) {
            $excludeArrayTable = [];

            // All field names configured and not restricted to admins
            if (is_array($GLOBALS['TCA'][$table]['columns'])
                && empty($GLOBALS['TCA'][$table]['ctrl']['adminOnly'])
                && (empty($GLOBALS['TCA'][$table]['ctrl']['rootLevel']) || !empty($GLOBALS['TCA'][$table]['ctrl']['security']['ignoreRootLevelRestriction']))
            ) {
                foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $_) {
                    if ($GLOBALS['TCA'][$table]['columns'][$field]['exclude']) {
                        // Get human readable names of fields
684
685
686
687
688
689
690
691
692
693
694
695
                        $translatedField = $languageService->sL($GLOBALS['TCA'][$table]['columns'][$field]['label']);
                        // Add entry, key 'labels' needed for sorting
                        $excludeArrayTable[] = [
                            'labels' => $translatedTable . ':' . $translatedField,
                            'sectionHeader' => $translatedTable,
                            'table' => $table,
                            'tableField' => $field,
                            'fieldName' => $field,
                            'fullField' => $field,
                            'fieldLabel' => $translatedField,
                            'origin' => 'tca',
                        ];
696
697
698
699
700
701
702
703
704
                    }
                }
            }
            // All FlexForm fields
            $flexFormArray = $this->getRegisteredFlexForms($table);
            foreach ($flexFormArray as $tableField => $flexForms) {
                // Prefix for field label, e.g. "Plugin Options:"
                $labelPrefix = '';
                if (!empty($GLOBALS['TCA'][$table]['columns'][$tableField]['label'])) {
705
                    $labelPrefix = $languageService->sL($GLOBALS['TCA'][$table]['columns'][$tableField]['label']);
706
707
708
                }
                // Get all sheets and title
                foreach ($flexForms as $extIdent => $extConf) {
709
                    $extTitle = $languageService->sL(trim($extConf['title']));
710
711
712
713
714
                    // Get all fields in sheet
                    foreach ($extConf['ds']['sheets'] as $sheetName => $sheet) {
                        if (empty($sheet['ROOT']['el']) || !is_array($sheet['ROOT']['el'])) {
                            continue;
                        }
715
                        foreach ($sheet['ROOT']['el'] as $pluginFieldName => $field) {
716
717
718
719
                            // Use only fields that have exclude flag set
                            if (empty($field['TCEforms']['exclude'])) {
                                continue;
                            }
720
721
722
723
724
725
726
727
728
729
730
731
732
733
                            $fieldLabel = !empty($field['TCEforms']['label'])
                                ? $languageService->sL($field['TCEforms']['label'])
                                : $pluginFieldName;
                            $excludeArrayTable[] = [
                                'labels' => trim($translatedTable . ' ' . $labelPrefix . ' ' . $extIdent, ': ') . ':' . $fieldLabel,
                                'sectionHeader' => trim(($translatedTable . ' ' . $labelPrefix . ' ' . $extIdent), ':'),
                                'table' => $table,
                                'tableField' => $tableField,
                                'extIdent' => $extIdent,
                                'fieldName' => $pluginFieldName,
                                'fullField' => $tableField . ';' . $extIdent . ';' . $sheetName . ';' . $pluginFieldName,
                                'fieldLabel' => $fieldLabel,
                                'origin' => 'flexForm',
                            ];
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
                        }
                    }
                }
            }
            // Sort fields by the translated value
            if (!empty($excludeArrayTable)) {
                usort($excludeArrayTable, function (array $array1, array $array2) {
                    $array1 = reset($array1);
                    $array2 = reset($array2);
                    if (is_string($array1) && is_string($array2)) {
                        return strcasecmp($array1, $array2);
                    }
                    return 0;
                });
                $finalExcludeArray = array_merge($finalExcludeArray, $excludeArrayTable);
            }
        }

        return $finalExcludeArray;
    }

    /**
     * Returns all registered FlexForm definitions with title and fields
     *
     * @param string $table Table to handle
     * @return array Data structures with speaking extension title
     */
    protected function getRegisteredFlexForms($table)
    {
        if (empty($table) || empty($GLOBALS['TCA'][$table]['columns'])) {
            return [];
        }
        $flexForms = [];
        foreach ($GLOBALS['TCA'][$table]['columns'] as $tableField => $fieldConf) {
            if (!empty($fieldConf['config']['type']) && !empty($fieldConf['config']['ds']) && $fieldConf['config']['type'] == 'flex') {
                $flexForms[$tableField] = [];
                // Get pointer fields
771
                $pointerFields = !empty($fieldConf['config']['ds_pointerField']) ? $fieldConf['config']['ds_pointerField'] : 'list_type,CType,default';
772
773
774
775
776
777
778
779
780
781
782
783
784
                $pointerFields = GeneralUtility::trimExplode(',', $pointerFields);
                // Get FlexForms
                foreach ($fieldConf['config']['ds'] as $flexFormKey => $dataStructure) {
                    // Get extension identifier (uses second value if it's not empty, "list" or "*", else first one)
                    $identFields = GeneralUtility::trimExplode(',', $flexFormKey);
                    $extIdent = $identFields[0];
                    if (!empty($identFields[1]) && $identFields[1] !== 'list' && $identFields[1] !== '*') {
                        $extIdent = $identFields[1];
                    }
                    // Load external file references
                    if (!is_array($dataStructure)) {
                        $file = GeneralUtility::getFileAbsFileName(str_ireplace('FILE:', '', $dataStructure));
                        if ($file && @is_file($file)) {
785
                            $dataStructure = file_get_contents($file);
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
                        }
                        $dataStructure = GeneralUtility::xml2array($dataStructure);
                        if (!is_array($dataStructure)) {
                            continue;
                        }
                    }
                    // Get flexform content
                    $dataStructure = GeneralUtility::resolveAllSheetsInDS($dataStructure);
                    if (empty($dataStructure['sheets']) || !is_array($dataStructure['sheets'])) {
                        continue;
                    }
                    // Use DS pointer to get extension title from TCA
                    // @todo: I don't understand this code ... does it make sense at all?
                    $title = $extIdent;
                    $keyFields = GeneralUtility::trimExplode(',', $flexFormKey);
                    foreach ($pointerFields as $pointerKey => $pointerName) {
802
803
804
805
806
                        if (empty($keyFields[$pointerKey])
                            || $keyFields[$pointerKey] === '*'
                            || $keyFields[$pointerKey] === 'list'
                            || $keyFields[$pointerKey] === 'default'
                        ) {
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
                            continue;
                        }
                        if (!empty($GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'])) {
                            $items = $GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'];
                            if (!is_array($items)) {
                                continue;
                            }
                            foreach ($items as $itemConf) {
                                if (!empty($itemConf[0]) && !empty($itemConf[1]) && $itemConf[1] == $keyFields[$pointerKey]) {
                                    $title = $itemConf[0];
                                    break 2;
                                }
                            }
                        }
                    }
                    $flexForms[$tableField][$extIdent] = [
                        'title' => $title,
                        'ds' => $dataStructure
                    ];
                }
            }
        }
        return $flexForms;
    }

    /**
     * Returns an array with explicit Allow/Deny fields.
     * Used for listing these field/value pairs in be_groups forms
     *
     * @return array Array with information from all of $GLOBALS['TCA']
     */
    protected function getExplicitAuthFieldValues()
    {
        $languageService = static::getLanguageService();
        $adLabel = [
842
843
            'ALLOW' => $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.allow'),
            'DENY' => $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.deny')
844
845
846
847
848
        ];
        $allowDenyOptions = [];
        foreach ($GLOBALS['TCA'] as $table => $_) {
            // All field names configured:
            if (is_array($GLOBALS['TCA'][$table]['columns'])) {
849
                foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $__) {
850
851
852
853
854
855
                    $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
                    if ($fieldConfig['type'] === 'select' && $fieldConfig['authMode']) {
                        // Check for items
                        if (is_array($fieldConfig['items'])) {
                            // Get Human Readable names of fields and table:
                            $allowDenyOptions[$table . ':' . $field]['tableFieldLabel'] =
856
857
                                $languageService->sL($GLOBALS['TCA'][$table]['ctrl']['title']) . ': '
                                . $languageService->sL($GLOBALS['TCA'][$table]['columns'][$field]['label']);
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
                            foreach ($fieldConfig['items'] as $iVal) {
                                // Values '' is not controlled by this setting.
                                if ((string)$iVal[1] !== '') {
                                    // Find iMode
                                    $iMode = '';
                                    switch ((string)$fieldConfig['authMode']) {
                                        case 'explicitAllow':
                                            $iMode = 'ALLOW';
                                            break;
                                        case 'explicitDeny':
                                            $iMode = 'DENY';
                                            break;
                                        case 'individual':
                                            if ($iVal[4] === 'EXPL_ALLOW') {
                                                $iMode = 'ALLOW';
                                            } elseif ($iVal[4] === 'EXPL_DENY') {
                                                $iMode = 'DENY';
                                            }
                                            break;
                                    }
                                    // Set iMode
                                    if ($iMode) {
                                        $allowDenyOptions[$table . ':' . $field]['items'][$iVal[1]] = [
                                            $iMode,
882
                                            $languageService->sL($iVal[0]),
883
884
885
886
887
888
889
890
891
892
893
894
895
896
                                            $adLabel[$iMode]
                                        ];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return $allowDenyOptions;
    }

    /**
897
898
     * Build query to fetch foreign records. Helper method of
     * addItemsFromForeignTable(), do not call otherwise.
899
900
901
     *
     * @param array $result Result array
     * @param string $localFieldName Current handle field name
902
     * @return QueryBuilder
903
     */
904
    protected function buildForeignTableQueryBuilder(array $result, string $localFieldName):  QueryBuilder
905
906
907
908
909
910
    {
        $backendUser = $this->getBackendUser();

        $foreignTableName = $result['processedTca']['columns'][$localFieldName]['config']['foreign_table'];
        $foreignTableClauseArray = $this->processForeignTableClause($result, $foreignTableName, $localFieldName);

911
912
913
914
915
916
917
918
919
920
        $fieldList = BackendUtility::getCommonSelectFields($foreignTableName, $foreignTableName . '.');
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($foreignTableName);

        $queryBuilder->getRestrictions()
            ->removeAll()
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));

        $queryBuilder
            ->select(...GeneralUtility::trimExplode(',', $fieldList, true))
921
922
            ->from($foreignTableName)
            ->where($foreignTableClauseArray['WHERE']);
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942

        if (!empty($foreignTableClauseArray['GROUPBY'])) {
            $queryBuilder->groupBy($foreignTableClauseArray['GROUPBY']);
        }

        if (!empty($foreignTableClauseArray['ORDERBY'])) {
            foreach ($foreignTableClauseArray['ORDERBY'] as $orderPair) {
                list($fieldName, $order) = $orderPair;
                $queryBuilder->addOrderBy($fieldName, $order);
            }
        }

        if (!empty($foreignTableClauseArray['LIMIT'])) {
            if (!empty($foreignTableClauseArray['LIMIT'][1])) {
                $queryBuilder->setMaxResults($foreignTableClauseArray['LIMIT'][1]);
                $queryBuilder->setFirstResult($foreignTableClauseArray['LIMIT'][0]);
            } elseif (!empty($foreignTableClauseArray['LIMIT'][0])) {
                $queryBuilder->setMaxResults($foreignTableClauseArray['LIMIT'][0]);
            }
        }
943
944
945
946
947
948

        // rootLevel = -1 means that elements can be on the rootlevel OR on any page (pid!=-1)
        // rootLevel = 0 means that elements are not allowed on root level
        // rootLevel = 1 means that elements are only on the root level (pid=0)
        $rootLevel = 0;
        if (isset($GLOBALS['TCA'][$foreignTableName]['ctrl']['rootLevel'])) {
949
            $rootLevel = (int)$GLOBALS['TCA'][$foreignTableName]['ctrl']['rootLevel'];
950
        }
951
952

        if ($rootLevel === -1) {
953
            $queryBuilder->andWhere($queryBuilder->expr()->neq($foreignTableName . '.pid', -1));
954
        } elseif ($rootLevel === 1) {
955
            $queryBuilder->andWhere($queryBuilder->expr()->eq($foreignTableName . '.pid', 0));
956
        } else {
957
            $queryBuilder->andWhere($backendUser->getPagePermsClause(1));
958
959
960
961
962
963
964
965
966
            if ($foreignTableName !== 'pages') {
                $queryBuilder
                    ->from('pages')
                    ->andWhere(
                        $queryBuilder->expr()->eq(
                            'pages.uid',
                            $queryBuilder->quoteIdentifier($foreignTableName . '.pid')
                        )
                    );
967
968
969
            }
        }

970
        return $queryBuilder;
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
    }

    /**
     * Replace markers in a where clause from TCA foreign_table_where
     *
     * ###REC_FIELD_[field name]###
     * ###THIS_UID### - is current element uid (zero if new).
     * ###CURRENT_PID### - is the current page id (pid of the record).
     * ###SITEROOT###
     * ###PAGE_TSCONFIG_ID### - a value you can set from Page TSconfig dynamically.
     * ###PAGE_TSCONFIG_IDLIST### - a value you can set from Page TSconfig dynamically.
     * ###PAGE_TSCONFIG_STR### - a value you can set from Page TSconfig dynamically.
     *
     * @param array $result Result array
     * @param string $foreignTableName Name of foreign table
     * @param string $localFieldName Current handle field name
     * @return array Query parts with keys WHERE, ORDERBY, GROUPBY, LIMIT
     */
    protected function processForeignTableClause(array $result, $foreignTableName, $localFieldName)
    {
991
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($foreignTableName);
992
        $localTable = $result['tableName'];
993
        $effectivePid = $result['effectivePid'];
994
995
996
997
998
999
1000

        $foreignTableClause = '';
        if (!empty($result['processedTca']['columns'][$localFieldName]['config']['foreign_table_where'])
            && is_string($result['processedTca']['columns'][$localFieldName]['config']['foreign_table_where'])
        ) {
            $foreignTableClause = $result['processedTca']['columns'][$localFieldName]['config']['foreign_table_where'];
            // Replace possible markers in query