SiteConfigurationController.php 34.4 KB
Newer Older
1
<?php
2

3
declare(strict_types=1);
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/*
 * 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!
 */

18
19
namespace TYPO3\CMS\Backend\Controller;

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Backend\Configuration\SiteTcaConfiguration;
use TYPO3\CMS\Backend\Exception\SiteValidationErrorException;
use TYPO3\CMS\Backend\Form\FormDataCompiler;
use TYPO3\CMS\Backend\Form\FormDataGroup\SiteConfigurationDataGroup;
use TYPO3\CMS\Backend\Form\FormResultCompiler;
use TYPO3\CMS\Backend\Form\NodeFactory;
use TYPO3\CMS\Backend\Routing\UriBuilder;
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Template\ModuleTemplate;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Configuration\SiteConfiguration;
use TYPO3\CMS\Core\Database\ConnectionPool;
35
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
36
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
37
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
38
39
40
41
42
43
44
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
use TYPO3\CMS\Core\Http\HtmlResponse;
use TYPO3\CMS\Core\Http\RedirectResponse;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
45
use TYPO3\CMS\Core\Site\Entity\Site;
46
47
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\Utility\GeneralUtility;
48
use TYPO3\CMS\Core\Utility\MathUtility;
49
use TYPO3\CMS\Core\Utility\StringUtility;
50
51
52
53
54
55
56
use TYPO3\CMS\Fluid\View\StandaloneView;
use TYPO3Fluid\Fluid\View\ViewInterface;

/**
 * Backend controller: The "Site management" -> "Sites" module
 *
 * List all site root pages, CRUD site configuration.
57
58
 *
 * @internal This class is a specific Backend controller implementation and is not considered part of the Public TYPO3 API.
59
60
61
 */
class SiteConfigurationController
{
62
63
    protected const ALLOWED_ACTIONS = ['overview', 'edit', 'save', 'delete'];

64
65
66
67
68
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
    /**
     * @var ModuleTemplate
     */
    protected $moduleTemplate;

    /**
     * @var ViewInterface
     */
    protected $view;

    /**
     * @var SiteFinder
     */
    protected $siteFinder;

    /**
     * Default constructor
     */
    public function __construct()
    {
        $this->siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
        $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
    }

    /**
     * Main entry method: Dispatch to other actions - those method names that end with "Action".
     *
     * @param ServerRequestInterface $request the current request
     * @return ResponseInterface the response with the content
     */
    public function handleRequest(ServerRequestInterface $request): ResponseInterface
    {
96
97
98
        // forcing uncached sites will re-initialize `SiteFinder`
        // which is used later by FormEngine (implicit behavior)
        $this->siteFinder->getAllSites(false);
99
        $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ContextMenu');
100
        $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
101
        $this->moduleTemplate->setTitle($this->getLanguageService()->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration_module.xlf:mlang_labels_tablabel'));
102
        $action = $request->getQueryParams()['action'] ?? $request->getParsedBody()['action'] ?? 'overview';
103
104
105
106
107

        if (!in_array($action, self::ALLOWED_ACTIONS, true)) {
            return new HtmlResponse('Action not allowed', 400);
        }

108
        $this->initializeView($action);
109

110
        $result = $this->{$action . 'Action'}($request);
111
112
113
114
115
116
117
118
119
120
        if ($result instanceof ResponseInterface) {
            return $result;
        }
        $this->moduleTemplate->setContent($this->view->render());
        return new HtmlResponse($this->moduleTemplate->renderContent());
    }

    /**
     * List pages that have 'is_siteroot' flag set - those that have the globe icon in page tree.
     * Link to Add / Edit / Delete for each.
121
122
     *
     * @param ServerRequestInterface $request
123
     */
124
    protected function overviewAction(ServerRequestInterface $request): void
125
    {
126
        $this->configureOverViewDocHeader();
127
128
        $allSites = $this->siteFinder->getAllSites();
        $pages = $this->getAllSitePages();
129
        $unassignedSites = [];
130
131
132
133
134
        foreach ($allSites as $identifier => $site) {
            $rootPageId = $site->getRootPageId();
            if (isset($pages[$rootPageId])) {
                $pages[$rootPageId]['siteIdentifier'] = $identifier;
                $pages[$rootPageId]['siteConfiguration'] = $site;
135
136
            } else {
                $unassignedSites[] = $site;
137
138
            }
        }
139

140
141
        $this->view->assignMultiple([
            'pages' => $pages,
142
143
            'unassignedSites' => $unassignedSites,
            'duplicatedEntryPoints' => $this->getDuplicatedEntryPoints($allSites, $pages),
144
        ]);
145
146
147
148
149
150
151
152
153
154
155
156
    }

    /**
     * Shows a form to create a new site configuration, or edit an existing one.
     *
     * @param ServerRequestInterface $request
     * @throws \RuntimeException
     */
    protected function editAction(ServerRequestInterface $request): void
    {
        $this->configureEditViewDocHeader();

157
        // Put site and friends TCA into global TCA
158
159
160
161
162
163
164
165
166
167
168
169
170
        // @todo: We might be able to get rid of that later
        $GLOBALS['TCA'] = array_merge($GLOBALS['TCA'], GeneralUtility::makeInstance(SiteTcaConfiguration::class)->getTca());

        $siteIdentifier = $request->getQueryParams()['site'] ?? null;
        $pageUid = (int)($request->getQueryParams()['pageUid'] ?? 0);

        if (empty($siteIdentifier) && empty($pageUid)) {
            throw new \RuntimeException('Either site identifier to edit a config or page uid to add new config must be set', 1521561148);
        }
        $isNewConfig = empty($siteIdentifier);

        $defaultValues = [];
        if ($isNewConfig) {
171
            $defaultValues['site']['rootPageId'] = $pageUid;
172
173
174
175
176
177
178
179
180
181
182
183
184
        }

        $allSites = $this->siteFinder->getAllSites();
        if (!$isNewConfig && !isset($allSites[$siteIdentifier])) {
            throw new \RuntimeException('Existing config for site ' . $siteIdentifier . ' not found', 1521561226);
        }

        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
        $returnUrl = $uriBuilder->buildUriFromRoute('site_configuration');

        $formDataGroup = GeneralUtility::makeInstance(SiteConfigurationDataGroup::class);
        $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
        $formDataCompilerInput = [
185
            'tableName' => 'site',
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
            'vanillaUid' => $isNewConfig ? $pageUid : $allSites[$siteIdentifier]->getRootPageId(),
            'command' => $isNewConfig ? 'new' : 'edit',
            'returnUrl' => (string)$returnUrl,
            'customData' => [
                'siteIdentifier' => $isNewConfig ? '' : $siteIdentifier,
            ],
            'defaultValues' => $defaultValues,
        ];
        $formData = $formDataCompiler->compile($formDataCompilerInput);
        $nodeFactory = GeneralUtility::makeInstance(NodeFactory::class);
        $formData['renderType'] = 'outerWrapContainer';
        $formResult = $nodeFactory->create($formData)->render();
        // Needed to be set for 'onChange="reload"' and reload on type change to work
        $formResult['doSaveFieldName'] = 'doSave';
        $formResultCompiler = GeneralUtility::makeInstance(FormResultCompiler::class);
        $formResultCompiler->mergeResult($formResult);
        $formResultCompiler->addCssFiles();
        // Always add rootPageId as additional field to have a reference for new records
        $this->view->assign('rootPageId', $isNewConfig ? $pageUid : $allSites[$siteIdentifier]->getRootPageId());
        $this->view->assign('returnUrl', $returnUrl);
        $this->view->assign('formEngineHtml', $formResult['html']);
        $this->view->assign('formEngineFooter', $formResultCompiler->printNeededJSFunctions());
    }

    /**
     * Save incoming data from editAction and redirect to overview or edit
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     * @throws \RuntimeException
     */
    protected function saveAction(ServerRequestInterface $request): ResponseInterface
    {
219
        // Put site and friends TCA into global TCA
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
        // @todo: We might be able to get rid of that later
        $GLOBALS['TCA'] = array_merge($GLOBALS['TCA'], GeneralUtility::makeInstance(SiteTcaConfiguration::class)->getTca());

        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
        $siteTca = GeneralUtility::makeInstance(SiteTcaConfiguration::class)->getTca();

        $overviewRoute = $uriBuilder->buildUriFromRoute('site_configuration', ['action' => 'overview']);
        $parsedBody = $request->getParsedBody();
        if (isset($parsedBody['closeDoc']) && (int)$parsedBody['closeDoc'] === 1) {
            // Closing means no save, just redirect to overview
            return new RedirectResponse($overviewRoute);
        }
        $isSave = $parsedBody['_savedok'] ?? $parsedBody['doSave'] ?? false;
        $isSaveClose = $parsedBody['_saveandclosedok'] ?? false;
        if (!$isSave && !$isSaveClose) {
            throw new \RuntimeException('Either save or save and close', 1520370364);
        }

238
239
        if (!isset($parsedBody['data']['site']) || !is_array($parsedBody['data']['site'])) {
            throw new \RuntimeException('No site data or site identifier given', 1521030950);
240
241
242
243
        }

        $data = $parsedBody['data'];
        // This can be NEW123 for new records
244
245
        $pageId = (int)key($data['site']);
        $sysSiteRow = current($data['site']);
246
247
248
249
250
251
252
253
254
        $siteIdentifier = $sysSiteRow['identifier'] ?? '';

        $isNewConfiguration = false;
        $currentIdentifier = '';
        try {
            $currentSite = $this->siteFinder->getSiteByRootPageId($pageId);
            $currentSiteConfiguration = $currentSite->getConfiguration();
            $currentIdentifier = $currentSite->getIdentifier();
        } catch (SiteNotFoundException $e) {
255
            $currentSiteConfiguration = [];
256
257
258
259
260
261
262
263
264
265
266
267
268
269
            $isNewConfiguration = true;
            $pageId = (int)$parsedBody['rootPageId'];
            if (!$pageId > 0) {
                // Early validation of rootPageId - it must always be given and greater than 0
                throw new \RuntimeException('No root page id found', 1521719709);
            }
        }

        // Validate site identifier and do not store or further process it
        $siteIdentifier = $this->validateAndProcessIdentifier($isNewConfiguration, $siteIdentifier, $pageId);
        unset($sysSiteRow['identifier']);

        try {
            $newSysSiteData = [];
270
            // Hard set rootPageId: This is TCA readOnly and not transmitted by FormEngine, but is also the "uid" of the site record
271
            $newSysSiteData['rootPageId'] = $pageId;
272
            foreach ($sysSiteRow as $fieldName => $fieldValue) {
273
                $type = $siteTca['site']['columns'][$fieldName]['config']['type'];
274
275
276
277
278
279
280
281
282
283
284
285
                switch ($type) {
                    case 'input':
                    case 'text':
                        $fieldValue = $this->validateAndProcessValue('site', $fieldName, $fieldValue);
                        $newSysSiteData[$fieldName] = $fieldValue;
                        break;

                    case 'inline':
                        $newSysSiteData[$fieldName] = [];
                        $childRowIds = GeneralUtility::trimExplode(',', $fieldValue, true);
                        if (!isset($siteTca['site']['columns'][$fieldName]['config']['foreign_table'])) {
                            throw new \RuntimeException('No foreign_table found for inline type', 1521555037);
286
                        }
287
288
289
290
291
292
293
294
295
296
                        $foreignTable = $siteTca['site']['columns'][$fieldName]['config']['foreign_table'];
                        foreach ($childRowIds as $childRowId) {
                            $childRowData = [];
                            if (!isset($data[$foreignTable][$childRowId])) {
                                if (!empty($currentSiteConfiguration[$fieldName][$childRowId])) {
                                    // A collapsed inline record: Fetch data from existing config
                                    $newSysSiteData[$fieldName][] = $currentSiteConfiguration[$fieldName][$childRowId];
                                    continue;
                                }
                                throw new \RuntimeException('No data found for table ' . $foreignTable . ' with id ' . $childRowId, 1521555177);
297
                            }
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
                            $childRow = $data[$foreignTable][$childRowId];
                            foreach ($childRow as $childFieldName => $childFieldValue) {
                                if ($childFieldName === 'pid') {
                                    // pid is added by inline by default, but not relevant for yml storage
                                    continue;
                                }
                                $type = $siteTca[$foreignTable]['columns'][$childFieldName]['config']['type'];
                                switch ($type) {
                                    case 'input':
                                    case 'select':
                                    case 'text':
                                        $childRowData[$childFieldName] = $childFieldValue;
                                        break;
                                    case 'check':
                                        $childRowData[$childFieldName] = (bool)$childFieldValue;
                                        break;
                                    default:
                                        throw new \RuntimeException('TCA type ' . $type . ' not implemented in site handling', 1521555340);
                                }
317
                            }
318
                            $newSysSiteData[$fieldName][] = $childRowData;
319
                        }
320
321
322
                        break;

                    case 'select':
323
                        $newSysSiteData[$fieldName] = MathUtility::canBeInterpretedAsInteger($fieldValue) ? (int)$fieldValue : $fieldValue;
324
325
                        break;

326
327
328
329
                    case 'check':
                        $newSysSiteData[$fieldName] = (bool)$fieldValue;
                        break;

330
331
                    default:
                        throw new \RuntimeException('TCA type "' . $type . '" is not implemented in site handling', 1521032781);
332
333
334
                }
            }

335
336
337
338
339
            // keep root config objects not given via GUI
            // this way extension authors are able to use their own objects on root level
            // that are not configurable via GUI
            // however: we overwrite the full subset of any GUI object to make sure we have a clean state
            $newSysSiteData = array_merge($currentSiteConfiguration, $newSysSiteData);
340
341
342
            $newSiteConfiguration = $this->validateFullStructure($newSysSiteData);

            // Persist the configuration
343
            $siteConfigurationManager = GeneralUtility::makeInstance(SiteConfiguration::class);
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
            if (!$isNewConfiguration && $currentIdentifier !== $siteIdentifier) {
                $siteConfigurationManager->rename($currentIdentifier, $siteIdentifier);
            }
            $siteConfigurationManager->write($siteIdentifier, $newSiteConfiguration);
        } catch (SiteValidationErrorException $e) {
            // Do not store new config if a validation error is thrown, but redirect only to show a generated flash message
        }

        $saveRoute = $uriBuilder->buildUriFromRoute('site_configuration', ['action' => 'edit', 'site' => $siteIdentifier]);
        if ($isSaveClose) {
            return new RedirectResponse($overviewRoute);
        }
        return new RedirectResponse($saveRoute);
    }

    /**
     * Validation and processing of site identifier
     *
     * @param bool $isNew If true, we're dealing with a new record
     * @param string $identifier Given identifier to validate and process
     * @param int $rootPageId Page uid this identifier is bound to
     * @return mixed Verified / modified value
     */
    protected function validateAndProcessIdentifier(bool $isNew, string $identifier, int $rootPageId)
    {
        $languageService = $this->getLanguageService();
        // Normal "eval" processing of field first
371
        $identifier = $this->validateAndProcessValue('site', 'identifier', $identifier);
372
373
374
375
376
377
378
        if ($isNew) {
            // Verify no other site with this identifier exists. If so, find a new unique name as
            // identifier and show a flash message the identifier has been adapted
            try {
                $this->siteFinder->getSiteByIdentifier($identifier);
                // Force this identifier to be unique
                $originalIdentifier = $identifier;
379
                $identifier = StringUtility::getUniqueId($identifier . '-');
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
                $message = sprintf(
                    $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierRenamed.message'),
                    $originalIdentifier,
                    $identifier
                );
                $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierRenamed.title');
                $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
                $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
                $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
                $defaultFlashMessageQueue->enqueue($flashMessage);
            } catch (SiteNotFoundException $e) {
                // Do nothing, this new identifier is ok
            }
        } else {
            // If this is an existing config, the site for this identifier must have the same rootPageId, otherwise
            // a user tried to rename a site identifier to a different site that already exists. If so, we do not rename
            // the site and show a flash message
            try {
                $site = $this->siteFinder->getSiteByIdentifier($identifier);
                if ($site->getRootPageId() !== $rootPageId) {
                    // Find original value and keep this
                    $origSite = $this->siteFinder->getSiteByRootPageId($rootPageId);
                    $originalIdentifier = $identifier;
                    $identifier = $origSite->getIdentifier();
                    $message = sprintf(
                        $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierExists.message'),
                        $originalIdentifier,
                        $identifier
                    );
                    $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierExists.title');
                    $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
                    $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
                    $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
                    $defaultFlashMessageQueue->enqueue($flashMessage);
                }
            } catch (SiteNotFoundException $e) {
                // User is renaming identifier which does not exist yet. That's ok
            }
        }
        return $identifier;
    }

    /**
     * Simple validation and processing method for incoming form field values.
     *
     * Note this does not support all TCA "eval" options but only what we really need.
     *
     * @param string $tableName Table name
     * @param string $fieldName Field name
     * @param mixed $fieldValue Incoming value from FormEngine
     * @return mixed Verified / modified value
     * @throws SiteValidationErrorException
     * @throws \RuntimeException
     */
    protected function validateAndProcessValue(string $tableName, string $fieldName, $fieldValue)
    {
        $languageService = $this->getLanguageService();
        $fieldConfig = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
        $handledEvals = [];
        if (!empty($fieldConfig['eval'])) {
            $evalArray = GeneralUtility::trimExplode(',', $fieldConfig['eval'], true);
            // Processing
            if (in_array('alphanum_x', $evalArray, true)) {
                $handledEvals[] = 'alphanum_x';
                $fieldValue = preg_replace('/[^a-zA-Z0-9_-]/', '', $fieldValue);
            }
            if (in_array('lower', $evalArray, true)) {
                $handledEvals[] = 'lower';
                $fieldValue = mb_strtolower($fieldValue, 'utf-8');
            }
            if (in_array('trim', $evalArray, true)) {
                $handledEvals[] = 'trim';
                $fieldValue = trim($fieldValue);
            }
            if (in_array('int', $evalArray, true)) {
                $handledEvals[] = 'int';
                $fieldValue = (int)$fieldValue;
            }
            // Validation throws - these should be handled client side already,
            // eg. 'required' being set and receiving empty, shouldn't happen server side
            if (in_array('required', $evalArray, true)) {
                $handledEvals[] = 'required';
                if (empty($fieldValue)) {
                    $message = sprintf(
                        $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.required.message'),
                        $fieldName
                    );
                    $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.required.title');
                    $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
                    $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
                    $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
                    $defaultFlashMessageQueue->enqueue($flashMessage);
                    throw new SiteValidationErrorException(
                        'Field ' . $fieldName . ' is set to required, but received empty.',
                        1521726421
                    );
                }
            }
            if (!empty(array_diff($evalArray, $handledEvals))) {
                throw new \RuntimeException('At least one not implemented \'eval\' in list ' . $fieldConfig['eval'], 1522491734);
            }
        }
        if (isset($fieldConfig['range']['lower'])) {
            $fieldValue = (int)$fieldValue < (int)$fieldConfig['range']['lower'] ? (int)$fieldConfig['range']['lower'] : (int)$fieldValue;
        }
        if (isset($fieldConfig['range']['upper'])) {
            $fieldValue = (int)$fieldValue > (int)$fieldConfig['range']['upper'] ? (int)$fieldConfig['range']['upper'] : (int)$fieldValue;
        }
        return $fieldValue;
    }

    /**
     * Last sanitation method after all data has been gathered. Check integrity
     * of full record, manipulate if possible, or throw exception if unfixable broken.
     *
     * @param array $newSysSiteData Incoming data
     * @return array Updated data if needed
     * @throws \RuntimeException
     */
    protected function validateFullStructure(array $newSysSiteData): array
    {
        $languageService = $this->getLanguageService();
        // Verify there are not two error handlers with the same error code
503
        if (isset($newSysSiteData['errorHandling']) && is_array($newSysSiteData['errorHandling'])) {
504
505
            $uniqueCriteria = [];
            $validChildren = [];
506
            foreach ($newSysSiteData['errorHandling'] as $child) {
507
508
509
510
511
                if (!isset($child['errorCode'])) {
                    throw new \RuntimeException('No errorCode found', 1521788518);
                }
                if (!in_array((int)$child['errorCode'], $uniqueCriteria, true)) {
                    $uniqueCriteria[] = (int)$child['errorCode'];
512
                    $child['errorCode'] = (int)$child['errorCode'];
513
514
515
516
517
518
519
520
521
522
523
524
525
                    $validChildren[] = $child;
                } else {
                    $message = sprintf(
                        $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateErrorCode.message'),
                        $child['errorCode']
                    );
                    $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateErrorCode.title');
                    $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
                    $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
                    $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
                    $defaultFlashMessageQueue->enqueue($flashMessage);
                }
            }
526
            $newSysSiteData['errorHandling'] = $validChildren;
527
528
529
        }

        // Verify there is only one inline child per sys_language record configured.
530
        if (!isset($newSysSiteData['languages']) || !is_array($newSysSiteData['languages']) || count($newSysSiteData['languages']) < 1) {
531
532
533
534
535
536
537
            throw new \RuntimeException(
                'No default language definition found. The interface does not allow this. Aborting',
                1521789306
            );
        }
        $uniqueCriteria = [];
        $validChildren = [];
538
        foreach ($newSysSiteData['languages'] as $child) {
539
540
541
542
543
            if (!isset($child['languageId'])) {
                throw new \RuntimeException('languageId not found', 1521789455);
            }
            if (!in_array((int)$child['languageId'], $uniqueCriteria, true)) {
                $uniqueCriteria[] = (int)$child['languageId'];
544
                $child['languageId'] = (int)$child['languageId'];
545
546
547
548
549
550
551
552
553
554
555
556
557
                $validChildren[] = $child;
            } else {
                $message = sprintf(
                    $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateLanguageId.title'),
                    $child['languageId']
                );
                $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateLanguageId.title');
                $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
                $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
                $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
                $defaultFlashMessageQueue->enqueue($flashMessage);
            }
        }
558
        $newSysSiteData['languages'] = $validChildren;
559

560
561
562
563
564
565
566
        // cleanup configuration
        foreach ($newSysSiteData as $identifier => $value) {
            if (is_array($value) && empty($value)) {
                unset($newSysSiteData[$identifier]);
            }
        }

567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
        return $newSysSiteData;
    }

    /**
     * Delete an existing configuration
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    protected function deleteAction(ServerRequestInterface $request): ResponseInterface
    {
        $siteIdentifier = $request->getQueryParams()['site'] ?? '';
        if (empty($siteIdentifier)) {
            throw new \RuntimeException('Not site identifier given', 1521565182);
        }
        // Verify site does exist, method throws if not
583
        GeneralUtility::makeInstance(SiteConfiguration::class)->delete($siteIdentifier);
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
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
        $overviewRoute = $uriBuilder->buildUriFromRoute('site_configuration', ['action' => 'overview']);
        return new RedirectResponse($overviewRoute);
    }

    /**
     * Sets up the Fluid View.
     *
     * @param string $templateName
     */
    protected function initializeView(string $templateName): void
    {
        $this->view = GeneralUtility::makeInstance(StandaloneView::class);
        $this->view->setTemplate($templateName);
        $this->view->setTemplateRootPaths(['EXT:backend/Resources/Private/Templates/SiteConfiguration']);
        $this->view->setPartialRootPaths(['EXT:backend/Resources/Private/Partials']);
        $this->view->setLayoutRootPaths(['EXT:backend/Resources/Private/Layouts']);
    }

    /**
     * Create document header buttons of "edit" action
     */
    protected function configureEditViewDocHeader(): void
    {
        $iconFactory = $this->moduleTemplate->getIconFactory();
        $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
        $lang = $this->getLanguageService();
        $closeButton = $buttonBar->makeLinkButton()
            ->setHref('#')
            ->setClasses('t3js-editform-close')
614
            ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:rm.closeDoc'))
615
            ->setShowLabelText(true)
616
617
            ->setIcon($iconFactory->getIcon('actions-close', Icon::SIZE_SMALL));
        $saveButton = $buttonBar->makeInputButton()
618
            ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:rm.saveDoc'))
619
620
            ->setName('_savedok')
            ->setValue('1')
621
            ->setShowLabelText(true)
622
623
624
            ->setForm('siteConfigurationController')
            ->setIcon($iconFactory->getIcon('actions-document-save', Icon::SIZE_SMALL));
        $buttonBar->addButton($closeButton);
625
        $buttonBar->addButton($saveButton, ButtonBar::BUTTON_POSITION_LEFT, 2);
626
627
628
629
630
    }

    /**
     * Create document header buttons of "overview" action
     */
631
    protected function configureOverViewDocHeader(): void
632
633
634
635
636
    {
        $iconFactory = $this->moduleTemplate->getIconFactory();
        $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
        $reloadButton = $buttonBar->makeLinkButton()
            ->setHref(GeneralUtility::getIndpEnv('REQUEST_URI'))
637
            ->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.reload'))
638
639
            ->setIcon($iconFactory->getIcon('actions-refresh', Icon::SIZE_SMALL));
        $buttonBar->addButton($reloadButton, ButtonBar::BUTTON_POSITION_RIGHT);
640
        $shortcutButton = $buttonBar->makeShortcutButton()
641
            ->setRouteIdentifier('site_configuration')
642
            ->setDisplayName($this->getLanguageService()->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration_module.xlf:mlang_labels_tablabel'));
643
        $buttonBar->addButton($shortcutButton, ButtonBar::BUTTON_POSITION_RIGHT);
644
645
646
647
648
649
650
651
652
653
    }

    /**
     * Returns a list of pages that have 'is_siteroot' set
     *
     * @return array
     */
    protected function getAllSitePages(): array
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
654
        $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
655
        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, 0));
656
657
658
659
660
661
        $statement = $queryBuilder
            ->select('*')
            ->from('pages')
            ->where(
                $queryBuilder->expr()->eq('sys_language_uid', 0),
                $queryBuilder->expr()->orX(
662
663
664
665
                    $queryBuilder->expr()->andX(
                        $queryBuilder->expr()->eq('pid', 0),
                        $queryBuilder->expr()->neq('doktype', PageRepository::DOKTYPE_SYSFOLDER)
                    ),
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
                    $queryBuilder->expr()->eq('is_siteroot', 1)
                )
            )
            ->orderBy('pid')
            ->addOrderBy('sorting')
            ->execute();

        $pages = [];
        while ($row = $statement->fetch()) {
            $row['rootline'] = BackendUtility::BEgetRootLine((int)$row['uid']);
            array_pop($row['rootline']);
            $row['rootline'] = array_reverse($row['rootline']);
            $i = 0;
            foreach ($row['rootline'] as &$record) {
                $record['margin'] = $i++ * 20;
            }
            $pages[(int)$row['uid']] = $row;
        }
        return $pages;
    }

687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
    /**
     * Get all entry duplicates which are used multiple times
     *
     * @param Site[] $allSites
     * @param array $pages
     * @return array
     */
    protected function getDuplicatedEntryPoints(array $allSites, array $pages): array
    {
        $duplicatedEntryPoints = [];

        foreach ($allSites as $identifier => $site) {
            if (!isset($pages[$site->getRootPageId()])) {
                continue;
            }
            foreach ($site->getAllLanguages() as $language) {
                $base = $language->getBase();
                $entryPoint = rtrim((string)$language->getBase(), '/');
                $scheme = $base->getScheme() ? $base->getScheme() . '://' : '//';
                $entryPointWithoutScheme = str_replace($scheme, '', $entryPoint);
                if (!isset($duplicatedEntryPoints[$entryPointWithoutScheme][$entryPoint])) {
                    $duplicatedEntryPoints[$entryPointWithoutScheme][$entryPoint] = 1;
                } else {
                    $duplicatedEntryPoints[$entryPointWithoutScheme][$entryPoint]++;
                }
            }
        }
        return array_filter($duplicatedEntryPoints, static function (array $variants): bool {
            return count($variants) > 1 || reset($variants) > 1;
        }, ARRAY_FILTER_USE_BOTH);
    }

719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
    /**
     * @return LanguageService
     */
    protected function getLanguageService(): LanguageService
    {
        return $GLOBALS['LANG'];
    }

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