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