PageLayoutController.php 50.2 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
41
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
42
use TYPO3\CMS\Core\Versioning\VersionState;
43
use TYPO3\CMS\Fluid\View\StandaloneView;
44
use TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper;
Nicole Cordes's avatar
Nicole Cordes committed
45

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

    /**
     * Thumbnails or not
     *
     * @var string
     */
64
    protected $imagemode;
65
66
67
68
69
70

    /**
     * Return URL
     *
     * @var string
     */
71
    protected $returnUrl;
72
73
74
75
76
77

    /**
     * PopView id - for opening a window with the page
     *
     * @var bool
     */
78
    protected $popView;
79
80
81
82
83
84

    /**
     * Page select perms clause
     *
     * @var string
     */
85
    protected $perms_clause;
86
87
88
89
90
91

    /**
     * Module TSconfig
     *
     * @var array
     */
92
    protected $modTSconfig = [];
93
94
95
96
97
98

    /**
     * Module shared TSconfig
     *
     * @var array
     */
99
    protected $modSharedTSconfig = [];
100
101
102
103
104

    /**
     * Current ids page record
     *
     * @var array
105
     * @internal
106
107
108
109
110
111
112
113
     */
    public $pageinfo;

    /**
     * "Pseudo" Description -table name
     *
     * @var string
     */
114
    protected $descrTable;
115
116
117
118
119
120

    /**
     * List of column-integers to edit. Is set from TSconfig, default is "1,0,2,3"
     *
     * @var string
     */
121
    protected $colPosList;
122
123
124
125
126
127

    /**
     * Currently selected language for editing content elements
     *
     * @var int
     */
128
    protected $current_sys_language;
129
130
131
132
133
134

    /**
     * Module configuration
     *
     * @var array
     */
135
    protected $MCONF = [];
136
137
138
139
140
141

    /**
     * Menu configuration
     *
     * @var array
     */
142
    protected $MOD_MENU = [];
143
144
145
146
147

    /**
     * Module settings (session variable)
     *
     * @var array
148
     * @internal
149
     */
150
    public $MOD_SETTINGS = [];
151
152
153
154
155
156

    /**
     * Module output accumulation
     *
     * @var string
     */
157
    protected $content;
158
159
160
161
162
163
164

    /**
     * List of column-integers accessible to the current BE user.
     * Is set from TSconfig, default is $colPosList
     *
     * @var string
     */
165
    protected $activeColPosList;
166
167
168
169
170
171

    /**
     * @var string
     */
    protected $editSelect;

172
173
174
175
176
    /**
     * Caches the available languages in a colPos
     *
     * @var array
     */
177
    protected $languagesInColumnCache = [];
178

179
180
181
182
183
184
185
186
187
188
189
190
    /**
     * @var IconFactory
     */
    protected $iconFactory;

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

191
192
193
194
195
196
197
198
199
200
    /**
     * @var ModuleTemplate
     */
    protected $moduleTemplate;

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

201
202
203
204
205
    /**
     * @var string
     */
    protected $searchContent;

206
207
208
209
210
    /**
     * @var SiteLanguage[]
     */
    protected $availableLanguages;

211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    /**
     * 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;
        $this->init($request);
        $this->main($request);
        return new HtmlResponse($this->moduleTemplate->renderContent());
    }

226
227
    /**
     * Initializing the module
228
     * @param ServerRequestInterface $request
229
     */
230
    protected function init(ServerRequestInterface $request): void
231
    {
232
233
234
235
        // Set the GPvars from outside
        $parsedBody = $request->getParsedBody();
        $queryParams = $request->getQueryParams();

236
        $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
237
        $this->iconFactory = $this->moduleTemplate->getIconFactory();
238
        $this->buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
239
240
241
        $this->getLanguageService()->includeLLFile('EXT:backend/Resources/Private/Language/locallang_layout.xlf');
        // Setting module configuration / page select clause
        $this->MCONF['name'] = $this->moduleName;
242
        $this->perms_clause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW);
243
244
245
246
247
248
249

        $this->id = (int)($parsedBody['id'] ?? $queryParams['id'] ?? 0);
        $this->imagemode = $parsedBody['imagemode'] ?? $queryParams['imagemode'] ?? null;
        $this->popView = $parsedBody['popView'] ?? $queryParams['popView'] ?? null;
        $returnUrl = $parsedBody['returnUrl'] ?? $queryParams['returnUrl'] ?? null;
        $this->returnUrl = GeneralUtility::sanitizeLocalUrl($returnUrl);

250
251
252
        // Load page info array:
        $this->pageinfo = BackendUtility::readPageAccess($this->id, $this->perms_clause);
        // Initialize menu
253
        $this->menuConfig($request);
254
255
256
257
258
259
260
261
        // Setting sys language from session var:
        $this->current_sys_language = (int)$this->MOD_SETTINGS['language'];
        // CSH / Descriptions:
        $this->descrTable = '_MOD_' . $this->moduleName;
    }

    /**
     * Initialize menu array
262
     * @param ServerRequestInterface $request
263
     */
264
    protected function menuConfig(ServerRequestInterface $request): void
265
    {
266
267
268
269
        // Set the GPvars from outside
        $parsedBody = $request->getParsedBody();
        $queryParams = $request->getQueryParams();

270
271
        /** @var SiteInterface $currentSite */
        $currentSite = $request->getAttribute('site');
272
        $this->availableLanguages = $currentSite->getAvailableLanguages($this->getBackendUser(), false, $this->id);
273

274
275
        $lang = $this->getLanguageService();
        // MENU-ITEMS:
276
        $this->MOD_MENU = [
277
            'tt_content_showHidden' => '',
278
            'function' => [
279
280
                1 => $lang->getLL('m_function_1'),
                2 => $lang->getLL('m_function_2')
281
282
            ],
            'language' => [
283
                0 => $lang->getLL('m_default')
284
285
            ]
        ];
286
        // initialize page/be_user TSconfig settings
287
288
289
        $pageTsConfig = BackendUtility::getPagesTSconfig($this->id);
        $this->modSharedTSconfig['properties'] = $pageTsConfig['mod.']['SHARED.'] ?? [];
        $this->modTSconfig['properties'] = $pageTsConfig['mod.']['web_layout.'] ?? [];
290

291
292
        // 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.
293
        if ($this->id) {
294
295
296
297
298
299
300
301
            // 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')
302
                ->where(
303
                    $queryBuilder->expr()->eq(
304
                        $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
305
                        $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
306
                    )
307
308
309
                )->execute();
            while ($pageTranslation = $statement->fetch()) {
                $languageId = $pageTranslation[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
310
311
                if (isset($this->availableLanguages[$languageId])) {
                    $this->MOD_MENU['language'][$languageId] = $this->availableLanguages[$languageId]->getTitle();
312
                }
313
            }
314
            // Override the label
315
316
            if (isset($this->availableLanguages[0])) {
                $this->MOD_MENU['language'][0] = $this->availableLanguages[0]->getTitle();
317
318
            }
        }
319
        // Initialize the available actions
320
        $actions = $this->initActions();
321
        // Clean up settings
322
        $this->MOD_SETTINGS = BackendUtility::getModuleData($this->MOD_MENU, $parsedBody['SET'] ?? $queryParams['SET'] ?? [], $this->moduleName);
323
        // For all elements to be shown in draft workspaces & to also show hidden elements by default if user hasn't disabled the option
324
325
326
        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
327
        ) {
328
329
            $this->MOD_SETTINGS['tt_content_showHidden'] = 1;
        }
330
331
        // Make action menu from available actions
        $this->makeActionMenu($actions);
332
333
334
    }

    /**
335
     * Initializes the available actions this module provides
336
     *
337
     * @return array the available actions
338
     */
339
    protected function initActions(): array
340
    {
341
        $actions = [
342
            1 => $this->getLanguageService()->getLL('m_function_1')
343
        ];
344
345
346
        // 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');
347
        }
348
        $this->makeLanguageMenu();
349
350
351
352
353
354
355
        // 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]);
            }
        }
356
357
358
359
360
361
362
363
364
365

        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
     */
366
    protected function makeActionMenu(array $actions): void
367
    {
368
369
370
371
        $actionMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
        $actionMenu->setIdentifier('actionMenu');
        $actionMenu->setLabel('');

372
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
373

374
        $defaultKey = null;
375
        $foundDefaultKey = false;
376
        foreach ($actions as $key => $action) {
377
378
379
            $menuItem = $actionMenu
                ->makeMenuItem()
                ->setTitle($action)
380
                ->setHref((string)$uriBuilder->buildUriFromRoute($this->moduleName) . '&id=' . $this->id . '&SET[function]=' . $key);
381

382
            if (!$foundDefaultKey) {
383
                $defaultKey = $key;
384
                $foundDefaultKey = true;
385
            }
386
387
            if ((int)$this->MOD_SETTINGS['function'] === $key) {
                $menuItem->setActive(true);
388
                $defaultKey = null;
389
390
            }
            $actionMenu->addMenuItem($menuItem);
391
        }
392
393
394
        if (isset($defaultKey)) {
            $this->MOD_SETTINGS['function'] = $defaultKey;
        }
395
        $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($actionMenu);
396
397
398
399
400
401
402
    }

    /**
     * Generate the flashmessages for current pid
     *
     * @return string HTML content with flashmessages
     */
403
    protected function getHeaderFlashMessagesForCurrentPid(): string
404
405
406
    {
        $content = '';
        $lang = $this->getLanguageService();
407

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

411
412
413
414
415
416
417
418
419
        // 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>';
420
                $view->assignMultiple([
421
422
423
                    'title' => $title,
                    'message' => $message,
                    'state' => InfoboxViewHelper::STATE_INFO
424
                ]);
425
426
                $content .= $view->render();
            }
427
428
429
430
        } elseif ($this->pageinfo['doktype'] === PageRepository::DOKTYPE_SHORTCUT) {
            $shortcutMode = (int)$this->pageinfo['shortcut_mode'];
            $pageRepository = GeneralUtility::makeInstance(PageRepository::class);
            $targetPage = [];
431
432
            $message = '';
            $state = InfoboxViewHelper::STATE_ERROR;
433

434
            if ($shortcutMode || $this->pageinfo['shortcut']) {
435
436
                switch ($shortcutMode) {
                    case PageRepository::SHORTCUT_MODE_NONE:
437
438
                        $targetPage = $this->getTargetPageIfVisible($pageRepository->getPage($this->pageinfo['shortcut']));
                        $message .= $targetPage === [] ? $lang->getLL('pageIsMisconfiguredOrNotAccessibleInternalLinkMessage') : '';
439
440
                        break;
                    case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
441
442
443
                        $menuOfPages = $pageRepository->getMenu($this->pageinfo['uid'], '*', 'sorting', 'AND hidden = 0');
                        $targetPage = reset($menuOfPages) ?: [];
                        $message .= $targetPage === [] ? $lang->getLL('pageIsMisconfiguredFirstSubpageMessage') : '';
444
445
                        break;
                    case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
446
447
448
449
450
451
452
453
454
455
456
                        $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;
457
458
                        break;
                }
459
460
                $message = htmlspecialchars($message);
                if ($targetPage !== [] && $shortcutMode !== PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE) {
461
462
                    $linkToPid = $this->local_linkThisScript(['id' => $targetPage['uid']]);
                    $path = BackendUtility::getRecordPath($targetPage['uid'], $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW), 1000);
463
                    $linkedPath = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($path) . '</a>';
464
465
466
                    $message .= sprintf(htmlspecialchars($lang->getLL('pageIsInternalLinkMessage')), $linkedPath);
                    $message .= ' (' . htmlspecialchars($lang->sL(BackendUtility::getLabelFromItemlist('pages', 'shortcut_mode', $shortcutMode))) . ')';
                    $state = InfoboxViewHelper::STATE_INFO;
467
468
                }
            } else {
469
470
                $message = htmlspecialchars($lang->getLL('pageIsMisconfiguredInternalLinkMessage'));
                $state = InfoboxViewHelper::STATE_ERROR;
471
            }
472
473
474
475
476
477
478

            $view->assignMultiple([
                'title' => $this->pageinfo['title'],
                'message' => $message,
                'state' => $state
            ]);
            $content .= $view->render();
479
480
481
482
483
484
485
486
487
488
489
        } 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) {
490
                    $externalUrlHtml = '<a href="' . $externalUrl . '" target="_blank" rel="noreferrer">' . $externalUrl . '</a>';
491
492
493
494
495
496
497
498
                    $view->assignMultiple([
                        'title' => $this->pageinfo['title'],
                        'message' => sprintf($lang->getLL('pageIsExternalLinkMessage'), $externalUrlHtml),
                        'state' => InfoboxViewHelper::STATE_INFO
                    ]);
                    $content .= $view->render();
                }
            }
499
500
501
502
        }
        // If content from different pid is displayed
        if ($this->pageinfo['content_from_pid']) {
            $contentPage = BackendUtility::getRecord('pages', (int)$this->pageinfo['content_from_pid']);
503
            $linkToPid = $this->local_linkThisScript(['id' => $this->pageinfo['content_from_pid']]);
504
            $title = BackendUtility::getRecordTitle('pages', $contentPage);
505
            $link = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($title) . ' (PID ' . (int)$this->pageinfo['content_from_pid'] . ')</a>';
506
            $message = sprintf($lang->getLL('content_from_pid_title'), $link);
507
            $view->assignMultiple([
508
509
510
                'title' => $title,
                'message' => $message,
                'state' => InfoboxViewHelper::STATE_INFO
511
            ]);
512
            $content .= $view->render();
513
514
515
516
517
518
519
520
521
522
523
        } 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();
            }
524
525
526
527
        }
        return $content;
    }

528
529
530
531
532
533
    /**
     * Get all pages with links where the content of a page $pageId is also shown on
     *
     * @param int $pageId
     * @return string
     */
534
    protected function getPageLinksWhereContentIsAlsoShownOn($pageId): string
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
    {
        $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) {
                $linkToPid = $this->local_linkThisScript(['id' => $row['uid']]);
                $title = BackendUtility::getRecordTitle('pages', $row);
                $link = '<a href="' . htmlspecialchars($linkToPid) . '">' . htmlspecialchars($title) . ' (PID ' . (int)$row['uid'] . ')</a>';
                $links[] = $link;
            }
        }
        return implode(', ', $links);
    }

557
558
559
    /**
     * @return string $title
     */
560
    protected function getLocalizedPageTitle(): string
561
562
    {
        if ($this->current_sys_language > 0) {
563
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
564
                ->getQueryBuilderForTable('pages');
565
566
567
568
            $queryBuilder->getRestrictions()
                ->removeAll()
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
                ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
569
            $localizedPage = $queryBuilder
570
                ->select('*')
571
                ->from('pages')
572
                ->where(
573
                    $queryBuilder->expr()->eq(
574
                        $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'],
575
576
                        $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
                    ),
577
                    $queryBuilder->expr()->eq(
578
                        $GLOBALS['TCA']['pages']['ctrl']['languageField'],
579
580
                        $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)
                    )
581
582
583
584
                )
                ->setMaxResults(1)
                ->execute()
                ->fetch();
585
586
            BackendUtility::workspaceOL('pages', $localizedPage);
            return $localizedPage['title'];
587
        }
588
        return $this->pageinfo['title'];
589
590
591
592
593
    }

    /**
     * Main function.
     * Creates some general objects and calls other functions for the main rendering of module content.
594
595
     *
     * @param ServerRequestInterface $request
596
     */
597
    protected function main(ServerRequestInterface $request): void
598
    {
599
        $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Recordlist/ClearCache');
600
601
602
        $lang = $this->getLanguageService();
        // Access check...
        // The page will show only if there is a valid page and if this page may be viewed by the user
603
        $access = is_array($this->pageinfo);
604
605
        // Content
        $content = '';
606
        if ($this->id && $access) {
607
608
            $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($this->pageinfo);

609
            $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
610

611
612
613
            $this->moduleTemplate->addJavaScriptCode('mainJsFunctions', '
                if (top.fsMod) {
                    top.fsMod.recentIds["web"] = ' . (int)$this->id . ';
614
                    top.fsMod.navFrameHighlightedID["web"] = top.fsMod.currentBank + "_" + ' . (int)$this->id . ';
615
616
617
                }
                ' . ($this->popView ? BackendUtility::viewOnClick($this->id, '', BackendUtility::BEgetRootLine($this->id)) : '') . '
                function deleteRecord(table,id,url) {   //
618
                    window.location.href = ' . GeneralUtility::quoteJSvalue((string)$uriBuilder->buildUriFromRoute('tce_db') . '&cmd[')
619
                                            . ' + table + "][" + id + "][delete]=1&redirect=" + encodeURIComponent(url);
620
621
622
623
                    return false;
                }
            ');

624
            // Find backend layout / columns
625
626
            $backendLayoutContainer = GeneralUtility::makeInstance(BackendLayoutView::class);
            $backendLayout = $backendLayoutContainer->getSelectedBackendLayout($this->id);
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
            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);

648
649
            $content .= $this->getHeaderFlashMessagesForCurrentPid();

650
            // Render the primary module content:
651
652
653
654
655
            $content .= '<form action="' . htmlspecialchars((string)$uriBuilder->buildUriFromRoute($this->moduleName, ['id' => $this->id, 'imagemode' => $this->imagemode])) . '" id="PageLayoutController" method="post">';
            // Page title
            $content .= '<h1 class="' . ($this->isPageEditable($this->current_sys_language) ? 't3js-title-inlineedit' : '') . '">' . htmlspecialchars($this->getLocalizedPageTitle()) . '</h1>';
            // All other listings
            $content .= $this->renderContent();
656
657
            $content .= '</form>';
            $content .= $this->searchContent;
658
            // Setting up the buttons for the docheader
659
660
            $this->makeButtons($request);

661
662
663
664
665
666
667
            // Create LanguageMenu
            $this->makeLanguageMenu();
        } else {
            $this->moduleTemplate->addJavaScriptCode(
                'mainJsFunctions',
                'if (top.fsMod) top.fsMod.recentIds["web"] = ' . (int)$this->id . ';'
            );
668
            $content .= '<h1>' . htmlspecialchars($GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']) . '</h1>';
669
670
            $view = GeneralUtility::makeInstance(StandaloneView::class);
            $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/InfoBox.html'));
671
            $view->assignMultiple([
672
673
                'title' => $lang->getLL('clickAPage_header'),
                'message' => $lang->getLL('clickAPage_content'),
674
                'state' => InfoboxViewHelper::STATE_INFO
675
            ]);
676
            $content .= $view->render();
677
        }
678
679
        // Set content
        $this->moduleTemplate->setContent($content);
680
681
682
    }

    /**
683
     * Rendering content
684
685
686
     *
     * @return string
     */
687
    protected function renderContent(): string
688
    {
689
        $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ContextMenu');
690
        $dbList = GeneralUtility::makeInstance(PageLayoutView::class);
691
        $dbList->doEdit = $this->isContentEditable($this->current_sys_language);
692
        $dbList->id = $this->id;
693
        $dbList->nextThree = MathUtility::forceIntegerInRange($this->modTSconfig['properties']['editFieldsAtATime'], 1, 10);
694
695
        $dbList->option_newWizard = empty($this->modTSconfig['properties']['disableNewContentElementWizard']);
        $dbList->defLangBinding = !empty($this->modTSconfig['properties']['defLangBinding']);
696
        $tableOutput = '';
697
698
        $backendLayoutContainer = GeneralUtility::makeInstance(BackendLayoutView::class);
        $tcaItems = $backendLayoutContainer->getColPosListItemsParsed($this->id);
699
700
701
702
703
        $pageRenderer = $this->getPageRenderer();
        $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LayoutModule/DragDrop');
        $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
        $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LayoutModule/Paste');
        if ($this->getBackendUser()->check('tables_select', 'tt_content')) {
704
            $h_func_b = '';
705
706
707
708
709
            // 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];
710
                }
711
            } else {
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
                // ... 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>';
739
740
            }
            // Start the dblist object:
741
            $dbList->start($this->id);
742
            // Generate the list of elements here:
743
            $tableOutput = $dbList->getTable_tt_content($this->id) . $h_func_b;
744
745
746
747
        }
        // Init the content
        $content = '';
        // Additional header content
748
749
750
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/db_layout.php']['drawHeaderHook'] ?? [] as $hook) {
            $params = [];
            $content .= GeneralUtility::callUserFunction($hook, $params, $this);
751
        }
752
        $content .= $tableOutput;
753
        // Making search form:
754
755
756
757
758
759
760
761
762
763
764
        if (!$this->modTSconfig['properties']['disableSearchBox']) {
            $this->searchContent = $this->getSearchBox();
            if ($this->searchContent) {
                $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ToggleSearchToolbox');
                $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);
            }
765
766
        }
        // Additional footer content
767
768
769
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/db_layout.php']['drawFooterHook'] ?? [] as $hook) {
            $params = [];
            $content .= GeneralUtility::callUserFunction($hook, $params, $this);
770
771
772
773
        }
        return $content;
    }

774
775
776
    /**
     * @return ModuleTemplate
     */
777
    protected function getModuleTemplate(): ModuleTemplate
778
779
780
781
    {
        return $this->moduleTemplate;
    }

782
783
784
785
786
787
    /***************************
     *
     * Sub-content functions, rendering specific parts of the module content.
     *
     ***************************/
    /**
788
     * This creates the buttons for the modules
789
     * @param ServerRequestInterface $request
790
     */
791
    protected function makeButtons(ServerRequestInterface $request): void
792
    {
793
794
795
796
        if ($this->MOD_SETTINGS['function'] == 1 || $this->MOD_SETTINGS['function'] == 2) {
            // Add CSH (Context Sensitive Help) icon to tool bar
            $contextSensitiveHelpButton = $this->buttonBar->makeHelpButton()
                ->setModuleName($this->descrTable)
797
                ->setFieldName('columns_' . $this->MOD_SETTINGS['function']);
798
799
            $this->buttonBar->addButton($contextSensitiveHelpButton);
        }
800
801
802
        $lang = $this->getLanguageService();
        // View page
        if (!VersionState::cast($this->pageinfo['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER)) {
803
804
805
806
807
808
809
810
811
            $languageParameter = $this->current_sys_language ? ('&L=' . $this->current_sys_language) : '';
            $onClick = BackendUtility::viewOnClick(
                $this->pageinfo['uid'],
                '',
                BackendUtility::BEgetRootLine($this->pageinfo['uid']),
                '',
                '',
                $languageParameter
            );
812
            $viewButton = $this->buttonBar->makeLinkButton()
813
                ->setOnClick($onClick)
814
                ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.showPage'))
815
                ->setIcon($this->iconFactory->getIcon('actions-view-page', Icon::SIZE_SMALL))
816
817
818
                ->setHref('#');

            $this->buttonBar->addButton($viewButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
819
820
        }
        // Shortcut
821
822
823
824
        $shortcutButton = $this->buttonBar->makeShortcutButton()
            ->setModuleName($this->moduleName)
            ->setGetVariables([
                'id',
825
                'route',
826
827
828
829
830
831
832
                'edit_record',
                'pointer',
                'new_unique_uid',
            ])
            ->setSetVariables(array_keys($this->MOD_MENU));
        $this->buttonBar->addButton($shortcutButton);

833
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
834
        // Cache
835
        if (empty($this->modTSconfig['properties']['disableAdvanced'])) {
836
            $clearCacheButton = $this->buttonBar->makeLinkButton()
837
838
839
                ->setHref('#')
                ->setDataAttributes(['id' => $this->pageinfo['uid']])
                ->setClasses('t3js-clear-page-cache')
840
                ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.clear_cache'))
841
                ->setIcon($this->iconFactory->getIcon('actions-system-cache-clear', Icon::SIZE_SMALL));
842
            $this->buttonBar->addButton($clearCacheButton, ButtonBar::BUTTON_POSITION_RIGHT, 1);
843
        }
844
        if (empty($this->modTSconfig['properties']['disableIconToolbar'])) {
845
            // Edit page properties and page language overlay icons
846
            if ($this->isPageEditable(0)) {
847
848
                /** @var \TYPO3\CMS\Core\Http\NormalizedParams */
                $normalizedParams = $request->getAttribute('normalizedParams');
849
                // Edit localized pages only when one specific language is selected
850
                if ($this->MOD_SETTINGS['function'] == 1 && $this->current_sys_language > 0) {
851
852
                    $localizationParentField = $GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField'];
                    $languageField = $GLOBALS['TCA']['pages']['ctrl']['languageField'];
853
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
854
                        ->getQueryBuilderForTable('pages');
855
856
857
858
859
860
                    $queryBuilder->getRestrictions()
                        ->removeAll()
                        ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
                        ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
                    $overlayRecord = $queryBuilder
                        ->select('uid')
861
                        ->from('pages')
862
                        ->where(
863
                            $queryBuilder->expr()->eq(
864
                                $localizationParentField,
865
866
867
                                $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
                            ),
                            $queryBuilder->expr()->eq(
868
                                $languageField,
869
870
                                $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)
                            )
871
872
873
874
                        )
                        ->setMaxResults(1)
                        ->execute()
                        ->fetch();
875
876
877
                    // Edit button
                    $urlParameters = [
                        'edit' => [
878
                            'pages' => [
879
880
881
                                $overlayRecord['uid'] => 'edit'
                            ]
                        ],
882
                        'returnUrl' => $normalizedParams->getRequestUri(),
883
                    ];
884
885

                    $url = (string)$uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
886
                    $editLanguageButton = $this->buttonBar->makeLinkButton()
887
                        ->setHref($url)
888
                        ->setTitle($lang->getLL('editPageLanguageOverlayProperties'))
889
890
                        ->setIcon($this->iconFactory->getIcon('mimetypes-x-content-page-language-overlay', Icon::SIZE_SMALL));
                    $this->buttonBar->addButton($editLanguageButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
891
                }
892
893
894
895
896
897
                $urlParameters = [
                    'edit' => [
                        'pages' => [
                            $this->id => 'edit'
                        ]
                    ],
898
                    'returnUrl' => $normalizedParams->getRequestUri(),
899
                ];
900
                $url = (string)$uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
901
                $editPageButton = $this->buttonBar->makeLinkButton()
902
                    ->setHref($url)
903
                    ->setTitle($lang->getLL('editPageProperties'))
904
905
                    ->setIcon($this->iconFactory->getIcon('actions-page-open', Icon::SIZE_SMALL));
                $this->buttonBar->addButton($editPageButton, ButtonBar::BUTTON_POSITION_LEFT, 3);
906
907
908
909
910
911
912
913
914
915
916
917
918
            }
        }
    }

    /*******************************
     *
     * Other functions
     *
     ******************************/
    /**
     * Returns the number of hidden elements (including those hidden by start/end times)
     * on the current page (for the current sys_language)
     *
919
     * @param array $contentConfig
920
921
     * @return int
     */
922
    protected function getNumberOfHiddenElements(array $contentConfig = []): int
923
    {
924
        $andWhere = [];
925
926
927
928
929
930
931
932
933
934
        $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(
935
936
937
                $queryBuilder->expr()->eq(
                    'pid',
                    $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
                )
            );

        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(
953
954
955
956
                $queryBuilder->expr()->eq(
                    'sys_language_uid',
                    $queryBuilder->createNamedParameter($this->current_sys_language, \PDO::PARAM_INT)
                )
957
            );
958
        }
959
960

        if (!empty($GLOBALS['TCA']['tt_content']['ctrl']['enablecolumns']['disabled'])) {
961
962
963
964
            $andWhere[] = $queryBuilder->expr()->neq(
                'hidden',
                $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
            );
965
966
967
968
        }

        if (!empty($GLOBALS['TCA']['tt_content']['ctrl']['enablecolumns']['starttime'])) {
            $andWhere[] = $queryBuilder->expr()->andX(
969
970
971
972
973
974
975
976
                $queryBuilder->expr()->neq(
                    'starttime',
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
                ),
                $queryBuilder->expr()->gt(
                    'starttime',
                    $queryBuilder->createNamedParameter($GLOBALS['SIM_ACCESS_TIME'], \PDO::PARAM_INT)
                )
977
978
979
980
981
            );
        }

        if (!empty($GLOBALS['TCA']['tt_content']['ctrl']['enablecolumns']['endtime'])) {
            $andWhere[] = $queryBuilder->expr()->andX(
982
983
984
985
986
987
988
989
                $queryBuilder->expr()->neq(
                    'endtime',
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
                ),
                $queryBuilder->expr()->lte(
                    'endtime',
                    $queryBuilder->createNamedParameter($GLOBALS['SIM_ACCESS_TIME'], \PDO::PARAM_INT)
                )
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
            );
        }

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

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

        return (int)$count;
1004
1005
1006
1007
1008
1009
1010
1011
1012
    }

    /**
     * Returns URL to the current script.
     * In particular the "popView" and "new_unique_uid" Get vars are unset.
     *
     * @param array $params Parameters array, merged with global GET vars.
     * @return string URL
     */
1013