34fedaf9f84aa679cb9cd03c81c40bd49d798d04
[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 $isNewConfiguration = true;
234 $pageId = (int)$parsedBody['rootPageId'];
235 if (!$pageId > 0) {
236 // Early validation of rootPageId - it must always be given and greater than 0
237 throw new \RuntimeException('No root page id found', 1521719709);
238 }
239 }
240
241 // Validate site identifier and do not store or further process it
242 $siteIdentifier = $this->validateAndProcessIdentifier($isNewConfiguration, $siteIdentifier, $pageId);
243 unset($sysSiteRow['identifier']);
244
245 try {
246 $newSysSiteData = [];
247 // Hard set rootPageId: This is TCA readOnly and not transmitted by FormEngine, but is also the "uid" of the site record
248 $newSysSiteData['site']['rootPageId'] = $pageId;
249 foreach ($sysSiteRow as $fieldName => $fieldValue) {
250 $type = $siteTca['site']['columns'][$fieldName]['config']['type'];
251 if ($type === 'input') {
252 $fieldValue = $this->validateAndProcessValue('site', $fieldName, $fieldValue);
253 $newSysSiteData['site'][$fieldName] = $fieldValue;
254 } elseif ($type === 'inline') {
255 $newSysSiteData['site'][$fieldName] = [];
256 $childRowIds = GeneralUtility::trimExplode(',', $fieldValue, true);
257 if (!isset($siteTca['site']['columns'][$fieldName]['config']['foreign_table'])) {
258 throw new \RuntimeException('No foreign_table found for inline type', 1521555037);
259 }
260 $foreignTable = $siteTca['site']['columns'][$fieldName]['config']['foreign_table'];
261 foreach ($childRowIds as $childRowId) {
262 $childRowData = [];
263 if (!isset($data[$foreignTable][$childRowId])) {
264 if (!empty($currentSiteConfiguration[$fieldName][$childRowId])) {
265 // A collapsed inline record: Fetch data from existing config
266 $newSysSiteData['site'][$fieldName][] = $currentSiteConfiguration[$fieldName][$childRowId];
267 continue;
268 }
269 throw new \RuntimeException('No data found for table ' . $foreignTable . ' with id ' . $childRowId, 1521555177);
270 }
271 $childRow = $data[$foreignTable][$childRowId];
272 foreach ($childRow as $childFieldName => $childFieldValue) {
273 if ($childFieldName === 'pid') {
274 // pid is added by inline by default, but not relevant for yml storage
275 continue;
276 }
277 $type = $siteTca[$foreignTable]['columns'][$childFieldName]['config']['type'];
278 if ($type === 'input') {
279 $childRowData[$childFieldName] = $childFieldValue;
280 } elseif ($type === 'select') {
281 $childRowData[$childFieldName] = $childFieldValue;
282 } elseif ($type === 'check') {
283 $childRowData[$childFieldName] = (bool)$childFieldValue;
284 } else {
285 throw new \RuntimeException('TCA type ' . $type . ' not implemented in site handling', 1521555340);
286 }
287 }
288 $newSysSiteData['site'][$fieldName][] = $childRowData;
289 }
290 } elseif ($type === 'select') {
291 $newSysSiteData['site'][$fieldName] = (int)$fieldValue;
292 } else {
293 throw new \RuntimeException('TCA type ' . $type . ' not implemented in site handling', 1521032781);
294 }
295 }
296
297 $newSiteConfiguration = $this->validateFullStructure($newSysSiteData);
298
299 // Persist the configuration
300 $siteConfigurationManager = GeneralUtility::makeInstance(SiteConfiguration::class, Environment::getConfigPath() . '/sites');
301 if (!$isNewConfiguration && $currentIdentifier !== $siteIdentifier) {
302 $siteConfigurationManager->rename($currentIdentifier, $siteIdentifier);
303 }
304 $siteConfigurationManager->write($siteIdentifier, $newSiteConfiguration);
305 } catch (SiteValidationErrorException $e) {
306 // Do not store new config if a validation error is thrown, but redirect only to show a generated flash message
307 }
308
309 $saveRoute = $uriBuilder->buildUriFromRoute('site_configuration', ['action' => 'edit', 'site' => $siteIdentifier]);
310 if ($isSaveClose) {
311 return new RedirectResponse($overviewRoute);
312 }
313 return new RedirectResponse($saveRoute);
314 }
315
316 /**
317 * Validation and processing of site identifier
318 *
319 * @param bool $isNew If true, we're dealing with a new record
320 * @param string $identifier Given identifier to validate and process
321 * @param int $rootPageId Page uid this identifier is bound to
322 * @return mixed Verified / modified value
323 */
324 protected function validateAndProcessIdentifier(bool $isNew, string $identifier, int $rootPageId)
325 {
326 $languageService = $this->getLanguageService();
327 // Normal "eval" processing of field first
328 $identifier = $this->validateAndProcessValue('site', 'identifier', $identifier);
329 if ($isNew) {
330 // Verify no other site with this identifier exists. If so, find a new unique name as
331 // identifier and show a flash message the identifier has been adapted
332 try {
333 $this->siteFinder->getSiteByIdentifier($identifier);
334 // Force this identifier to be unique
335 $originalIdentifier = $identifier;
336 $identifier = $identifier . '-' . str_replace('.', '', uniqid((string)mt_rand(), true));
337 $message = sprintf(
338 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierRenamed.message'),
339 $originalIdentifier,
340 $identifier
341 );
342 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierRenamed.title');
343 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
344 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
345 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
346 $defaultFlashMessageQueue->enqueue($flashMessage);
347 } catch (SiteNotFoundException $e) {
348 // Do nothing, this new identifier is ok
349 }
350 } else {
351 // If this is an existing config, the site for this identifier must have the same rootPageId, otherwise
352 // a user tried to rename a site identifier to a different site that already exists. If so, we do not rename
353 // the site and show a flash message
354 try {
355 $site = $this->siteFinder->getSiteByIdentifier($identifier);
356 if ($site->getRootPageId() !== $rootPageId) {
357 // Find original value and keep this
358 $origSite = $this->siteFinder->getSiteByRootPageId($rootPageId);
359 $originalIdentifier = $identifier;
360 $identifier = $origSite->getIdentifier();
361 $message = sprintf(
362 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierExists.message'),
363 $originalIdentifier,
364 $identifier
365 );
366 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.identifierExists.title');
367 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
368 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
369 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
370 $defaultFlashMessageQueue->enqueue($flashMessage);
371 }
372 } catch (SiteNotFoundException $e) {
373 // User is renaming identifier which does not exist yet. That's ok
374 }
375 }
376 return $identifier;
377 }
378
379 /**
380 * Simple validation and processing method for incoming form field values.
381 *
382 * Note this does not support all TCA "eval" options but only what we really need.
383 *
384 * @param string $tableName Table name
385 * @param string $fieldName Field name
386 * @param mixed $fieldValue Incoming value from FormEngine
387 * @return mixed Verified / modified value
388 * @throws SiteValidationErrorException
389 * @throws \RuntimeException
390 */
391 protected function validateAndProcessValue(string $tableName, string $fieldName, $fieldValue)
392 {
393 $languageService = $this->getLanguageService();
394 $fieldConfig = $GLOBALS['TCA'][$tableName]['columns'][$fieldName]['config'];
395 $handledEvals = [];
396 if (!empty($fieldConfig['eval'])) {
397 $evalArray = GeneralUtility::trimExplode(',', $fieldConfig['eval'], true);
398 // Processing
399 if (in_array('alphanum_x', $evalArray, true)) {
400 $handledEvals[] = 'alphanum_x';
401 $fieldValue = preg_replace('/[^a-zA-Z0-9_-]/', '', $fieldValue);
402 }
403 if (in_array('lower', $evalArray, true)) {
404 $handledEvals[] = 'lower';
405 $fieldValue = mb_strtolower($fieldValue, 'utf-8');
406 }
407 if (in_array('trim', $evalArray, true)) {
408 $handledEvals[] = 'trim';
409 $fieldValue = trim($fieldValue);
410 }
411 if (in_array('int', $evalArray, true)) {
412 $handledEvals[] = 'int';
413 $fieldValue = (int)$fieldValue;
414 }
415 // Validation throws - these should be handled client side already,
416 // eg. 'required' being set and receiving empty, shouldn't happen server side
417 if (in_array('required', $evalArray, true)) {
418 $handledEvals[] = 'required';
419 if (empty($fieldValue)) {
420 $message = sprintf(
421 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.required.message'),
422 $fieldName
423 );
424 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.required.title');
425 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
426 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
427 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
428 $defaultFlashMessageQueue->enqueue($flashMessage);
429 throw new SiteValidationErrorException(
430 'Field ' . $fieldName . ' is set to required, but received empty.',
431 1521726421
432 );
433 }
434 }
435 if (!empty(array_diff($evalArray, $handledEvals))) {
436 throw new \RuntimeException('At least one not implemented \'eval\' in list ' . $fieldConfig['eval'], 1522491734);
437 }
438 }
439 if (isset($fieldConfig['range']['lower'])) {
440 $fieldValue = (int)$fieldValue < (int)$fieldConfig['range']['lower'] ? (int)$fieldConfig['range']['lower'] : (int)$fieldValue;
441 }
442 if (isset($fieldConfig['range']['upper'])) {
443 $fieldValue = (int)$fieldValue > (int)$fieldConfig['range']['upper'] ? (int)$fieldConfig['range']['upper'] : (int)$fieldValue;
444 }
445 return $fieldValue;
446 }
447
448 /**
449 * Last sanitation method after all data has been gathered. Check integrity
450 * of full record, manipulate if possible, or throw exception if unfixable broken.
451 *
452 * @param array $newSysSiteData Incoming data
453 * @return array Updated data if needed
454 * @throws \RuntimeException
455 */
456 protected function validateFullStructure(array $newSysSiteData): array
457 {
458 $languageService = $this->getLanguageService();
459 // Verify there are not two error handlers with the same error code
460 if (isset($newSysSiteData['site']['errorHandling']) && is_array($newSysSiteData['site']['errorHandling'])) {
461 $uniqueCriteria = [];
462 $validChildren = [];
463 foreach ($newSysSiteData['site']['errorHandling'] as $child) {
464 if (!isset($child['errorCode'])) {
465 throw new \RuntimeException('No errorCode found', 1521788518);
466 }
467 if (!in_array((int)$child['errorCode'], $uniqueCriteria, true)) {
468 $uniqueCriteria[] = (int)$child['errorCode'];
469 $validChildren[] = $child;
470 } else {
471 $message = sprintf(
472 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateErrorCode.message'),
473 $child['errorCode']
474 );
475 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateErrorCode.title');
476 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
477 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
478 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
479 $defaultFlashMessageQueue->enqueue($flashMessage);
480 }
481 }
482 $newSysSiteData['site']['errorHandling'] = $validChildren;
483 }
484
485 // Verify there is only one inline child per sys_language record configured.
486 if (!isset($newSysSiteData['site']['languages']) || !is_array($newSysSiteData['site']['languages']) || count($newSysSiteData['site']['languages']) < 1) {
487 throw new \RuntimeException(
488 'No default language definition found. The interface does not allow this. Aborting',
489 1521789306
490 );
491 }
492 $uniqueCriteria = [];
493 $validChildren = [];
494 foreach ($newSysSiteData['site']['languages'] as $child) {
495 if (!isset($child['languageId'])) {
496 throw new \RuntimeException('languageId not found', 1521789455);
497 }
498 if (!in_array((int)$child['languageId'], $uniqueCriteria, true)) {
499 $uniqueCriteria[] = (int)$child['languageId'];
500 $validChildren[] = $child;
501 } else {
502 $message = sprintf(
503 $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateLanguageId.title'),
504 $child['languageId']
505 );
506 $messageTitle = $languageService->sL('LLL:EXT:backend/Resources/Private/Language/locallang_siteconfiguration.xlf:validation.duplicateLanguageId.title');
507 $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $message, $messageTitle, FlashMessage::WARNING, true);
508 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
509 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
510 $defaultFlashMessageQueue->enqueue($flashMessage);
511 }
512 }
513 $newSysSiteData['site']['languages'] = $validChildren;
514
515 return $newSysSiteData;
516 }
517
518 /**
519 * Delete an existing configuration
520 *
521 * @param ServerRequestInterface $request
522 * @return ResponseInterface
523 */
524 protected function deleteAction(ServerRequestInterface $request): ResponseInterface
525 {
526 $siteIdentifier = $request->getQueryParams()['site'] ?? '';
527 if (empty($siteIdentifier)) {
528 throw new \RuntimeException('Not site identifier given', 1521565182);
529 }
530 // Verify site does exist, method throws if not
531 GeneralUtility::makeInstance(SiteConfiguration::class, Environment::getConfigPath() . '/sites')->delete($siteIdentifier);
532 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
533 $overviewRoute = $uriBuilder->buildUriFromRoute('site_configuration', ['action' => 'overview']);
534 return new RedirectResponse($overviewRoute);
535 }
536
537 /**
538 * Sets up the Fluid View.
539 *
540 * @param string $templateName
541 */
542 protected function initializeView(string $templateName): void
543 {
544 $this->view = GeneralUtility::makeInstance(StandaloneView::class);
545 $this->view->setTemplate($templateName);
546 $this->view->setTemplateRootPaths(['EXT:backend/Resources/Private/Templates/SiteConfiguration']);
547 $this->view->setPartialRootPaths(['EXT:backend/Resources/Private/Partials']);
548 $this->view->setLayoutRootPaths(['EXT:backend/Resources/Private/Layouts']);
549 }
550
551 /**
552 * Create document header buttons of "edit" action
553 */
554 protected function configureEditViewDocHeader(): void
555 {
556 $iconFactory = $this->moduleTemplate->getIconFactory();
557 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
558 $lang = $this->getLanguageService();
559 $closeButton = $buttonBar->makeLinkButton()
560 ->setHref('#')
561 ->setClasses('t3js-editform-close')
562 ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:rm.closeDoc'))
563 ->setShowLabelText(true)
564 ->setIcon($iconFactory->getIcon('actions-close', Icon::SIZE_SMALL));
565 $saveButton = $buttonBar->makeInputButton()
566 ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:rm.saveDoc'))
567 ->setName('_savedok')
568 ->setValue('1')
569 ->setShowLabelText(true)
570 ->setForm('siteConfigurationController')
571 ->setIcon($iconFactory->getIcon('actions-document-save', Icon::SIZE_SMALL));
572 $buttonBar->addButton($closeButton);
573 $buttonBar->addButton($saveButton, ButtonBar::BUTTON_POSITION_LEFT, 2);
574 }
575
576 /**
577 * Create document header buttons of "overview" action
578 */
579 protected function configureOverViewDocHeader(): void
580 {
581 $iconFactory = $this->moduleTemplate->getIconFactory();
582 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
583 $reloadButton = $buttonBar->makeLinkButton()
584 ->setHref(GeneralUtility::getIndpEnv('REQUEST_URI'))
585 ->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.reload'))
586 ->setIcon($iconFactory->getIcon('actions-refresh', Icon::SIZE_SMALL));
587 $buttonBar->addButton($reloadButton, ButtonBar::BUTTON_POSITION_RIGHT);
588 if ($this->getBackendUser()->mayMakeShortcut()) {
589 $getVars = ['id', 'route'];
590 $shortcutButton = $buttonBar->makeShortcutButton()
591 ->setModuleName('site_configuration')
592 ->setGetVariables($getVars);
593 $buttonBar->addButton($shortcutButton, ButtonBar::BUTTON_POSITION_RIGHT);
594 }
595 }
596
597 /**
598 * Returns a list of pages that have 'is_siteroot' set
599 *
600 * @return array
601 */
602 protected function getAllSitePages(): array
603 {
604 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
605 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
606 $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class, 0, false));
607 $statement = $queryBuilder
608 ->select('*')
609 ->from('pages')
610 ->where(
611 $queryBuilder->expr()->eq('sys_language_uid', 0),
612 $queryBuilder->expr()->orX(
613 $queryBuilder->expr()->andX(
614 $queryBuilder->expr()->eq('pid', 0),
615 $queryBuilder->expr()->neq('doktype', PageRepository::DOKTYPE_SYSFOLDER)
616 ),
617 $queryBuilder->expr()->eq('is_siteroot', 1)
618 )
619 )
620 ->orderBy('pid')
621 ->addOrderBy('sorting')
622 ->execute();
623
624 $pages = [];
625 while ($row = $statement->fetch()) {
626 $row['rootline'] = BackendUtility::BEgetRootLine((int)$row['uid']);
627 array_pop($row['rootline']);
628 $row['rootline'] = array_reverse($row['rootline']);
629 $i = 0;
630 foreach ($row['rootline'] as &$record) {
631 $record['margin'] = $i++ * 20;
632 }
633 $pages[(int)$row['uid']] = $row;
634 }
635 return $pages;
636 }
637
638 /**
639 * @return LanguageService
640 */
641 protected function getLanguageService(): LanguageService
642 {
643 return $GLOBALS['LANG'];
644 }
645
646 /**
647 * @return BackendUserAuthentication
648 */
649 protected function getBackendUser(): BackendUserAuthentication
650 {
651 return $GLOBALS['BE_USER'];
652 }
653 }