PageLayoutController.php 48.7 KB
Newer Older
1
<?php
2

3
declare(strict_types=1);
4

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
namespace TYPO3\CMS\Backend\Controller;

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

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

    /**
     * Module TSconfig
     *
     * @var array
     */
67
    protected $modTSconfig = [];
68
69
70
71
72
73

    /**
     * Module shared TSconfig
     *
     * @var array
     */
74
    protected $modSharedTSconfig = [];
75
76
77
78
79

    /**
     * Current ids page record
     *
     * @var array
80
     * @internal
81
82
83
84
85
86
87
88
     */
    public $pageinfo;

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

    /**
     * Currently selected language for editing content elements
     *
     * @var int
     */
96
    protected $current_sys_language;
97
98
99
100
101
102

    /**
     * Menu configuration
     *
     * @var array
     */
103
    protected $MOD_MENU = [];
104
105
106
107
108

    /**
     * Module settings (session variable)
     *
     * @var array
109
     * @internal
110
     */
111
    public $MOD_SETTINGS = [];
112
113
114
115
116
117
118

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

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

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

133
134
135
136
137
138
139
140
141
142
    /**
     * @var ModuleTemplate
     */
    protected $moduleTemplate;

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

143
144
145
146
147
    /**
     * @var string
     */
    protected $searchContent;

148
149
150
151
152
    /**
     * @var SiteLanguage[]
     */
    protected $availableLanguages;

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

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

    /**
164
     * @var PageLayoutContext
165
     */
166
    protected $context;
167

168
169
170
171
172
173
174
175
176
177
    /**
     * 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;
178
        $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
179
        $this->pageRenderer = $this->moduleTemplate->getPageRenderer();
180
        $this->iconFactory = $this->moduleTemplate->getIconFactory();
181
        $this->uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
182
        $this->buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
183
184
        $this->getLanguageService()->includeLLFile('EXT:backend/Resources/Private/Language/locallang_layout.xlf');
        // Setting module configuration / page select clause
185
        $this->id = (int)($request->getParsedBody()['id'] ?? $request->getQueryParams()['id'] ?? 0);
186

187
188
        // Load page info array
        $this->pageinfo = BackendUtility::readPageAccess($this->id, $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW));
189
190
191
192
193
194
        $this->context = GeneralUtility::makeInstance(
            PageLayoutContext::class,
            $this->pageinfo,
            GeneralUtility::makeInstance(BackendLayoutView::class)->getBackendLayoutForPage($this->id)
        );

195
196
197
198
199
200
201
        /** @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.'] ?? [];
202

203
        // Initialize menu
204
        $this->menuConfig($request);
205
        // Setting sys language from session var
206
        $this->current_sys_language = (int)$this->MOD_SETTINGS['language'];
207
208
209
210
211

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

        $this->main($request);
        return new HtmlResponse($this->moduleTemplate->renderContent());
212
213
214
215
    }

    /**
     * Initialize menu array
216
     * @param ServerRequestInterface $request
217
     */
218
    protected function menuConfig(ServerRequestInterface $request): void
219
220
    {
        // MENU-ITEMS:
221
        $this->MOD_MENU = [
222
            'tt_content_showHidden' => '',
223
            'function' => [
224
225
                1 => $this->getLanguageService()->getLL('m_function_1'),
                2 => $this->getLanguageService()->getLL('m_function_2')
226
227
            ],
            'language' => [
228
                0 => $this->getLanguageService()->getLL('m_default')
229
230
            ]
        ];
231

232
233
        // 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.
234
        if ($this->id) {
235
236
237
238
239
            // 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))
240
                ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->getBackendUser()->workspace));
241
242
            $statement = $queryBuilder->select('uid', $GLOBALS['TCA']['pages']['ctrl']['languageField'])
                ->from('pages')
243
                ->where(
244
                    $queryBuilder->expr()->eq(
245
                        $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
246
                        $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
247
                    )
248
249
250
                )->execute();
            while ($pageTranslation = $statement->fetch()) {
                $languageId = $pageTranslation[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
251
252
                if (isset($this->availableLanguages[$languageId])) {
                    $this->MOD_MENU['language'][$languageId] = $this->availableLanguages[$languageId]->getTitle();
253
                }
254
            }
255
            // Override the label
256
257
            if (isset($this->availableLanguages[0])) {
                $this->MOD_MENU['language'][0] = $this->availableLanguages[0]->getTitle();
258
259
            }
        }
260
        // Initialize the available actions
261
        $actions = $this->initActions();
262
        // Clean up settings
263
        $this->MOD_SETTINGS = BackendUtility::getModuleData($this->MOD_MENU, $request->getParsedBody()['SET'] ?? $request->getQueryParams()['SET'] ?? [], $this->moduleName);
264
        // For all elements to be shown in draft workspaces & to also show hidden elements by default if user hasn't disabled the option
265
266
267
        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
268
        ) {
269
270
            $this->MOD_SETTINGS['tt_content_showHidden'] = 1;
        }
271
272
        // Make action menu from available actions
        $this->makeActionMenu($actions);
273
274
275
    }

    /**
276
     * Initializes the available actions this module provides
277
     *
278
     * @return array the available actions
279
     */
280
    protected function initActions(): array
281
    {
282
        $actions = [
283
            1 => $this->getLanguageService()->getLL('m_function_1')
284
        ];
285
286
287
        // 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');
288
        }
289
        $this->makeLanguageMenu();
290
291
292
293
294
295
296
        // 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]);
            }
        }
297
298
299
300
301
302
303
304
305
306

        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
     */
307
    protected function makeActionMenu(array $actions): void
308
    {
309
310
311
312
        $actionMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
        $actionMenu->setIdentifier('actionMenu');
        $actionMenu->setLabel('');

313
        $defaultKey = null;
314
        $foundDefaultKey = false;
315
        foreach ($actions as $key => $action) {
316
317
318
            $menuItem = $actionMenu
                ->makeMenuItem()
                ->setTitle($action)
319
                ->setHref((string)$this->uriBuilder->buildUriFromRoute($this->moduleName) . '&id=' . $this->id . '&SET[function]=' . $key);
320

321
            if (!$foundDefaultKey) {
322
                $defaultKey = $key;
323
                $foundDefaultKey = true;
324
            }
325
326
            if ((int)$this->MOD_SETTINGS['function'] === $key) {
                $menuItem->setActive(true);
327
                $defaultKey = null;
328
329
            }
            $actionMenu->addMenuItem($menuItem);
330
        }
331
332
333
        if (isset($defaultKey)) {
            $this->MOD_SETTINGS['function'] = $defaultKey;
        }
334
        $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($actionMenu);
335
336
337
338
339
340
341
    }

    /**
     * Generate the flashmessages for current pid
     *
     * @return string HTML content with flashmessages
     */
342
    protected function getHeaderFlashMessagesForCurrentPid(): string
343
344
345
    {
        $content = '';
        $lang = $this->getLanguageService();
346

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

350
351
352
353
354
355
356
357
358
        // 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>';
359
                $view->assignMultiple([
360
361
362
                    'title' => $title,
                    'message' => $message,
                    'state' => InfoboxViewHelper::STATE_INFO
363
                ]);
364
365
                $content .= $view->render();
            }
366
367
368
369
        } elseif ($this->pageinfo['doktype'] === PageRepository::DOKTYPE_SHORTCUT) {
            $shortcutMode = (int)$this->pageinfo['shortcut_mode'];
            $pageRepository = GeneralUtility::makeInstance(PageRepository::class);
            $targetPage = [];
370
371
            $message = '';
            $state = InfoboxViewHelper::STATE_ERROR;
372

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

            $view->assignMultiple([
                'title' => $this->pageinfo['title'],
                'message' => $message,
                'state' => $state
            ]);
            $content .= $view->render();
418
419
420
421
422
423
424
425
426
427
428
        } 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) {
429
                    $externalUrlHtml = '<a href="' . $externalUrl . '" target="_blank" rel="noreferrer">' . $externalUrl . '</a>';
430
431
432
433
434
435
436
437
                    $view->assignMultiple([
                        'title' => $this->pageinfo['title'],
                        'message' => sprintf($lang->getLL('pageIsExternalLinkMessage'), $externalUrlHtml),
                        'state' => InfoboxViewHelper::STATE_INFO
                    ]);
                    $content .= $view->render();
                }
            }
438
439
440
441
        }
        // If content from different pid is displayed
        if ($this->pageinfo['content_from_pid']) {
            $contentPage = BackendUtility::getRecord('pages', (int)$this->pageinfo['content_from_pid']);
442
            $linkToPid = GeneralUtility::linkThisScript(['id' => $this->pageinfo['content_from_pid']]);
443
            $title = BackendUtility::getRecordTitle('pages', $contentPage);
444
            $link = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($title) . ' (PID ' . (int)$this->pageinfo['content_from_pid'] . ')</a>';
445
            $message = sprintf($lang->getLL('content_from_pid_title'), $link);
446
            $view->assignMultiple([
447
448
449
                'title' => $title,
                'message' => $message,
                'state' => InfoboxViewHelper::STATE_INFO
450
            ]);
451
            $content .= $view->render();
452
453
454
455
456
457
458
459
460
461
462
        } 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();
            }
463
464
465
466
        }
        return $content;
    }

467
468
469
470
471
472
    /**
     * Get all pages with links where the content of a page $pageId is also shown on
     *
     * @param int $pageId
     * @return string
     */
473
    protected function getPageLinksWhereContentIsAlsoShownOn($pageId): string
474
475
476
477
478
479
480
481
482
483
484
485
486
    {
        $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) {
487
                $linkToPid = GeneralUtility::linkThisScript(['id' => $row['uid']]);
488
489
490
491
492
493
494
495
                $title = BackendUtility::getRecordTitle('pages', $row);
                $link = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($title) . ' (PID ' . (int)$row['uid'] . ')</a>';
                $links[] = $link;
            }
        }
        return implode(', ', $links);
    }

496
497
498
    /**
     * @return string $title
     */
499
    protected function getLocalizedPageTitle(): string
500
501
    {
        if ($this->current_sys_language > 0) {
502
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
503
                ->getQueryBuilderForTable('pages');
504
505
506
            $queryBuilder->getRestrictions()
                ->removeAll()
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
507
                ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->getBackendUser()->workspace));
508
            $localizedPage = $queryBuilder
509
                ->select('*')
510
                ->from('pages')
511
                ->where(
512
                    $queryBuilder->expr()->eq(
513
                        $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
514
515
                        $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
                    ),
516
                    $queryBuilder->expr()->eq(
517
                        $GLOBALS['TCA']['pages']['ctrl']['languageField'],
518
519
                        $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)
                    )
520
521
522
523
                )
                ->setMaxResults(1)
                ->execute()
                ->fetch();
524
525
            BackendUtility::workspaceOL('pages', $localizedPage);
            return $localizedPage['title'];
526
        }
527
        return $this->pageinfo['title'];
528
529
530
531
532
    }

    /**
     * Main function.
     * Creates some general objects and calls other functions for the main rendering of module content.
533
534
     *
     * @param ServerRequestInterface $request
535
     */
536
    protected function main(ServerRequestInterface $request): void
537
    {
538
        $content = '';
539
540
        // Access check...
        // The page will show only if there is a valid page and if this page may be viewed by the user
541
        if ($this->id && is_array($this->pageinfo)) {
542
543
            $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($this->pageinfo);

544
545
546
            $this->moduleTemplate->addJavaScriptCode('mainJsFunctions', '
                if (top.fsMod) {
                    top.fsMod.recentIds["web"] = ' . (int)$this->id . ';
547
                    top.fsMod.navFrameHighlightedID["web"] = top.fsMod.currentBank + "_" + ' . (int)$this->id . ';
548
549
                }
                function deleteRecord(table,id,url) {   //
550
                    window.location.href = ' . GeneralUtility::quoteJSvalue((string)$this->uriBuilder->buildUriFromRoute('tce_db') . '&cmd[')
551
                                            . ' + table + "][" + id + "][delete]=1&redirect=" + encodeURIComponent(url);
552
553
554
555
                    return false;
                }
            ');

556
557
            $backendLayout = $this->context->getBackendLayout();

558
            // Find backend layout / columns
559
560
            if (!empty($backendLayout->getColumnPositionNumbers())) {
                $this->colPosList = implode(',', $backendLayout->getColumnPositionNumbers());
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
            }
            // 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);

580
581
            $content .= $this->getHeaderFlashMessagesForCurrentPid();

582
            // Render the primary module content:
583
            $content .= '<form action="' . htmlspecialchars((string)$this->uriBuilder->buildUriFromRoute($this->moduleName, ['id' => $this->id])) . '" id="PageLayoutController" method="post">';
584
585
586
587
            // Page title
            $content .= '<h1 class="' . ($this->isPageEditable($this->current_sys_language) ? 't3js-title-inlineedit' : '') . '">' . htmlspecialchars($this->getLocalizedPageTitle()) . '</h1>';
            // All other listings
            $content .= $this->renderContent();
588
589
            $content .= '</form>';
            $content .= $this->searchContent;
590
            // Setting up the buttons for the docheader
591
592
            $this->makeButtons($request);

593
594
595
596
597
598
599
            // Create LanguageMenu
            $this->makeLanguageMenu();
        } else {
            $this->moduleTemplate->addJavaScriptCode(
                'mainJsFunctions',
                'if (top.fsMod) top.fsMod.recentIds["web"] = ' . (int)$this->id . ';'
            );
600
            $content .= '<h1>' . htmlspecialchars($GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']) . '</h1>';
601
602
            $view = GeneralUtility::makeInstance(StandaloneView::class);
            $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/InfoBox.html'));
603
            $view->assignMultiple([
604
605
                'title' => $this->getLanguageService()->getLL('clickAPage_header'),
                'message' => $this->getLanguageService()->getLL('clickAPage_content'),
606
                'state' => InfoboxViewHelper::STATE_INFO
607
            ]);
608
            $content .= $view->render();
609
        }
610
611
        // Set content
        $this->moduleTemplate->setContent($content);
612
613
614
    }

    /**
615
     * Rendering content
616
617
618
     *
     * @return string
     */
619
    protected function renderContent(): string
620
    {
621
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ContextMenu');
622
623
624
625
626
627
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Tooltip');
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Localization');
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LayoutModule/DragDrop');
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LayoutModule/Paste');
        $this->pageRenderer->addInlineLanguageLabelFile('EXT:backend/Resources/Private/Language/locallang_layout.xlf');
628

629
        $backendLayout = $this->context->getBackendLayout();
630

631
        $configuration = $this->context->getDrawingConfiguration();
632
633
634
635
        $configuration->setDefaultLanguageBinding(!empty($this->modTSconfig['properties']['defLangBinding']));
        $configuration->setActiveColumns(GeneralUtility::trimExplode(',', $this->activeColPosList));
        $configuration->setShowHidden((bool)$this->MOD_SETTINGS['tt_content_showHidden']);
        $configuration->setLanguageColumns($this->MOD_MENU['language']);
636
637
        $configuration->setShowNewContentWizard(empty($this->modTSconfig['properties']['disableNewContentElementWizard']));
        $configuration->setSelectedLanguageId((int)$this->MOD_SETTINGS['language']);
638
639
640
        if ($this->MOD_SETTINGS['function'] == 2) {
            $configuration->setLanguageMode(true);
        }
641

642
        $numberOfHiddenElements = $this->getNumberOfHiddenElements($configuration->getLanguageColumns());
643

644
        if (GeneralUtility::makeInstance(Features::class)->isFeatureEnabled('fluidBasedPageModule')) {
645
            $pageLayoutDrawer = $this->context->getBackendLayoutRenderer();
646
647

            $pageActionsCallback = null;
648
            if ($this->context->isPageEditable()) {
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
                $languageOverlayId = 0;
                $pageLocalizationRecord = BackendUtility::getRecordLocalization('pages', $this->id, (int)$this->current_sys_language);
                if (is_array($pageLocalizationRecord)) {
                    $pageLocalizationRecord = reset($pageLocalizationRecord);
                }
                if (!empty($pageLocalizationRecord['uid'])) {
                    $languageOverlayId = $pageLocalizationRecord['uid'];
                }
                $pageActionsCallback = 'function(PageActions) {
                    PageActions.setPageId(' . (int)$this->id . ');
                    PageActions.setLanguageOverlayId(' . $languageOverlayId . ');
                }';
            }
            $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/PageActions', $pageActionsCallback);
            $tableOutput = $pageLayoutDrawer->drawContent();
        } else {
665
            $dbList = PageLayoutView::createFromPageLayoutContext($this->context);
666
667
            // Setting up the tt_content columns to show
            $colList = array_keys($backendLayout->getUsedColumns());
668
669
670
671
672
            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);
673
674
675
            $tableOutput = $dbList->getTable_tt_content($this->id);
        }

676
        if ($this->getBackendUser()->check('tables_select', 'tt_content') && $numberOfHiddenElements > 0) {
677
            // Toggle hidden ContentElements
678
679
680
681
682
683
684
            $tableOutput .= '
                <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>';
685
        }
686

687
688
689
        // Init the content
        $content = '';
        // Additional header content
690
691
692
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/db_layout.php']['drawHeaderHook'] ?? [] as $hook) {
            $params = [];
            $content .= GeneralUtility::callUserFunction($hook, $params, $this);
693
        }
694
        $content .= $tableOutput;
695
        // Making search form:
696
697
698
        if (!$this->modTSconfig['properties']['disableSearchBox']) {
            $this->searchContent = $this->getSearchBox();
            if ($this->searchContent) {
699
                $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ToggleSearchToolbox');
700
701
702
703
704
705
706
                $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);
            }
707
708
        }
        // Additional footer content
709
710
711
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/db_layout.php']['drawFooterHook'] ?? [] as $hook) {
            $params = [];
            $content .= GeneralUtility::callUserFunction($hook, $params, $this);
712
713
714
715
716
717
718
719
720
721
        }
        return $content;
    }

    /***************************
     *
     * Sub-content functions, rendering specific parts of the module content.
     *
     ***************************/
    /**
722
     * This creates the buttons for the modules
723
     * @param ServerRequestInterface $request
724
     */
725
    protected function makeButtons(ServerRequestInterface $request): void
726
    {
727
728
729
730
731
        // 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);
732
733
        $lang = $this->getLanguageService();
        // View page
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
        $pageTsConfig = BackendUtility::getPagesTSconfig($this->id);
        // Exclude sysfolders, spacers and recycler by default
        $excludeDokTypes = [
            PageRepository::DOKTYPE_RECYCLER,
            PageRepository::DOKTYPE_SYSFOLDER,
            PageRepository::DOKTYPE_SPACER
        ];
        // Custom override of values
        if (isset($pageTsConfig['TCEMAIN.']['preview.']['disableButtonForDokType'])) {
            $excludeDokTypes = GeneralUtility::intExplode(
                ',',
                $pageTsConfig['TCEMAIN.']['preview.']['disableButtonForDokType'],
                true
            );
        }

        if (
            !in_array((int)$this->pageinfo['doktype'], $excludeDokTypes, true)
            && !VersionState::cast($this->pageinfo['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)
        ) {
754
755
756
757
758
759
760
761
762
            $languageParameter = $this->current_sys_language ? ('&L=' . $this->current_sys_language) : '';
            $onClick = BackendUtility::viewOnClick(
                $this->pageinfo['uid'],
                '',
                BackendUtility::BEgetRootLine($this->pageinfo['uid']),
                '',
                '',
                $languageParameter
            );
763
            $viewButton = $this->buttonBar->makeLinkButton()
764
                ->setOnClick($onClick)
765
                ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.showPage'))
766
                ->setIcon($this->iconFactory->getIcon('actions-view-page', Icon::SIZE_SMALL))
767
768
769
                ->setHref('#');

            $this->buttonBar->addButton($viewButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
770
771
        }
        // Shortcut
772
773
774
775
        $shortcutButton = $this->buttonBar->makeShortcutButton()
            ->setModuleName($this->moduleName)
            ->setGetVariables([
                'id',
776
                'route',
777
778
779
780
781
                'edit_record',
            ])
            ->setSetVariables(array_keys($this->MOD_MENU));
        $this->buttonBar->addButton($shortcutButton);

782
        // Cache
783
        if (empty($this->modTSconfig['properties']['disableAdvanced'])) {
784
            $clearCacheButton = $this->buttonBar->makeLinkButton()
785
786
787
                ->setHref('#')
                ->setDataAttributes(['id' => $this->pageinfo['uid']])
                ->setClasses('t3js-clear-page-cache')
788
                ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.clear_cache'))
789
                ->setIcon($this->iconFactory->getIcon('actions-system-cache-clear', Icon::SIZE_SMALL));
790
            $this->buttonBar->addButton($clearCacheButton, ButtonBar::BUTTON_POSITION_RIGHT, 1);
791
        }
792
        if (empty($this->modTSconfig['properties']['disableIconToolbar'])) {
793
            // Edit page properties and page language overlay icons
794
            if ($this->isPageEditable(0)) {
795
796
                /** @var \TYPO3\CMS\Core\Http\NormalizedParams */
                $normalizedParams = $request->getAttribute('normalizedParams');
797
                // Edit localized pages only when one specific language is selected
798
                if ($this->MOD_SETTINGS['function'] == 1 && $this->current_sys_language > 0) {
799
800
                    $localizationParentField = $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'];
                    $languageField = $GLOBALS['TCA']['pages']['ctrl']['languageField'];
801
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
802
                        ->getQueryBuilderForTable('pages');
803
804
805
                    $queryBuilder->getRestrictions()
                        ->removeAll()
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
806
                        ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->getBackendUser()->workspace));
807
808
                    $overlayRecord = $queryBuilder
                        ->select('uid')
809
                        ->from('pages')
810
                        ->where(
811
                            $queryBuilder->expr()->eq(
812
                                $localizationParentField,
813
814
815
                                $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
                            ),
                            $queryBuilder->expr()->eq(
816
                                $languageField,
817
818
                                $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)
                            )
819
820
821
822
                        )
                        ->setMaxResults(1)
                        ->execute()
                        ->fetch();
823
                    BackendUtility::workspaceOL('pages', $overlayRecord, (int)$this->getBackendUser()->workspace);
824
825
826
                    // Edit button
                    $urlParameters = [
                        'edit' => [
827
                            'pages' => [
828
829
830
                                $overlayRecord['uid'] => 'edit'
                            ]
                        ],
831
                        'returnUrl' => $normalizedParams->getRequestUri(),
832
                    ];
833

834
                    $url = (string)$this->uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
835
                    $editLanguageButton = $this->buttonBar->makeLinkButton()
836
                        ->setHref($url)
837
                        ->setTitle($lang->getLL('editPageLanguageOverlayProperties'))
838
839
                        ->setIcon($this->iconFactory->getIcon('mimetypes-x-content-page-language-overlay', Icon::SIZE_SMALL));
                    $this->buttonBar->addButton($editLanguageButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
840
                }
841
842
843
844
845
846
                $urlParameters = [
                    'edit' => [
                        'pages' => [
                            $this->id => 'edit'
                        ]
                    ],
847
                    'returnUrl' => $normalizedParams->getRequestUri(),
848
                ];
849
                $url = (string)$this->uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
850
                $editPageButton = $this->buttonBar->makeLinkButton()
851
                    ->setHref($url)
852
                    ->setTitle($lang->getLL('editPageProperties'))
853
854
                    ->setIcon($this->iconFactory->getIcon('actions-page-open', Icon::SIZE_SMALL));
                $this->buttonBar->addButton($editPageButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
855
856
857
858
859
860
861
862
863
864
865
866
867
            }
        }
    }

    /*******************************
     *
     * Other functions
     *
     ******************************/
    /**
     * Returns the number of hidden elements (including those hidden by start/end times)
     * on the current page (for the current sys_language)
     *
868
     * @param array $languageColumns
869
870
     * @return int
     */
871
    protected function getNumberOfHiddenElements(array $languageColumns): int
872
    {
873
        $andWhere = [];
874
875
876
877
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tt_content');
        $queryBuilder->getRestrictions()
            ->removeAll()
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
878
            ->add(GeneralUtility::makeInstance(WorkspaceRestriction::class, (int)$this->getBackendUser()->workspace));
879
880
881
882
883

        $queryBuilder
            ->count('uid')
            ->from('tt_content')
            ->where(
884
885
886
                $queryBuilder->expr()->eq(
                    'pid',
                    $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
887
888
889
                )
            );

890
        if (!empty($languageColumns)) {
891
892
893
894
895
896
897
898
899
900
901
            // 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(
902
903
904
905
                $queryBuilder->expr()->eq(
                    'sys_language_uid',
                    $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)
                )
906
            );
907
        }
908
909

        if (!empty($GLOBALS['TCA']['tt_content']['ctrl']['enablecolumns']['disabled'])) {
910
911
912
913
            $andWhere[] = $queryBuilder->expr()->neq(
                'hidden',
                $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
            );
914
915
916
917
        }

        if (!empty($GLOBALS['TCA']['tt_content']['ctrl']['enablecolumns']['starttime'])) {
            $andWhere[] = $queryBuilder->expr()->andX(
918
919
920
921
922
923
924
925
                $queryBuilder->expr()->neq(
                    'starttime',
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
                ),
                $queryBuilder->expr()->gt(
                    'starttime',
                    $queryBuilder->createNamedParameter($GLOBALS['SIM_ACCESS_TIME'], \PDO::PARAM_INT)
                )
926
927
928
929
930
            );
        }

        if (!empty($GLOBALS['TCA']['tt_content']['ctrl']['enablecolumns']['endtime'])) {
            $andWhere[] = $queryBuilder->expr()->andX(
931
932
933
934
935
936
937
938
                $queryBuilder->expr()->neq(
                    'endtime',
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
                ),
                $queryBuilder->expr()->lte(
                    'endtime',
                    $queryBuilder->createNamedParameter($GLOBALS['SIM_ACCESS_TIME'], \PDO::PARAM_INT)
                )
939
940
941
942
943
944
945
946
947
948
949
950
951
952
            );
        }

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

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

        return (int)$count;
953
954
955
    }

    /**
956
     * Check if page can be edited by current user
957
     *
958
     * @param int $languageId
959
960
     * @return bool
     */
961
    protected function isPageEditable(int $languageId): bool
962
    {
963
964
965
        if ($this->getBackendUser()->isAdmin()) {
            return true;
        }