RecordProvider.php 21.6 KB
Newer Older
1
<?php
2
declare(strict_types = 1);
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace TYPO3\CMS\Backend\ContextMenu\ItemProviders;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * 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.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

18
use TYPO3\CMS\Backend\Routing\UriBuilder;
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Type\Bitmask\JsConfirmation;
use TYPO3\CMS\Core\Type\Bitmask\Permission;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Versioning\VersionState;

/**
 * Class responsible for providing click menu items for db records which don't have custom provider (as e.g. pages)
 */
class RecordProvider extends AbstractProvider
{
    /**
     * Database record
     *
     * @var array
     */
    protected $record = [];

    /**
     * Database record of the page $this->record is placed on
     *
     * @var array
     */
    protected $pageRecord = [];

    /**
     * Local cache for the result of BackendUserAuthentication::calcPerms()
     *
     * @var int
     */
    protected $pagePermissions = 0;

    /**
     * @var array
     */
    protected $itemsConfiguration = [
        'view' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.view',
57
            'iconIdentifier' => 'actions-view',
58
59
60
61
62
63
64
65
66
            'callbackAction' => 'viewRecord'
        ],
        'edit' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.edit',
            'iconIdentifier' => 'actions-open',
            'callbackAction' => 'editRecord'
        ],
        'new' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.new',
67
            'iconIdentifier' => 'actions-add',
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
            'callbackAction' => 'newRecord'
        ],
        'info' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.info',
            'iconIdentifier' => 'actions-document-info',
            'callbackAction' => 'openInfoPopUp'
        ],
        'divider1' => [
            'type' => 'divider'
        ],
        'copy' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.copy',
            'iconIdentifier' => 'actions-edit-copy',
            'callbackAction' => 'copy'
        ],
        'copyRelease' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.copy',
            'iconIdentifier' => 'actions-edit-copy-release',
            'callbackAction' => 'clipboardRelease'
        ],
        'cut' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.cut',
            'iconIdentifier' => 'actions-edit-cut',
            'callbackAction' => 'cut'
        ],
        'cutRelease' => [
94
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.cutrelease',
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
            'iconIdentifier' => 'actions-edit-cut-release',
            'callbackAction' => 'clipboardRelease'
        ],
        'pasteAfter' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.pasteafter',
            'iconIdentifier' => 'actions-document-paste-after',
            'callbackAction' => 'pasteAfter'
        ],
        'divider2' => [
            'type' => 'divider'
        ],
        'more' => [
            'type' => 'submenu',
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.more',
            'iconIdentifier' => '',
            'callbackAction' => 'openSubmenu',
            'childItems' => [
                'newWizard' => [
                    'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:CM_newWizard',
114
                    'iconIdentifier' => 'actions-add',
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
                    'callbackAction' => 'newContentWizard',
                ],
                'openListModule' => [
                    'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:CM_db_list',
                    'iconIdentifier' => 'actions-system-list-open',
                    'callbackAction' => 'openListModule',
                ],
            ],
        ],
        'divider3' => [
            'type' => 'divider'
        ],
        'enable' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:enable',
            'iconIdentifier' => 'actions-edit-unhide',
            'callbackAction' => 'enableRecord',
        ],
        'disable' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_common.xlf:disable',
            'iconIdentifier' => 'actions-edit-hide',
            'callbackAction' => 'disableRecord',
        ],
        'delete' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:cm.delete',
            'iconIdentifier' => 'actions-edit-delete',
            'callbackAction' => 'deleteRecord',
        ],
        'history' => [
            'label' => 'LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:CM_history',
            'iconIdentifier' => 'actions-document-history-open',
            'callbackAction' => 'openHistoryPopUp',
        ],
    ];

    /**
     * Whether this provider should kick in
     *
     * @return bool
     */
    public function canHandle(): bool
    {
        if (in_array($this->table, ['sys_file', 'sys_filemounts', 'sys_file_storage', 'pages'], true)
            || strpos($this->table, '-drag') !== false) {
            return false;
        }
        return isset($GLOBALS['TCA'][$this->table]);
    }

    /**
     * Initialize db record
     */
    protected function initialize()
    {
        parent::initialize();
        $this->record = BackendUtility::getRecordWSOL($this->table, $this->identifier);
170
        $this->initPermissions();
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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
    }

    /**
     * Priority is set to lower then default value, in order to skip this provider if there is less generic provider available.
     *
     * @return int
     */
    public function getPriority(): int
    {
        return 60;
    }

    /**
     * This provider works as a fallback if there is no provider dedicated for certain table, thus it's only kicking in when $items are empty.
     *
     * @param array $items
     * @return array
     */
    public function addItems(array $items): array
    {
        if (!empty($items)) {
            return $items;
        }
        $this->initialize();
        return $this->prepareItems($this->itemsConfiguration);
    }

    /**
     * Whether a given item can be rendered (e.g. user has enough permissions)
     *
     * @param string $itemName
     * @param string $type
     * @return bool
     */
    protected function canRender(string $itemName, string $type): bool
    {
        if (in_array($type, ['divider', 'submenu'], true)) {
            return true;
        }
        if (in_array($itemName, $this->disabledItems, true)) {
            return false;
        }
        $canRender = false;
        switch ($itemName) {
            case 'view':
                $canRender = $this->canBeViewed();
                break;
            case 'edit':
            case 'new':
                $canRender = $this->canBeEdited();
                break;
            case 'newWizard':
                $canRender = $this->canOpenNewCEWizard();
                break;
            case 'info':
                $canRender = $this->canShowInfo();
                break;
            case 'enable':
                $canRender = $this->canBeEnabled();
                break;
            case 'disable':
                $canRender = $this->canBeDisabled();
                break;
            case 'delete':
                $canRender = $this->canBeDeleted();
                break;
            case 'history':
                $canRender = $this->canShowHistory();
                break;
            case 'openListModule':
                $canRender = $this->canOpenListModule();
                break;
            case 'copy':
                $canRender = $this->canBeCopied();
                break;
            case 'copyRelease':
                $canRender = $this->isRecordInClipboard('copy');
                break;
            case 'cut':
                $canRender = $this->canBeCut();
                break;
            case 'cutRelease':
                $canRender = $this->isRecordInClipboard('cut');
                break;
            case 'pasteAfter':
                $canRender = $this->canBePastedAfter();
                break;
        }
        return $canRender;
    }

    /**
     * Saves calculated permissions for a page containing given record, to speed things up
     */
    protected function initPermissions()
    {
        $this->pageRecord = BackendUtility::getRecord('pages', $this->record['pid']);
        $this->pagePermissions = $this->backendUser->calcPerms($this->pageRecord);
    }

    /**
     * Returns true if a current user have access to given permission
     *
     * @see BackendUserAuthentication::doesUserHaveAccess()
     * @param int $permission
     * @return bool
     */
    protected function hasPagePermission(int $permission): bool
    {
        return $this->backendUser->isAdmin() || ($this->pagePermissions & $permission) == $permission;
    }

    /**
     * Additional attributes for JS
     *
     * @param string $itemName
     * @return array
     */
    protected function getAdditionalAttributes(string $itemName): array
    {
        $attributes = [];
        if ($itemName === 'view') {
            $attributes += $this->getViewAdditionalAttributes();
        }
        if ($itemName === 'newWizard' && $this->table === 'tt_content') {
            $tsConfig = BackendUtility::getModTSconfig($this->record['pid'], 'mod');
297
            $moduleName = $tsConfig['properties']['newContentElementWizard.']['override'] ?? 'new_content_element_wizard';
298
299
300
301
302
303
            $urlParameters = [
                'id' => $this->record['pid'],
                'sys_language_uid' => $this->record['sys_language_uid'],
                'colPos' => $this->record['colPos'],
                'uid_pid' => -$this->record['uid']
            ];
304
305
            $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
            $url = (string)$uriBuilder->buildUriFromRoute($moduleName, $urlParameters);
306
307
308
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
            $attributes += [
                'data-new-wizard-url' => htmlspecialchars($url)
            ];
        }
        if ($itemName === 'delete') {
            $attributes += $this->getDeleteAdditionalAttributes();
        }
        if ($itemName === 'openListModule') {
            $attributes += [
                'data-page-uid' => $this->record['pid']
            ];
        }
        if ($itemName === 'pasteAfter') {
            $attributes += $this->getPasteAdditionalAttributes('after');
        }
        return $attributes;
    }

    /**
     * Additional attributes for the 'view' item
     *
     * @return array
     */
    protected function getViewAdditionalAttributes(): array
    {
        $attributes = [];
        $viewLink = $this->getViewLink();
        if ($viewLink) {
            $attributes += [
                'data-preview-url' => htmlspecialchars($viewLink),
            ];
        }
        return $attributes;
    }

    /**
     * Additional attributes for the pasteInto and pasteAfter items
     *
     * @param string $type "after" or "into"
     * @return array
     */
    protected function getPasteAdditionalAttributes(string $type): array
    {
        $attributes = [];
        if ($this->backendUser->jsConfirmation(JsConfirmation::COPY_MOVE_PASTE)) {
            $selItem = $this->clipboard->getSelectedRecord();
            $title = $this->languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_mod_web_list.xlf:clip_paste');

            $confirmMessage = sprintf(
                $this->languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:mess.'
                    . ($this->clipboard->currentMode() === 'copy' ? 'copy' : 'move') . '_' . $type),
                GeneralUtility::fixed_lgd_cs($selItem['_RECORD_TITLE'], $this->backendUser->uc['titleLen']),
                GeneralUtility::fixed_lgd_cs(BackendUtility::getRecordTitle($this->table, $this->record), $this->backendUser->uc['titleLen'])
            );
            $attributes += [
                'data-title' => htmlspecialchars($title),
                'data-message' => htmlspecialchars($confirmMessage)
            ];
        }
        return $attributes;
    }

    /**
     * Additional data for a "delete" action (confirmation modal title and message)
     *
     * @return array
     */
    protected function getDeleteAdditionalAttributes(): array
    {
        $attributes = [];
        if ($this->backendUser->jsConfirmation(JsConfirmation::DELETE)) {
            $recordTitle = GeneralUtility::fixed_lgd_cs(BackendUtility::getRecordTitle($this->table, $this->record), $this->backendUser->uc['titleLen']);

            $title = $this->languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_mod_web_list.xlf:delete');
            $confirmMessage = sprintf(
                $this->languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:mess.delete'),
                $recordTitle
            );
            $confirmMessage .= BackendUtility::referenceCount(
                $this->table,
                $this->record['uid'],
                ' ' . $this->languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.referencesToRecord')
            );
            $confirmMessage .= BackendUtility::translationCount(
                $this->table,
                $this->record['uid'],
                ' ' . $this->languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.translationsOfRecord')
            );
            $attributes += [
                'data-title' => htmlspecialchars($title),
                'data-message' => htmlspecialchars($confirmMessage)
            ];
        }
        return $attributes;
    }

    /**
     * Returns id of the Page used for preview
     *
     * @return int
     */
    protected function getPreviewPid(): int
    {
        return (int)$this->record['pid'];
    }

    /**
     * Returns the view link
     *
     * @return string
     */
    protected function getViewLink(): string
    {
419
420
421
422
423
424
425
426
427
        $anchorSection = '';
        $additionalParams = '';
        if ($this->table === 'tt_content') {
            $anchorSection = '#c' . $this->record['uid'];
            $language = (int)$this->record[$GLOBALS['TCA']['tt_content']['ctrl']['languageField']];
            if ($language > 0) {
                $additionalParams = '&L=' . $language;
            }
        }
428
429
430
431
        $javascriptLink = BackendUtility::viewOnClick(
            $this->getPreviewPid(),
            '',
            null,
432
433
434
            $anchorSection,
            '',
            $additionalParams
435
        );
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
        $extractedLink = '';
        if (preg_match('/window\\.open\\(\'([^\']+)\'/i', $javascriptLink, $match)) {
            // Clean JSON-serialized ampersands ('&')
            // @see GeneralUtility::quoteJSvalue()
            $extractedLink = json_decode('"' . trim($match[1], '"') . '"');
        }
        return $extractedLink;
    }

    /**
     * Checks if the page is allowed to show info
     *
     * @return bool
     */
    protected function canShowInfo(): bool
    {
        return true;
    }

    /**
     * Checks if the page is allowed to show info
     *
     * @return bool
     */
    protected function canShowHistory(): bool
    {
        return true;
    }

    /**
     * Checks if the record can be previewed in frontend
     *
     * @return bool
     */
    protected function canBeViewed(): bool
    {
        return $this->table === 'tt_content';
    }

    /**
     * Whether a record can be edited
     *
     * @return bool
     */
    protected function canBeEdited(): bool
    {
        if (isset($GLOBALS['TCA'][$this->table]['ctrl']['readOnly']) && $GLOBALS['TCA'][$this->table]['ctrl']['readOnly']) {
            return false;
        }
        if ($this->backendUser->isAdmin()) {
            return true;
        }
        if (isset($GLOBALS['TCA'][$this->table]['ctrl']['adminOnly']) && $GLOBALS['TCA'][$this->table]['ctrl']['adminOnly']) {
            return false;
        }

        $access = !$this->isRecordLocked()
            && $this->backendUser->check('tables_modify', $this->table)
            && $this->hasPagePermission(Permission::CONTENT_EDIT);
        return $access;
    }

    /**
499
     * Checks if disableDelete flag is set in TSConfig for the current table
500
501
502
     *
     * @return bool
     */
503
    protected function isDeletionDisabledInTS(): bool
504
505
    {
        $disableDeleteTS = $this->backendUser->getTSConfig('options.disableDelete');
Christian Kuhn's avatar
Christian Kuhn committed
506
        $disableDelete = (bool)trim($disableDeleteTS['properties'][$this->table] ?? (string)$disableDeleteTS['value']);
507
508
509
510
511
512
513
514
515
516
517
        return $disableDelete;
    }

    /**
     * Checks if the user has the right to delete the page
     *
     * @return bool
     */
    protected function canBeDeleted(): bool
    {
        return !$this->isDeletionDisabledInTS() && $this->canBeEdited();
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
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
631
632
633
634
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
665
666
667
668
669
670
671
672
673
674
    }

    /**
     * Returns true if current record can be unhidden/enabled
     *
     * @return bool
     */
    protected function canBeEnabled(): bool
    {
        return $this->hasDisableColumnWithValue(1) && $this->canBeEdited();
    }

    /**
     * Returns true if current record can be hidden
     *
     * @return bool
     */
    protected function canBeDisabled(): bool
    {
        return $this->hasDisableColumnWithValue(0) && $this->canBeEdited();
    }

    /**
     * Returns true new content element wizard can be shown
     *
     * @return bool
     */
    protected function canOpenNewCEWizard(): bool
    {
        $tsConfig = BackendUtility::getModTSconfig($this->record['pid'], 'mod.web_layout');
        $wizardEnabled = true;
        if (isset($tsConfig['properties']['disableNewContentElementWizard'])) {
            $wizardEnabled = false;
        }
        return $this->table === 'tt_content' && $wizardEnabled && $this->canBeEdited();
    }

    /**
     * @return bool
     */
    protected function canOpenListModule(): bool
    {
        return $this->backendUser->check('modules', 'web_list');
    }

    /**
     * @return bool
     */
    protected function canBeCopied(): bool
    {
        return !$this->isRecordInClipboard('copy')
            && !$this->isRecordATranslation();
    }

    /**
     * @return bool
     */
    protected function canBeCut(): bool
    {
        return !$this->isRecordInClipboard('cut')
            && $this->canBeEdited()
            && !$this->isRecordATranslation();
    }

    /**
     * Paste after is only shown for records from the same table (comparing record in clipboard and record clicked)
     *
     * @return bool
     */
    protected function canBePastedAfter(): bool
    {
        $clipboardElementCount = count($this->clipboard->elFromTable($this->table));

        return $clipboardElementCount
            && $this->backendUser->check('tables_modify', $this->table)
            && $this->hasPagePermission(Permission::CONTENT_EDIT);
    }

    /**
     * Checks if table have "disable" column (e.g. "hidden"), if user has access to this column
     * and if it contains given value
     *
     * @param int $value
     * @return bool
     */
    protected function hasDisableColumnWithValue(int $value): bool
    {
        if (isset($GLOBALS['TCA'][$this->table]['ctrl']['enablecolumns']['disabled'])) {
            $hiddenFieldName = $GLOBALS['TCA'][$this->table]['ctrl']['enablecolumns']['disabled'];
            if (
                $hiddenFieldName !== '' && !empty($GLOBALS['TCA'][$this->table]['columns'][$hiddenFieldName]['exclude'])
                && $this->backendUser->check('non_exclude_fields', $this->table . ':' . $hiddenFieldName)
            ) {
                return (int)$this->record[$hiddenFieldName] === (int)$value;
            }
        }
        return false;
    }

    /**
     * Record is locked if page is locked or page is not locked but record is
     *
     * @return bool
     */
    protected function isRecordLocked(): bool
    {
        return (int)$this->pageRecord['editlock'] === 1
            || isset($GLOBALS['TCA'][$this->table]['ctrl']['editlock'])
            && (int)$this->record[$GLOBALS['TCA'][$this->table]['ctrl']['editlock']] === 1;
    }

    /**
     * Returns true is a current record is a delete placeholder
     *
     * @return bool
     */
    protected function isDeletePlaceholder(): bool
    {
        if (!isset($this->record['t3ver_state'])) {
            return false;
        }
        return VersionState::cast($this->record['t3ver_state'])->equals(VersionState::DELETE_PLACEHOLDER);
    }

    /**
     * Checks if current record is in the "normal" pad of the clipboard
     *
     * @param string $mode "copy", "cut" or '' for any mode
     * @return bool
     */
    protected function isRecordInClipboard(string $mode = ''): bool
    {
        $isSelected = '';
        if ($this->clipboard->current === 'normal') {
            $isSelected = $this->clipboard->isSelected($this->table, $this->record['uid']);
        }
        return $mode === '' ? !empty($isSelected) : $isSelected === $mode;
    }

    /**
     * Returns true is a record ia a translation
     *
     * @return bool
     */
    protected function isRecordATranslation(): bool
    {
        return BackendUtility::isTableLocalizable($this->table) && (int)$this->record[$GLOBALS['TCA'][$this->table]['ctrl']['transOrigPointerField']] !== 0;
    }

    /**
     * @return string
     */
    protected function getIdentifier(): string
    {
        return $this->record['uid'];
    }
}