ElementHistoryController.php 18.7 KB
Newer Older
1
2
3
<?php
namespace TYPO3\CMS\Backend\Controller\ContentElement;

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
20
use TYPO3\CMS\Backend\History\RecordHistory;
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
21
use TYPO3\CMS\Backend\Template\ModuleTemplate;
22
use TYPO3\CMS\Backend\Utility\BackendUtility;
23
use TYPO3\CMS\Core\History\RecordHistoryStore;
24
use TYPO3\CMS\Core\Imaging\Icon;
25
use TYPO3\CMS\Core\Utility\DiffUtility;
Nicole Cordes's avatar
Nicole Cordes committed
26
use TYPO3\CMS\Core\Utility\GeneralUtility;
27
use TYPO3\CMS\Fluid\View\StandaloneView;
Nicole Cordes's avatar
Nicole Cordes committed
28

29
/**
30
 * Controller for showing the history module of TYPO3s backend
Nicole Cordes's avatar
Nicole Cordes committed
31
 * @see \TYPO3\CMS\Backend\History\RecordHistory
32
 */
33
class ElementHistoryController
34
35
{
    /**
36
     * @var ServerRequestInterface
37
     */
38
    protected $request;
39
40

    /**
41
42
43
44
45
46
47
48
49
50
51
     * @var StandaloneView
     */
    protected $view;

    /**
     * @var RecordHistory
     */
    protected $historyObject;

    /**
     * Display diff or not (0-no diff, 1-inline)
52
     *
53
     * @var int
54
     */
55
    protected $showDiff = 1;
56
57
58
59

    /**
     * @var array
     */
60
    protected $recordCache = [];
61

62
63
64
65
66
67
68
    /**
     * ModuleTemplate object
     *
     * @var ModuleTemplate
     */
    protected $moduleTemplate;

69
70
71
72
73
    /**
     * Constructor
     */
    public function __construct()
    {
74
        $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
75
        $this->view = $this->initializeView();
76
77
78
79
80
81
82
83
84
85
86
87
    }

    /**
     * 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)
    {
88
89
        $this->request = $request;
        $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation([]);
90

91
92
93
94
95
        $lastHistoryEntry = (int)($request->getParsedBody()['historyEntry'] ?: $request->getQueryParams()['historyEntry']);
        $rollbackFields = $request->getParsedBody()['rollbackFields'] ?: $request->getQueryParams()['rollbackFields'];
        $element = $request->getParsedBody()['element'] ?: $request->getQueryParams()['element'];
        $displaySettings = $this->prepareDisplaySettings();
        $this->view->assign('currentSelection', $displaySettings);
96

97
        $this->showDiff = (int)$displaySettings['showDiff'];
98

99
        // Start history object
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
        $this->historyObject = GeneralUtility::makeInstance(RecordHistory::class, $element, $rollbackFields);
        $this->historyObject->setShowSubElements((int)$displaySettings['showSubElements']);
        $this->historyObject->setLastHistoryEntry($lastHistoryEntry);
        if ($displaySettings['maxSteps']) {
            $this->historyObject->setMaxSteps((int)$displaySettings['maxSteps']);
        }

        // Do the actual logic now (rollback, show a diff for certain changes,
        // or show the full history of a page or a specific record)
        $this->historyObject->createChangeLog();
        if (!empty($this->historyObject->changeLog)) {
            if ($this->historyObject->shouldPerformRollback()) {
                $this->historyObject->performRollback();
            } elseif ($lastHistoryEntry) {
                $completeDiff = $this->historyObject->createMultipleDiff();
                $this->displayMultipleDiff($completeDiff);
                $this->view->assign('showDifferences', true);
                $this->view->assign('fullViewUrl', $this->buildUrl(['historyEntry' => '']));
            }
            if ($this->historyObject->getElementData()) {
                $this->displayHistory($this->historyObject->changeLog);
            }
        }

        $elementData = $this->historyObject->getElementData();
        if ($elementData) {
            $this->setPagePath($elementData[0], $elementData[1]);
            // Get link to page history if the element history is shown
            if ($elementData[0] !== 'pages') {
                $this->view->assign('singleElement', true);
                $parentPage = BackendUtility::getRecord($elementData[0], $elementData[1], '*', '', false);
                if ($parentPage['pid'] > 0 && BackendUtility::readPageAccess($parentPage['pid'], $this->getBackendUser()->getPagePermsClause(1))) {
                    $this->view->assign('fullHistoryUrl', $this->buildUrl([
                        'element' => 'pages:' . $parentPage['pid'],
                        'historyEntry' => '',
                        'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
                    ]));
                }
            }
        }
140

141
        $this->view->assign('TYPO3_REQUEST_URI', GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'));
142

143
        // Setting up the buttons and markers for docheader
144
        $this->getButtons();
145
        // Build the <body> for the module
146
147
148
149
        $this->moduleTemplate->setContent($this->view->render());

        $response->getBody()->write($this->moduleTemplate->renderContent());
        return $response;
150
151
152
    }

    /**
153
     * Creates the correct path to the current record
154
     *
155
156
     * @param string $table
     * @param int $uid
157
     */
158
    protected function setPagePath($table, $uid)
159
    {
160
161
162
163
164
165
166
167
168
169
170
171
172
        $uid = (int)$uid;

        if ($table === 'pages') {
            $pageId = $uid;
        } else {
            $record = BackendUtility::getRecord($table, $uid, '*', '', false);
            $pageId = $record['pid'];
        }

        $pageAccess = BackendUtility::readPageAccess($pageId, $this->getBackendUser()->getPagePermsClause(1));
        if (is_array($pageAccess)) {
            $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($pageAccess);
        }
173
174
175
176
177
178
179
    }

    /**
     * Create the panel of buttons for submitting the form or otherwise perform operations.
     */
    protected function getButtons()
    {
180
181
182
183
184
185
186
        $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();

        $helpButton = $buttonBar->makeHelpButton()
            ->setModuleName('xMOD_csh_corebe')
            ->setFieldName('history_log');
        $buttonBar->addButton($helpButton);

187
        // Get returnUrl parameter
188
189
        $returnUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'));
        if ($returnUrl) {
190
191
            $backButton = $buttonBar->makeLinkButton()
                ->setHref($returnUrl)
192
                ->setTitle($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.closeDoc'))
193
194
                ->setIcon($this->moduleTemplate->getIconFactory()->getIcon('actions-view-go-back', Icon::SIZE_SMALL));
            $buttonBar->addButton($backButton, ButtonBar::BUTTON_POSITION_LEFT, 10);
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
297
298
299
300
301
302
303
304
305
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
    /**
     * Displays settings evaluation
     */
    protected function prepareDisplaySettings()
    {
        // Get current selection from UC, merge data, write it back to UC
        $currentSelection = is_array($this->getBackendUser()->uc['moduleData']['history'])
            ? $this->getBackendUser()->uc['moduleData']['history']
            : ['maxSteps' => '', 'showDiff' => 1, 'showSubElements' => 1];
        $currentSelectionOverride = $this->request->getParsedBody()['settings'] ? $this->request->getParsedBody()['settings'] : $this->request->getQueryParams()['settings'];
        if (is_array($currentSelectionOverride) && !empty($currentSelectionOverride)) {
            $currentSelection = array_merge($currentSelection, $currentSelectionOverride);
            $this->getBackendUser()->uc['moduleData']['history'] = $currentSelection;
            $this->getBackendUser()->writeUC($this->getBackendUser()->uc);
        }
        // Display selector for number of history entries
        $selector['maxSteps'] = [
            10 => [
                'value' => 10
            ],
            20 => [
                'value' => 20
            ],
            50 => [
                'value' => 50
            ],
            100 => [
                'value' => 100
            ],
            999 => [
                'value' => 'maxSteps_all'
            ]
        ];
        $selector['showDiff'] = [
            0 => [
                'value' => 'showDiff_no'
            ],
            1 => [
                'value' => 'showDiff_inline'
            ]
        ];
        $selector['showSubElements'] = [
            0 => [
                'value' => 'no'
            ],
            1 => [
                'value' => 'yes'
            ]
        ];

        $scriptUrl = GeneralUtility::linkThisScript();

        foreach ($selector as $key => $values) {
            foreach ($values as $singleKey => $singleVal) {
                $selector[$key][$singleKey]['scriptUrl'] = htmlspecialchars(GeneralUtility::quoteJSvalue($scriptUrl . '&settings[' . $key . ']=' . $singleKey));
            }
        }
        $this->view->assign('settings', $selector);
        return $currentSelection;
    }

    /**
     * Displays a diff over multiple fields including rollback links
     *
     * @param array $diff Difference array
     */
    protected function displayMultipleDiff(array $diff)
    {
        // Get all array keys needed
        $arrayKeys = array_merge(array_keys($diff['newData']), array_keys($diff['insertsDeletes']), array_keys($diff['oldData']));
        $arrayKeys = array_unique($arrayKeys);
        if (!empty($arrayKeys)) {
            $lines = [];
            foreach ($arrayKeys as $key) {
                $singleLine = [];
                $elParts = explode(':', $key);
                // Turn around diff because it should be a "rollback preview"
                if ((int)$diff['insertsDeletes'][$key] === 1) {
                    // insert
                    $singleLine['insertDelete'] = 'delete';
                } elseif ((int)$diff['insertsDeletes'][$key] === -1) {
                    $singleLine['insertDelete'] = 'insert';
                }
                // Build up temporary diff array
                // turn around diff because it should be a "rollback preview"
                if ($diff['newData'][$key]) {
                    $tmpArr = [
                        'newRecord' => $diff['oldData'][$key],
                        'oldRecord' => $diff['newData'][$key]
                    ];
                    $singleLine['differences'] = $this->renderDiff($tmpArr, $elParts[0], $elParts[1]);
                }
                $elParts = explode(':', $key);
                $singleLine['revertRecordUrl'] = $this->buildUrl(['rollbackFields' => $key]);
                $singleLine['title'] = $this->generateTitle($elParts[0], $elParts[1]);
                $lines[] = $singleLine;
            }
            $this->view->assign('revertAllUrl', $this->buildUrl(['rollbackFields' => 'ALL']));
            $this->view->assign('multipleDiff', $lines);
        }
    }

    /**
     * Shows the full change log
     *
     * @param array $historyEntries
     */
    protected function displayHistory(array $historyEntries)
    {
        if (empty($historyEntries)) {
            return;
        }
        $languageService = $this->getLanguageService();
        $lines = [];
        $beUserArray = BackendUtility::getUserNames();

        // Traverse changeLog array:
        foreach ($historyEntries as $entry) {
            // Build up single line
            $singleLine = [];

            // Get user names
            $singleLine['backendUserUid'] = $entry['userid'];
            $singleLine['backendUserName'] = $entry['userid'] ? $beUserArray[$entry['userid']]['username'] : '';
            // Executed by switch user
            if (!empty($entry['originaluserid'])) {
                $singleLine['originalBackendUserName'] = $beUserArray[$entry['originaluserid']]['username'];
            }

            // Diff link
            $singleLine['diffUrl'] = $this->buildUrl(['historyEntry' => $entry['uid']]);
            // Add time
            $singleLine['time'] = BackendUtility::datetime($entry['tstamp']);
            // Add age
            $singleLine['age'] = BackendUtility::calcAge($GLOBALS['EXEC_TIME'] - $entry['tstamp'], $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:labels.minutesHoursDaysYears'));

            $singleLine['title'] = $this->generateTitle($entry['tablename'], $entry['recuid']);
            $singleLine['elementUrl'] = $this->buildUrl(['element' => $entry['tablename'] . ':' . $entry['recuid']]);
336
            $singleLine['actiontype'] = $entry['actiontype'];
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
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
            if ((int)$entry['actiontype'] === RecordHistoryStore::ACTION_MODIFY) {
                // show changes
                if (!$this->showDiff) {
                    // Display field names instead of full diff
                    // Re-write field names with labels
                    $tmpFieldList = array_keys($entry['newRecord']);
                    foreach ($tmpFieldList as $key => $value) {
                        $tmp = str_replace(':', '', $languageService->sL(BackendUtility::getItemLabel($entry['tablename'], $value)));
                        if ($tmp) {
                            $tmpFieldList[$key] = $tmp;
                        } else {
                            // remove fields if no label available
                            unset($tmpFieldList[$key]);
                        }
                    }
                    $singleLine['fieldNames'] = implode(',', $tmpFieldList);
                } else {
                    // Display diff
                    $singleLine['differences'] = $this->renderDiff($entry, $entry['tablename']);
                }
            }
            // put line together
            $lines[] = $singleLine;
        }
        $this->view->assign('history', $lines);
    }

    /**
     * Renders HTML table-rows with the comparison information of an sys_history entry record
     *
     * @param array $entry sys_history entry record.
     * @param string $table The table name
     * @param int $rollbackUid If set to UID of record, display rollback links
     * @return array array of records
     */
    protected function renderDiff($entry, $table, $rollbackUid = 0): array
    {
        $lines = [];
        if (is_array($entry['newRecord'])) {
            /* @var DiffUtility $diffUtility */
            $diffUtility = GeneralUtility::makeInstance(DiffUtility::class);
            $diffUtility->stripTags = false;
            $fieldsToDisplay = array_keys($entry['newRecord']);
            $languageService = $this->getLanguageService();
            foreach ($fieldsToDisplay as $fN) {
                if (is_array($GLOBALS['TCA'][$table]['columns'][$fN]) && $GLOBALS['TCA'][$table]['columns'][$fN]['config']['type'] !== 'passthrough') {
                    // Create diff-result:
                    $diffres = $diffUtility->makeDiffDisplay(
                        BackendUtility::getProcessedValue($table, $fN, $entry['oldRecord'][$fN], 0, true),
                        BackendUtility::getProcessedValue($table, $fN, $entry['newRecord'][$fN], 0, true)
                    );
                    $rollbackUrl = '';
                    if ($rollbackUid) {
                        $rollbackUrl = $this->buildUrl(['rollbackFields' => ($table . ':' . $rollbackUid . ':' . $fN)]);
                    }
                    $lines[] = [
                        'title' => $languageService->sL(BackendUtility::getItemLabel($table, $fN)),
                        'rollbackUrl' => $rollbackUrl,
                        'result' => str_replace('\n', PHP_EOL, str_replace('\r\n', '\n', $diffres))
                    ];
                }
            }
        }
        return $lines;
    }

    /**
     * Generates the URL for a link to the current page
     *
     * @param array $overrideParameters
     * @return string
     */
    protected function buildUrl($overrideParameters = []): string
    {
        $params = [];
        // Setting default values based on GET parameters:
        if ($this->historyObject->getElementData()) {
            $params['element'] = $this->historyObject->getElementString();
        }
        $params['historyEntry'] = $this->historyObject->lastHistoryEntry;
        // Merging overriding values:
        $params = array_merge($params, $overrideParameters);
        // Make the link:
        return BackendUtility::getModuleUrl('record_history', $params);
    }

    /**
     * Generates the title and puts the record title behind
     *
     * @param string $table
     * @param string $uid
     * @return string
     */
    protected function generateTitle($table, $uid): string
    {
        $title = $table . ':' . $uid;
        if (!empty($GLOBALS['TCA'][$table]['ctrl']['label'])) {
            $record = $this->getRecord($table, $uid);
            $title .= ' (' . BackendUtility::getRecordTitle($table, $record, true) . ')';
        }
        return $title;
    }

    /**
     * Gets a database record (cached).
     *
     * @param string $table
     * @param int $uid
     * @return array|NULL
     */
    protected function getRecord($table, $uid)
    {
        if (!isset($this->recordCache[$table][$uid])) {
            $this->recordCache[$table][$uid] = BackendUtility::getRecord($table, $uid, '*', '', false);
        }
        return $this->recordCache[$table][$uid];
    }

    /**
     * Returns a new standalone view, shorthand function
     *
     * @return StandaloneView
     */
    protected function initializeView()
    {
        /** @var StandaloneView $view */
        $view = GeneralUtility::makeInstance(StandaloneView::class);
        $view->setLayoutRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Layouts')]);
        $view->setPartialRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Partials')]);
        $view->setTemplateRootPaths([GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates')]);

        $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates/RecordHistory/Main.html'));

        $view->getRequest()->setControllerExtensionName('Backend');
        return $view;
    }

474
475
476
    /**
     * Returns LanguageService
     *
477
     * @return \TYPO3\CMS\Core\Localization\LanguageService
478
479
480
481
482
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }
483
484
485
486
487
488
489
490
491
492

    /**
     * Gets the current backend user.
     *
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
     */
    protected function getBackendUser()
    {
        return $GLOBALS['BE_USER'];
    }
493
}