PageLayoutController.php 46.8 KB
Newer Older
1
<?php
2
declare(strict_types = 1);
3
4
namespace TYPO3\CMS\Backend\Controller;

5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
9
10
 * 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.
11
 *
12
13
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
16
 * The TYPO3 project - inspiring people to share!
 */
17

18
19
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
20
use TYPO3\CMS\Backend\Module\ModuleLoader;
21
use TYPO3\CMS\Backend\Routing\UriBuilder;
22
23
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Template\ModuleTemplate;
Nicole Cordes's avatar
Nicole Cordes committed
24
use TYPO3\CMS\Backend\Utility\BackendUtility;
25
26
use TYPO3\CMS\Backend\View\BackendLayoutView;
use TYPO3\CMS\Backend\View\PageLayoutView;
27
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
28
29
30
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
31
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
32
use TYPO3\CMS\Core\Http\HtmlResponse;
33
34
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
35
use TYPO3\CMS\Core\Localization\LanguageService;
36
use TYPO3\CMS\Core\Page\PageRenderer;
37
use TYPO3\CMS\Core\Site\Entity\SiteInterface;
38
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
39
use TYPO3\CMS\Core\Type\Bitmask\Permission;
Nicole Cordes's avatar
Nicole Cordes committed
40
use TYPO3\CMS\Core\Utility\GeneralUtility;
41
use TYPO3\CMS\Core\Versioning\VersionState;
42
use TYPO3\CMS\Fluid\View\StandaloneView;
43
use TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper;
Nicole Cordes's avatar
Nicole Cordes committed
44

45
46
47
/**
 * Script Class for Web > Layout module
 */
48
49
50
51
52
53
class PageLayoutController
{
    /**
     * Page Id for which to make the listing
     *
     * @var int
54
     * @internal
55
56
57
58
59
60
61
62
     */
    public $id;

    /**
     * Module TSconfig
     *
     * @var array
     */
63
    protected $modTSconfig = [];
64
65
66
67
68
69

    /**
     * Module shared TSconfig
     *
     * @var array
     */
70
    protected $modSharedTSconfig = [];
71
72
73
74
75

    /**
     * Current ids page record
     *
     * @var array
76
     * @internal
77
78
79
80
81
82
83
84
     */
    public $pageinfo;

    /**
     * List of column-integers to edit. Is set from TSconfig, default is "1,0,2,3"
     *
     * @var string
     */
85
    protected $colPosList;
86
87
88
89
90
91

    /**
     * Currently selected language for editing content elements
     *
     * @var int
     */
92
    protected $current_sys_language;
93
94
95
96
97
98

    /**
     * Menu configuration
     *
     * @var array
     */
99
    protected $MOD_MENU = [];
100
101
102
103
104

    /**
     * Module settings (session variable)
     *
     * @var array
105
     * @internal
106
     */
107
    public $MOD_SETTINGS = [];
108
109
110
111
112
113
114

    /**
     * List of column-integers accessible to the current BE user.
     * Is set from TSconfig, default is $colPosList
     *
     * @var string
     */
115
    protected $activeColPosList;
116
117
118
119
120
121
122
123
124
125
126
127
128

    /**
     * @var IconFactory
     */
    protected $iconFactory;

    /**
     * The name of the module
     *
     * @var string
     */
    protected $moduleName = 'web_layout';

129
130
131
132
133
134
135
136
137
138
    /**
     * @var ModuleTemplate
     */
    protected $moduleTemplate;

    /**
     * @var ButtonBar
     */
    protected $buttonBar;

139
140
141
142
143
    /**
     * @var string
     */
    protected $searchContent;

144
145
146
147
148
    /**
     * @var SiteLanguage[]
     */
    protected $availableLanguages;

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    /**
     * @var PageRenderer
     */
    protected $pageRenderer;

    /**
     * @var UriBuilder
     */
    protected $uriBuilder;

    /**
     * @var BackendLayoutView
     */
    protected $backendLayouts;

164
165
166
167
168
169
170
171
172
173
    /**
     * Injects the request object for the current request or subrequest
     * As this controller goes only through the main() method, it is rather simple for now
     *
     * @param ServerRequestInterface $request the current request
     * @return ResponseInterface the response with the content
     */
    public function mainAction(ServerRequestInterface $request): ResponseInterface
    {
        $GLOBALS['SOBE'] = $this;
174
        $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
175
        $this->pageRenderer = $this->moduleTemplate->getPageRenderer();
176
        $this->iconFactory = $this->moduleTemplate->getIconFactory();
177
        $this->uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
178
        $this->buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
179
        $this->backendLayouts = GeneralUtility::makeInstance(BackendLayoutView::class);
180
181
        $this->getLanguageService()->includeLLFile('EXT:backend/Resources/Private/Language/locallang_layout.xlf');
        // Setting module configuration / page select clause
182
        $this->id = (int)($request->getParsedBody()['id'] ?? $request->getQueryParams()['id'] ?? 0);
183

184
185
186
187
188
189
190
191
192
        // Load page info array
        $this->pageinfo = BackendUtility::readPageAccess($this->id, $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW));
        /** @var SiteInterface $currentSite */
        $currentSite = $request->getAttribute('site');
        $this->availableLanguages = $currentSite->getAvailableLanguages($this->getBackendUser(), false, $this->id);
        // initialize page/be_user TSconfig settings
        $pageTsConfig = BackendUtility::getPagesTSconfig($this->id);
        $this->modSharedTSconfig['properties'] = $pageTsConfig['mod.']['SHARED.'] ?? [];
        $this->modTSconfig['properties'] = $pageTsConfig['mod.']['web_layout.'] ?? [];
193

194
        // Initialize menu
195
        $this->menuConfig($request);
196
        // Setting sys language from session var
197
        $this->current_sys_language = (int)$this->MOD_SETTINGS['language'];
198
199
200
201
202

        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Recordlist/ClearCache');

        $this->main($request);
        return new HtmlResponse($this->moduleTemplate->renderContent());
203
204
205
206
    }

    /**
     * Initialize menu array
207
     * @param ServerRequestInterface $request
208
     */
209
    protected function menuConfig(ServerRequestInterface $request): void
210
211
    {
        // MENU-ITEMS:
212
        $this->MOD_MENU = [
213
            'tt_content_showHidden' => '',
214
            'function' => [
215
216
                1 => $this->getLanguageService()->getLL('m_function_1'),
                2 => $this->getLanguageService()->getLL('m_function_2')
217
218
            ],
            'language' => [
219
                0 => $this->getLanguageService()->getLL('m_default')
220
221
            ]
        ];
222

223
224
        // First, select all localized page records on the current page.
        // Each represents a possibility for a language on the page. Add these to language selector.
225
        if ($this->id) {
226
227
228
229
230
231
232
233
            // Compile language data for pid != 0 only. The language drop-down is not shown on pid 0
            // since pid 0 can't be localized.
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
            $queryBuilder->getRestrictions()->removeAll()
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
                ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
            $statement = $queryBuilder->select('uid', $GLOBALS['TCA']['pages']['ctrl']['languageField'])
                ->from('pages')
234
                ->where(
235
                    $queryBuilder->expr()->eq(
236
                        $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
237
                        $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
238
                    )
239
240
241
                )->execute();
            while ($pageTranslation = $statement->fetch()) {
                $languageId = $pageTranslation[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
242
243
                if (isset($this->availableLanguages[$languageId])) {
                    $this->MOD_MENU['language'][$languageId] = $this->availableLanguages[$languageId]->getTitle();
244
                }
245
            }
246
            // Override the label
247
248
            if (isset($this->availableLanguages[0])) {
                $this->MOD_MENU['language'][0] = $this->availableLanguages[0]->getTitle();
249
250
            }
        }
251
        // Initialize the available actions
252
        $actions = $this->initActions();
253
        // Clean up settings
254
        $this->MOD_SETTINGS = BackendUtility::getModuleData($this->MOD_MENU, $request->getParsedBody()['SET'] ?? $request->getQueryParams()['SET'] ?? [], $this->moduleName);
255
        // For all elements to be shown in draft workspaces & to also show hidden elements by default if user hasn't disabled the option
256
257
258
        if ($this->getBackendUser()->workspace != 0
            || !isset($this->MOD_SETTINGS['tt_content_showHidden'])
            || $this->MOD_SETTINGS['tt_content_showHidden'] !== '0'
Pawel Cieslik's avatar
Pawel Cieslik committed
259
        ) {
260
261
            $this->MOD_SETTINGS['tt_content_showHidden'] = 1;
        }
262
263
        // Make action menu from available actions
        $this->makeActionMenu($actions);
264
265
266
    }

    /**
267
     * Initializes the available actions this module provides
268
     *
269
     * @return array the available actions
270
     */
271
    protected function initActions(): array
272
    {
273
        $actions = [
274
            1 => $this->getLanguageService()->getLL('m_function_1')
275
        ];
276
277
278
        // Find if there are ANY languages at all (and if not, do not show the language option from function menu).
        if (count($this->availableLanguages) > 1) {
            $actions[2] = $this->getLanguageService()->getLL('m_function_2');
279
        }
280
        $this->makeLanguageMenu();
281
282
283
284
285
286
287
        // Page / user TSconfig blinding of menu-items
        $blindActions = $this->modTSconfig['properties']['menu.']['functions.'] ?? [];
        foreach ($blindActions as $key => $value) {
            if (!$value && array_key_exists($key, $actions)) {
                unset($actions[$key]);
            }
        }
288
289
290
291
292
293
294
295
296
297

        return $actions;
    }

    /**
     * This creates the dropdown menu with the different actions this module is able to provide.
     * For now they are Columns, Quick Edit and Languages.
     *
     * @param array $actions array with the available actions
     */
298
    protected function makeActionMenu(array $actions): void
299
    {
300
301
302
303
        $actionMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
        $actionMenu->setIdentifier('actionMenu');
        $actionMenu->setLabel('');

304
        $defaultKey = null;
305
        $foundDefaultKey = false;
306
        foreach ($actions as $key => $action) {
307
308
309
            $menuItem = $actionMenu
                ->makeMenuItem()
                ->setTitle($action)
310
                ->setHref((string)$this->uriBuilder->buildUriFromRoute($this->moduleName) . '&id=' . $this->id . '&SET[function]=' . $key);
311

312
            if (!$foundDefaultKey) {
313
                $defaultKey = $key;
314
                $foundDefaultKey = true;
315
            }
316
317
            if ((int)$this->MOD_SETTINGS['function'] === $key) {
                $menuItem->setActive(true);
318
                $defaultKey = null;
319
320
            }
            $actionMenu->addMenuItem($menuItem);
321
        }
322
323
324
        if (isset($defaultKey)) {
            $this->MOD_SETTINGS['function'] = $defaultKey;
        }
325
        $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($actionMenu);
326
327
328
329
330
331
332
    }

    /**
     * Generate the flashmessages for current pid
     *
     * @return string HTML content with flashmessages
     */
333
    protected function getHeaderFlashMessagesForCurrentPid(): string
334
335
336
    {
        $content = '';
        $lang = $this->getLanguageService();
337

338
339
340
        $view = GeneralUtility::makeInstance(StandaloneView::class);
        $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/InfoBox.html'));

341
342
343
344
345
346
347
348
349
        // If page is a folder
        if ($this->pageinfo['doktype'] == PageRepository::DOKTYPE_SYSFOLDER) {
            $moduleLoader = GeneralUtility::makeInstance(ModuleLoader::class);
            $moduleLoader->load($GLOBALS['TBE_MODULES']);
            $modules = $moduleLoader->modules;
            if (is_array($modules['web']['sub']['list'])) {
                $title = $lang->getLL('goToListModule');
                $message = '<p>' . $lang->getLL('goToListModuleMessage') . '</p>';
                $message .= '<a class="btn btn-info" href="javascript:top.goToModule(\'web_list\',1);">' . $lang->getLL('goToListModule') . '</a>';
350
                $view->assignMultiple([
351
352
353
                    'title' => $title,
                    'message' => $message,
                    'state' => InfoboxViewHelper::STATE_INFO
354
                ]);
355
356
                $content .= $view->render();
            }
357
358
359
360
        } elseif ($this->pageinfo['doktype'] === PageRepository::DOKTYPE_SHORTCUT) {
            $shortcutMode = (int)$this->pageinfo['shortcut_mode'];
            $pageRepository = GeneralUtility::makeInstance(PageRepository::class);
            $targetPage = [];
361
362
            $message = '';
            $state = InfoboxViewHelper::STATE_ERROR;
363

364
            if ($shortcutMode || $this->pageinfo['shortcut']) {
365
366
                switch ($shortcutMode) {
                    case PageRepository::SHORTCUT_MODE_NONE:
367
368
                        $targetPage = $this->getTargetPageIfVisible($pageRepository->getPage($this->pageinfo['shortcut']));
                        $message .= $targetPage === [] ? $lang->getLL('pageIsMisconfiguredOrNotAccessibleInternalLinkMessage') : '';
369
370
                        break;
                    case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
371
372
373
                        $menuOfPages = $pageRepository->getMenu($this->pageinfo['uid'], '*', 'sorting', 'AND hidden = 0');
                        $targetPage = reset($menuOfPages) ?: [];
                        $message .= $targetPage === [] ? $lang->getLL('pageIsMisconfiguredFirstSubpageMessage') : '';
374
375
                        break;
                    case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
376
377
378
379
380
381
382
383
384
385
386
                        $targetPage = $this->getTargetPageIfVisible($pageRepository->getPage($this->pageinfo['pid']));
                        $message .= $targetPage === [] ? $lang->getLL('pageIsMisconfiguredParentPageMessage') : '';
                        break;
                    case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
                        $possibleTargetPages = $pageRepository->getMenu($this->pageinfo['uid'], '*', 'sorting', 'AND hidden = 0');
                        if ($possibleTargetPages === []) {
                            $message .= $lang->getLL('pageIsMisconfiguredOrNotAccessibleRandomInternalLinkMessage');
                            break;
                        }
                        $message = $lang->getLL('pageIsRandomInternalLinkMessage');
                        $state = InfoboxViewHelper::STATE_INFO;
387
388
                        break;
                }
389
390
                $message = htmlspecialchars($message);
                if ($targetPage !== [] && $shortcutMode !== PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE) {
391
                    $linkToPid = GeneralUtility::linkThisScript(['id' => $targetPage['uid']]);
392
                    $path = BackendUtility::getRecordPath($targetPage['uid'], $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW), 1000);
393
                    $linkedPath = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($path) . '</a>';
394
395
396
                    $message .= sprintf(htmlspecialchars($lang->getLL('pageIsInternalLinkMessage')), $linkedPath);
                    $message .= ' (' . htmlspecialchars($lang->sL(BackendUtility::getLabelFromItemlist('pages', 'shortcut_mode', $shortcutMode))) . ')';
                    $state = InfoboxViewHelper::STATE_INFO;
397
398
                }
            } else {
399
400
                $message = htmlspecialchars($lang->getLL('pageIsMisconfiguredInternalLinkMessage'));
                $state = InfoboxViewHelper::STATE_ERROR;
401
            }
402
403
404
405
406
407
408

            $view->assignMultiple([
                'title' => $this->pageinfo['title'],
                'message' => $message,
                'state' => $state
            ]);
            $content .= $view->render();
409
410
411
412
413
414
415
416
417
418
419
        } elseif ($this->pageinfo['doktype'] === PageRepository::DOKTYPE_LINK) {
            if (empty($this->pageinfo['url'])) {
                $view->assignMultiple([
                    'title' => $this->pageinfo['title'],
                    'message' => $lang->getLL('pageIsMisconfiguredExternalLinkMessage'),
                    'state' => InfoboxViewHelper::STATE_ERROR
                ]);
                $content .= $view->render();
            } else {
                $externalUrl = htmlspecialchars(GeneralUtility::makeInstance(PageRepository::class)->getExtURL($this->pageinfo));
                if ($externalUrl !== false) {
420
                    $externalUrlHtml = '<a href="' . $externalUrl . '" target="_blank" rel="noreferrer">' . $externalUrl . '</a>';
421
422
423
424
425
426
427
428
                    $view->assignMultiple([
                        'title' => $this->pageinfo['title'],
                        'message' => sprintf($lang->getLL('pageIsExternalLinkMessage'), $externalUrlHtml),
                        'state' => InfoboxViewHelper::STATE_INFO
                    ]);
                    $content .= $view->render();
                }
            }
429
430
431
432
        }
        // If content from different pid is displayed
        if ($this->pageinfo['content_from_pid']) {
            $contentPage = BackendUtility::getRecord('pages', (int)$this->pageinfo['content_from_pid']);
433
            $linkToPid = GeneralUtility::linkThisScript(['id' => $this->pageinfo['content_from_pid']]);
434
            $title = BackendUtility::getRecordTitle('pages', $contentPage);
435
            $link = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($title) . ' (PID ' . (int)$this->pageinfo['content_from_pid'] . ')</a>';
436
            $message = sprintf($lang->getLL('content_from_pid_title'), $link);
437
            $view->assignMultiple([
438
439
440
                'title' => $title,
                'message' => $message,
                'state' => InfoboxViewHelper::STATE_INFO
441
            ]);
442
            $content .= $view->render();
443
444
445
446
447
448
449
450
451
452
453
        } else {
            $links = $this->getPageLinksWhereContentIsAlsoShownOn($this->pageinfo['uid']);
            if (!empty($links)) {
                $message = sprintf($lang->getLL('content_on_pid_title'), $links);
                $view->assignMultiple([
                    'title' => '',
                    'message' => $message,
                    'state' => InfoboxViewHelper::STATE_INFO
                ]);
                $content .= $view->render();
            }
454
455
456
457
        }
        return $content;
    }

458
459
460
461
462
463
    /**
     * Get all pages with links where the content of a page $pageId is also shown on
     *
     * @param int $pageId
     * @return string
     */
464
    protected function getPageLinksWhereContentIsAlsoShownOn($pageId): string
465
466
467
468
469
470
471
472
473
474
475
476
477
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
        $queryBuilder->getRestrictions()->removeAll();
        $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
        $queryBuilder
            ->select('*')
            ->from('pages')
            ->where($queryBuilder->expr()->eq('content_from_pid', $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)));

        $links = [];
        $rows = $queryBuilder->execute()->fetchAll();
        if (!empty($rows)) {
            foreach ($rows as $row) {
478
                $linkToPid = GeneralUtility::linkThisScript(['id' => $row['uid']]);
479
480
481
482
483
484
485
486
                $title = BackendUtility::getRecordTitle('pages', $row);
                $link = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($title) . ' (PID ' . (int)$row['uid'] . ')</a>';
                $links[] = $link;
            }
        }
        return implode(', ', $links);
    }

487
488
489
    /**
     * @return string $title
     */
490
    protected function getLocalizedPageTitle(): string
491
492
    {
        if ($this->current_sys_language > 0) {
493
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
494
                ->getQueryBuilderForTable('pages');
495
496
497
498
            $queryBuilder->getRestrictions()
                ->removeAll()
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
                ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
499
            $localizedPage = $queryBuilder
500
                ->select('*')
501
                ->from('pages')
502
                ->where(
503
                    $queryBuilder->expr()->eq(
504
                        $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
505
506
                        $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
                    ),
507
                    $queryBuilder->expr()->eq(
508
                        $GLOBALS['TCA']['pages']['ctrl']['languageField'],
509
510
                        $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)
                    )
511
512
513
514
                )
                ->setMaxResults(1)
                ->execute()
                ->fetch();
515
516
            BackendUtility::workspaceOL('pages', $localizedPage);
            return $localizedPage['title'];
517
        }
518
        return $this->pageinfo['title'];
519
520
521
522
523
    }

    /**
     * Main function.
     * Creates some general objects and calls other functions for the main rendering of module content.
524
525
     *
     * @param ServerRequestInterface $request
526
     */
527
    protected function main(ServerRequestInterface $request): void
528
    {
529
        $content = '';
530
531
        // Access check...
        // The page will show only if there is a valid page and if this page may be viewed by the user
532
        if ($this->id && is_array($this->pageinfo)) {
533
534
            $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($this->pageinfo);

535
536
537
            $this->moduleTemplate->addJavaScriptCode('mainJsFunctions', '
                if (top.fsMod) {
                    top.fsMod.recentIds["web"] = ' . (int)$this->id . ';
538
                    top.fsMod.navFrameHighlightedID["web"] = top.fsMod.currentBank + "_" + ' . (int)$this->id . ';
539
540
                }
                function deleteRecord(table,id,url) {   //
541
                    window.location.href = ' . GeneralUtility::quoteJSvalue((string)$this->uriBuilder->buildUriFromRoute('tce_db') . '&cmd[')
542
                                            . ' + table + "][" + id + "][delete]=1&redirect=" + encodeURIComponent(url);
543
544
545
546
                    return false;
                }
            ');

547
            // Find backend layout / columns
548
            $backendLayout = $this->backendLayouts->getSelectedBackendLayout($this->id);
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
            if (!empty($backendLayout['__colPosList'])) {
                $this->colPosList = implode(',', $backendLayout['__colPosList']);
            }
            // Removing duplicates, if any
            $this->colPosList = array_unique(GeneralUtility::intExplode(',', $this->colPosList));
            // Accessible columns
            if (isset($this->modSharedTSconfig['properties']['colPos_list']) && trim($this->modSharedTSconfig['properties']['colPos_list']) !== '') {
                $this->activeColPosList = array_unique(GeneralUtility::intExplode(',', trim($this->modSharedTSconfig['properties']['colPos_list'])));
                // Match with the list which is present in the colPosList for the current page
                if (!empty($this->colPosList) && !empty($this->activeColPosList)) {
                    $this->activeColPosList = array_unique(array_intersect(
                        $this->activeColPosList,
                        $this->colPosList
                    ));
                }
            } else {
                $this->activeColPosList = $this->colPosList;
            }
            $this->activeColPosList = implode(',', $this->activeColPosList);
            $this->colPosList = implode(',', $this->colPosList);

570
571
            $content .= $this->getHeaderFlashMessagesForCurrentPid();

572
            // Render the primary module content:
573
            $content .= '<form action="' . htmlspecialchars((string)$this->uriBuilder->buildUriFromRoute($this->moduleName, ['id' => $this->id])) . '" id="PageLayoutController" method="post">';
574
575
576
577
            // Page title
            $content .= '<h1 class="' . ($this->isPageEditable($this->current_sys_language) ? 't3js-title-inlineedit' : '') . '">' . htmlspecialchars($this->getLocalizedPageTitle()) . '</h1>';
            // All other listings
            $content .= $this->renderContent();
578
579
            $content .= '</form>';
            $content .= $this->searchContent;
580
            // Setting up the buttons for the docheader
581
582
            $this->makeButtons($request);

583
584
585
586
587
588
589
            // Create LanguageMenu
            $this->makeLanguageMenu();
        } else {
            $this->moduleTemplate->addJavaScriptCode(
                'mainJsFunctions',
                'if (top.fsMod) top.fsMod.recentIds["web"] = ' . (int)$this->id . ';'
            );
590
            $content .= '<h1>' . htmlspecialchars($GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']) . '</h1>';
591
592
            $view = GeneralUtility::makeInstance(StandaloneView::class);
            $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/InfoBox.html'));
593
            $view->assignMultiple([
594
595
                'title' => $this->getLanguageService()->getLL('clickAPage_header'),
                'message' => $this->getLanguageService()->getLL('clickAPage_content'),
596
                'state' => InfoboxViewHelper::STATE_INFO
597
            ]);
598
            $content .= $view->render();
599
        }
600
601
        // Set content
        $this->moduleTemplate->setContent($content);
602
603
604
    }

    /**
605
     * Rendering content
606
607
608
     *
     * @return string
     */
609
    protected function renderContent(): string
610
    {
611
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ContextMenu');
612
        $dbList = GeneralUtility::makeInstance(PageLayoutView::class);
613
        $dbList->doEdit = $this->isContentEditable($this->current_sys_language);
614
615
        $dbList->option_newWizard = empty($this->modTSconfig['properties']['disableNewContentElementWizard']);
        $dbList->defLangBinding = !empty($this->modTSconfig['properties']['defLangBinding']);
616
        $tableOutput = '';
617
618
619
620
        $tcaItems = $this->backendLayouts->getColPosListItemsParsed($this->id);
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LayoutModule/DragDrop');
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LayoutModule/Paste');
621
        if ($this->getBackendUser()->check('tables_select', 'tt_content')) {
622
            $h_func_b = '';
623
624
625
626
627
            // Setting up the tt_content columns to show:
            if (is_array($GLOBALS['TCA']['tt_content']['columns']['colPos']['config']['items'])) {
                $colList = [];
                foreach ($tcaItems as $temp) {
                    $colList[] = $temp[1];
628
                }
629
            } else {
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
                // ... should be impossible that colPos has no array. But this is the fallback should it make any sense:
                $colList = ['1', '0', '2', '3'];
            }
            if ($this->colPosList !== '') {
                $colList = array_intersect(GeneralUtility::intExplode(',', $this->colPosList), $colList);
            }
            // The order of the rows: Default is left(1), Normal(0), right(2), margin(3)
            $dbList->tt_contentConfig['cols'] = implode(',', $colList);
            $dbList->tt_contentConfig['activeCols'] = $this->activeColPosList;
            $dbList->tt_contentConfig['showHidden'] = $this->MOD_SETTINGS['tt_content_showHidden'];
            $dbList->tt_contentConfig['sys_language_uid'] = (int)$this->current_sys_language;
            // If the function menu is set to "Language":
            if ($this->MOD_SETTINGS['function'] == 2) {
                $dbList->tt_contentConfig['languageMode'] = 1;
                $dbList->tt_contentConfig['languageCols'] = $this->MOD_MENU['language'];
                $dbList->tt_contentConfig['languageColsPointer'] = $this->current_sys_language;
            }
            // Toggle hidden ContentElements
            $numberOfHiddenElements = $this->getNumberOfHiddenElements($dbList->tt_contentConfig);
            if ($numberOfHiddenElements > 0) {
                $h_func_b = '
                    <div class="checkbox">
                        <label for="checkTt_content_showHidden">
                            <input type="checkbox" id="checkTt_content_showHidden" class="checkbox" name="SET[tt_content_showHidden]" value="1" ' . ($this->MOD_SETTINGS['tt_content_showHidden'] ? 'checked="checked"' : '') . ' />
                            ' . htmlspecialchars($this->getLanguageService()->getLL('hiddenCE')) . ' (<span class="t3js-hidden-counter">' . $numberOfHiddenElements . '</span>)
                        </label>
                    </div>';
657
            }
658
            // Generate the list of content elements
659
            $tableOutput = $dbList->getTable_tt_content($this->id) . $h_func_b;
660
661
662
663
        }
        // Init the content
        $content = '';
        // Additional header content
664
665
666
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/db_layout.php']['drawHeaderHook'] ?? [] as $hook) {
            $params = [];
            $content .= GeneralUtility::callUserFunction($hook, $params, $this);
667
        }
668
        $content .= $tableOutput;
669
        // Making search form:
670
671
672
        if (!$this->modTSconfig['properties']['disableSearchBox']) {
            $this->searchContent = $this->getSearchBox();
            if ($this->searchContent) {
673
                $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ToggleSearchToolbox');
674
675
676
677
678
679
680
                $toggleSearchFormButton = $this->buttonBar->makeLinkButton()
                    ->setClasses('t3js-toggle-search-toolbox')
                    ->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.title.searchIcon'))
                    ->setIcon($this->iconFactory->getIcon('actions-search', Icon::SIZE_SMALL))
                    ->setHref('#');
                $this->buttonBar->addButton($toggleSearchFormButton, ButtonBar::BUTTON_POSITION_LEFT, 4);
            }
681
682
        }
        // Additional footer content
683
684
685
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/db_layout.php']['drawFooterHook'] ?? [] as $hook) {
            $params = [];
            $content .= GeneralUtility::callUserFunction($hook, $params, $this);
686
687
688
689
690
691
692
693
694
695
        }
        return $content;
    }

    /***************************
     *
     * Sub-content functions, rendering specific parts of the module content.
     *
     ***************************/
    /**
696
     * This creates the buttons for the modules
697
     * @param ServerRequestInterface $request
698
     */
699
    protected function makeButtons(ServerRequestInterface $request): void
700
    {
701
702
703
704
705
        // Add CSH (Context Sensitive Help) icon to tool bar
        $contextSensitiveHelpButton = $this->buttonBar->makeHelpButton()
            ->setModuleName('_MOD_' . $this->moduleName)
            ->setFieldName('columns_' . $this->MOD_SETTINGS['function']);
        $this->buttonBar->addButton($contextSensitiveHelpButton);
706
707
708
        $lang = $this->getLanguageService();
        // View page
        if (!VersionState::cast($this->pageinfo['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)) {
709
710
711
712
713
714
715
716
717
            $languageParameter = $this->current_sys_language ? ('&L=' . $this->current_sys_language) : '';
            $onClick = BackendUtility::viewOnClick(
                $this->pageinfo['uid'],
                '',
                BackendUtility::BEgetRootLine($this->pageinfo['uid']),
                '',
                '',
                $languageParameter
            );
718
            $viewButton = $this->buttonBar->makeLinkButton()
719
                ->setOnClick($onClick)
720
                ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.showPage'))
721
                ->setIcon($this->iconFactory->getIcon('actions-view-page', Icon::SIZE_SMALL))
722
723
724
                ->setHref('#');

            $this->buttonBar->addButton($viewButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
725
726
        }
        // Shortcut
727
728
729
730
        $shortcutButton = $this->buttonBar->makeShortcutButton()
            ->setModuleName($this->moduleName)
            ->setGetVariables([
                'id',
731
                'route',
732
733
734
735
736
                'edit_record',
            ])
            ->setSetVariables(array_keys($this->MOD_MENU));
        $this->buttonBar->addButton($shortcutButton);

737
        // Cache
738
        if (empty($this->modTSconfig['properties']['disableAdvanced'])) {
739
            $clearCacheButton = $this->buttonBar->makeLinkButton()
740
741
742
                ->setHref('#')
                ->setDataAttributes(['id' => $this->pageinfo['uid']])
                ->setClasses('t3js-clear-page-cache')
743
                ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.clear_cache'))
744
                ->setIcon($this->iconFactory->getIcon('actions-system-cache-clear', Icon::SIZE_SMALL));
745
            $this->buttonBar->addButton($clearCacheButton, ButtonBar::BUTTON_POSITION_RIGHT, 1);
746
        }
747
        if (empty($this->modTSconfig['properties']['disableIconToolbar'])) {
748
            // Edit page properties and page language overlay icons
749
            if ($this->isPageEditable(0)) {
750
751
                /** @var \TYPO3\CMS\Core\Http\NormalizedParams */
                $normalizedParams = $request->getAttribute('normalizedParams');
752
                // Edit localized pages only when one specific language is selected
753
                if ($this->MOD_SETTINGS['function'] == 1 && $this->current_sys_language > 0) {
754
755
                    $localizationParentField = $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'];
                    $languageField = $GLOBALS['TCA']['pages']['ctrl']['languageField'];
756
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
757
                        ->getQueryBuilderForTable('pages');
758
759
760
761
762
763
                    $queryBuilder->getRestrictions()
                        ->removeAll()
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
                        ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
                    $overlayRecord = $queryBuilder
                        ->select('uid')
764
                        ->from('pages')
765
                        ->where(
766
                            $queryBuilder->expr()->eq(
767
                                $localizationParentField,
768
769
770
                                $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
                            ),
                            $queryBuilder->expr()->eq(
771
                                $languageField,
772
773
                                $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)
                            )
774
775
776
777
                        )
                        ->setMaxResults(1)
                        ->execute()
                        ->fetch();
778
779
780
                    // Edit button
                    $urlParameters = [
                        'edit' => [
781
                            'pages' => [
782
783
784
                                $overlayRecord['uid'] => 'edit'
                            ]
                        ],
785
                        'returnUrl' => $normalizedParams->getRequestUri(),
786
                    ];
787

788
                    $url = (string)$this->uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
789
                    $editLanguageButton = $this->buttonBar->makeLinkButton()
790
                        ->setHref($url)
791
                        ->setTitle($lang->getLL('editPageLanguageOverlayProperties'))
792
793
                        ->setIcon($this->iconFactory->getIcon('mimetypes-x-content-page-language-overlay', Icon::SIZE_SMALL));
                    $this->buttonBar->addButton($editLanguageButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
794
                }
795
796
797
798
799
800
                $urlParameters = [
                    'edit' => [
                        'pages' => [
                            $this->id => 'edit'
                        ]
                    ],
801
                    'returnUrl' => $normalizedParams->getRequestUri(),
802
                ];
803
                $url = (string)$this->uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
804
                $editPageButton = $this->buttonBar->makeLinkButton()
805
                    ->setHref($url)
806
                    ->setTitle($lang->getLL('editPageProperties'))
807
808
                    ->setIcon($this->iconFactory->getIcon('actions-page-open', Icon::SIZE_SMALL));
                $this->buttonBar->addButton($editPageButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
809
810
811
812
813
814
815
816
817
818
819
820
821
            }
        }
    }

    /*******************************
     *
     * Other functions
     *
     ******************************/
    /**
     * Returns the number of hidden elements (including those hidden by start/end times)
     * on the current page (for the current sys_language)
     *
822
     * @param array $contentConfig
823
824
     * @return int
     */
825
    protected function getNumberOfHiddenElements(array $contentConfig = []): int
826
    {
827
        $andWhere = [];
828
829
830
831
832
833
834
835
836
837
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tt_content');
        $queryBuilder->getRestrictions()
            ->removeAll()
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
            ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));

        $queryBuilder
            ->count('uid')
            ->from('tt_content')
            ->where(
838
839
840
                $queryBuilder->expr()->eq(
                    'pid',
                    $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
                )
            );

        if (!empty($contentConfig['languageCols']) && is_array($contentConfig['languageCols'])) {
            // Multi-language view is active
            if ($this->current_sys_language > 0) {
                $queryBuilder->andWhere(
                    $queryBuilder->expr()->in(
                        'sys_language_uid',
                        [0, $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)]
                    )
                );
            }
        } else {
            $queryBuilder->andWhere(
856
857
858
859
                $queryBuilder->expr()->eq(
                    'sys_language_uid',
                    $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)
                )
860
            );
861
        }
862
863

        if (!empty($GLOBALS['TCA']['tt_content']['ctrl']['enablecolumns']['disabled'])) {
864
865
866
867
            $andWhere[] = $queryBuilder->expr()->neq(
                'hidden',
                $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
            );
868
869
870
871
        }

        if (!empty($GLOBALS['TCA']['tt_content']['ctrl']['enablecolumns']['starttime'])) {
            $andWhere[] = $queryBuilder->expr()->andX(
872
873
874
875
876
877
878
879
                $queryBuilder->expr()->neq(
                    'starttime',
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
                ),
                $queryBuilder->expr()->gt(
                    'starttime',
                    $queryBuilder->createNamedParameter($GLOBALS['SIM_ACCESS_TIME'], \PDO::PARAM_INT)
                )
880
881
882
883
884
            );
        }

        if (!empty($GLOBALS['TCA']['tt_content']['ctrl']['enablecolumns']['endtime'])) {
            $andWhere[] = $queryBuilder->expr()->andX(
885
886
887
888
889
890
891
892
                $queryBuilder->expr()->neq(
                    'endtime',
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
                ),
                $queryBuilder->expr()->lte(
                    'endtime',
                    $queryBuilder->createNamedParameter($GLOBALS['SIM_ACCESS_TIME'], \PDO::PARAM_INT)
                )
893
894
895
896
897
898
899
900
901
902
903
904
905
906
            );
        }

        if (!empty($andWhere)) {
            $queryBuilder->andWhere(
                $queryBuilder->expr()->orX(...$andWhere)
            );
        }

        $count = $queryBuilder
            ->execute()
            ->fetchColumn(0);

        return (int)$count;
907
908
909
    }

    /**
910
     * Check if page can be edited by current user
911
     *
912
     * @param int|null $languageId
913
914
     * @return bool
     */
915
    protected function isPageEditable(int $languageId): bool
916
    {
917
918
919
        if ($this->getBackendUser()->isAdmin()) {
            return true;
        }
920

921
922
923
        return !$this->pageinfo['editlock']
            && $this->getBackendUser()->doesUserHaveAccess($this->pageinfo, Permission::PAGE_EDIT)
            && $this->getBackendUser()->checkLanguageAccess($languageId);
924
925
926
927
928
    }

    /**
     * Check if content can be edited by current user
     *
929
     * @param int $languageId
930
931
     * @return bool
     */
932
    protected function isContentEditable(int $languageId): bool
933
    {
934
935
936
        if ($this->getBackendUser()->isAdmin()) {
            return true;
        }
937

938
939
940
        return !$this->pageinfo['editlock']
            && $this->getBackendUser()->doesUserHaveAccess($this->pageinfo, Permission::CONTENT_EDIT)
            && $this->getBackendUser()->checkLanguageAccess($languageId);
941
942
    }

943
944
945
    /**
     * Returns LanguageService
     *
946
     * @return LanguageService
947
     */
948
    protected function getLanguageService(): LanguageService
949
950
951
952
953
954
955
    {
        return $GLOBALS['LANG'];
    }

    /**
     * Returns the current BE user.
     *
956
     * @return BackendUserAuthentication
957
     */
958
    protected function getBackendUser(): BackendUserAuthentication
959
960
961
962
    {
        return $GLOBALS['BE_USER'];
    }

963
964
965
    /**
     * Make the LanguageMenu
     */
966
    protected function makeLanguageMenu(): void
967
968
969
970
971
972
973
974
    {
        if (count($this->MOD_MENU['language']) > 1) {
            $languageMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
            $languageMenu->setIdentifier('languageMenu');
            foreach ($this->MOD_MENU['language'] as $key => $language) {
                $menuItem = $languageMenu
                    ->makeMenuItem()
                    ->setTitle($language)
975
                    ->setHref((string)$this->uriBuilder->buildUriFromRoute($this->moduleName) . '&id=' . $this->id . '&SET[language]=' . $key);
976
977
978
979
980
981
982
983
                if ((int)$this->current_sys_language === $key) {
                    $menuItem->setActive(true);
                }
                $languageMenu->addMenuItem($menuItem);
            }
            $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($languageMenu);
        }
    }
984

985
986
987
988
989
990
991
992
993
994
995
    /**
     * Returns the target page if visible
     *
     * @param array $targetPage
     *
     * @return array
     */
    protected function getTargetPageIfVisible(array $targetPage): array
    {
        return !(bool)($targetPage['hidden'] ?? false) ? $targetPage : [];
    }
996
997
<