DatabaseRecordList.php 168 KB
Newer Older
1
<?php
2

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

16
17
namespace TYPO3\CMS\Recordlist\RecordList;

18
use Psr\Http\Message\ServerRequestInterface;
19
use TYPO3\CMS\Backend\Backend\Avatar\Avatar;
20
use TYPO3\CMS\Backend\Configuration\TranslationConfigurationProvider;
Markus Klein's avatar
Markus Klein committed
21
use TYPO3\CMS\Backend\RecordList\RecordListGetTableHookInterface;
22
use TYPO3\CMS\Backend\Routing\PreviewUriBuilder;
23
use TYPO3\CMS\Backend\Routing\UriBuilder;
24
25
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Template\ModuleTemplate;
26
use TYPO3\CMS\Backend\Tree\View\PageTreeView;
27
use TYPO3\CMS\Backend\Utility\BackendUtility;
28
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
29
use TYPO3\CMS\Core\Cache\CacheManager;
30
use TYPO3\CMS\Core\Database\Connection;
31
use TYPO3\CMS\Core\Database\ConnectionPool;
32
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
33
use TYPO3\CMS\Core\Database\Query\QueryHelper;
34
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
35
use TYPO3\CMS\Core\Database\Query\Restriction\WorkspaceRestriction;
36
use TYPO3\CMS\Core\Database\ReferenceIndex;
37
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
38
39
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
40
41
use TYPO3\CMS\Core\LinkHandling\Exception\UnknownLinkHandlerException;
use TYPO3\CMS\Core\LinkHandling\LinkService;
42
use TYPO3\CMS\Core\Localization\LanguageService;
43
use TYPO3\CMS\Core\Log\LogManager;
44
use TYPO3\CMS\Core\Service\DependencyOrderingService;
45
use TYPO3\CMS\Core\Type\Bitmask\Permission;
46
use TYPO3\CMS\Core\Utility\CsvUtility;
47
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
48
use TYPO3\CMS\Core\Utility\GeneralUtility;
49
50
use TYPO3\CMS\Core\Utility\HttpUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
51
use TYPO3\CMS\Core\Versioning\VersionState;
52
use TYPO3\CMS\Fluid\View\StandaloneView;
53

54
55
/**
 * Class for rendering of Web>List module
56
 * @internal This class is a specific TYPO3 Backend implementation and is not part of the TYPO3's Core API.
57
 */
58
class DatabaseRecordList
59
60
61
62
63
64
65
66
67
68
69
{
    // *********
    // External:
    // *********

    /**
     * Used to indicate which tables (values in the array) that can have a
     * create-new-record link. If the array is empty, all tables are allowed.
     *
     * @var string[]
     */
70
    public $allowedNewTables = [];
71
72
73
74
75
76
77

    /**
     * Used to indicate which tables (values in the array) that cannot have a
     * create-new-record link. If the array is empty, all tables are allowed.
     *
     * @var string[]
     */
78
    public $deniedNewTables = [];
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

    /**
     * If TRUE, will disable the rendering of clipboard + control panels.
     *
     * @var bool
     */
    public $dontShowClipControlPanels = false;

    /**
     * If TRUE, will show the clipboard in the field list.
     *
     * @var bool
     */
    public $showClipboard = false;

    /**
     * If TRUE, will DISABLE all control panels in lists. (Takes precedence)
     *
     * @var bool
     */
    public $noControlPanels = false;

    /**
     * If TRUE, clickmenus will be rendered
     *
     * @var bool
     */
    public $clickMenuEnabled = true;

    /**
     * Space icon used for alignment
     *
     * @var string
     */
    public $spaceIcon;

    /**
     * Disable single table view
     *
     * @var bool
     */
    public $disableSingleTableView = false;

    // *********
    // Internal:
    // *********

    /**
     * Set to the page record (see writeTop())
     *
     * @var string[]
     */
131
    public $pageRow = [];
132

133
134
135
136
137
138
139
140
141
142
143
144
145
    /**
     * Contains sys language icons and titles
     *
     * @var array
     */
    public $languageIconTitles = [];

    /**
     * Tables which should not list their translations
     *
     * @var string
     */
    public $hideTranslations = '';
146
147
148
149
150
151
152
153

    /**
     * If set, the listing is returned as CSV instead.
     *
     * @var bool
     */
    public $csvOutput = false;

154
155
156
157
158
159
160
161
162
163
164
165
166
167
    /**
     * Cache for record path
     *
     * @var mixed[]
     */
    public $recPath_cache = [];

    /**
     * Field, to sort list by
     *
     * @var string
     */
    public $sortField;

168
169
170
171
172
173
174
175
    /**
     * Module data
     *
     * @internal
     * @var array
     */
    protected $moduleData =  [];

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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    /**
     * Page id
     *
     * @var int
     */
    public $id;

    /**
     * Used for tracking duplicate values of fields
     *
     * @var string[]
     */
    public $duplicateStack = [];

    /**
     * If TRUE, records are listed only if a specific table is selected.
     *
     * @var bool
     */
    public $listOnlyInSingleTableMode = false;

    /**
     * @var TranslationConfigurationProvider
     */
    public $translateTools;

    /**
     * @var array[] Module configuration
     */
    public $modTSconfig;

    /**
     * Keys are fieldnames and values are td-css-classes to add in addElement();
     *
     * @var array
     */
    public $addElement_tdCssClass = [];

    /**
     * Used for tracking next/prev uids
     *
     * @var int[][]
     */
    public $currentTable = [];

    /**
     * Indicates if all available fields for a user should be selected or not.
     *
     * @var int
     */
    public $allFields = 0;

    /**
     * Number of records to show
     *
     * @var int
     */
    public $showLimit = 0;

    /**
     * Decides the columns shown. Filled with values that refers to the keys of the data-array. $this->fieldArray[0] is the title column.
     *
     * @var array
     */
    public $fieldArray = [];

    /**
     * Tables which should not get listed
     *
     * @var string
     */
    public $hideTables = '';

    /**
     * Containing which fields to display in extended mode
     *
     * @var string[]
     */
    public $displayFields;

    /**
     * Page select permissions
     *
     * @var string
     */
    public $perms_clause = '';

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

    /**
     * Tablename if single-table mode
     *
     * @var string
     */
    public $table = '';

    /**
     * Some permissions...
     *
280
     * @var Permission
281
     */
282
    public $calcPerms;
283
284
285
286
287
288
289
290
291
292
293
294
295

    /**
     * Mode for what happens when a user clicks the title of a record.
     *
     * @var string
     */
    public $clickTitleMode = '';

    /**
     * Levels to search down.
     *
     * @var int
     */
296
    public $searchLevels = 0;
297
298
299
300
301
302
303
304
305
306
307

    /**
     * TSconfig which overwrites TCA-Settings
     *
     * @var mixed[][]
     */
    public $tableTSconfigOverTCA = [];

    /**
     * Fields to display for the current table
     *
308
     * @var string[][]
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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
     */
    public $setFields = [];

    /**
     * Pointer for browsing list
     *
     * @var int
     */
    public $firstElementNumber = 0;

    /**
     * Search string
     *
     * @var string
     */
    public $searchString = '';

    /**
     * Field, indicating to sort in reverse order.
     *
     * @var bool
     */
    public $sortRev;

    /**
     * String, can contain the field name from a table which must have duplicate values marked.
     *
     * @var string
     */
    public $duplicateField;

    /**
     * Specify a list of tables which are the only ones allowed to be displayed.
     *
     * @var string
     */
    public $tableList = '';

    /**
     * Used to accumulate CSV lines for CSV export.
     *
     * @var string[]
     */
    protected $csvLines = [];

354
355
356
357
358
359
360
361
362
363
364
365
    /**
     * Clipboard object
     *
     * @var \TYPO3\CMS\Backend\Clipboard\Clipboard
     */
    public $clipObj;

    /**
     * Tracking names of elements (for clipboard use)
     *
     * @var string[]
     */
366
    public $CBnames = [];
367
368
369
370
371
372

    /**
     * [$tablename][$uid] = number of references to this record
     *
     * @var int[][]
     */
373
    protected $referenceCount = [];
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393

    /**
     * Injected by RecordList
     *
     * @var string[]
     */
    public $MOD_MENU;

    /**
     * If defined the records are editable
     *
     * @var bool
     */
    protected $editable = true;

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

394
395
396
397
398
    /**
     * @var UriBuilder
     */
    protected $uriBuilder;

399
    /**
400
401
402
403
404
405
406
407
     * Array with before/after setting for tables
     * Structure:
     * 'tableName' => [
     *    'before' => ['A', ...]
     *    'after' => []
     *  ]
     *
     * @var array[]
408
     */
409
410
411
412
413
414
415
416
417
418
419
    protected $tableDisplayOrder = [];

    /**
     * Override the page ids taken into account by getPageIdConstraint()
     *
     * @var array
     */
    protected $overridePageIdList = [];

    /**
     * Override/add urlparameters in listUrl() method
420
     * @var mixed[]
421
422
423
     */
    protected $overrideUrlParameters = [];

424
425
426
427
428
429
430
    /**
     * Current link: array with table names and uid
     *
     * @var array
     */
    protected $currentLink = [];

431
432
433
434
435
436
437
    /**
     * Only used to render translated records, used in list module to show page translations
     *
     * @var bool
     */
    protected $showOnlyTranslatedRecords = false;

438
    /**
439
     * This array contains all possible language uids, which could be translations of a record (excluding pages) in the default language
440
     *
441
442
443
444
445
446
     * It mainly depends on the current pageUid.
     * Translations are possible, depending on
     * - the site config
     * - already translated page records
     *
     * @var int[]
447
     */
448
    protected $possibleTranslations = [];
449

450
451
452
    /**
     * All languages that are allowed by the user
     *
453
454
     * This is used for the translation handling of pages only.
     *
455
456
457
458
     * @var array
     */
    protected $languagesAllowedForUser = [];

459
460
461
462
    /**
     * Constructor
     */
    public function __construct()
463
    {
464
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
465
        $this->uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
466
        $this->translateTools = GeneralUtility::makeInstance(TranslationConfigurationProvider::class);
467
        $this->calcPerms = new Permission();
468
469
    }

470
471
472
473
474
    /**
     * Create the panel of buttons for submitting the form or otherwise perform
     * operations.
     *
     * @param ModuleTemplate $moduleTemplate
475
     * @param ServerRequestInterface $request
476
     */
477
    public function getDocHeaderButtons(ModuleTemplate $moduleTemplate, ServerRequestInterface $request)
478
479
    {
        $buttonBar = $moduleTemplate->getDocHeaderComponent()->getButtonBar();
480
        $modulePageTsConfig = BackendUtility::getPagesTSconfig($this->id)['mod.']['web_list.'] ?? [];
481
482
483
        $backendUser = $this->getBackendUserAuthentication();
        $lang = $this->getLanguageService();
        // Get users permissions for this page record:
484
        $localCalcPerms = new Permission($backendUser->calcPerms($this->pageRow));
485
486
        // CSH
        if ((string)$this->id === '') {
487
            $fieldName = 'list_module_noId';
488
        } elseif (!$this->id) {
489
            $fieldName = 'list_module_root';
490
        } else {
491
            $fieldName = 'list_module';
492
        }
493
494
495
        $cshButton = $buttonBar->makeHelpButton()
            ->setModuleName('xMOD_csh_corebe')
            ->setFieldName($fieldName);
496
497
498
499
        $buttonBar->addButton($cshButton);
        if (isset($this->id)) {
            // View Exclude doktypes 254,255 Configuration:
            // mod.web_list.noViewWithDokTypes = 254,255
500
501
            if (isset($modulePageTsConfig['noViewWithDokTypes'])) {
                $noViewDokTypes = GeneralUtility::trimExplode(',', $modulePageTsConfig['noViewWithDokTypes'], true);
502
503
            } else {
                //default exclusion: doktype 254 (folder), 255 (recycler)
504
                $noViewDokTypes = [
505
506
                    PageRepository::DOKTYPE_SYSFOLDER,
                    PageRepository::DOKTYPE_RECYCLER
507
                ];
508
509
            }
            // New record on pages that are not locked by editlock
510
            if (!($modulePageTsConfig['noCreateRecordsLink'] ?? false) && $this->editLockPermissions()) {
511
                $newRecordButton = $buttonBar->makeLinkButton()
512
                    ->setHref((string)$this->uriBuilder->buildUriFromRoute('db_new', ['id' => $this->id, 'returnUrl' => $this->listURL()]))
513
                    ->setTitle($lang->getLL('newRecordGeneral'))
514
                    ->setIcon($this->iconFactory->getIcon('actions-add', Icon::SIZE_SMALL));
515
                $buttonBar->addButton($newRecordButton, ButtonBar::BUTTON_POSITION_LEFT, 10);
516
            }
517
            if (!in_array($this->pageRow['doktype'] ?? null, $noViewDokTypes)) {
518
519
520
                $previewDataAttributes = PreviewUriBuilder::create((int)$this->id)
                    ->withRootLine(BackendUtility::BEgetRootLine($this->id))
                    ->buildDispatcherDataAttributes();
521
522
                $viewButton = $buttonBar->makeLinkButton()
                    ->setHref('#')
523
                    ->setDataAttributes($previewDataAttributes ?? [])
524
                    ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.showPage'))
525
                    ->setIcon($this->iconFactory->getIcon('actions-view-page', Icon::SIZE_SMALL));
526
                $buttonBar->addButton($viewButton, ButtonBar::BUTTON_POSITION_LEFT, 20);
527
528
529
            }
            // If edit permissions are set, see
            // \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
530
            if ($localCalcPerms->editPagePermissionIsGranted() && !empty($this->id) && $this->editLockPermissions() && $backendUser->checkLanguageAccess(0)) {
531
                // Edit
532
533
534
535
536
537
538
539
                $editLink = $this->uriBuilder->buildUriFromRoute('record_edit', [
                    'edit' => [
                        'pages' => [
                            $this->pageRow['uid'] => 'edit'
                        ]
                    ],
                    'returnUrl' => $this->listURL()
                ]);
540
                $editButton = $buttonBar->makeLinkButton()
541
                    ->setHref($editLink)
542
                    ->setTitle($lang->getLL('editPage'))
543
                    ->setIcon($this->iconFactory->getIcon('actions-page-open', Icon::SIZE_SMALL));
544
                $buttonBar->addButton($editButton, ButtonBar::BUTTON_POSITION_LEFT, 20);
545
546
            }
            // Paste
547
            if ($this->showClipboard && ($localCalcPerms->createPagePermissionIsGranted() || $localCalcPerms->editContentPermissionIsGranted()) && $this->editLockPermissions()) {
548
549
                $elFromTable = $this->clipObj->elFromTable('');
                if (!empty($elFromTable)) {
550
                    $confirmMessage = $this->clipObj->confirmMsgText('pages', $this->pageRow, 'into', $elFromTable);
551
552
                    $pasteButton = $buttonBar->makeLinkButton()
                        ->setHref($this->clipObj->pasteUrl('', $this->id))
553
                        ->setTitle($lang->getLL('clip_paste'))
554
555
556
557
558
559
                        ->setClasses('t3js-modal-trigger')
                        ->setDataAttributes([
                            'severity' => 'warning',
                            'content' => $confirmMessage,
                            'title' => $lang->getLL('clip_paste')
                        ])
560
                        ->setIcon($this->iconFactory->getIcon('actions-document-paste-into', Icon::SIZE_SMALL));
561
                    $buttonBar->addButton($pasteButton, ButtonBar::BUTTON_POSITION_LEFT, 40);
562
563
564
                }
            }
            // Cache
565
566
567
568
569
570
571
572
573
            if ($this->id !== 0) {
                $clearCacheButton = $buttonBar->makeLinkButton()
                    ->setHref('#')
                    ->setDataAttributes(['id' => $this->id])
                    ->setClasses('t3js-clear-page-cache')
                    ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.clear_cache'))
                    ->setIcon($this->iconFactory->getIcon('actions-system-cache-clear', Icon::SIZE_SMALL));
                $buttonBar->addButton($clearCacheButton, ButtonBar::BUTTON_POSITION_RIGHT);
            }
574
575
576
            if ($this->table && (!isset($modulePageTsConfig['noExportRecordsLinks'])
                || (isset($modulePageTsConfig['noExportRecordsLinks'])
                    && !$modulePageTsConfig['noExportRecordsLinks']))
577
578
579
580
            ) {
                // CSV
                $csvButton = $buttonBar->makeLinkButton()
                    ->setHref($this->listURL() . '&csv=1')
581
                    ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.csv'))
582
583
                    ->setIcon($this->iconFactory->getIcon('actions-document-export-csv', Icon::SIZE_SMALL))
                    ->setShowLabelText(true);
584
                $buttonBar->addButton($csvButton, ButtonBar::BUTTON_POSITION_LEFT, 40);
585
586
                // Export
                if (ExtensionManagementUtility::isLoaded('impexp')) {
587
                    $url = (string)$this->uriBuilder->buildUriFromRoute('tx_impexp_export');
588
589
                    $exportButton = $buttonBar->makeLinkButton()
                        ->setHref($url . '&tx_impexp[list][]=' . rawurlencode($this->table . ':' . $this->id))
590
                        ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:rm.export'))
591
592
                        ->setIcon($this->iconFactory->getIcon('actions-document-export-t3d', Icon::SIZE_SMALL))
                        ->setShowLabelText(true);
593
                    $buttonBar->addButton($exportButton, ButtonBar::BUTTON_POSITION_LEFT, 40);
594
595
596
597
598
                }
            }
            // Reload
            $reloadButton = $buttonBar->makeLinkButton()
                ->setHref($this->listURL())
599
                ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.reload'))
600
601
                ->setIcon($this->iconFactory->getIcon('actions-refresh', Icon::SIZE_SMALL));
            $buttonBar->addButton($reloadButton, ButtonBar::BUTTON_POSITION_RIGHT);
602

603
            // Shortcut
604
            $shortCutButton = $buttonBar->makeShortcutButton()->setRouteIdentifier('web_list');
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
            $queryParams = $request->getQueryParams();
            $arguments = [
                'route' => $queryParams['route'],
                'id' => $this->id
            ];
            $potentialArguments = [
                'pointer',
                'table',
                'search_field',
                'search_levels',
                'showLimit',
                'sortField',
                'sortRev'
            ];
            foreach ($potentialArguments as $argument) {
                if (!empty($queryParams[$argument])) {
                    $arguments[$argument] = $queryParams[$argument];
                }
623
            }
624
625
626
627
628
            $moduleSettings = $this->moduleData;
            foreach ($moduleSettings as $moduleSettingKey => $moduleSettingValue) {
                $arguments['GET'][$moduleSettingKey] = $moduleSettingValue;
            }
            $shortCutButton->setArguments($arguments);
629
            $shortCutButton->setDisplayName($this->getShortcutTitle($arguments));
630
631
            $buttonBar->addButton($shortCutButton, ButtonBar::BUTTON_POSITION_RIGHT);

632
633
            // Back
            if ($this->returnUrl) {
634
635
                $backButton = $buttonBar->makeLinkButton()
                    ->setHref($this->returnUrl)
636
                    ->setTitle($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.goBack'))
637
638
                    ->setIcon($this->iconFactory->getIcon('actions-view-go-back', Icon::SIZE_SMALL));
                $buttonBar->addButton($backButton, ButtonBar::BUTTON_POSITION_LEFT);
639
640
641
642
            }
        }
    }

643
644
645
646
647
648
649
650
    /**
     * Creates the listing of records from a single table
     *
     * @param string $table Table name
     * @param int $id Page id
     * @throws \UnexpectedValueException
     * @return string HTML table with the listing for the record.
     */
651
    public function getTable($table, $id)
652
    {
653
654
        // Finding the total amount of records on the page
        $queryBuilderTotalItems = $this->getQueryBuilder($table, $id, [], ['*'], false, 0, 1);
655
        $totalItems = (int)$queryBuilderTotalItems->count('*')
656
657
            ->execute()
            ->fetchColumn();
658
        if ($totalItems === 0) {
659
660
            return '';
        }
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
        // set the limits
        // Use default value and overwrite with page ts config and tca config depending on the current view
        // Force limit in range 5, 10000

        // default 100
        $itemsLimitSingleTable = MathUtility::forceIntegerInRange((int)(
            $GLOBALS['TCA'][$table]['interface']['maxSingleDBListItems'] ??
            $this->modTSconfig['properties']['itemsLimitSingleTable'] ??
            100
        ), 5, 10000);

        // default 20
        $itemsLimitPerTable = MathUtility::forceIntegerInRange((int)(
            $GLOBALS['TCA'][$table]['interface']['maxDBListItems'] ??
            $this->modTSconfig['properties']['itemsLimitPerTable'] ??
            20
        ), 5, 10000);

        // Set limit depending on the view (single table vs. default)
680
        $iLimit = $this->table ? $itemsLimitSingleTable : $itemsLimitPerTable;
681
682
683

        // Set limit from search
        if ($this->showLimit) {
684
            $iLimit = $this->showLimit;
685
686
687
688
        }

        // csv export - set no limit at all
        if ($this->csvOutput) {
689
            $iLimit = 0;
690
        }
691

692
693
694
695
696
697
698
        // Init
        $titleCol = $GLOBALS['TCA'][$table]['ctrl']['label'];
        $l10nEnabled = $GLOBALS['TCA'][$table]['ctrl']['languageField']
            && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];

        // Setting fields selected in fieldselectBox (saved in uc)
        $rowListArray = [];
699
        if ($this->allFields && is_array($this->setFields[$table] ?? null)) {
700
701
702
703
704
            $rowListArray = $this->makeFieldList($table, false, true);
            if ($this->csvOutput === false) {
                $rowListArray[] = '_PATH_';
                $rowListArray[] = '_REF_';
            }
705
            $rowListArray = array_intersect($rowListArray, $this->setFields[$table]);
706
        }
707
708
        // if no columns have been specified, show description (if configured)
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['descriptionColumn']) && empty($rowListArray)) {
709
            $rowListArray[] = $GLOBALS['TCA'][$table]['ctrl']['descriptionColumn'];
710
711
712
        }
        $backendUser = $this->getBackendUserAuthentication();
        $lang = $this->getLanguageService();
713
714
715
716
717
        // Get configuration of collapsed tables from user uc
        $tablesCollapsed = is_array($backendUser->uc['moduleData']['list'])
            ? $backendUser->uc['moduleData']['list']
            : [];
        $tableCollapsed = (bool)($tablesCollapsed[$table] ?? false);
718
719
        // prepare space icon
        $this->spaceIcon = '<span class="btn btn-default disabled">' . $this->iconFactory->getIcon('empty-empty', Icon::SIZE_SMALL)->render() . '</span>';
720
        // Place the $titleCol as the first column always!
721
        $this->fieldArray = [];
722
723
        // Add title column
        $this->fieldArray[] = $titleCol;
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
        if ($this->csvOutput === false) {
            // Control-Panel
            if ($this->noControlPanels === false) {
                $this->fieldArray[] = '_CONTROL_';
            }
            // Clipboard
            if ($this->showClipboard && $this->noControlPanels === false) {
                $this->fieldArray[] = '_CLIPBOARD_';
            }
            // Ref
            if (!in_array('_REF_', $rowListArray, true) && !$this->dontShowClipControlPanels) {
                $this->fieldArray[] = '_REF_';
            }
            // Path
            if (!in_array('_PATH_', $rowListArray, true) && $this->searchLevels) {
                $this->fieldArray[] = '_PATH_';
            }
            // Localization
            if ($l10nEnabled) {
                $this->fieldArray[] = '_LOCALIZATION_';
                // Do not show the "Localize to:" field when only translated records should be shown
                if (!$this->showOnlyTranslatedRecords) {
                    $this->fieldArray[] = '_LOCALIZATION_b';
                }
748
            }
749
750
751
752
753
754
755
        }
        // Cleaning up:
        $this->fieldArray = array_unique(array_merge($this->fieldArray, $rowListArray));
        // Creating the list of fields to include in the SQL query:
        $selectFields = $this->fieldArray;
        $selectFields[] = 'uid';
        $selectFields[] = 'pid';
756
        if ($table === 'pages') {
757
758
759
760
761
762
763
764
765
766
767
            $selectFields[] = 'module';
            $selectFields[] = 'extendToSubpages';
            $selectFields[] = 'nav_hide';
            $selectFields[] = 'doktype';
            $selectFields[] = 'shortcut';
            $selectFields[] = 'shortcut_mode';
            $selectFields[] = 'mount_pid';
        }
        if (is_array($GLOBALS['TCA'][$table]['ctrl']['enablecolumns'])) {
            $selectFields = array_merge($selectFields, $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']);
        }
768
        foreach (['type', 'typeicon_column', 'editlock'] as $field) {
769
770
771
772
            if ($GLOBALS['TCA'][$table]['ctrl'][$field]) {
                $selectFields[] = $GLOBALS['TCA'][$table]['ctrl'][$field];
            }
        }
773
        if (BackendUtility::isTableWorkspaceEnabled($table)) {
774
775
            $selectFields[] = 't3ver_state';
            $selectFields[] = 't3ver_wsid';
776
            $selectFields[] = 't3ver_oid';
777
778
779
780
781
782
783
784
785
786
787
788
789
        }
        if ($l10nEnabled) {
            $selectFields[] = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
            $selectFields[] = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
        }
        if ($GLOBALS['TCA'][$table]['ctrl']['label_alt']) {
            $selectFields = array_merge(
                $selectFields,
                GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], true)
            );
        }
        // Unique list!
        $selectFields = array_unique($selectFields);
790
        $fieldListFields = $this->makeFieldList($table, true);
791
792
        // Making sure that the fields in the field-list ARE in the field-list from TCA!
        $selectFields = array_intersect($selectFields, $fieldListFields);
793

794
795
        // Implode it into a list of fields for the SQL-statement.
        $selFieldList = implode(',', $selectFields);
796

797
        if ($this->firstElementNumber > 2 && $iLimit > 0) {
798
            // Get the two previous rows for sorting if displaying page > 1
Georg Ringer's avatar
Georg Ringer committed
799
            $this->firstElementNumber -= 2;
800
801
            $iLimit += 2;
            $queryBuilder = $this->getQueryBuilder($table, $id, [], array_values($selectFields), true, $this->firstElementNumber, $iLimit);
Georg Ringer's avatar
Georg Ringer committed
802
            $this->firstElementNumber += 2;
803
            $iLimit -= 2;
804
        } else {
805
            $queryBuilder = $this->getQueryBuilder($table, $id, [], array_values($selectFields), true, $this->firstElementNumber, $iLimit);
806
807
808
        }

        // Init:
809
        $queryResult = $queryBuilder->execute();
810
811
812
813
814
815
        $dbCount = 0;
        $out = '';
        $tableHeader = '';
        $listOnlyInSingleTableMode = $this->listOnlyInSingleTableMode && !$this->table;
        // If the count query returned any number of records, we perform the real query,
        // selecting records.
816
        if ($totalItems) {
817
818
            // Fetch records only if not in single table mode
            if ($listOnlyInSingleTableMode) {
819
                $dbCount = $totalItems;
820
821
822
            } else {
                // Set the showLimit to the number of records when outputting as CSV
                if ($this->csvOutput) {
823
824
825
                    $this->showLimit = $totalItems;
                    $iLimit = $totalItems;
                    $dbCount = $totalItems;
826
                } else {
827
                    if ($this->firstElementNumber + $this->showLimit <= $totalItems) {
828
829
                        $dbCount = $this->showLimit + 2;
                    } else {
830
                        $dbCount = $totalItems - $this->firstElementNumber + 2;
831
                    }
832
833
834
835
836
                }
            }
        }
        // If any records was selected, render the list:
        if ($dbCount) {
837
            $tableIdentifier = $table;
838
839
            // Use a custom table title for translated pages
            if ($table == 'pages' && $this->showOnlyTranslatedRecords) {
840
841
842
843
                // pages records in list module are split into two own sections, one for pages with
                // sys_language_uid = 0 "Page" and an own section for sys_language_uid > 0 "Page Translation".
                // This if sets the different title for the page translation case and a unique table identifier
                // which is used in DOM as id.
844
                $tableTitle = htmlspecialchars($lang->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:pageTranslation'));
845
                $tableIdentifier = 'pages_translated';
846
847
848
849
850
            } else {
                $tableTitle = htmlspecialchars($lang->sL($GLOBALS['TCA'][$table]['ctrl']['title']));
                if ($tableTitle === '') {
                    $tableTitle = $table;
                }
851
852
            }
            // Header line is drawn
853
            $theData = [];
854
855
            if ($this->disableSingleTableView) {
                $theData[$titleCol] = '<span class="c-table">' . BackendUtility::wrapInHelp($table, '', $tableTitle)
856
                    . '</span> (<span class="t3js-table-total-items">' . $totalItems . '</span>)';
857
858
            } else {
                $icon = $this->table
859
860
                    ? '<span title="' . htmlspecialchars($lang->getLL('contractView')) . '">' . $this->iconFactory->getIcon('actions-view-table-collapse', Icon::SIZE_SMALL)->render() . '</span>'
                    : '<span title="' . htmlspecialchars($lang->getLL('expandView')) . '">' . $this->iconFactory->getIcon('actions-view-table-expand', Icon::SIZE_SMALL)->render() . '</span>';
861
                $theData[$titleCol] = $this->linkWrapTable($table, $tableTitle . ' (<span class="t3js-table-total-items">' . $totalItems . '</span>) ' . $icon);
862
863
864
865
866
            }
            if ($listOnlyInSingleTableMode) {
                $tableHeader .= BackendUtility::wrapInHelp($table, '', $theData[$titleCol]);
            } else {
                // Render collapse button if in multi table mode
867
                $collapseButton = '';
868
869
                if (!$this->table) {
                    $icon = '<span class="collapseIcon">' . $this->iconFactory->getIcon(($tableCollapsed ? 'actions-view-list-expand' : 'actions-view-list-collapse'), Icon::SIZE_SMALL)->render() . '</span>';
870
871
872
873
874
                    $collapseButton = '<button type="button"'
                        . ' class="btn btn-default btn-sm pull-right t3js-toggle-recordlist"'
                        . ' aria-expanded="' . ($tableCollapsed ? 'false' : 'true') . '"'
                        . ' aria-label="' . sprintf(htmlspecialchars($lang->getLL('collapseExpandTable')), $tableTitle) . '"'
                        . ' data-table="' . htmlspecialchars($tableIdentifier) . '"'
875
876
                        . ' data-bs-toggle="collapse"'
                        . ' data-bs-target="#recordlist-' . htmlspecialchars($tableIdentifier) . '">'
877
878
                        . $icon
                        . '</button>';
879
                }
880
                $tableHeader .= $theData[$titleCol] . $collapseButton;
881
882
883
884
885
            }
            // Render table rows only if in multi table view or if in single table view
            $rowOutput = '';
            if (!$listOnlyInSingleTableMode || $this->table) {
                // Fixing an order table for sortby tables
886
887
                $this->currentTable = [];
                $currentIdList = [];
888
889
890
891
                $doSort = $GLOBALS['TCA'][$table]['ctrl']['sortby'] && !$this->sortField;
                $prevUid = 0;
                $prevPrevUid = 0;
                // Get first two rows and initialize prevPrevUid and prevUid if on page > 1
892
                if ($this->firstElementNumber > 2 && $iLimit > 0) {
893
                    $row = $queryResult->fetch();
894
                    $prevPrevUid = -((int)$row['uid']);
895
                    $row = $queryResult->fetch();
896
897
                    $prevUid = $row['uid'];
                }
898
                $accRows = [];
899
                // Accumulate rows here
900
                while ($row = $queryResult->fetch()) {
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
                    if (!$this->isRowListingConditionFulfilled($table, $row)) {
                        continue;
                    }
                    // In offline workspace, look for alternative record:
                    BackendUtility::workspaceOL($table, $row, $backendUser->workspace, true);
                    if (is_array($row)) {
                        $accRows[] = $row;
                        $currentIdList[] = $row['uid'];
                        if ($doSort) {
                            if ($prevUid) {
                                $this->currentTable['prev'][$row['uid']] = $prevPrevUid;
                                $this->currentTable['next'][$prevUid] = '-' . $row['uid'];
                                $this->currentTable['prevUid'][$row['uid']] = $prevUid;
                            }
                            $prevPrevUid = isset($this->currentTable['prev'][$row['uid']]) ? -$prevUid : $row['pid'];
                            $prevUid = $row['uid'];
                        }
                    }
                }
                // CSV initiated
                if ($this->csvOutput) {
922
                    $this->addHeaderRowToCSV();
923
924
                }
                // Render items:
925
926
                $this->CBnames = [];
                $this->duplicateStack = [];
927
928
929
                $cc = 0;
                foreach ($accRows as $row) {
                    // Render item row if counter < limit
930
                    if ($cc < $iLimit) {
931
                        $cc++;
932
933
                        // Reset translations
                        $translations = [];
934
935
936
937
938
                        // Initialize with FALSE which causes the localization panel to not beeing displayed as
                        // the record is already localized, in free mode or has sys_language_uid -1 set.
                        // Only set to TRUE if TranslationConfigurationProvider::translationInfo() returns
                        // an array indicating the record can be translated.
                        $translationEnabled = false;
939
940
941
942
                        // Guard clause so we can quickly return if a record is localized to "all languages"
                        // It should only be possible to localize a record off default (uid 0)
                        if ($l10nEnabled && (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']] !== -1) {
                            $translationsRaw = $this->translateTools->translationInfo($table, $row['uid'], 0, $row, $selFieldList);
943
944
945
946
947
                            if (is_array($translationsRaw)) {
                                $translationEnabled = true;
                                if (is_array($translationsRaw['translations'])) {
                                    $translations = $translationsRaw['translations'];
                                }
948
949
                            }
                        }
950
                        $rowOutput .= $this->renderListRow($table, $row, $cc, $titleCol, '', 0, $translations, $translationEnabled);
951
                        // If no search happened it means that the selected
952
                        // records are either default or All language and here we will not select translations
953
                        // which point to the main record:
954
                        if ($l10nEnabled && $this->searchString === '' && !($this->hideTranslations === '*' || GeneralUtility::inList($this->hideTranslations, $table))) {
955
956
957
958
959
960
961
962
                            foreach ($translations as $lRow) {
                                if (!$this->isRowListingConditionFulfilled($table, $lRow)) {
                                    continue;
                                }
                                // In offline workspace, look for alternative record:
                                BackendUtility::workspaceOL($table, $lRow, $backendUser->workspace, true);
                                if (is_array($lRow) && $backendUser->checkLanguageAccess($lRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
                                    $currentIdList[] = $lRow['uid'];
963
                                    $rowOutput .= $this->renderListRow($table, $lRow, $cc, $titleCol, '', 18, [], false);
964
965
966
967
968
969
970
971
                                }
                            }
                        }
                    }
                }
                // Record navigation is added to the beginning and end of the table if in single
                // table mode
                if ($this->table) {
972
                    $rowOutput = $this->renderListNavigation('top', $totalItems, $iLimit, (string)$table) . $rowOutput . $this->renderListNavigation('bottom', $totalItems, $iLimit, (string)$table);
973
974
                } else {
                    // Show that there are more records than shown
975
976
977
                    if ($totalItems > $itemsLimitPerTable) {
                        $countOnFirstPage = $totalItems > $itemsLimitSingleTable ? $itemsLimitSingleTable : $totalItems;
                        $hasMore = $totalItems > $itemsLimitSingleTable;
978
                        $colspan =  (count($this->fieldArray) + 1);
979
                        $rowOutput .= '<tr><td colspan="' . $colspan . '">
980
								<a href="' . htmlspecialchars($this->listURL() . '&table=' . rawurlencode($tableIdentifier)) . '" class="btn btn-default">'
981
                            . '<span class="t3-icon fa fa-chevron-down"></span> <i>[1 - ' . $countOnFirstPage . ($hasMore ? '+' : '') . ']</i></a>
982
								</td></tr>';
983
984
985
986
987
                    }
                }
                // The header row for the table is now created:
                $out .= $this->renderListHeader($table, $currentIdList);
            }
988

989
            $collapseClass = $tableCollapsed && !$this->table ? 'collapse' : 'collapse show';
990
            $dataState = $tableCollapsed && !$this->table ? 'collapsed' : 'expanded';
991

992
993
994
995
            // The list of records is added after the header:
            $out .= $rowOutput;
            // ... and it is all wrapped in a table:
            $out = '
996
997
998
999



			<!--
1000
				DB listing of elements:	"' . htmlspecialchars($tableIdentifier) . '"
1001
			-->
1002
				<div class="panel panel-space panel-default recordlist">
1003
1004
1005
					<div class="panel-heading">
					' . $tableHeader . '
					</div>
1006
					<div class="' . $collapseClass . '" data-state="' . $dataState . '" id="recordlist-' . htmlspecialchars($tableIdentifier) . '">
1007
						<div class="table-fit">
1008
							<table data-table="' . htmlspecialchars($tableIdentifier) . '" class="table table-striped table-hover' . ($listOnlyInSingleTableMode ? ' typo3-dblist-overview' : '') . '">
1009
1010
1011
								' . $out . '
							</table>
						</div>
1012
1013
1014
					</div>
				</div>
			';
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
            // Output csv if...
            // This ends the page with exit.
            if ($this->csvOutput) {
                $this->outputCSV($table);
            }
        }
        // Return content:
        return $out;
    }

1025
1026
1027
1028
1029
1030
    /**
     * Get viewOnClick link for pages or tt_content records
     *
     * @param string $table
     * @param array $row
     *
1031
     * @return PreviewUriBuilder
1032
     */
1033
    protected function getPreviewUriBuilder(string $table, array $row): PreviewUriBuilder
1034
1035
    {
        if ($table === 'tt_content') {
1036
1037
1038
1039
1040
1041
            // Link to a content element, possibly translated and with anchor
            $additionalParams = '';
            $language = (int)$row[$GLOBALS['TCA']['tt_content']['ctrl']['languageField']];
            if ($language > 0) {
                $additionalParams = '&L=' . $language;
            }
1042
1043
1044
            $previewUriBuilder = PreviewUriBuilder::create((int)$this->id)
                ->withSection('#c' . $row['uid'])
                ->withAdditionalQueryParameters($additionalParams);
1045
        } elseif ($table === 'pages' && $row[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']] > 0) {
1046
            // Link to a page translation needs uid of default language page as id
1047
1048
1049
1050
1051
            $languageParentId = (int)$row[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']];
            $language = (int)$row[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
            $previewUriBuilder = PreviewUriBuilder::create($languageParentId)
                ->withSection('#c' . $row['uid'])
                ->withAdditionalQueryParameters('&L=' . $language);
1052
1053
        } else {
            // Link to a page in the default language
1054
            $previewUriBuilder = PreviewUriBuilder::create((int)$row['uid']);
1055
        }
1056
        return $previewUriBuilder;
1057
1058
    }

1059
1060
1061
    /**
     * Check if all row listing conditions are fulfilled.
     *
1062
     * This function serves as a dummy method to be overridden in extending classes.
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
     *
     * @param string $table Table name
     * @param string[] $row Record
     * @return bool True, if all conditions are fulfilled.
     */
    protected function isRowListingConditionFulfilled($table, $row)
    {
        return true;
    }

    /**
     * Rendering a single row for the list
     *
     * @param string $table Table name
     * @param mixed[] $row Current record
     * @param int $cc Counter, counting for each time an element is rendered (used for alternating colors)
     * @param string $titleCol Table field (column) where header value is found
     * @param string $thumbsCol Table field (column) where (possible) thumbnails can be found
     * @param int $indent Indent from left.
1082
1083
     * @param array $translations Array of already existing translations for the current record
     * @param bool $translationEnabled Whether the record can be translated
1084
     * @return string Table row for the element
1085
     * @internal
1086
1087
     * @see getTable()
     */
1088
    public function renderListRow($table, $row, $cc, $titleCol, $thumbsCol, $indent, array $translations, bool $translationEnabled)
1089
1090
1091
1092
    {
        if (!is_array($row)) {
            return '';
        }
1093
        $languageService = $this->getLanguageService();
1094
1095
1096
1097
1098
1099
1100
        $rowOutput = '';
        $id_orig = null;
        // If in search mode, make sure the preview will show the correct page
        if ((string)$this->searchString !== '') {
            $id_orig = $this->id;
            $this->id = $row['pid'];
        }
1101
1102

        $tagAttributes = [
1103
            'class' => [],
1104
            'data-table' => $table,
1105
            'title' => 'id=' . $row['uid'],
1106
1107
        ];

1108
1109
1110
1111
1112
1113
1114
1115
        // Add active class to record of current link
        if (
            isset($this->currentLink['tableNames'])
            && (int)$this->currentLink['uid'] === (int)$row['uid']
            && GeneralUtility::inList($this->currentLink['tableNames'], $table)
        ) {
            $tagAttributes['class'][] = 'active';
        }
1116
        // Overriding with versions background color if any:
1117
1118
1119
        if (!empty($row['_CSSCLASS'])) {
            $tagAttributes['class'] = [$row['_CSSCLASS']];
        }
1120
1121
1122

        $tagAttributes['class'][] = 't3js-entity';

1123
        // The icon with link
1124
        $toolTip = BackendUtility::getRecordToolTip($row, $table);
1125
        $additionalStyle = $indent ? ' style="margin-left: ' . $indent . 'px;"' : '';
1126
        $iconImg = '<span ' . $toolTip . ' ' . $additionalStyle . '>'
1127
1128
            . $this->iconFactory->getIconForRecord($table, $row, Icon::SIZE_SMALL)->render()
            . '</span>';
1129
        $theIcon = ($this->clickMenuEnabled && !$this->isRecordDeletePlaceholder($row)) ? BackendUtility::wrapClickMenuOnIcon($iconImg, $table, $row['uid']) : $iconImg;
1130
        // Preparing and getting the data-array
1131
        $theData = [];
1132
        $deletePlaceholderClass = '';
1133
1134
1135
1136
1137
1138
1139
        foreach ($this->fieldArray as $fCol) {
            if ($fCol == $titleCol) {
                $recTitle = BackendUtility::getRecordTitle($table, $row, false, true);
                $warning = '';
                // If the record is edit-locked	by another user, we will show a little warning sign:
                $lockInfo = BackendUtility::isRecordLocked($table, $row['uid']);
                if ($lockInfo) {
1140
                    $warning = '<span data-bs-toggle="tooltip" data-bs-placement="right" data-title="' . htmlspecialchars($lockInfo['msg']) . '">'
1141
                        . $this->iconFactory->getIcon('warning-in-use', Icon::SIZE_SMALL)->render() . '</span>';
1142
                }
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
                if ($this->isRecordDeletePlaceholder($row)) {
                    // Delete placeholder records do not link to formEngine edit and are rendered strike-through
                    $deletePlaceholderClass = ' deletePlaceholder';
                    $theData[$fCol] = $theData['__label'] =
                        $warning
                        . '<span title="' . htmlspecialchars($languageService->sL('LLL:EXT:recordlist/Resources/Private/Language/locallang.xlf:row.deletePlaceholder.title')) . '">'
                            . htmlspecialchars($recTitle)
                        . '</span>';
                } else {
                    $theData[$fCol] = $theData['__label'] = $warning . $this->linkWrapItems($table, $row['uid'], $recTitle, $row);
                }
1154
            } elseif ($fCol === 'pid') {
1155
                $theData[$fCol] = $row[$fCol];
1156
1157
1158
1159
1160
1161
1162
1163
1164
            } elseif ($fCol !== '' && $fCol === ($GLOBALS['TCA'][$table]['ctrl']['cruser_id'] ?? '')) {
                $beUserRecord = BackendUtility::getRecord('be_users', (