NewRecordController.php 33.7 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
use Psr\Http\Message\ResponseInterface;
18
use Psr\Http\Message\ServerRequestInterface;
19
use TYPO3\CMS\Backend\Routing\UriBuilder;
20
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
21
use TYPO3\CMS\Backend\Template\ModuleTemplate;
22
23
use TYPO3\CMS\Backend\Tree\View\NewRecordPageTreeView;
use TYPO3\CMS\Backend\Tree\View\PagePositionMap;
Nicole Cordes's avatar
Nicole Cordes committed
24
use TYPO3\CMS\Backend\Utility\BackendUtility;
25
26
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
27
use TYPO3\CMS\Core\Imaging\Icon;
Nicole Cordes's avatar
Nicole Cordes committed
28
29
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
30
use TYPO3\CMS\Core\Utility\HttpUtility;
31
use TYPO3\CMS\Core\Utility\PathUtility;
32
33
use TYPO3\CMS\Frontend\Page\PageRepository;

34
35
36
/**
 * Script class for 'db_new'
 */
37
class NewRecordController
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
{
    /**
     * @var array
     */
    public $pageinfo;

    /**
     * @var array
     */
    public $pidInfo;

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

    /**
     * @var int
     */
    public $newPagesInto;

    /**
     * @var int
     */
    public $newContentInto;

    /**
     * @var int
     */
    public $newPagesAfter;

    /**
     * Determines, whether "Select Position" for new page should be shown
     *
     * @var bool
     */
    protected $newPagesSelectPosition = true;

    /**
     * @var array
     */
    public $web_list_modTSconfig;

    /**
     * @var array
     */
    public $allowedNewTables;

    /**
     * @var array
     */
    public $deniedNewTables;

    /**
     * @var array
     */
    public $web_list_modTSconfig_pid;

    /**
     * @var array
     */
    public $allowedNewTables_pid;

    /**
     * @var array
     */
    public $deniedNewTables_pid;

    /**
     * @var string
     */
    public $code;

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

    /**
     * @var int
     */
    public $id;

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

    /**
     * pagesOnly flag.
     *
     * @var int
     */
    public $pagesOnly;

    /**
     * @var string
     */
    public $perms_clause;

    /**
     * Accumulated HTML output
     *
     * @var string
     */
    public $content;

    /**
     * @var array
     */
    public $tRows;

150
151
152
153
154
155
156
    /**
     * ModuleTemplate object
     *
     * @var ModuleTemplate
     */
    protected $moduleTemplate;

157
158
159
160
161
    /**
     * Constructor
     */
    public function __construct()
    {
162
        $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
163
        $GLOBALS['SOBE'] = $this;
164
        $this->getLanguageService()->includeLLFile('EXT:lang/Resources/Private/Language/locallang_misc.xlf');
165
166
167
168
169
170
171
172
173
174
175
176
177
        $this->init();
    }

    /**
     * Constructor function for the class
     */
    protected function init()
    {
        $beUser = $this->getBackendUserAuthentication();
        // Page-selection permission clause (reading)
        $this->perms_clause = $beUser->getPagePermsClause(1);
        // This will hide records from display - it has nothing to do with user rights!!
        if ($pidList = $beUser->getTSConfigVal('options.hideRecords.pages')) {
178
179
180
            if (!empty($pidList)) {
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
                    ->getQueryBuilderForTable('pages');
181
                $this->perms_clause .= ' AND ' . $queryBuilder->expr()->notIn(
182
183
184
                    'pages.uid',
                    GeneralUtility::intExplode(',', $pidList)
                );
185
186
187
188
189
190
191
192
            }
        }
        // Setting GPvars:
        // The page id to operate from
        $this->id = (int)GeneralUtility::_GP('id');
        $this->returnUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'));
        $this->pagesOnly = GeneralUtility::_GP('pagesOnly');
        // Setting up the context sensitive menu:
193
        $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ContextMenu');
194
        $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Tooltip');
195
196
197
        $this->moduleTemplate->getPageRenderer()->loadRequireJsModule(
            'TYPO3/CMS/Backend/Wizard/NewContentElement',
            'function(NewContentElement) {
198
199
200
201
202
203
204
                require([\'jquery\'], function($) {
                    $(function() {
                        $(\'.t3js-toggle-new-content-element-wizard\').click(function() {
                            var $me = $(this);
                            NewContentElement.wizard($me.data(\'url\'), $me.data(\'title\'));
                        });
                    });
205
206
207
                });
            }'
        );
208
209
        // Creating content
        $this->content = '';
210
        $this->content .= '<h1>'
211
            . $this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:db_new.php.pagetitle')
212
            . '</h1>';
213
214
215
216
217
218
219
220
        // Id a positive id is supplied, ask for the page record with permission information contained:
        if ($this->id > 0) {
            $this->pageinfo = BackendUtility::readPageAccess($this->id, $this->perms_clause);
        }
        // If a page-record was returned, the user had read-access to the page.
        if ($this->pageinfo['uid']) {
            // Get record of parent page
            $this->pidInfo = BackendUtility::getRecord('pages', $this->pageinfo['pid']);
221
222
            // Checking the permissions for the user with regard to the parent page: Can he create new pages, new
            // content record, new page after?
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
            if ($beUser->doesUserHaveAccess($this->pageinfo, 8)) {
                $this->newPagesInto = 1;
            }
            if ($beUser->doesUserHaveAccess($this->pageinfo, 16)) {
                $this->newContentInto = 1;
            }
            if (($beUser->isAdmin() || is_array($this->pidInfo)) && $beUser->doesUserHaveAccess($this->pidInfo, 8)) {
                $this->newPagesAfter = 1;
            }
        } elseif ($beUser->isAdmin()) {
            // Admins can do it all
            $this->newPagesInto = 1;
            $this->newContentInto = 1;
            $this->newPagesAfter = 0;
        } else {
            // People with no permission can do nothing
            $this->newPagesInto = 0;
            $this->newContentInto = 0;
            $this->newPagesAfter = 0;
        }
    }

    /**
     * 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)
    {
        $this->main();

257
        $response->getBody()->write($this->moduleTemplate->renderContent());
258
259
260
261
262
263
264
265
266
        return $response;
    }

    /**
     * Main processing, creating the list of new record tables to select from
     */
    public function main()
    {
        // If there was a page - or if the user is admin (admins has access to the root) we proceed:
267
268
269
270
271
272
273
        if (!empty($this->pageinfo['uid']) || $this->getBackendUserAuthentication()->isAdmin()) {
            if (empty($this->pageinfo)) {
                // Explicitly pass an empty array to the docHeader
                $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation([]);
            } else {
                $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($this->pageinfo);
            }
274
275
            // Acquiring TSconfig for this module/current page:
            $this->web_list_modTSconfig = BackendUtility::getModTSconfig($this->pageinfo['uid'], 'mod.web_list');
276
277
278
279
280
281
282
283
284
285
            $this->allowedNewTables = GeneralUtility::trimExplode(
                ',',
                $this->web_list_modTSconfig['properties']['allowedNewTables'],
                true
            );
            $this->deniedNewTables = GeneralUtility::trimExplode(
                ',',
                $this->web_list_modTSconfig['properties']['deniedNewTables'],
                true
            );
286
287
            // Acquiring TSconfig for this module/parent page:
            $this->web_list_modTSconfig_pid = BackendUtility::getModTSconfig($this->pageinfo['pid'], 'mod.web_list');
288
289
290
291
292
293
294
295
296
297
            $this->allowedNewTables_pid = GeneralUtility::trimExplode(
                ',',
                $this->web_list_modTSconfig_pid['properties']['allowedNewTables'],
                true
            );
            $this->deniedNewTables_pid = GeneralUtility::trimExplode(
                ',',
                $this->web_list_modTSconfig_pid['properties']['deniedNewTables'],
                true
            );
298
299
300
301
302
303
304
305
306
307
308
309
310
            // More init:
            if (!$this->showNewRecLink('pages')) {
                $this->newPagesInto = 0;
            }
            if (!$this->showNewRecLink('pages', $this->allowedNewTables_pid, $this->deniedNewTables_pid)) {
                $this->newPagesAfter = 0;
            }
            // Set header-HTML and return_url
            if (is_array($this->pageinfo) && $this->pageinfo['uid']) {
                $title = strip_tags($this->pageinfo[$GLOBALS['TCA']['pages']['ctrl']['label']]);
            } else {
                $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
            }
311
            $this->moduleTemplate->setTitle($title);
312
313
314
315
316
317
318
319
320
            // GENERATE the HTML-output depending on mode (pagesOnly is the page wizard)
            // Regular new element:
            if (!$this->pagesOnly) {
                $this->regularNew();
            } elseif ($this->showNewRecLink('pages')) {
                // Pages only wizard
                $this->pagesOnly();
            }
            // Add all the content to an output section
321
            $this->content .= '<div>' . $this->code . '</div>';
322
            // Setting up the buttons and markers for docheader
323
            $this->getButtons();
324
            // Build the <body> for the module
325
            $this->moduleTemplate->setContent($this->content);
326
327
328
329
330
331
332
333
        }
    }

    /**
     * Create the panel of buttons for submitting the form or otherwise perform operations.
     */
    protected function getButtons()
    {
334
335
        $lang = $this->getLanguageService();
        $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
336
337
338
339
        // Regular new element:
        if (!$this->pagesOnly) {
            // New page
            if ($this->showNewRecLink('pages')) {
340
                $newPageButton = $buttonBar->makeLinkButton()
341
                    ->setHref(GeneralUtility::linkThisScript(['pagesOnly' => '1']))
342
                    ->setTitle($lang->sL('LLL:EXT:backend/Resources/Private/Language/locallang_layout.xlf:newPage'))
343
344
                    ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-page-new', Icon::SIZE_SMALL));
                $buttonBar->addButton($newPageButton, ButtonBar::BUTTON_POSITION_LEFT, 20);
345
346
            }
            // CSH
347
348
            $cshButton = $buttonBar->makeHelpButton()->setModuleName('xMOD_csh_corebe')->setFieldName('new_regular');
            $buttonBar->addButton($cshButton);
349
350
351
352
        } elseif ($this->showNewRecLink('pages')) {
            // Pages only wizard
            // CSH
            $buttons['csh'] = BackendUtility::cshItem('xMOD_csh_corebe', 'new_pages');
353
354
            $cshButton = $buttonBar->makeHelpButton()->setModuleName('xMOD_csh_corebe')->setFieldName('new_pages');
            $buttonBar->addButton($cshButton);
355
356
        }
        // Back
357
358
359
        if ($this->returnUrl) {
            $returnButton = $buttonBar->makeLinkButton()
                ->setHref($this->returnUrl)
360
                ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.goBack'))
361
362
                ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-view-go-back', Icon::SIZE_SMALL));
            $buttonBar->addButton($returnButton, ButtonBar::BUTTON_POSITION_LEFT, 10);
363
        }
364

365
366
367
368
        if (is_array($this->pageinfo) && $this->pageinfo['uid']) {
            // View
            $pagesTSconfig = BackendUtility::getPagesTSconfig($this->pageinfo['uid']);
            if (isset($pagesTSconfig['TCEMAIN.']['preview.']['disableButtonForDokType'])) {
369
370
371
372
373
                $excludeDokTypes = GeneralUtility::intExplode(
                    ',',
                    $pagesTSconfig['TCEMAIN.']['preview.']['disableButtonForDokType'],
                    true
                );
374
375
            } else {
                // exclude sysfolders and recycler by default
376
                $excludeDokTypes = [
377
378
379
                    PageRepository::DOKTYPE_RECYCLER,
                    PageRepository::DOKTYPE_SYSFOLDER,
                    PageRepository::DOKTYPE_SPACER
380
                ];
381
382
            }
            if (!in_array((int)$this->pageinfo['doktype'], $excludeDokTypes, true)) {
383
384
385
386
387
388
389
                $viewButton = $buttonBar->makeLinkButton()
                    ->setHref('#')
                    ->setOnClick(BackendUtility::viewOnClick(
                        $this->pageinfo['uid'],
                        '',
                        BackendUtility::BEgetRootLine($this->pageinfo['uid'])
                    ))
390
                    ->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.showPage'))
391
                    ->setIcon($this->moduleTemplate->getIconFactory()->getIcon(
392
                        'actions-view-page',
393
394
395
                        Icon::SIZE_SMALL
                    ));
                $buttonBar->addButton($viewButton, ButtonBar::BUTTON_POSITION_LEFT, 30);
396
397
398
399
400
401
402
403
404
            }
        }
    }

    /**
     * Creates the position map for pages wizard
     */
    public function pagesOnly()
    {
405
406
407
408
409
410
411
412
413
414
415
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable('sys_language');
        $queryBuilder->getRestrictions()
            ->removeAll()
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
        $numberOfPages = $queryBuilder
            ->count('*')
            ->from('pages')
            ->execute()
            ->fetchColumn(0);

416
        if ($numberOfPages > 0) {
417
            $this->code .= '<h3>' . htmlspecialchars($this->getLanguageService()->getLL('selectPosition')) . ':</h3>';
418
419
            $positionMap = GeneralUtility::makeInstance(PagePositionMap::class, NewRecordPageTreeView::class);
            /** @var $positionMap \TYPO3\CMS\Backend\Tree\View\PagePositionMap */
420
421
422
423
424
425
            $this->code .= $positionMap->positionTree(
                $this->id,
                $this->pageinfo,
                $this->perms_clause,
                $this->returnUrl
            );
426
        } else {
427
428
            /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
            $uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
429
430
431
432
433
434
435
436
            // No pages yet, no need to prompt for position, redirect to page creation.
            $urlParameters = [
                'edit' => [
                    'pages' => [
                        0 => 'new'
                    ]
                ],
                'returnNewPageId' => 1,
437
                'returnUrl' => (string)$uriBuilder->buildUriFromRoute('db_new', ['id' => $this->id, 'pagesOnly' => '1'])
438
            ];
439
            $url = (string)$uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
440
441
442
443
444
445
446
447
448
449
450
451
            @ob_end_clean();
            HttpUtility::redirect($url);
        }
    }

    /**
     * Create a regular new element (pages and records)
     */
    public function regularNew()
    {
        $lang = $this->getLanguageService();
        // Initialize array for accumulating table rows:
452
        $this->tRows = [];
453
454
455
456
457
        // Get TSconfig for current page
        $pageTS = BackendUtility::getPagesTSconfig($this->id);
        // Finish initializing new pages options with TSconfig
        // Each new page option may be hidden by TSconfig
        // Enabled option for the position of a new page
458
        $this->newPagesSelectPosition = !empty($pageTS['mod.']['wizards.']['newRecord.']['pages.']['show.']['pageSelectPosition']);
459
        // Pseudo-boolean (0/1) for backward compatibility
460
461
        $displayNewPagesIntoLink = $this->newPagesInto && !empty($pageTS['mod.']['wizards.']['newRecord.']['pages.']['show.']['pageInside']);
        $displayNewPagesAfterLink = $this->newPagesAfter && !empty($pageTS['mod.']['wizards.']['newRecord.']['pages.']['show.']['pageAfter']);
462
463
464
465
466
        // Slight spacer from header:
        $this->code .= '';
        // New Page
        $table = 'pages';
        $v = $GLOBALS['TCA'][$table];
467
468
        $pageIcon = $this->moduleTemplate->getIconFactory()->getIconForRecord(
            $table,
469
            [],
470
471
472
            Icon::SIZE_SMALL
        )->render();
        $newPageIcon = $this->moduleTemplate->getIconFactory()->getIcon('actions-page-new', Icon::SIZE_SMALL)->render();
473
474
        $rowContent = '';
        // New pages INSIDE this pages
475
        $newPageLinks = [];
476
477
478
479
480
        if ($displayNewPagesIntoLink
            && $this->isTableAllowedForThisPage($this->pageinfo, 'pages')
            && $this->getBackendUserAuthentication()->check('tables_modify', 'pages')
            && $this->getBackendUserAuthentication()->workspaceCreateNewRecord(($this->pageinfo['_ORIG_uid'] ?: $this->id), 'pages')
        ) {
481
            // Create link to new page inside:
482
483
484
485
486
487
            $recordIcon = $this->moduleTemplate->getIconFactory()->getIconForRecord($table, [], Icon::SIZE_SMALL)->render();
            $newPageLinks[] = $this->linkWrap(
                $recordIcon . htmlspecialchars($lang->sL($v['ctrl']['title'])) . ' (' . htmlspecialchars($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:db_new.php.inside')) . ')',
                $table,
                $this->id
            );
488
489
        }
        // New pages AFTER this pages
490
491
492
493
494
        if ($displayNewPagesAfterLink
            && $this->isTableAllowedForThisPage($this->pidInfo, 'pages')
            && $this->getBackendUserAuthentication()->check('tables_modify', 'pages')
            && $this->getBackendUserAuthentication()->workspaceCreateNewRecord($this->pidInfo['uid'], 'pages')
        ) {
495
            $newPageLinks[] = $this->linkWrap($pageIcon . htmlspecialchars($lang->sL($v['ctrl']['title'])) . ' (' . htmlspecialchars($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:db_new.php.after')) . ')', 'pages', -$this->id);
496
497
498
499
        }
        // New pages at selection position
        if ($this->newPagesSelectPosition && $this->showNewRecLink('pages')) {
            // Link to page-wizard:
500
            $newPageLinks[] = '<a href="' . htmlspecialchars(GeneralUtility::linkThisScript(['pagesOnly' => 1])) . '">' . $pageIcon . htmlspecialchars($lang->getLL('pageSelectPosition')) . '</a>';
501
502
503
504
505
506
507
508
509
510
511
512
        }
        // Assemble all new page links
        $numPageLinks = count($newPageLinks);
        for ($i = 0; $i < $numPageLinks; $i++) {
            $rowContent .= '<li>' . $newPageLinks[$i] . '</li>';
        }
        if ($this->showNewRecLink('pages')) {
            $rowContent = '<ul class="list-tree"><li>' . $newPageIcon . '<strong>' .
                $lang->getLL('createNewPage') . '</strong><ul>' . $rowContent . '</ul></li>';
        } else {
            $rowContent = '<ul class="list-tree"><li><ul>' . $rowContent . '</li></ul>';
        }
513
514
        /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
        $uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
515
        // Compile table row
516
517
        $startRows = [$rowContent];
        $iconFile = [];
518
519
        // New tables (but not pages) INSIDE this pages
        $isAdmin = $this->getBackendUserAuthentication()->isAdmin();
520
        $newContentIcon = $this->moduleTemplate->getIconFactory()->getIcon('actions-document-new', Icon::SIZE_SMALL)->render();
521
522
523
524
        if ($this->newContentInto) {
            if (is_array($GLOBALS['TCA'])) {
                $groupName = '';
                foreach ($GLOBALS['TCA'] as $table => $v) {
525
                    $rootLevelConfiguration = isset($v['ctrl']['rootLevel']) ? (int)$v['ctrl']['rootLevel'] : 0;
526
                    if ($table !== 'pages'
527
528
529
                        && $this->showNewRecLink($table)
                        && $this->isTableAllowedForThisPage($this->pageinfo, $table)
                        && $this->getBackendUserAuthentication()->check('tables_modify', $table)
530
                        && ($rootLevelConfiguration === -1 || ($this->id xor $rootLevelConfiguration))
531
532
                        && $this->getBackendUserAuthentication()->workspaceCreateNewRecord(($this->pageinfo['_ORIG_uid'] ? $this->pageinfo['_ORIG_uid'] : $this->id), $table)
                    ) {
533
                        $newRecordIcon = $this->moduleTemplate->getIconFactory()->getIconForRecord($table, [], Icon::SIZE_SMALL)->render();
534
535
536
                        $rowContent = '';
                        $thisTitle = '';
                        // Create new link for record:
537
                        $newLink = $this->linkWrap($newRecordIcon . htmlspecialchars($lang->sL($v['ctrl']['title'])), $table, $this->id);
538
                        // If the table is 'tt_content', create link to wizard
539
                        if ($table === 'tt_content') {
540
                            $groupName = $lang->getLL('createNewContent');
541
542
543
                            $rowContent = $newContentIcon
                                . '<strong>' . $lang->getLL('createNewContent') . '</strong>'
                                . '<ul>';
544
545
                            // If mod.newContentElementWizard.override is set, use that extension's wizard instead:
                            $tsConfig = BackendUtility::getModTSconfig($this->id, 'mod');
546
547
                            $moduleName = isset($tsConfig['properties']['newContentElementWizard.']['override'])
                                ? $tsConfig['properties']['newContentElementWizard.']['override']
548
                                : 'new_content_element_wizard';
549
                            $url = (string)$uriBuilder->buildUriFromRoute($moduleName, ['id' => $this->id, 'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')]);
550
551
552
553
554
555
556
                            $rowContent .= '<li>' . $newLink . ' ' . BackendUtility::wrapInHelp($table, '') . '</li>'
                                . '<li>'
                                . '<a href="#" data-url="' . htmlspecialchars($url) . '" data-title="' . htmlspecialchars($this->getLanguageService()->getLL('newContentElement')) . '" class="t3js-toggle-new-content-element-wizard">'
                                . $newContentIcon . htmlspecialchars($lang->getLL('clickForWizard'))
                                . '</a>'
                                . '</li>'
                                . '</ul>';
557
558
559
560
561
562
563
564
565
566
567
                        } else {
                            // Get the title
                            if ($v['ctrl']['readOnly'] || $v['ctrl']['hideTable'] || $v['ctrl']['is_static']) {
                                continue;
                            }
                            if ($v['ctrl']['adminOnly'] && !$isAdmin) {
                                continue;
                            }
                            $nameParts = explode('_', $table);
                            $thisTitle = '';
                            $_EXTKEY = '';
568
                            if ($nameParts[0] === 'tx' || $nameParts[0] === 'tt') {
569
                                // Try to extract extension name
570
                                if (substr($v['ctrl']['title'], 0, 8) === 'LLL:EXT:') {
571
572
                                    $_EXTKEY = substr($v['ctrl']['title'], 8);
                                    $_EXTKEY = substr($_EXTKEY, 0, strpos($_EXTKEY, '/'));
573
                                    if ($_EXTKEY !== '') {
574
575
576
577
578
                                        // First try to get localisation of extension title
                                        $temp = explode(':', substr($v['ctrl']['title'], 9 + strlen($_EXTKEY)));
                                        $langFile = $temp[0];
                                        $thisTitle = $lang->sL('LLL:EXT:' . $_EXTKEY . '/' . $langFile . ':extension.title');
                                        // If no localisation available, read title from ext_emconf.php
579
580
                                        $extPath = ExtensionManagementUtility::extPath($_EXTKEY);
                                        $extEmConfFile = $extPath . 'ext_emconf.php';
581
                                        if (!$thisTitle && is_file($extEmConfFile)) {
582
                                            $EM_CONF = [];
583
584
585
                                            include $extEmConfFile;
                                            $thisTitle = $EM_CONF[$_EXTKEY]['title'];
                                        }
586
                                        $iconFile[$_EXTKEY] = '<img src="' . PathUtility::getAbsoluteWebPath(ExtensionManagementUtility::getExtensionIcon($extPath, true)) . '" ' . 'width="16" height="16" ' . 'alt="' . $thisTitle . '" />';
587
588
589
590
591
592
593
594
595
596
                                    }
                                }
                                if (empty($thisTitle)) {
                                    $_EXTKEY = $nameParts[1];
                                    $thisTitle = $nameParts[1];
                                    $iconFile[$_EXTKEY] = '';
                                }
                            } else {
                                $_EXTKEY = 'system';
                                $thisTitle = $lang->getLL('system_records');
597
                                $iconFile['system'] = $this->moduleTemplate->getIconFactory()->getIcon('apps-pagetree-root', Icon::SIZE_SMALL)->render();
598
                            }
599
600

                            if ($groupName === '' || $groupName !== $_EXTKEY) {
601
602
603
604
605
                                $groupName = empty($v['ctrl']['groupName']) ? $_EXTKEY : $v['ctrl']['groupName'];
                            }
                            $rowContent .= $newLink;
                        }
                        // Compile table row:
606
                        if ($table === 'tt_content') {
607
608
609
610
611
612
613
614
615
616
617
618
619
620
                            $startRows[] = '<li>' . $rowContent . '</li>';
                        } else {
                            $this->tRows[$groupName]['title'] = $thisTitle;
                            $this->tRows[$groupName]['html'][] = $rowContent;
                            $this->tRows[$groupName]['table'][] = $table;
                        }
                    }
                }
            }
        }
        // User sort
        if (isset($pageTS['mod.']['wizards.']['newRecord.']['order'])) {
            $this->newRecordSortList = GeneralUtility::trimExplode(',', $pageTS['mod.']['wizards.']['newRecord.']['order'], true);
        }
621
        uksort($this->tRows, [$this, 'sortNewRecordsByConfig']);
622
        // Compile table row:
623
        $finalRows = [];
624
625
626
627
628
629
630
631
632
        $finalRows[] = implode('', $startRows);
        foreach ($this->tRows as $key => $value) {
            $row = '<li>' . $iconFile[$key] . ' <strong>' . $value['title'] . '</strong><ul>';
            foreach ($value['html'] as $recordKey => $record) {
                $row .= '<li>' . $record . ' ' . BackendUtility::wrapInHelp($value['table'][$recordKey], '') . '</li>';
            }
            $row .= '</ul></li>';
            $finalRows[] = $row;
        }
633
634

        $finalRows[] = '</ul>';
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
        // Make table:
        $this->code .= implode('', $finalRows);
    }

    /**
     * User array sort function used by regularNew
     *
     * @param string $a First array element for compare
     * @param string $b First array element for compare
     * @return int -1 for lower, 0 for equal, 1 for greater
     */
    public function sortNewRecordsByConfig($a, $b)
    {
        if (!empty($this->newRecordSortList)) {
            if (in_array($a, $this->newRecordSortList) && in_array($b, $this->newRecordSortList)) {
                // Both are in the list, return relative to position in array
                $sub = array_search($a, $this->newRecordSortList) - array_search($b, $this->newRecordSortList);
                $ret = ($sub < 0 ? -1 : $sub == 0) ? 0 : 1;
            } elseif (in_array($a, $this->newRecordSortList)) {
                // First element is in array, put to top
                $ret = -1;
            } elseif (in_array($b, $this->newRecordSortList)) {
                // Second element is in array, put first to bottom
                $ret = 1;
            } else {
                // No element is in array, return alphabetic order
                $ret = strnatcasecmp($this->tRows[$a]['title'], $this->tRows[$b]['title']);
            }
            return $ret;
        }
665
666
        // Return alphabetic order
        return strnatcasecmp($this->tRows[$a]['title'], $this->tRows[$b]['title']);
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
    }

    /**
     * Links the string $code to a create-new form for a record in $table created on page $pid
     *
     * @param string $linkText Link text
     * @param string $table Table name (in which to create new record)
     * @param int $pid PID value for the "&edit['.$table.']['.$pid.']=new" command (positive/negative)
     * @param bool $addContentTable If $addContentTable is set, then a new tt_content record is created together with pages
     * @return string The link.
     */
    public function linkWrap($linkText, $table, $pid, $addContentTable = false)
    {
        $urlParameters = [
            'edit' => [
                $table => [
                    $pid => 'new'
                ]
            ],
            'returnUrl' => $this->returnUrl
        ];
688
        if ($table === 'pages' && $addContentTable) {
689
690
            $urlParameters['tt_content']['prev'] = 'new';
            $urlParameters['returnNewPageId'] = 1;
691
692
        } elseif ($table === 'pages') {
            $urlParameters['overrideVals']['pages']['doktype'] = (int)$this->pageinfo['doktype'];
693
        }
694
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
695
        $url = (string)$uriBuilder->buildUriFromRoute('record_edit', $urlParameters);
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
        return '<a href="' . htmlspecialchars($url) . '">' . $linkText . '</a>';
    }

    /**
     * Returns TRUE if the tablename $checkTable is allowed to be created on the page with record $pid_row
     *
     * @param array $pid_row Record for parent page.
     * @param string $checkTable Table name to check
     * @return bool Returns TRUE if the tablename $checkTable is allowed to be created on the page with record $pid_row
     */
    public function isTableAllowedForThisPage($pid_row, $checkTable)
    {
        if (!is_array($pid_row)) {
            return $this->getBackendUserAuthentication()->isAdmin();
        }
        // be_users and be_groups may not be created anywhere but in the root.
712
        if ($checkTable === 'be_users' || $checkTable === 'be_groups') {
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
            return false;
        }
        // Checking doktype:
        $doktype = (int)$pid_row['doktype'];
        if (!($allowedTableList = $GLOBALS['PAGES_TYPES'][$doktype]['allowedTables'])) {
            $allowedTableList = $GLOBALS['PAGES_TYPES']['default']['allowedTables'];
        }
        // If all tables or the table is listed as an allowed type, return TRUE
        if (strstr($allowedTableList, '*') || GeneralUtility::inList($allowedTableList, $checkTable)) {
            return true;
        }

        return false;
    }

    /**
     * Returns TRUE if:
     * - $allowedNewTables and $deniedNewTables are empty
731
732
     * - the table is not found in $deniedNewTables and $allowedNewTables is not set or the $table tablename is found in
     *   $allowedNewTables
733
734
735
736
737
738
739
     *
     * If $table tablename is found in $allowedNewTables and $deniedNewTables, $deniedNewTables
     * has priority over $allowedNewTables.
     *
     * @param string $table Table name to test if in allowedTables
     * @param array $allowedNewTables Array of new tables that are allowed.
     * @param array $deniedNewTables Array of new tables that are not allowed.
740
     *
741
742
     * @return bool Returns TRUE if a link for creating new records should be displayed for $table
     */
743
    public function showNewRecLink($table, array $allowedNewTables = [], array $deniedNewTables = [])
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
    {
        if (!$this->getBackendUserAuthentication()->check('tables_modify', $table)) {
            return false;
        }

        $allowedNewTables = $allowedNewTables ?: $this->allowedNewTables;
        $deniedNewTables = $deniedNewTables ?: $this->deniedNewTables;
        // No deny/allow tables are set:
        if (empty($allowedNewTables) && empty($deniedNewTables)) {
            return true;
        }

        return !in_array($table, $deniedNewTables) && (empty($allowedNewTables) || in_array($table, $allowedNewTables));
    }

    /**
     * Checks if sys_language records are present
     *
     * @return bool
     */
    protected function checkIfLanguagesExist()
    {
766
767
768
769
770
771
772
773
774
775
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable('sys_language');
        $queryBuilder->getRestrictions()->removeAll();

        $count = $queryBuilder
            ->count('uid')
            ->from('sys_language')
            ->execute()
            ->fetchColumn(0);
        return (bool)$count;
776
777
778
779
780
    }

    /**
     * Return language service instance
     *
781
     * @return \TYPO3\CMS\Core\Localization\LanguageService
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }

    /**
     * Returns the global BackendUserAuthentication object.
     *
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
     */
    protected function getBackendUserAuthentication()
    {
        return $GLOBALS['BE_USER'];
    }
797
}