PageLayoutController.php 74.9 KB
Newer Older
1
2
3
<?php
namespace TYPO3\CMS\Backend\Controller;

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

17
18
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
19
20
21
22
23
use TYPO3\CMS\Backend\Form\Exception\AccessDeniedException;
use TYPO3\CMS\Backend\Form\FormDataCompiler;
use TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord;
use TYPO3\CMS\Backend\Form\FormResultCompiler;
use TYPO3\CMS\Backend\Form\NodeFactory;
24
25
26
27
use TYPO3\CMS\Backend\Module\ModuleLoader;
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Template\ModuleTemplate;
use TYPO3\CMS\Backend\Tree\View\ContentLayoutPagePositionMap;
Nicole Cordes's avatar
Nicole Cordes committed
28
use TYPO3\CMS\Backend\Utility\BackendUtility;
29
30
use TYPO3\CMS\Backend\View\BackendLayoutView;
use TYPO3\CMS\Backend\View\PageLayoutView;
31
use TYPO3\CMS\Core\Database\ConnectionPool;
32
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
33
34
use TYPO3\CMS\Core\Database\Query\Restriction\BackendWorkspaceRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
35
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
36
use TYPO3\CMS\Core\DataHandling\DataHandler;
37
38
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
39
40
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
41
use TYPO3\CMS\Core\Page\PageRenderer;
42
use TYPO3\CMS\Core\Type\Bitmask\Permission;
Nicole Cordes's avatar
Nicole Cordes committed
43
use TYPO3\CMS\Core\Utility\GeneralUtility;
44
use TYPO3\CMS\Core\Utility\HttpUtility;
Nicole Cordes's avatar
Nicole Cordes committed
45
use TYPO3\CMS\Core\Utility\MathUtility;
46
use TYPO3\CMS\Core\Versioning\VersionState;
47
use TYPO3\CMS\Fluid\View\StandaloneView;
48
use TYPO3\CMS\Fluid\ViewHelpers\Be\InfoboxViewHelper;
49
use TYPO3\CMS\Frontend\Page\PageRepository;
50
use TYPO3\CMS\Recordlist\RecordList;
Nicole Cordes's avatar
Nicole Cordes committed
51

52
53
54
/**
 * Script Class for Web > Layout module
 */
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
class PageLayoutController
{
    /**
     * Page Id for which to make the listing
     *
     * @var int
     */
    public $id;

    /**
     * Pointer - for browsing list of records.
     *
     * @var int
     */
    public $pointer;

    /**
     * Thumbnails or not
     *
     * @var string
     */
    public $imagemode;

    /**
     * Search-fields
     *
     * @var string
     */
    public $search_field;

    /**
     * Search-levels
     *
     * @var int
     */
    public $search_levels;

    /**
     * Show-limit
     *
     * @var int
     */
    public $showLimit;

    /**
     * Return URL
     *
     * @var string
     */
    public $returnUrl;

    /**
     * Clear-cache flag - if set, clears page cache for current id.
     *
     * @var bool
     */
    public $clear_cache;

    /**
     * PopView id - for opening a window with the page
     *
     * @var bool
     */
    public $popView;

    /**
     * QuickEdit: Variable, that tells quick edit what to show/edit etc.
     * Format is [tablename]:[uid] with some exceptional values for both parameters (with special meanings).
     *
     * @var string
     */
    public $edit_record;

    /**
     * QuickEdit: If set, this variable tells quick edit that the last edited record had
     * this value as UID and we should look up the new, real uid value in sys_log.
     *
     * @var string
     */
    public $new_unique_uid;

    /**
     * Page select perms clause
     *
     * @var string
     */
    public $perms_clause;

    /**
     * Module TSconfig
     *
     * @var array
     */
    public $modTSconfig;

    /**
     * Module shared TSconfig
     *
     * @var array
     */
    public $modSharedTSconfig;

    /**
     * Current ids page record
     *
     * @var array
     */
    public $pageinfo;

    /**

     * "Pseudo" Description -table name
     *
     * @var string
     */
    public $descrTable;

    /**
     * List of column-integers to edit. Is set from TSconfig, default is "1,0,2,3"
     *
     * @var string
     */
    public $colPosList;

    /**
     * Flag: If content can be edited or not.
     *
     * @var bool
     */
    public $EDIT_CONTENT;

    /**
     * Users permissions integer for this page.
     *
     * @var int
     */
    public $CALC_PERMS;

    /**
     * Currently selected language for editing content elements
     *
     * @var int
     */
    public $current_sys_language;

    /**
     * Module configuration
     *
     * @var array
     */
205
    public $MCONF = [];
206
207
208
209
210
211

    /**
     * Menu configuration
     *
     * @var array
     */
212
    public $MOD_MENU = [];
213
214
215
216
217
218

    /**
     * Module settings (session variable)
     *
     * @var array
     */
219
    public $MOD_SETTINGS = [];
220
221
222
223
224

    /**
     * Array of tables to be listed by the Web > Page module in addition to the default tables
     *
     * @var array
225
     * @deprecated since TYPO3 CMS 8, will be removed in TYPO3 CMS 9.
226
     */
227
    public $externalTables = [];
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

    /**
     * Module output accumulation
     *
     * @var string
     */
    public $content;

    /**
     * List of column-integers accessible to the current BE user.
     * Is set from TSconfig, default is $colPosList
     *
     * @var string
     */
    public $activeColPosList;

    /**
     * @var array
     */
247
    protected $eRParts = [];
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278

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

    /**
     * @var bool
     */
    protected $deleteButton;

    /**
     * @var bool
     */
    protected $undoButton;

    /**
     * @var array
     */
    protected $undoButtonR;

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

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

279
280
281
282
283
    /**
     * Caches the available languages in a colPos
     *
     * @var array
     */
284
    protected $languagesInColumnCache = [];
285

286
287
288
289
290
291
292
293
294
295
296
297
    /**
     * @var IconFactory
     */
    protected $iconFactory;

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

298
299
300
301
302
303
304
305
306
307
    /**
     * @var ModuleTemplate
     */
    protected $moduleTemplate;

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

308
309
310
311
312
    /**
     * @var string
     */
    protected $searchContent;

313
314
315
316
317
318
319
    /**
     * Initializing the module
     *
     * @return void
     */
    public function init()
    {
320
        $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
321
        $this->iconFactory = $this->moduleTemplate->getIconFactory();
322
        $this->buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
        $this->getLanguageService()->includeLLFile('EXT:backend/Resources/Private/Language/locallang_layout.xlf');
        // Setting module configuration / page select clause
        $this->MCONF['name'] = $this->moduleName;
        $this->perms_clause = $this->getBackendUser()->getPagePermsClause(1);
        // Get session data
        $sessionData = $this->getBackendUser()->getSessionData(RecordList::class);
        $this->search_field = !empty($sessionData['search_field']) ? $sessionData['search_field'] : '';
        // GPvars:
        $this->id = (int)GeneralUtility::_GP('id');
        $this->pointer = GeneralUtility::_GP('pointer');
        $this->imagemode = GeneralUtility::_GP('imagemode');
        $this->clear_cache = GeneralUtility::_GP('clear_cache');
        $this->popView = GeneralUtility::_GP('popView');
        $this->edit_record = GeneralUtility::_GP('edit_record');
        $this->new_unique_uid = GeneralUtility::_GP('new_unique_uid');
        $this->search_field = GeneralUtility::_GP('search_field');
        $this->search_levels = GeneralUtility::_GP('search_levels');
        $this->showLimit = GeneralUtility::_GP('showLimit');
        $this->returnUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'));
        $this->externalTables = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['cms']['db_layout']['addTables'];
        $sessionData['search_field'] = $this->search_field;
        // Store session data
        $this->getBackendUser()->setAndSaveSessionData(RecordList::class, $sessionData);
        // Load page info array:
        $this->pageinfo = BackendUtility::readPageAccess($this->id, $this->perms_clause);
        // Initialize menu
        $this->menuConfig();
        // 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
     *
     * @return void
     */
    public function menuConfig()
    {
        $lang = $this->getLanguageService();
        // MENU-ITEMS:
365
        $this->MOD_MENU = [
366
            'tt_content_showHidden' => '',
367
            'function' => [
368
369
370
                0 => $lang->getLL('m_function_0'),
                1 => $lang->getLL('m_function_1'),
                2 => $lang->getLL('m_function_2')
371
372
            ],
            'language' => [
373
                0 => $lang->getLL('m_default')
374
375
            ]
        ];
376
377
378
        // initialize page/be_user TSconfig settings
        $this->modSharedTSconfig = BackendUtility::getModTSconfig($this->id, 'mod.SHARED');
        $this->modTSconfig = BackendUtility::getModTSconfig($this->id, 'mod.' . $this->moduleName);
379
        // example settings:
380
381
382
383
384
        //  $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['cms']['db_layout']['addTables']['tx_myext'] =
        //      array ('default' => array(
        //              'MENU' => 'LLL:EXT:tx_myext/locallang_db.xlf:menuDefault',
        //              'fList' =>  'title,description,image',
        //              'icon' => TRUE));
385
        if (is_array($this->externalTables)) {
386
387
388
389
390
391
            if (!empty($this->externalTables)) {
                GeneralUtility::deprecationLog('The rendering of records in the page module by using '
                    . '$GLOBALS[\'TYPO3_CONF_VARS\'][\'EXTCONF\'][\'cms\'][\'db_layout\'][\'addTables\']'
                    . ' has been deprecated since TYPO3 CMS 8 and will be removed in TYPO3 CMS 9.'
                );
            }
392
393
394
395
396
397
398
399
400
401
402
403
404
            foreach ($this->externalTables as $table => $tableSettings) {
                // delete the default settings from above
                if (is_array($this->MOD_MENU[$table])) {
                    unset($this->MOD_MENU[$table]);
                }
                if (is_array($tableSettings) && count($tableSettings) > 1) {
                    foreach ($tableSettings as $key => $settings) {
                        $this->MOD_MENU[$table][$key] = $lang->sL($settings['MENU']);
                    }
                }
            }
        }
        // First, select all pages_language_overlay records on the current page. Each represents a possibility for a language on the page. Add these to language selector.
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_language');
        $queryBuilder->getRestrictions()->removeAll();
        if ($this->id) {
            $queryBuilder->select('sys_language.uid AS uid', 'sys_language.title AS title')
                ->from('sys_language')
                ->join(
                    'sys_language',
                    'pages_language_overlay',
                    'pages_language_overlay',
                    $queryBuilder->expr()->eq('sys_language.uid', $queryBuilder->quoteIdentifier('pages_language_overlay.sys_language_uid'))
                )
                ->where(
                    $queryBuilder->expr()->eq('pages_language_overlay.deleted', 0),
                    $queryBuilder->expr()->eq('pages_language_overlay.pid', (int)$this->id),
                    $queryBuilder->expr()->orX(
                        $queryBuilder->expr()->gte('pages_language_overlay.t3ver_state', (int)(new VersionState(VersionState::DEFAULT_STATE))),
                        $queryBuilder->expr()->eq('pages_language_overlay.t3ver_wsid', (int)$this->getBackendUser()->workspace)
                    )
                )
                ->groupBy('pages_language_overlay.sys_language_uid', 'sys_language.uid', 'sys_language.pid',
                    'sys_language.tstamp', 'sys_language.hidden', 'sys_language.title',
                    'sys_language.language_isocode', 'sys_language.static_lang_isocode', 'sys_language.flag')
427
                ->orderBy('sys_language.sorting');
428
429
430
431
432
433
434
435
            if (!$this->getBackendUser()->isAdmin()) {
                $queryBuilder->andWhere($queryBuilder->expr()->eq('sys_language.hidden', 0));
            }
            $statement = $queryBuilder->execute();
        } else {
            $queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(HiddenRestriction::class));
            $statement = $queryBuilder->select('uid', 'title')
                ->from('sys_language')
436
                ->orderBy('sorting')
437
438
439
                ->execute();
        }
        while ($lRow = $statement->fetch()) {
440
            if ($this->getBackendUser()->checkLanguageAccess($lRow['uid'])) {
441
                $this->MOD_MENU['language'][$lRow['uid']] = $lRow['title'];
442
443
            }
        }
444
445
        // Setting alternative default label:
        if (($this->modSharedTSconfig['properties']['defaultLanguageLabel'] || $this->modTSconfig['properties']['defaultLanguageLabel']) && isset($this->MOD_MENU['language'][0])) {
446
            $this->MOD_MENU['language'][0] = $this->modTSconfig['properties']['defaultLanguageLabel'] ? $this->modTSconfig['properties']['defaultLanguageLabel'] : $this->modSharedTSconfig['properties']['defaultLanguageLabel'];
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
        }
        // Clean up settings
        $this->MOD_SETTINGS = BackendUtility::getModuleData($this->MOD_MENU, GeneralUtility::_GP('SET'), $this->moduleName);
        // For all elements to be shown in draft workspaces & to also show hidden elements by default if user hasn't disabled the option
        if ($this->getBackendUser()->workspace != 0 || $this->MOD_SETTINGS['tt_content_showHidden'] !== '0') {
            $this->MOD_SETTINGS['tt_content_showHidden'] = 1;
        }
        $this->makeActionMenu();
    }

    /**
     * This creates the dropdown menu with the different actions this module is able to provide.
     * For now they are Columns, Quick Edit and Languages.
     *
     * @return void
     */
    protected function makeActionMenu()
    {
465
        $availableActionArray = [
466
467
468
            0 => $this->getLanguageService()->getLL('m_function_0'),
            1 => $this->getLanguageService()->getLL('m_function_1'),
            2 => $this->getLanguageService()->getLL('m_function_2')
469
        ];
470
        // Find if there are ANY languages at all (and if not, remove the language option from function menu).
471
472
473
474
475
476
477
478
479
480
481
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_language');
        if ($this->getBackendUser()->isAdmin()) {
            $queryBuilder->getRestrictions()->removeAll();
        }

        $count = $queryBuilder
            ->count('uid')
            ->from('sys_language')
            ->execute()
            ->fetchColumn(0);

482
        if (!$count) {
483
            unset($availableActionArray['2']);
484
485
486
        }
        // page/be_user TSconfig settings and blinding of menu-items
        if ($this->modTSconfig['properties']['QEisDefault']) {
487
            ksort($availableActionArray);
488
        }
489
        $availableActionArray = BackendUtility::unsetMenuItems($this->modTSconfig['properties'], $availableActionArray, 'menu.function');
490
491
        // Remove QuickEdit as option if page type is not...
        if (!GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['FE']['content_doktypes'] . ',6', $this->pageinfo['doktype'])) {
492
            unset($availableActionArray[0]);
493
        }
494
495
496
497
        $actionMenu = $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->makeMenu();
        $actionMenu->setIdentifier('actionMenu');
        $actionMenu->setLabel('');

498
        $defaultKey = null;
499
        $foundDefaultKey = false;
500
501
502
503
504
        foreach ($availableActionArray as $key => $action) {
            $menuItem = $actionMenu
                ->makeMenuItem()
                ->setTitle($action)
                ->setHref(BackendUtility::getModuleUrl($this->moduleName) . '&id=' . $this->id . '&SET[function]=' . $key);
505

506
            if (!$foundDefaultKey) {
507
                $defaultKey = $key;
508
                $foundDefaultKey = true;
509
            }
510
511
            if ((int)$this->MOD_SETTINGS['function'] === $key) {
                $menuItem->setActive(true);
512
                $defaultKey = null;
513
514
            }
            $actionMenu->addMenuItem($menuItem);
515
        }
516
517
518
        if (isset($defaultKey)) {
            $this->MOD_SETTINGS['function'] = $defaultKey;
        }
519
        $this->moduleTemplate->getDocHeaderComponent()->getMenuRegistry()->addMenu($actionMenu);
520
521
522
523
524
525
526
527
528
    }

    /**
     * Clears page cache for the current id, $this->id
     *
     * @return void
     */
    public function clearCache()
    {
529
530
        if ($this->clear_cache && !empty($this->pageinfo)) {
            $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
531
            $dataHandler->start([], []);
532
            $dataHandler->clear_cacheCmd($this->id);
533
534
535
536
537
538
539
540
541
542
543
544
        }
    }

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

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

549
550
551
552
553
554
555
556
557
        // 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>';
558
                $view->assignMultiple([
559
560
561
                    'title' => $title,
                    'message' => $message,
                    'state' => InfoboxViewHelper::STATE_INFO
562
                ]);
563
564
                $content .= $view->render();
            }
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
        } elseif ($this->pageinfo['doktype'] === PageRepository::DOKTYPE_SHORTCUT) {
            $shortcutMode = (int)$this->pageinfo['shortcut_mode'];
            $pageRepository = GeneralUtility::makeInstance(PageRepository::class);
            $targetPage = [];

            if ($this->pageinfo['shortcut'] || $shortcutMode) {
                switch ($shortcutMode) {
                    case PageRepository::SHORTCUT_MODE_NONE:
                        $targetPage = $pageRepository->getPage($this->pageinfo['shortcut']);
                        break;
                    case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
                        $targetPage = reset($pageRepository->getMenu($this->pageinfo['shortcut'] ?: $this->pageinfo['uid']));
                        break;
                    case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
                        $targetPage = $pageRepository->getPage($this->pageinfo['pid']);
                        break;
                }

                $message = '';
                if ($shortcutMode === PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE) {
                    $message .= sprintf($lang->getLL('pageIsRandomInternalLinkMessage'));
                } else {
                    $linkToPid = $this->local_linkThisScript(['id' => $targetPage['uid']]);
                    $path = BackendUtility::getRecordPath($targetPage['uid'], $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW), 1000);
                    $linkedPath = '<a href="' . $linkToPid . '">' . htmlspecialchars($path) . '</a>';
                    $message .= sprintf($lang->getLL('pageIsInternalLinkMessage'), $linkedPath);
                }

                $message .= ' (' . htmlspecialchars($lang->sL(BackendUtility::getLabelFromItemlist('pages', 'shortcut_mode', $shortcutMode))) . ')';

                $view->assignMultiple([
                    'title' => $this->pageinfo['title'],
                    'message' => $message,
                    'state' => InfoboxViewHelper::STATE_INFO
                ]);
                $content .= $view->render();
            } else {
                if (empty($targetPage) && $shortcutMode !== PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE) {
                    $view->assignMultiple([
                        'title' => $this->pageinfo['title'],
                        'message' => $lang->getLL('pageIsMisconfiguredInternalLinkMessage'),
                        'state' => InfoboxViewHelper::STATE_ERROR
                    ]);
                    $content .= $view->render();
                }
            }
        } 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) {
                    $externalUrlHtml = '<a href="' . $externalUrl . '" target="_blank" rel="noopener">' . $externalUrl . '</a>';
                    $view->assignMultiple([
                        'title' => $this->pageinfo['title'],
                        'message' => sprintf($lang->getLL('pageIsExternalLinkMessage'), $externalUrlHtml),
                        'state' => InfoboxViewHelper::STATE_INFO
                    ]);
                    $content .= $view->render();
                }
            }
631
632
633
634
        }
        // If content from different pid is displayed
        if ($this->pageinfo['content_from_pid']) {
            $contentPage = BackendUtility::getRecord('pages', (int)$this->pageinfo['content_from_pid']);
635
            $linkToPid = $this->local_linkThisScript(['id' => $this->pageinfo['content_from_pid']]);
636
            $title = BackendUtility::getRecordTitle('pages', $contentPage);
637
            $link = '<a href="' . $linkToPid . '">' . htmlspecialchars($title) . ' (PID ' . (int)$this->pageinfo['content_from_pid'] . ')</a>';
638
            $message = sprintf($lang->getLL('content_from_pid_title'), $link);
639
            $view->assignMultiple([
640
641
642
                'title' => $title,
                'message' => $message,
                'state' => InfoboxViewHelper::STATE_INFO
643
            ]);
644
            $content .= $view->render();
645
646
647
648
649
650
651
652
653
654
655
        }
        return $content;
    }

    /**
     *
     * @return string $title
     */
    protected function getLocalizedPageTitle()
    {
        if ($this->current_sys_language > 0) {
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
                ->getQueryBuilderForTable('pages_language_overlay');
            $queryBuilder->getRestrictions()
                ->removeAll()
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
                ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
            $overlayRecord = $queryBuilder
                ->select('title')
                ->from('pages_language_overlay')
                ->where(
                    $queryBuilder->expr()->eq('pid', (int)$this->id),
                    $queryBuilder->expr()->eq('sys_language_uid', (int)$this->current_sys_language)
                )
                ->setMaxResults(1)
                ->execute()
                ->fetch();
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
            return $overlayRecord['title'];
        } else {
            return $this->pageinfo['title'];
        }
    }

    /**
     * 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
     * @param ResponseInterface $response
     * @return ResponseInterface the response with the content
     */
    public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
    {
        $GLOBALS['SOBE'] = $this;
        $this->init();
        $this->clearCache();
        $this->main();
692
        $response->getBody()->write($this->moduleTemplate->renderContent());
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
        return $response;
    }

    /**
     * Main function.
     * Creates some general objects and calls other functions for the main rendering of module content.
     *
     * @return void
     */
    public function main()
    {
        $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
        $access = is_array($this->pageinfo) ? 1 : 0;
708
709
        // Content
        $content = '';
710
711
712
        if ($this->id && $access) {
            // Initialize permission settings:
            $this->CALC_PERMS = $this->getBackendUser()->calcPerms($this->pageinfo);
713
            $this->EDIT_CONTENT = $this->contentIsNotLockedForEditors();
714

715
716
            $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($this->pageinfo);

717
            // override the default jumpToUrl
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
            $this->moduleTemplate->addJavaScriptCode('jumpToUrl', '
                function jumpToUrl(URL,formEl) {
                    if (document.editform && TBE_EDITOR.isFormChanged)  {   // Check if the function exists... (works in all browsers?)
                        if (!TBE_EDITOR.isFormChanged()) {
                            window.location.href = URL;
                        } else if (formEl) {
                            if (formEl.type=="checkbox") formEl.checked = formEl.checked ? 0 : 1;
                        }
                    } else {
                        window.location.href = URL;
                    }
                }
            ');
            $this->moduleTemplate->addJavaScriptCode('mainJsFunctions', '
                if (top.fsMod) {
                    top.fsMod.recentIds["web"] = ' . (int)$this->id . ';
                    top.fsMod.navFrameHighlightedID["web"] = "pages' . (int)$this->id . '_"+top.fsMod.currentBank; ' . (int)$this->id . ';
                }
                ' . ($this->popView ? BackendUtility::viewOnClick($this->id, '', BackendUtility::BEgetRootLine($this->id)) : '') . '
                function deleteRecord(table,id,url) {   //
738
739
                    window.location.href = ' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('tce_db') . '&cmd[')
                                             . ' + table + "][" + id + "][delete]=1&redirect=" + encodeURIComponent(url) + "&vC=' . $this->getBackendUser()->veriCode() . '&prErr=1&uPT=1";
740
741
742
743
                    return false;
                }
            ');

744
            // Find backend layout / columns
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
            $backendLayout = GeneralUtility::callUserFunction(BackendLayoutView::class . '->getSelectedBackendLayout', $this->id, $this);
            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);

767
768
            $content .= $this->getHeaderFlashMessagesForCurrentPid();

769
770
771
            // Render the primary module content:
            if ($this->MOD_SETTINGS['function'] == 0) {
                // QuickEdit
772
                $content .= '<form action="' . htmlspecialchars(BackendUtility::getModuleUrl('tce_db', ['prErr' => 1, 'uPT' => 1])) . '" method="post" enctype="multipart/form-data" name="editform" id="PageLayoutController" onsubmit="return TBE_EDITOR.checkSubmit(1);">';
773
                $content .= $this->renderQuickEdit();
774
            } else {
775
                $content .= '<form action="' . htmlspecialchars(BackendUtility::getModuleUrl($this->moduleName, ['id' => $this->id, 'imagemode' =>  $this->imagemode])) . '" id="PageLayoutController" method="post">';
776
                // Page title
777
                $content .= '<h1 class="t3js-title-inlineedit">' . htmlspecialchars($this->getLocalizedPageTitle()) . '</h1>';
778
                // All other listings
779
                $content .= $this->renderListContent();
780
            }
781
782
            $content .= '</form>';
            $content .= $this->searchContent;
783
784
785
786
787
788
789
790
791
792
            // Setting up the buttons for the docheader
            $this->makeButtons($this->MOD_SETTINGS['function'] == 0 ? 'quickEdit' : '');
            // Create LanguageMenu
            $this->makeLanguageMenu();
        } else {
            $this->moduleTemplate->addJavaScriptCode(
                'mainJsFunctions',
                'if (top.fsMod) top.fsMod.recentIds["web"] = ' . (int)$this->id . ';'
            );
            $content .= '<h1>' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '</h1>';
793
794
            $view = GeneralUtility::makeInstance(StandaloneView::class);
            $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/InfoBox.html'));
795
            $view->assignMultiple([
796
797
                'title' => $lang->getLL('clickAPage_header'),
                'message' => $lang->getLL('clickAPage_content'),
798
                'state' => InfoboxViewHelper::STATE_INFO
799
            ]);
800
            $content .= $view->render();
801
        }
802
803
        // Set content
        $this->moduleTemplate->setContent($content);
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
    }

    /**
     * Rendering the quick-edit view.
     *
     * @return string
     */
    public function renderQuickEdit()
    {
        $beUser = $this->getBackendUser();
        $lang = $this->getLanguageService();
        // Set the edit_record value for internal use in this function:
        $edit_record = $this->edit_record;
        // If a command to edit all records in a column is issue, then select all those elements, and redirect to FormEngine
        if (substr($edit_record, 0, 9) == '_EDIT_COL') {
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tt_content');
            if ($this->MOD_SETTINGS['tt_content_showHidden']) {
                $queryBuilder->getRestrictions()->removeAll()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
            }
            $statement = $queryBuilder->select('*')
                ->from('tt_content')
                ->orderBy('sorting')
                ->where(
                    $queryBuilder->expr()->eq('pid', (int)$this->id),
                    $queryBuilder->expr()->eq('colPos', (int)substr($edit_record, 10)),
                    $queryBuilder->expr()->eq('sys_language_uid', (int)$this->current_sys_language),
                    $queryBuilder->expr()->orX(
                        $queryBuilder->expr()->gte('t3ver_state', (int)(new VersionState(VersionState::DEFAULT_STATE))),
                        $queryBuilder->expr()->eq('t3ver_wsid', (int)$beUser->workspace)
                    )
                )
                ->execute();
836
            $idListA = [];
837
            while ($cRow = $statement->fetch()) {
838
839
                $idListA[] = $cRow['uid'];
            }
840
            $url = BackendUtility::getModuleUrl('record_edit', [
841
                'edit[tt_content][' . implode(',', $idListA) . ']' => 'edit',
842
843
                'returnUrl' => $this->local_linkThisScript(['edit_record' => ''])
            ]);
844
845
846
847
            HttpUtility::redirect($url);
        }
        // If the former record edited was the creation of a NEW record, this will look up the created records uid:
        if ($this->new_unique_uid) {
848
849
850
851
852
853
854
855
856
857
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_log');
            $queryBuilder->getRestrictions()->removeAll();
            $sys_log_row = $queryBuilder->select('tablename', 'recuid')
                ->from('sys_log')
                ->where(
                    $queryBuilder->expr()->eq('userid', (int)$beUser->user['uid']),
                    $queryBuilder->expr()->eq('NEWid', $queryBuilder->createNamedParameter($this->new_unique_uid))
                )
                ->execute()
                ->fetch();
858
859
860
861
            if (is_array($sys_log_row)) {
                $edit_record = $sys_log_row['tablename'] . ':' . $sys_log_row['recuid'];
            }
        }
862
        $edit_record = $this->makeQuickEditMenu($edit_record);
863
864
865
866
867
868
869
        // Splitting the edit-record cmd value into table/uid:
        $this->eRParts = explode(':', $edit_record);
        $tableName = $this->eRParts[0];
        // Delete-button flag?
        $this->deleteButton = MathUtility::canBeInterpretedAsInteger($this->eRParts[1]) && $edit_record && ($tableName !== 'pages' && $this->EDIT_CONTENT || $tableName === 'pages' && $this->CALC_PERMS & Permission::PAGE_DELETE);
        // If undo-button should be rendered (depends on available items in sys_history)
        $this->undoButton = false;
870
871
872
873
874
875
876
877
878
879
880
881
882
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_history');
        $queryBuilder->getRestrictions()->removeAll();
        $this->undoButtonR = $queryBuilder->select('tstamp')
            ->from('sys_history')
            ->where(
                $queryBuilder->expr()->eq('tablename', $queryBuilder->createNamedParameter($tableName)),
                $queryBuilder->expr()->eq('recuid', (int)$this->eRParts[1])
            )
            ->orderBy('tstamp', 'DESC')
            ->setMaxResults(1)
            ->execute()
            ->fetch();
        if ($this->undoButtonR) {
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
            $this->undoButton = true;
        }
        // Setting up the Return URL for coming back to THIS script (if links take the user to another script)
        $R_URL_parts = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
        $R_URL_getvars = GeneralUtility::_GET();
        unset($R_URL_getvars['popView']);
        unset($R_URL_getvars['new_unique_uid']);
        $R_URL_getvars['edit_record'] = $edit_record;
        $this->R_URI = $R_URL_parts['path'] . '?' . GeneralUtility::implodeArrayForUrl('', $R_URL_getvars);

        // Creating editing form:
        if ($edit_record) {
            // Splitting uid parts for special features, if new:
            list($uidVal, $neighborRecordUid, $ex_colPos) = explode('/', $this->eRParts[1]);

            if ($uidVal === 'new') {
                $command = 'new';
                // Page id of this new record
                $theUid = $this->id;
                if ($neighborRecordUid) {
                    $theUid = $neighborRecordUid;
                }
            } else {
                $command = 'edit';
                $theUid = $uidVal;
                // Convert $uidVal to workspace version if any:
                $draftRecord = BackendUtility::getWorkspaceVersionOfRecord($beUser->workspace, $tableName, $theUid, 'uid');
                if ($draftRecord) {
                    $theUid = $draftRecord['uid'];
                }
            }

            // @todo: Hack because DatabaseInitializeNewRow reads from _GP directly
916
            $GLOBALS['_GET']['defVals'][$tableName] = [
917
918
                'colPos' => (int)$ex_colPos,
                'sys_language_uid' => (int)$this->current_sys_language
919
            ];
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959

            /** @var TcaDatabaseRecord $formDataGroup */
            $formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
            /** @var FormDataCompiler $formDataCompiler */
            $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
            /** @var NodeFactory $nodeFactory */
            $nodeFactory = GeneralUtility::makeInstance(NodeFactory::class);

            try {
                $formDataCompilerInput = [
                    'tableName' => $tableName,
                    'vanillaUid' => (int)$theUid,
                    'command' => $command,
                ];
                $formData = $formDataCompiler->compile($formDataCompilerInput);

                if ($command !== 'new') {
                    BackendUtility::lockRecords($tableName, $formData['databaseRow']['uid'], $tableName === 'tt_content' ? $formData['databaseRow']['pid'] : 0);
                }

                $formData['renderType'] = 'outerWrapContainer';
                $formResult = $nodeFactory->create($formData)->render();

                $panel = $formResult['html'];
                $formResult['html'] = '';

                /** @var FormResultCompiler $formResultCompiler */
                $formResultCompiler = GeneralUtility::makeInstance(FormResultCompiler::class);
                $formResultCompiler->mergeResult($formResult);

                $row = $formData['databaseRow'];
                $new_unique_uid = '';
                if ($command === 'new') {
                    $new_unique_uid = $row['uid'];
                }

                // Add hidden fields:
                if ($uidVal == 'new') {
                    $panel .= '<input type="hidden" name="data[' . $tableName . '][' . $row['uid'] . '][pid]" value="' . $row['pid'] . '" />';
                }
960
961
                $redirect = ($uidVal == 'new' ? BackendUtility::getModuleUrl(
                    $this->moduleName,
Claus Due's avatar
Claus Due committed
962
                    ['id' => $this->id, 'new_unique_uid' => $new_unique_uid, 'returnUrl' => $this->returnUrl]
963
                ) : $this->R_URI);
964
                $panel .= '
965
966
967
968
                    <input type="hidden" name="_serialNumber" value="' . md5(microtime()) . '" />
                    <input type="hidden" name="edit_record" value="' . $edit_record . '" />
                    <input type="hidden" name="redirect" value="' . htmlspecialchars($redirect) . '" />
                    ';
969
                // Add JavaScript as needed around the form:
970
                $content = $formResultCompiler->addCssFiles() . $panel . $formResultCompiler->printNeededJSFunctions();
971
972
973
974
975
976

                // Display "is-locked" message:
                if ($command === 'edit') {
                    $lockInfo = BackendUtility::isRecordLocked($tableName, $formData['databaseRow']['uid']);
                    if ($lockInfo) {
                        /** @var \TYPO3\CMS\Core\Messaging\FlashMessage $flashMessage */
977
                        $flashMessage = GeneralUtility::makeInstance(FlashMessage::class, $lockInfo['msg'], '', FlashMessage::WARNING);
978
979
980
981
982
983
984
985
986
                        /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
                        $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
                        /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
                        $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
                        $defaultFlashMessageQueue->enqueue($flashMessage);
                    }
                }
            } catch (AccessDeniedException $e) {
                // If no edit access, print error message:
987
                $content = '<h2>' . htmlspecialchars($lang->getLL('noAccess')) . '</h2>';
988
                $content .= '<div>' . $lang->getLL('noAccess_msg') . '<br /><br />' . ($beUser->errorMsg ? 'Reason: ' . $beUser->errorMsg . '<br /><br />' : '') . '</div>';
989
990
991
            }
        } else {
            // If no edit access, print error message:
992
993
            $content = '<h2>' . $lang->getLL('noAccess') . '</h2>';
            $content .= '<div>' . $lang->getLL('noAccess_msg') . '</div>';
994
995
        }

996
        // Element selection matrix:
997
        if ($tableName === 'tt_content' && MathUtility::canBeInterpretedAsInteger($this->eRParts[1])) {
998
999
            $content .= '<h2>' . $lang->getLL('CEonThisPage') . '</h2>';
            // PositionMap
1000
            $posMap = GeneralUtility::makeInstance(ContentLayoutPagePositionMap::class);