AbstractItemProvider.php 62.3 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
use Doctrine\DBAL\DBALException;
18
19
20
use TYPO3\CMS\Backend\Module\ModuleLoader;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
21
use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidIdentifierException;
22
use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
23
24
25
26
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;
27
use TYPO3\CMS\Core\Database\RelationHandler;
28
use TYPO3\CMS\Core\Imaging\Icon;
29
use TYPO3\CMS\Core\Imaging\IconFactory;
30
use TYPO3\CMS\Core\Imaging\IconRegistry;
31
use TYPO3\CMS\Core\Messaging\FlashMessage;
32
use TYPO3\CMS\Core\Messaging\FlashMessageQueue;
33
use TYPO3\CMS\Core\Messaging\FlashMessageService;
34
use TYPO3\CMS\Core\Utility\ArrayUtility;
35
use TYPO3\CMS\Core\Utility\GeneralUtility;
36
use TYPO3\CMS\Core\Utility\MathUtility;
37
38
39
40
41
42
use TYPO3\CMS\Lang\LanguageService;

/**
 * Contains methods used by Data providers that handle elements
 * with single items like select, radio and some more.
 */
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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'];
57

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

75
76
77
78
79
80
81
82
83
84
        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(
85
                $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:error.items_proc_func_error'),
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
                $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);
        }
102

103
104
        return $items;
    }
105

106
107
108
109
    /**
     * PageTsConfig addItems:
     *
     * TCEFORMS.aTable.aField[.types][.aType].addItems.aValue = aLabel,
110
     * with type specific options merged by pageTsConfig already
111
     *
112
113
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
114
115
116
117
118
119
120
121
     * @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'];
122
        $iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
123
124
        if (!empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['addItems.'])
            && is_array($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['addItems.'])
125
        ) {
126
            $addItemsArray = $result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['addItems.'];
127
128
129
130
131
132
            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"
133
                $iconIdentifier = null;
134
135
136
137
                if (isset($addItemsArray[$value . '.'])
                    && is_array($addItemsArray[$value . '.'])
                    && !empty($addItemsArray[$value . '.']['icon'])
                ) {
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
                    $iconIdentifier = $addItemsArray[$value . '.']['icon'];
                    if (!$iconRegistry->isRegistered($iconIdentifier)) {
                        GeneralUtility::deprecationLog(
                            'Using a file path for icon in pageTsConfig addItems is deprecated.' .
                            'Use a registered iconIdentifier instead'
                        );
                        $iconPath = GeneralUtility::getFileAbsFileName($iconIdentifier);
                        if ($iconPath !== '') {
                            $iconIdentifier = md5($iconPath);
                            $iconRegistry->registerIcon(
                                $iconIdentifier,
                                $iconRegistry->detectIconProvider($iconPath),
                                [
                                    'source' => $iconPath
                                ]
                            );
                        }
                    }
156
                }
157
                $items[] = [$label, $value, $iconIdentifier];
158
159
160
161
            }
        }
        return $items;
    }
162

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    /**
     * 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();
184
        $iconRegistry = GeneralUtility::makeInstance(IconRegistry::class);
185
186
187
        $iconFactory = GeneralUtility::makeInstance(IconFactory::class);

        $special = $result['processedTca']['columns'][$fieldName]['config']['special'];
188
        switch (true) {
189
            case $special === 'tables':
190
191
192
                foreach ($GLOBALS['TCA'] as $currentTable => $_) {
                    if (!empty($GLOBALS['TCA'][$currentTable]['ctrl']['adminOnly'])) {
                        // Hide "admin only" tables
193
194
                        continue;
                    }
195
196
197
198
199
200
201
202
203
204
                    $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];
205
                }
206
                break;
207
            case $special === 'pagetypes':
208
209
210
211
212
213
214
215
216
217
218
219
220
221
                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];
                    }
222
                }
223
                break;
224
            case $special === 'exclude':
225
226
227
228
229
230
231
232
                $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
233
                            $icon = $iconFactory->mapRecordTypeToIconIdentifier($excludeArray['table'], []);
234
235
236
237
238
239
240
241
242
                            $items[$excludeArray['sectionHeader']] = [
                                $excludeArray['sectionHeader'],
                                '--div--',
                                $icon
                            ];
                        }
                    } else {
                        // Add header if not yet set for table
                        if (!isset($items[$excludeArray['table']])) {
243
                            $icon = $iconFactory->mapRecordTypeToIconIdentifier($excludeArray['table'], []);
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
                            $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:
259
                    $items[] = [
260
261
262
263
                        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
264
                    ];
265
                }
266
                break;
267
            case $special === 'explicitValues':
268
269
270
271
                $theTypes = $this->getExplicitAuthFieldValues();
                $icons = [
                    'ALLOW' => 'status-status-permission-granted',
                    'DENY' => 'status-status-permission-denied'
272
                ];
273
274
275
276
                // Traverse types:
                foreach ($theTypes as $tableFieldKey => $theTypeArrays) {
                    if (is_array($theTypeArrays['items'])) {
                        // Add header:
277
                        $items[] = [
278
279
                            $theTypeArrays['tableFieldLabel'],
                            '--div--',
280
                        ];
281
282
283
284
285
286
287
288
289
                        // 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]]
                            ];
                        }
290
291
                    }
                }
292
                break;
293
            case $special === 'languages':
294
295
                foreach ($result['systemLanguageRows'] as $language) {
                    if ($language['uid'] !== -1) {
296
                        $items[] = [
297
298
299
                            0 => $language['title'] . ' [' . $language['uid'] . ']',
                            1 => $language['uid'],
                            2 => $language['flagIconIdentifier']
300
                        ];
301
302
303
                    }
                }
                break;
304
            case $special === 'custom':
305
306
307
308
309
                $customOptions = $GLOBALS['TYPO3_CONF_VARS']['BE']['customPermOptions'];
                if (is_array($customOptions)) {
                    foreach ($customOptions as $coKey => $coValue) {
                        if (is_array($coValue['items'])) {
                            // Add header:
310
                            $items[] = [
311
312
                                $languageService->sL($coValue['header']),
                                '--div--'
313
                            ];
314
315
316
317
                            // Traverse items:
                            foreach ($coValue['items'] as $itemKey => $itemCfg) {
                                $icon = 'empty-empty';
                                $helpText = [];
318
319
320
321
322
323
                                if (!empty($itemCfg[1])) {
                                    if ($iconRegistry->isRegistered($itemCfg[1])) {
                                        // Use icon identifier when registered
                                        $icon = $itemCfg[1];
                                    }
                                }
324
325
326
327
328
329
330
331
332
333
                                if (!empty($itemCfg[2])) {
                                    $helpText['description'] = $languageService->sL($itemCfg[2]);
                                }
                                $items[] = [
                                    $languageService->sL($itemCfg[0]),
                                    $coKey . ':' . preg_replace('/[:|,]/', '', $itemKey),
                                    $icon,
                                    $helpText
                                ];
                            }
334
335
336
                        }
                    }
                }
337
                break;
338
            case $special === 'modListGroup' || $special === 'modListUser':
339
                /** @var ModuleLoader $loadModules */
340
341
342
343
344
                $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) {
345
346
                        $moduleLabels = $loadModules->getLabelsForModule($theMod);
                        list($mainModule, $subModule) = explode('_', $theMod, 2);
347
                        // Icon:
348
                        if (!empty($subModule)) {
349
                            $icon = $loadModules->modules[$mainModule]['sub'][$subModule]['iconIdentifier'];
350
                        } else {
351
                            $icon = $loadModules->modules[$theMod]['iconIdentifier'];
352
                        }
353
354
                        // Add help text
                        $helpText = [
355
356
                            'title' => $languageService->sL($moduleLabels['shortdescription']),
                            'description' => $languageService->sL($moduleLabels['description'])
357
                        ];
358

359
                        $label = '';
360
361
362
363
                        // Add label for main module if this is a submodule
                        if (!empty($subModule)) {
                            $mainModuleLabels = $loadModules->getLabelsForModule($mainModule);
                            $label .= $languageService->sL($mainModuleLabels['title']) . '>';
364
                        }
365
366
                        // Add modules own label now
                        $label .= $languageService->sL($moduleLabels['title']);
367

368
                        // Item configuration
369
370
                        $items[] = [$label, $theMod, $icon, $helpText];
                    }
371
                }
372
373
374
375
376
377
                break;
            default:
                throw new \UnexpectedValueException(
                    'Unknown special value ' . $special . ' for field ' . $fieldName . ' of table ' . $result['tableName'],
                    1439298496
                );
378
379
380
381
382
383
384
385
386
387
388
389
390
        }
        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
391
     * @throws \RuntimeException
392
393
394
395
396
397
398
399
400
     */
    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;
        }

401
402
403
404
405
406
407
408
        $fileFolderRaw = $result['processedTca']['columns'][$fieldName]['config']['fileFolder'];
        $fileFolder = GeneralUtility::getFileAbsFileName($fileFolderRaw);
        if ($fileFolder === '') {
            throw new \RuntimeException(
                'Invalid folder given for item processing: ' . $fileFolderRaw . ' for table ' . $result['tableName'] . ', field ' . $fieldName,
                1479399227
            );
        }
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
        $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']))
426
                    ? $fileFolder . $fileReference
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
                    : '';
                $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
448
     * @throws \UnexpectedValueException
449
450
451
452
453
454
455
456
457
458
459
460
461
     */
    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'];
462
463
464
465
466
467
468
469
470

        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
            );
        }

471
        $queryBuilder = $this->buildForeignTableQueryBuilder($result, $fieldName);
472
473
474
475
476
        try {
            $queryResult = $queryBuilder->execute();
        } catch (DBALException $e) {
            $databaseError = $e->getPrevious()->getMessage();
        }
477
478
479

        // Early return on error with flash message
        if (!empty($databaseError)) {
480
            $msg = $databaseError . '. ';
481
482
            $msg .= $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:error.database_schema_mismatch');
            $msgTitle = $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:error.database_schema_mismatch_title');
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
            /** @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);
            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);

501
        while ($foreignRow = $queryResult->fetch()) {
502
503
            BackendUtility::workspaceOL($foreignTable, $foreignRow);
            if (is_array($foreignRow)) {
504
505
506
507
508
509
510
511
512
513
                // 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'];
                }
514
                if ($iconFieldName && $iconPath && $foreignRow[$iconFieldName]) {
515
                    // Prepare the row icon if available
516
                    $iParts = GeneralUtility::trimExplode(',', $foreignRow[$iconFieldName], true);
517
                    $icon = $iconPath . '/' . trim($iParts[0]);
518
                } else {
519
                    // Else, determine icon based on record type, or a generic fallback
520
521
522
523
                    $icon = $iconFactory->mapRecordTypeToIconIdentifier($foreignTable, $foreignRow);
                }
                // Add the item
                $items[] = [
524
                    $labelPrefix . BackendUtility::getRecordTitle($foreignTable, $foreignRow),
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
                    $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'];
547
        if (!isset($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
548
549
550
551
552
            || !is_string($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['keepItems'])
        ) {
            return $items;
        }

553
554
555
556
557
558
        // 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 [];
        }

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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
        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) {
708
            $tableToTranslation[$table] = $languageService->sL($conf['ctrl']['title']);
709
710
711
712
713
714
715
716
717
718
719
720
721
722
        }
        // 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
723
724
725
726
727
728
729
730
731
732
733
734
                        $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',
                        ];
735
736
737
738
739
740
741
742
743
                    }
                }
            }
            // 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'])) {
744
                    $labelPrefix = $languageService->sL($GLOBALS['TCA'][$table]['columns'][$tableField]['label']);
745
                }
746
                // Get all sheets
747
748
                foreach ($flexForms as $extIdent => $extConf) {
                    // Get all fields in sheet
749
                    foreach ($extConf['sheets'] as $sheetName => $sheet) {
750
751
752
                        if (empty($sheet['ROOT']['el']) || !is_array($sheet['ROOT']['el'])) {
                            continue;
                        }
753
                        foreach ($sheet['ROOT']['el'] as $pluginFieldName => $field) {
754
755
756
757
                            // Use only fields that have exclude flag set
                            if (empty($field['TCEforms']['exclude'])) {
                                continue;
                            }
758
759
760
761
762
763
764
765
766
767
768
769
770
771
                            $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',
                            ];
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
                        }
                    }
                }
            }
            // 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;
    }

    /**
794
795
     * Returns FlexForm data structures it finds. Used in select "special" for be_groups
     * to set "exclude" flags for single flex form fields.
796
     *
797
     * This only finds flex forms registered in 'ds' config sections.
798
     * This does not resolve other sophisticated flex form data structure references.
799
     *
800
801
802
803
804
805
806
807
     * @todo: This approach is limited and doesn't find everything. It works for casual tt_content plugins, though:
     * @todo: The data structure identifier determination depends on data row, but we don't have all rows at hand here.
     * @todo: The code thus "guesses" some standard data structure identifier scenarios and tries to resolve those.
     * @todo: This guessing can not be solved in a good way. A general registry of "all" possible data structures is
     * @todo: probably not wanted, since that wouldn't work for truly dynamic DS calculations. Probably the only
     * @todo: thing we could do here is a hook to allow extensions declaring specific data structures to
     * @todo: allow backend admins to set exclude flags for certain fields in those cases.
     *
808
     * @param string $table Table to handle
809
     * @return array Data structures
810
811
812
813
814
815
     */
    protected function getRegisteredFlexForms($table)
    {
        if (empty($table) || empty($GLOBALS['TCA'][$table]['columns'])) {
            return [];
        }
816
        $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
817
818
        $flexForms = [];
        foreach ($GLOBALS['TCA'][$table]['columns'] as $tableField => $fieldConf) {
819
            if (!empty($fieldConf['config']['type']) && !empty($fieldConf['config']['ds']) && $fieldConf['config']['type'] === 'flex') {
820
                $flexForms[$tableField] = [];
821
                foreach (array_keys($fieldConf['config']['ds']) as $flexFormKey) {
822
823
824
825
826
827
                    // 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];
                    }
828
829
830
831
832
833
                    $flexFormDataStructureIdentifier = json_encode([
                        'type' => 'tca',
                        'tableName' => $table,
                        'fieldName' => $tableField,
                        'dataStructureKey' => $flexFormKey,
                    ]);
834
835
836
837
838
839
840
841
                    try {
                        $dataStructure = $flexFormTools->parseDataStructureByIdentifier($flexFormDataStructureIdentifier);
                        $flexForms[$tableField][$extIdent] = $dataStructure;
                    } catch (InvalidIdentifierException $e) {
                        // Deliberately empty: The DS identifier is guesswork and the flex ds parser throws
                        // this exception if it can not resolve to a valid data structure. This is "ok" here
                        // and the exception is just eaten.
                    }
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
                }
            }
        }
        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 = [
858
859
            'ALLOW' => $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.allow'),
            'DENY' => $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.deny')
860
861
862
863
864
        ];
        $allowDenyOptions = [];
        foreach ($GLOBALS['TCA'] as $table => $_) {
            // All field names configured:
            if (is_array($GLOBALS['TCA'][$table]['columns'])) {
865
                foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $__) {
866
867
868
869
870
871
                    $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'] =
872
873
                                $languageService->sL($GLOBALS['TCA'][$table]['ctrl']['title']) . ': '
                                . $languageService->sL($GLOBALS['TCA'][$table]['columns'][$field]['label']);
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
                            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,
898
                                            $languageService->sL($iVal[0]),
899
900
901
902
903
904
905
906
907
908
909
910
911
912
                                            $adLabel[$iMode]
                                        ];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return $allowDenyOptions;
    }

    /**
913
914
     * Build query to fetch foreign records. Helper method of
     * addItemsFromForeignTable(), do not call otherwise.
915
916
917
     *
     * @param array $result Result array
     * @param string $localFieldName Current handle field name
918
     * @return QueryBuilder
919
     */
920
    protected function buildForeignTableQueryBuilder(array $result, string $localFieldName):  QueryBuilder
921
922
923
924
925
926
    {
        $backendUser = $this->getBackendUser();

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

927
928
929
930
931
932
933
934
935
936
        $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))
937
938
            ->from($foreignTableName)
            ->where($foreignTableClauseArray['WHERE']);
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958

        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]);
            }
        }
959
960
961
962
963
964

        // 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'])) {
965
            $rootLevel = (int)$GLOBALS['TCA'][$foreignTableName]['ctrl']['rootLevel'];
966
        }
967
968

        if ($rootLevel === -1) {
969
970
971
972
973
974
            $queryBuilder->andWhere(
                $queryBuilder->expr()->neq(
                    $foreignTableName . '.pid',
                    $queryBuilder->createNamedParameter(-1, \PDO::PARAM_INT)
                )
            );
975
        } elseif ($rootLevel === 1) {
976
977
978
979
980
981
            $queryBuilder->andWhere(
                $queryBuilder->expr()->eq(
                    $foreignTableName . '.pid',
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
                )
            );
982
        } else {
983
            $queryBuilder->andWhere($backendUser->getPagePermsClause(1));
984
985
986
987
988
989
990
991
992
            if ($foreignTableName !== 'pages') {
                $queryBuilder
                    ->from('pages')
                    ->andWhere(
                        $queryBuilder->expr()->eq(
                            'pages.uid',
                            $queryBuilder->quoteIdentifier($foreignTableName . '.pid')
                        )
                    );
993
994
995
            }
        }

996
        return $queryBuilder;
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
    }

    /**
     * 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)
    {
1017
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($foreignTableName);
1018
        $localTable = $result['tableName'];
1019
        $effectivePid = $result['effectivePid'];
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034

        $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
            if (strstr($foreignTableClause, '###REC_FIELD_')) {
                // " AND table.field='###REC_FIELD_field1###' AND ..." -> array(" AND table.field='", "field1###' AND ...")
                $whereClauseParts = explode('###REC_FIELD_', $foreignTableClause);
                foreach ($whereClauseParts as $key => $value) {
                    if ($key !== 0) {
                        // "field1###' AND ..." -> array("field1", "' AND ...")
                        $whereClauseSubParts = explode('###', $value, 2);
                        // @todo: Throw exception if there is no value? What happens for NEW records?
1035
1036
                        $databaseRowKey = empty($result['flexParentDatabaseRow']) ? 'databaseRow' : 'flexParentDatabaseRow';
                        $rowFieldValue = isset($result[$databaseRowKey][$whereClauseSubParts[0]]) ? $result[$databaseRowKey][$whereClauseSubParts[0]] : '';
1037
1038
1039
1040
1041
1042
                        if (is_array($rowFieldValue)) {
                            // If a select or group field is used here, it may have been processed already and
                            // is now an array. Use first selected value in this case.
                            $rowFieldValue = $rowFieldValue[0];
                        }
                        if (substr($whereClauseParts[0], -1) === '\'' && $whereClauseSubParts[1][0] === '\'') {
1043
1044
                            $whereClauseParts[0] = substr($whereClauseParts[0], 0, -1);
                            $whereClauseSubParts[1] = substr($whereClauseSubParts[1], 1);
1045
                        }
1046
                        $whereClauseParts[$key] = $connection->quote($rowFieldValue) . $whereClauseSubParts[1];
1047
1048
1049
1050
                    }
                }
                $foreignTableClause = implode('', $whereClauseParts);
            }
1051
1052
1053
1054
1055
1056
            // Use pid from parent page clause if in flex flom context
            if (strpos($foreignTableClause, '###CURRENT_PID###') !== false
                && !empty($result['flexParentDatabaseRow']['pid'])
            ) {
                $effectivePid = $result['flexParentDatabaseRow']['pid'];
            }
1057
1058
1059
1060
1061
1062
1063
1064

            $siteRootUid = 0;
            foreach ($result['rootline'] as $rootlinePage) {
                if (!empty($rootlinePage['is_siteroot'])) {
                    $siteRootUid = (int)$rootlinePage['uid'];
                    break;
                }
            }
1065

1066
            $pageTsConfigId = 0;
1067
1068
1069
1070
            if ($result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_ID']) {
                // @deprecated since TYPO3 v8, will be removed in TYPO3 v9 - see also the flexHack part in TcaFlexProcess
                $pageTsConfigId = (int)$result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_ID'];
            }
1071
1072
1073
            if ($result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_ID']) {
                $pageTsConfigId = (int)$result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_ID'];
            }
1074

1075
            $pageTsConfigIdList = 0;
1076
1077
1078
1079
            if ($result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_IDLIST']) {
                // @deprecated since TYPO3 v8, will be removed in TYPO3 v9 - see also the flexHack part in TcaFlexProcess
                $pageTsConfigIdList = $result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_IDLIST'];
            }
1080
1081
            if ($result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_IDLIST']) {
                $pageTsConfigIdList = $result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_IDLIST'];
1082
1083
1084
1085
1086
1087
            }
            $pageTsConfigIdListArray = GeneralUtility::trimExplode(',', $pageTsConfigIdList, true);
            $pageTsConfigIdList = [];
            foreach ($pageTsConfigIdListArray as $pageTsConfigIdListElement) {
                if (MathUtility::canBeInterpretedAsInteger($pageTsConfigIdListElement)) {
                    $pageTsConfigIdList[] = (int)$pageTsConfigIdListElement;
1088
1089
                }
            }
1090
1091
            $pageTsConfigIdList = implode(',', $pageTsConfigIdList);

1092
            $pageTsConfigString = '';
1093
1094
            if ($result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_STR']) {
                // @deprecated since TYPO3 v8, will be removed in TYPO3 v9 - see also the flexHack part in TcaFlexProcess
1095
                $pageTsConfigString = $connection->quote($result['pageTsConfig']['flexHack.']['PAGE_TSCONFIG_STR']);
1096
            }
1097
1098
            if ($result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_STR']) {
                $pageTsConfigString = $result['pageTsConfig']['TCEFORM.'][$localTable . '.'][$localFieldName . '.']['PAGE_TSCONFIG_STR'];
1099
                $pageTsConfigString = $connection->quote($pageTsConfigString);
1100
1101
1102
1103
1104
1105
1106
1107
1108
            }

            $foreignTableClause = str_replace(
                [
                    '###CURRENT_PID###',
                    '###THIS_UID###',
                    '###SITEROOT###',
                    '###PAGE_TSCONFIG_ID###',
                    '###PAGE_TSCONFIG_IDLIST###',
1109
                    '\'###PAGE_TSCONFIG_STR###\'',
1110
1111
1112
                    '###PAGE_TSCONFIG_STR###'
                ],
                [
1113
                    (int)$effectivePid,
1114
1115
1116
1117
                    (int)$result['databaseRow']['uid'],
                    $siteRootUid,
                    $pageTsConfigId,
                    $pageTsConfigIdList,
1118
                    $pageTsConfigString,
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
                    $pageTsConfigString
                ],
                $foreignTableClause
            );
        }

        // Split the clause into an array with keys WHERE, GROUPBY, ORDERBY, LIMIT
        // Prepend a space to make sure "[[:space:]]+" will find a space there for the first element.
        $foreignTableClause = ' ' . $foreignTableClause;
        $foreignTableClauseArray = [
            'WHERE' => '',
            'GROUPBY' => '',
            'ORDERBY' => '',
            'LIMIT' => '',
        ];
        // Find LIMIT
        $reg = [];
        if (preg_match('/^(.*)[[:space:]]+LIMIT[[:space:]]+([[:alnum:][:space:],._]+)$/i', $foreignTableClause, $reg)) {
1137
            $foreignTableClauseArray['LIMIT'] = GeneralUtility::intExplode(',', trim($reg[2]), true);
1138
1139
1140
1141
1142
            $foreignTableClause = $reg[1];
        }
        // Find ORDER BY
        $reg = [];
        if (preg_match('/^(.*)[[:space:]]+ORDER[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $foreignTableClause, $reg)) {
1143
            $foreignTableClauseArray['ORDERBY'] = QueryHelper::parseOrderBy(trim($reg[2]));
1144
1145
1146
1147
1148
            $foreignTableClause = $reg[1];
        }
        // Find GROUP BY
        $reg = [];
        if (preg_match('/^(.*)[[:space:]]+GROUP[[:space:]]+BY[[:space:]]+([[:alnum:][:space:],._]+)$/i', $foreignTableClause, $reg)) {
1149
            $foreignTableClauseArray['GROUPBY'] = QueryHelper::parseGroupBy(trim($reg[2]));
1150
1151
1152
            $foreignTableClause = $reg[1];
        }
        // Rest is assumed to be "WHERE" clause
1153
        $foreignTableClauseArray['WHERE'] = QueryHelper::stripLogicalOperatorPrefix($foreignTableClause);
1154
1155
1156
1157

        return $foreignTableClauseArray;
    }

1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
    /**
     * Convert the current database values into an array
     *
     * @param array $row database row
     * @param string $fieldName fieldname to process
     * @return array
     */
    protected function processDatabaseFieldValue(array $row, $fieldName)
    {
        $currentDatabaseValues = array_key_exists($fieldName, $row)
            ? $row[$fieldName]
            : '';
1170
1171
1172
1173
        if (!is_array($currentDatabaseValues)) {
            $currentDatabaseValues = GeneralUtility::trimExplode(',', $currentDatabaseValues, true);
        }
        return $currentDatabaseValues;
1174
1175
    }

1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
    /**
     * Validate and sanitize database row values of the select field with the given name.
     * Creates an array out of databaseRow[selectField] values.
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result The current result array.
     * @param string $fieldName Name of the current select field.
     * @param array $staticValues Array with statically defined items, item value is used as array key.
     * @return array
     */
    protected function processSelectFieldValue(array $result, $fieldName, array $staticValues)
    {
        $fieldConfig = $result['processedTca']['columns'][$fieldName];

1191
        $currentDatabaseValueArray = array_key_exists($fieldName, $result['databaseRow']) ? $result['databaseRow'][$fieldName] : [];
1192
1193
1194
1195
        $newDatabaseValueArray = [];

        // Add all values that were defined by static methods and do not come from the relation
        // e.g. TCA, TSconfig, itemProcFunc etc.
1196
        foreach ($currentDatabaseValueArray as $value) {
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
            if (isset($staticValues[$value])) {
                $newDatabaseValueArray[] = $value;
            }
        }

        if (isset($fieldConfig['config']['foreign_table']) && !empty($fieldConfig['config']['foreign_table'])) {
            /** @var RelationHandler $relationHandler */
            $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
            $relationHandler->registerNonTableValues = !empty($fieldConfig['config']['allowNonIdValues']);
            if (!empty($fieldConfig['config']['MM']) && $result['command'] !== 'new') {
                // MM relation
                $relationHandler->start(
1209
                    implode(',', $currentDatabaseValueArray),
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
                    $fieldConfig['config']['foreign_table'],
                    $fieldConfig['config']['MM'],
                    $result['databaseRow']['uid'],
                    $result['tableName'],
                    $fieldConfig['config']
                );
            } else {
                // Non MM relation
                // If not dealing with MM relations, use default live uid, not versioned uid for record relations
                $relationHandler->start(
1220
                    implode(',', $currentDatabaseValueArray),
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
                    $fieldConfig['config']['foreign_table'],
                    '',
                    $this->getLiveUid($result),
                    $result['tableName'],
                    $fieldConfig['config']
                );
            }
            $newDatabaseValueArray = array_merge($newDatabaseValueArray, $relationHandler->getValueArray());
        }

1231
1232
1233
        if ($fieldConfig['config']['multiple']) {
            return $newDatabaseValueArray;
        }
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
        return array_unique($newDatabaseValueArray);
    }

    /**
     * Translate the item labels
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $result Result array
     * @param array $itemArray Items
     * @param string $table
     * @param string $fieldName
     * @return array
     */
    public function translateLabels(array $result, array $itemArray, $table, $fieldName)
    {
        $languageService = $this->getLanguageService();

        foreach ($itemArray as $key => $item) {
            if (!isset($dynamicItems[$key])) {
                $staticValues[$item[1]] = $item;
            }
            if (isset($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['altLabels.'][$item[1]])
                && !empty($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['altLabels.'][$item[1]])
            ) {
                $label = $languageService->sL($result['pageTsConfig']['TCEFORM.'][$table . '.'][$fieldName . '.']['altLabels.'][$item[1]]);
            } else {
1261
                $label = $languageService->sL(trim($item[0]));
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
            }
            $value = strlen((string)$item[1]) > 0 ? $item[1] : '';
            $icon = $item[2] ?: null;
            $helpText = $item[3] ?: null;
            $itemArray[$key] = [
                $label,
                $value,
                $icon,
                $helpText
            ];
        }

        return $itemArray;
    }

    /**
     * Sanitize incoming item array
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param mixed $itemArray
     * @param string $tableName
     * @param string $fieldName
1285
     * @throws \UnexpectedValueException
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
     * @return array
     */
    public function sanitizeItemArray($itemArray, $tableName, $fieldName)
    {
        if (!is_array($itemArray)) {
            $itemArray = [];
        }
        foreach ($itemArray as $item) {
            if (!is_array($item)) {
                throw new \UnexpectedValueException(
                    'An item in field ' . $fieldName . ' of table ' . $tableName . ' is not an array as expected',
                    1439288036
                );
            }
        }

        return $itemArray;
    }

    /**
     * Make sure maxitems is always filled with a valid integer value.
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param mixed $maxItems
     * @return int
1312
     * @deprecated since TYPO3 v8, will be removed in TYPO3 v9
1313
1314
1315
     */
    public function sanitizeMaxItems($maxItems)
    {
1316
        GeneralUtility::logDeprecatedFunction();
1317
        if (!empty($maxItems)
1318
            && (int)$maxItems >= 1
1319
1320
1321
        ) {
            $maxItems = (int)$maxItems;
        } else {
1322
            $maxItems = 99999;
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
        }

        return $maxItems;
    }

    /**
     * Gets the record uid of the live default record. If already
     * pointing to the live record, the submitted record uid is returned.
     *
     * @param array $result Result array
     * @return int
     * @throws \UnexpectedValueException
     */
    protected function getLiveUid(array $result)
    {
        $table = $result['tableName'];
        $row = $result['databaseRow'];
        $uid = $row['uid'];
        if (!empty($result['processedTca']['ctrl']['versioningWS'])
            && $result['pid'] === -1
        ) {
            if (empty($row['t3ver_oid'])) {
                throw new \UnexpectedValueException(
                    'No t3ver_oid found for record ' . $row['uid'] . ' on table ' . $table,
                    1440066481
                );
            }
            $uid = $row['t3ver_oid'];
        }
        return $uid;
    }

    /**
     * Determine the static values in the item array
     *
     * Used by TcaSelectItems and TcaSelectTreeItems data providers
     *
     * @param array $itemArray All item records for the select field
     * @param array $dynamicItemArray Item records from dynamic sources
     * @return array
1363
     * @todo: Check method usage, it's probably bogus in select context and was removed from select tree already.
1364
     */
1365
    protected function getStaticValues($itemArray, $dynamicItemArray)
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
    {
        $staticValues = [];
        foreach ($itemArray as $key => $item) {
            if (!isset($dynamicItemArray[$key])) {
                $staticValues[$item[1]] = $item;
            }
        }
        return $staticValues;
    }

1376
1377
1378
1379
1380
1381
1382
    /**
     * @return LanguageService
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }
1383
1384
1385
1386
1387
1388
1389
1390

    /**
     * @return BackendUserAuthentication
     */
    protected function getBackendUser()
    {
        return $GLOBALS['BE_USER'];
    }
1391
}