[BUGFIX] Initialize site configuration for new sites
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / SiteConfigurationController.php
1 <?php
2 declare(strict_types = 1);
3 namespace TYPO3\CMS\Backend\Controller;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use Psr\Http\Message\ResponseInterface;
19 use Psr\Http\Message\ServerRequestInterface;
20 use TYPO3\CMS\Backend\Configuration\SiteTcaConfiguration;
21 use TYPO3\CMS\Backend\Exception\SiteValidationErrorException;
22 use TYPO3\CMS\Backend\Form\FormDataCompiler;
23 use TYPO3\CMS\Backend\Form\FormDataGroup\SiteConfigurationDataGroup;
24 use TYPO3\CMS\Backend\Form\FormResultCompiler;
25 use TYPO3\CMS\Backend\Form\NodeFactory;
26 use TYPO3\CMS\Backend\Routing\UriBuilder;
27 use TYPO3\CMS\Backend\Template\Components\ButtonBar;
28 use TYPO3\CMS\Backend\Template\ModuleTemplate;
29 use TYPO3\CMS\Backend\Utility\BackendUtility;
30 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
31 use TYPO3\CMS\Core\Configuration\SiteConfiguration;
32 use TYPO3\CMS\Core\Core\Environment;
33 use TYPO3\CMS\Core\Database\ConnectionPool;
34 use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
35 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
36 use TYPO3\CMS\Core\Exception\SiteNotFoundException;
37 use TYPO3\CMS\Core\Http\HtmlResponse;
38 use TYPO3\CMS\Core\Http\RedirectResponse;
39 use TYPO3\CMS\Core\Imaging\Icon;
40 use TYPO3\CMS\Core\Localization\LanguageService;
41 use TYPO3\CMS\Core\Messaging\FlashMessage;
42 use TYPO3\CMS\Core\Messaging\FlashMessageService;
43 use TYPO3\CMS\Core\Site\SiteFinder;
44 use TYPO3\CMS\Core\Utility\GeneralUtility;
45 use TYPO3\CMS\Fluid\View\StandaloneView;
46 use TYPO3\CMS\Frontend\Page\PageRepository;
47 use TYPO3Fluid\Fluid\View\ViewInterface;
48
49 /**
50 * Backend controller: The "Site management" -> "Sites" module
51 *
52 * List all site root pages, CRUD site configuration.
53 */
54 class SiteConfigurationController
55 {
56 /**
57 * @var ModuleTemplate
58 */
59 protected $moduleTemplate;
60
61 /**
62 * @var ViewInterface
63 */
64 protected $view;
65
66 /**
67 * @var SiteFinder
68 */
69 protected $siteFinder;
70
71 /**
72 * Default constructor
73 */
74 public function __construct()
75 {
76 $this->siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
77 $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
78 }
79
80 /**
81 * Main entry method: Dispatch to other actions - those method names that end with "Action".
82 *
83 * @param ServerRequestInterface $request the current request
84 * @return ResponseInterface the response with the content
85 */
86 public function handleRequest(ServerRequestInterface $request): ResponseInterface
87 {
88 $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ContextMenu');
89 $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
90 $action = $request->getQueryParams()['action'] ?? $request->getParsedBody()['action'] ?? 'overview';
91 $this->initializeView($action);
92 $result = call_user_func_array([$this, $action . 'Action'], [$request]);
93 if ($result instanceof ResponseInterface) {
94 return $result;
95 }
96 $this->moduleTemplate->setContent($this->view->render());
97 return new HtmlResponse($this->moduleTemplate->renderContent());
98 }
99
100 /**
101 * List pages that have 'is_siteroot' flag set - those that have the globe icon in page tree.
102 * Link to Add / Edit / Delete for each.
103 */
104 protected function overviewAction(): void
105 {
106 $this->configureOverViewDocHeader();
107 $allSites = $this->siteFinder->getAllSites();
108 $pages = $this->getAllSitePages();
109 $unassignedSites = [];
110 foreach ($allSites as $identifier => $site) {
111 $rootPageId = $site->getRootPageId();
112 if (isset($pages[$rootPageId])) {
113 $pages[$rootPageId]['siteIdentifier'] = $identifier;
114 $pages[$rootPageId]['siteConfiguration'] = $site;
115 } else {
116 $unassignedSites[] = $site;
117 }
118 }
119 $this->view->assignMultiple([
120 'pages' => $pages,
121 'unassignedSites' => $unassignedSites
122 ]);
123 }
124
125 /**
126 * Shows a form to create a new site configuration, or edit an existing one.
127 *
128 * @param ServerRequestInterface $request
129 * @throws \RuntimeException
130 */
131 protected function editAction(ServerRequestInterface $request): void
132 {
133 $this->configureEditViewDocHeader();
134
135 // Put site and friends TCA into global TCA
136 // @todo: We might be able to get rid of that later
137 $GLOBALS['TCA'] = array_merge($GLOBALS['TCA'], GeneralUtility::makeInstance(SiteTcaConfiguration::class)->getTca());
138
139 $siteIdentifier = $request->getQueryParams()['site'] ?? null;
140 $pageUid = (int)($request->getQueryParams()['pageUid'] ?? 0);
141
142 if (empty($siteIdentifier) && empty($pageUid)) {
143 throw new \RuntimeException('Either site identifier to edit a config or page uid to add new config must be set', 1521561148);
144 }
145 $isNewConfig = empty($siteIdentifier);
146
147 $defaultValues = [];
148 if ($isNewConfig) {
149 $defaultValues['site']['rootPageId'] = $pageUid;
150 }
151
152 $allSites = $this->siteFinder->getAllSites();
153 if (!$isNewConfig && !isset($allSites[$siteIdentifier])) {
154 throw new \RuntimeException('Existing config for site ' . $siteIdentifier . ' not found', 1521561226);
155 }
156
157 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
158 $returnUrl = $uriBuilder->buildUriFromRoute('site_configuration');
159
160 $formDataGroup = GeneralUtility::makeInstance(SiteConfigurationDataGroup::class);
161 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
162 $formDataCompilerInput = [
163 'tableName' => 'site',
164 'vanillaUid' => $isNewConfig ? $pageUid : $allSites[$siteIdentifier]->getRootPageId(),
165 'command' => $isNewConfig ? 'new' : 'edit',
166 'returnUrl' => (string)$returnUrl,
167 'customData' => [
168 'siteIdentifier' => $isNewConfig ? '' : $siteIdentifier,
169 ],
170 'defaultValues' => $defaultValues,
171 ];
172 $formData = $formDataCompiler->compile($formDataCompilerInput);
173 $nodeFactory = GeneralUtility::makeInstance(NodeFactory::class);
174 $formData['renderType'] = 'outerWrapContainer';
175 $formResult = $nodeFactory->create($formData)->render();
176 // Needed to be set for 'onChange="reload"' and reload on type change to work
177 $formResult['doSaveFieldName'] = 'doSave';
178 $formResultCompiler = GeneralUtility::makeInstance(FormResultCompiler::class);
179 $formResultCompiler->mergeResult($formResult);
180 $formResultCompiler->addCssFiles();
181 // Always add rootPageId as additional field to have a reference for new records
182 $this->view->assign('rootPageId', $isNewConfig ? $pageUid : $allSites[$siteIdentifier]->getRootPageId());
183 $this->view->assign('returnUrl', $returnUrl);
184 $this->view->assign('formEngineHtml', $formResult['html']);
185 $this->view->assign('formEngineFooter', $formResultCompiler->printNeededJSFunctions());
186 }
187
188 /**
189 * Save incoming data from editAction and redirect to overview or edit
190 *
191 * @param ServerRequestInterface $request
192 * @return ResponseInterface
193 * @throws \RuntimeException
194 */
195 protected function saveAction(ServerRequestInterface $request): ResponseInterface
196 {
197 // Put site and friends TCA into global TCA
198 // @todo: We might be able to get rid of that later
199 $GLOBALS['TCA'] = array_merge($GLOBALS['TCA'], GeneralUtility::makeInstance(SiteTcaConfiguration::class)->getTca());
200
201 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
202 $siteTca = GeneralUtility::makeInstance(SiteTcaConfiguration::class)->getTca();
203
204 $overviewRoute = $uriBuilder->buildUriFromRoute('site_configuration', ['action' => 'overview']);
205 $parsedBody = $request->getParsedBody();
206 if (isset($parsedBody['closeDoc']) && (int)$parsedBody['closeDoc'] === 1) {
207 // Closing means no save, just redirect to overview
208 return new RedirectResponse($overviewRoute);
209 }
210 $isSave = $parsedBody['_savedok'] ?? $parsedBody['doSave'] ?? false;
211 $isSaveClose = $parsedBody['_saveandclosedok'] ?? false;
212 if (!$isSave && !$isSaveClose) {
213 throw new \RuntimeException('Either save or save and close', 1520370364);
214 }
215
216 if (!isset($parsedBody['data']['site']) || !is_array($parsedBody['data']['site'])) {
217 throw new \RuntimeException('No site data or site identifier given', 1521030950);
218 }
219
220 $data = $parsedBody['data'];
221 // This can be NEW123 for new records
222 $pageId = (int)key($data['site']);
223 $sysSiteRow = current($data['site']);
224 $siteIdentifier = $sysSiteRow['identifier'] ?? '';
225
226 $isNewConfiguration = false;
227 $currentIdentifier = '';
228 try {
229 $currentSite = $this->siteFinder->getSiteByRootPageId($pageId);
230 $currentSiteConfiguration = $currentSite->getConfiguration();
231 $currentIdentifier = $currentSite->getIdentifier();
232 } catch (SiteNotFoundException $e) {
233 $currentSiteConfiguration = [];
234 $isNewConfiguration = true;
235 $pageId = (int)$parsedBody['rootPageId'];
236 if (!$pageId > 0) {
237 // Early validation of rootPageId - it must always be given and greater than 0
238 throw new \RuntimeException('No root page id found', 1521719709);
239 }
240 }
241
242 // Validate site identifier and do not store or further process it
243 $siteIdentifier = $this->validateAndProcessIdentifier($isNewConfiguration, $siteIdentifier, $pageId);
244 unset($sysSiteRow['identifier']);
245
246 try {
247 $newSysSiteData = [];
248 // Hard set rootPageId: This is TCA readOnly and not transmitted by FormEngine, but is also the "uid" of the site record
249 $newSysSiteData['rootPageId'] = $pageId;
250 foreach ($sysSiteRow as $fieldName => $fieldValue) {
251 $type = $siteTca['site']['columns'][$fieldName]['config']['type'];
252 if ($type === 'input') {
253 $fieldValue = $this->validateAndProcessValue('site', $fieldName, $fieldValue);
254 $newSysSiteData[$fieldName] = $fieldValue;
255 } elseif ($type === 'inline') {
256 $newSysSiteData[$fieldName] = [];
257 $childRowIds = GeneralUtility::trimExplode(',', $fieldValue, true);
258 if (!isset($siteTca['site']['columns'][$fieldName]['config']['foreign_table'])) {
259 throw new \RuntimeException('No foreign_table found for inline type', 1521555037);
260 }
261 $foreignTable = $siteTca['site']['columns'][$fieldName]['config']['foreign_table'];
262 foreach ($childRowIds as $childRowId) {
263 $childRowData = [];
264 if (!isset($data[$foreignTable][$childRowId])) {
265 if (!empty($currentSiteConfiguration[$fieldName][$childRowId])) {
266 // A collapsed inline record: Fetch data from existing config
267 $newSysSiteData[$fieldName][] = $currentSiteConfiguration[$fieldName][$childRowId];
268 continue;
269 }
270 throw new \RuntimeException('No data found for table ' . $foreignTable . ' with id ' . $childRowId, 1521555177);
271 }
272 $childRow = $data[$foreignTable][$childRowId];
273 foreach ($childRow as $childFieldName => $childFieldValue) {
274 if ($childFieldName === 'pid') {
275 // pid is added by inline by default, but not relevant for yml storage
276 continue;
277 }
278 $type = $siteTca[$foreignTable]['columns'][$childFieldName]['config']['type'];
279 switch ($type) {
280 case 'input':
281 case 'select':
282 case 'text':
283 $childRowData[$childFieldName] = $childFieldValue;
284 break;
285 case 'check':
286 $childRowData[$childFieldName] = (bool)$childFieldValue;
287 break;
288 default:
289 throw new \RuntimeException('TCA type ' . $type . ' not implemented in site handling', 1521555340);
290 }
291 }
292 $newSysSiteData[$fieldName][] = $childRowData;
293 }
294 } elseif ($type === 'select') {
295 $newSysSiteData[$fieldName] = (int)$fieldValue;
296 } else {
297 throw new \RuntimeException('TCA type ' . $type . ' not implemented in site handling', 1521032781);
298 }
299 }
300
301 // keep root config objects not given via GUI
302 // this way extension authors are able to use their own objects on root level
303 // that are not configurable via GUI
304 // however: we overwrite the full subset of any GUI object to make sure we have a clean state
305 $newSysSiteData = array_merge($currentSiteConfiguration, $newSysSiteData);
306 $newSiteConfiguration = $this->validateFullStructure($newSysSiteData);
307
308 // Persist the configuration
309 $siteConfigurationManager = GeneralUtility::makeInstance(SiteConfiguration::class, Environment::getConfigPath() . '/sites');
310 if (!$isNewConfiguration && $currentIdentifier !== $siteIdentifier) {
311 $siteConfigurationManager->rename($currentIdentifier, $siteIdentifier);
312 }
313 $siteConfigurationManager->write($siteIdentifier, $newSiteConfiguration);
314 } catch (SiteValidationErrorException $e) {
315 // Do not store new config if a validation error is thrown, but redirect only to show a generated flash message
316 }
317
318 $saveRoute = $uriBuilder->buildUriFromRoute('site_configuration', ['action' => 'edit', 'site' => $siteIdentifier]);
319 if ($isSaveClose) {
320 return new RedirectResponse($overviewRoute);
321 }
322 return new RedirectResponse($saveRoute);
323 }
324
325 /**
326 * Validation and processing of site identifier
327 *
328 * @param bool $isNew If true, we're dealing with a new record
329 * @param string $identifier Given identifier to validate and process
330 * @param int $rootPageId Page uid this identifier is bound to
331 * @return mixed Verified / modified value
332 */
333 protected function validateAndProcessIdentifier(bool $isNew, string $identifier, int $rootPageId)
334 {
335 $languageService = $this->getLanguageService();
336 // Normal "eval" processing of field first
337 $identifier = $this->validateAndProcessValue('site', 'identifier', $identifier);
338 if ($isNew) {
339 // Verify no other site with this identifier exists. If so, find a new unique name as
340 // identifier and show a flash message the identifier has been adapted
341 try {
342 $this->siteFinder->getSiteByIdentifier($identifier);
343 // Force this identifier to be unique
344 $originalIdentifier = $identifier;
345 $identifier = $identifier . '-' . str_replace('.', '', uniqid((string)mt_rand(), true));
346 $message = sprintf(
347 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierRenamed.message'),
348 $originalIdentifier,
349 $identifier
350 );
351 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierRenamed.title');
352 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
353 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
354 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
355 $defaultFlashMessageQueue->enqueue($flashMessage);
356 } catch (SiteNotFoundException $e) {
357 // Do nothing, this new identifier is ok
358 }
359 } else {
360 // If this is an existing config, the site for this identifier must have the same rootPageId, otherwise
361 // a user tried to rename a site identifier to a different site that already exists. If so, we do not rename
362 // the site and show a flash message
363 try {
364 $site = $this->siteFinder->getSiteByIdentifier($identifier);
365 if ($site->getRootPageId() !== $rootPageId) {
366 // Find original value and keep this
367 $origSite = $this->siteFinder->getSiteByRootPageId($rootPageId);
368 $originalIdentifier = $identifier;
369 $identifier = $origSite->getIdentifier();
370 $message = sprintf(
371 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierExists.message'),
372 $originalIdentifier,
373 $identifier
374 );
375 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierExists.title');
376 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
377 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
378 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
379 $defaultFlashMessageQueue->enqueue($flashMessage);
380 }
381 } catch (SiteNotFoundException $e) {
382 // User is renaming identifier which does not exist yet. That's ok
383 }
384 }
385 return $identifier;
386 }
387
388 /**
389 * Simple validation and processing method for incoming form field values.
390 *
391 * Note this does not support all TCA "eval" options but only what we really need.
392 *
393 * @param string $tableName Table name
394 * @param string $fieldName Field name
395 * @param mixed $fieldValue Incoming value from FormEngine
396 * @return mixed Verified / modified value
397 * @throws SiteValidationErrorException
398 * @throws \RuntimeException
399 */
400 protected function validateAndProcessValue(string $tableName, string $fieldName, $fieldValue)
401 {
402 $languageService = $this->getLanguageService();
403 $fieldConfig = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
404 $handledEvals = [];
405 if (!empty($fieldConfig['eval'])) {
406 $evalArray = GeneralUtility::trimExplode(',', $fieldConfig['eval'], true);
407 // Processing
408 if (in_array('alphanum_x', $evalArray, true)) {
409 $handledEvals[] = 'alphanum_x';
410 $fieldValue = preg_replace('/[^a-zA-Z0-9_-]/', '', $fieldValue);
411 }
412 if (in_array('lower', $evalArray, true)) {
413 $handledEvals[] = 'lower';
414 $fieldValue = mb_strtolower($fieldValue, 'utf-8');
415 }
416 if (in_array('trim', $evalArray, true)) {
417 $handledEvals[] = 'trim';
418 $fieldValue = trim($fieldValue);
419 }
420 if (in_array('int', $evalArray, true)) {
421 $handledEvals[] = 'int';
422 $fieldValue = (int)$fieldValue;
423 }
424 // Validation throws - these should be handled client side already,
425 // eg. 'required' being set and receiving empty, shouldn't happen server side
426 if (in_array('required', $evalArray, true)) {
427 $handledEvals[] = 'required';
428 if (empty($fieldValue)) {
429 $message = sprintf(
430 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.required.message'),
431 $fieldName
432 );
433 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.required.title');
434 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
435 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
436 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
437 $defaultFlashMessageQueue->enqueue($flashMessage);
438 throw new SiteValidationErrorException(
439 'Field ' . $fieldName . ' is set to required, but received empty.',
440 1521726421
441 );
442 }
443 }
444 if (!empty(array_diff($evalArray, $handledEvals))) {
445 throw new \RuntimeException('At least one not implemented \'eval\' in list ' . $fieldConfig['eval'], 1522491734);
446 }
447 }
448 if (isset($fieldConfig['range']['lower'])) {
449 $fieldValue = (int)$fieldValue < (int)$fieldConfig['range']['lower'] ? (int)$fieldConfig['range']['lower'] : (int)$fieldValue;
450 }
451 if (isset($fieldConfig['range']['upper'])) {
452 $fieldValue = (int)$fieldValue > (int)$fieldConfig['range']['upper'] ? (int)$fieldConfig['range']['upper'] : (int)$fieldValue;
453 }
454 return $fieldValue;
455 }
456
457 /**
458 * Last sanitation method after all data has been gathered. Check integrity
459 * of full record, manipulate if possible, or throw exception if unfixable broken.
460 *
461 * @param array $newSysSiteData Incoming data
462 * @return array Updated data if needed
463 * @throws \RuntimeException
464 */
465 protected function validateFullStructure(array $newSysSiteData): array
466 {
467 $languageService = $this->getLanguageService();
468 // Verify there are not two error handlers with the same error code
469 if (isset($newSysSiteData['errorHandling']) && is_array($newSysSiteData['errorHandling'])) {
470 $uniqueCriteria = [];
471 $validChildren = [];
472 foreach ($newSysSiteData['errorHandling'] as $child) {
473 if (!isset($child['errorCode'])) {
474 throw new \RuntimeException('No errorCode found', 1521788518);
475 }
476 if (!in_array((int)$child['errorCode'], $uniqueCriteria, true)) {
477 $uniqueCriteria[] = (int)$child['errorCode'];
478 $validChildren[] = $child;
479 } else {
480 $message = sprintf(
481 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateErrorCode.message'),
482 $child['errorCode']
483 );
484 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateErrorCode.title');
485 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
486 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
487 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
488 $defaultFlashMessageQueue->enqueue($flashMessage);
489 }
490 }
491 $newSysSiteData['errorHandling'] = $validChildren;
492 }
493
494 // Verify there is only one inline child per sys_language record configured.
495 if (!isset($newSysSiteData['languages']) || !is_array($newSysSiteData['languages']) || count($newSysSiteData['languages']) < 1) {
496 throw new \RuntimeException(
497 'No default language definition found. The interface does not allow this. Aborting',
498 1521789306
499 );
500 }
501 $uniqueCriteria = [];
502 $validChildren = [];
503 foreach ($newSysSiteData['languages'] as $child) {
504 if (!isset($child['languageId'])) {
505 throw new \RuntimeException('languageId not found', 1521789455);
506 }
507 if (!in_array((int)$child['languageId'], $uniqueCriteria, true)) {
508 $uniqueCriteria[] = (int)$child['languageId'];
509 $validChildren[] = $child;
510 } else {
511 $message = sprintf(
512 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateLanguageId.title'),
513 $child['languageId']
514 );
515 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateLanguageId.title');
516 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
517 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
518 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
519 $defaultFlashMessageQueue->enqueue($flashMessage);
520 }
521 }
522 $newSysSiteData['languages'] = $validChildren;
523
524 return $newSysSiteData;
525 }
526
527 /**
528 * Delete an existing configuration
529 *
530 * @param ServerRequestInterface $request
531 * @return ResponseInterface
532 */
533 protected function deleteAction(ServerRequestInterface $request): ResponseInterface
534 {
535 $siteIdentifier = $request->getQueryParams()['site'] ?? '';
536 if (empty($siteIdentifier)) {
537 throw new \RuntimeException('Not site identifier given', 1521565182);
538 }
539 // Verify site does exist, method throws if not
540 GeneralUtility::makeInstance(SiteConfiguration::class, Environment::getConfigPath() . '/sites')->delete($siteIdentifier);
541 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
542 $overviewRoute = $uriBuilder->buildUriFromRoute('site_configuration', ['action' => 'overview']);
543 return new RedirectResponse($overviewRoute);
544 }
545
546 /**
547 * Sets up the Fluid View.
548 *
549 * @param string $templateName
550 */
551 protected function initializeView(string $templateName): void
552 {
553 $this->view = GeneralUtility::makeInstance(StandaloneView::class);
554 $this->view->setTemplate($templateName);
555 $this->view->setTemplateRootPaths(['EXT:backend/Resources/Private/Templates/SiteConfiguration']);
556 $this->view->setPartialRootPaths(['EXT:backend/Resources/Private/Partials']);
557 $this->view->setLayoutRootPaths(['EXT:backend/Resources/Private/Layouts']);
558 }
559
560 /**
561 * Create document header buttons of "edit" action
562 */
563 protected function configureEditViewDocHeader(): void
564 {
565 $iconFactory = $this->moduleTemplate->getIconFactory();
566 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
567 $lang = $this->getLanguageService();
568 $closeButton = $buttonBar->makeLinkButton()
569 ->setHref('#')
570 ->setClasses('t3js-editform-close')
571 ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:rm.closeDoc'))
572 ->setShowLabelText(true)
573 ->setIcon($iconFactory->getIcon('actions-close', Icon::SIZE_SMALL));
574 $saveButton = $buttonBar->makeInputButton()
575 ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:rm.saveDoc'))
576 ->setName('_savedok')
577 ->setValue('1')
578 ->setShowLabelText(true)
579 ->setForm('siteConfigurationController')
580 ->setIcon($iconFactory->getIcon('actions-document-save', Icon::SIZE_SMALL));
581 $buttonBar->addButton($closeButton);
582 $buttonBar->addButton($saveButton, ButtonBar::BUTTON_POSITION_LEFT, 2);
583 }
584
585 /**
586 * Create document header buttons of "overview" action
587 */
588 protected function configureOverViewDocHeader(): void
589 {
590 $iconFactory = $this->moduleTemplate->getIconFactory();
591 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
592 $reloadButton = $buttonBar->makeLinkButton()
593 ->setHref(GeneralUtility::getIndpEnv('REQUEST_URI'))
594 ->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.reload'))
595 ->setIcon($iconFactory->getIcon('actions-refresh', Icon::SIZE_SMALL));
596 $buttonBar->addButton($reloadButton, ButtonBar::BUTTON_POSITION_RIGHT);
597 if ($this->getBackendUser()->mayMakeShortcut()) {
598 $getVars = ['id', 'route'];
599 $shortcutButton = $buttonBar->makeShortcutButton()
600 ->setModuleName('site_configuration')
601 ->setGetVariables($getVars);
602 $buttonBar->addButton($shortcutButton, ButtonBar::BUTTON_POSITION_RIGHT);
603 }
604 }
605
606 /**
607 * Returns a list of pages that have 'is_siteroot' set
608 *
609 * @return array
610 */
611 protected function getAllSitePages(): array
612 {
613 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
614 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
615 $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, 0, false));
616 $statement = $queryBuilder
617 ->select('*')
618 ->from('pages')
619 ->where(
620 $queryBuilder->expr()->eq('sys_language_uid', 0),
621 $queryBuilder->expr()->orX(
622 $queryBuilder->expr()->andX(
623 $queryBuilder->expr()->eq('pid', 0),
624 $queryBuilder->expr()->neq('doktype', PageRepository::DOKTYPE_SYSFOLDER)
625 ),
626 $queryBuilder->expr()->eq('is_siteroot', 1)
627 )
628 )
629 ->orderBy('pid')
630 ->addOrderBy('sorting')
631 ->execute();
632
633 $pages = [];
634 while ($row = $statement->fetch()) {
635 $row['rootline'] = BackendUtility::BEgetRootLine((int)$row['uid']);
636 array_pop($row['rootline']);
637 $row['rootline'] = array_reverse($row['rootline']);
638 $i = 0;
639 foreach ($row['rootline'] as &$record) {
640 $record['margin'] = $i++ * 20;
641 }
642 $pages[(int)$row['uid']] = $row;
643 }
644 return $pages;
645 }
646
647 /**
648 * @return LanguageService
649 */
650 protected function getLanguageService(): LanguageService
651 {
652 return $GLOBALS['LANG'];
653 }
654
655 /**
656 * @return BackendUserAuthentication
657 */
658 protected function getBackendUser(): BackendUserAuthentication
659 {
660 return $GLOBALS['BE_USER'];
661 }
662 }