-
Notifications
You must be signed in to change notification settings - Fork 638
/
MissingRelationsCommand.php
397 lines (365 loc) · 19.2 KB
/
MissingRelationsCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
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
<?php
declare(strict_types=1);
/*
* 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!
*/
namespace TYPO3\CMS\Lowlevel\Command;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use TYPO3\CMS\Backend\Command\ProgressListener\ReferenceIndexProgressListener;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Core\Bootstrap;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\ReferenceIndex;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Finds references and soft-references to
* - records which are marked as deleted (e.g. still in the system as reminder)
* - offline versions (references should never point to offline versions)
* - non-existing records (records which have been deleted not via DataHandler)
*
* The later (non-soft-reference variants) can be automatically fixed by simply removing
* the references from the refindex.
*/
class MissingRelationsCommand extends Command
{
/**
* @var ConnectionPool
*/
private $connectionPool;
public function __construct(ConnectionPool $connectionPool)
{
$this->connectionPool = $connectionPool;
parent::__construct();
}
/**
* Configure the command by defining the name, options and arguments
*/
public function configure()
{
$this
->setHelp('
Assumptions:
- a perfect integrity of the reference index table (always update the reference index table before using this tool!)
- all database references to check are integers greater than zero
- does not check if a referenced record is inside an offline branch, another workspace etc. which could make the reference useless in reality or otherwise question integrity
Records may be missing for these reasons (except software bugs):
- someone deleted the record which is technically not an error although it might be a mistake that someone did so.
- after flushing published versions and/or deleted-flagged records a number of new missing references might appear; those were pointing to records just flushed.
An automatic repair is only possible for managed references are (not for soft references), for
offline versions records and non-existing records. If you just want to list them, use the --dry-run option.
The references in this case are removed.
If the option "--dry-run" is not set, all managed files (TCA/FlexForm attachments) will silently remove the references
to non-existing and offline version records.
All soft references with relations to non-existing records, offline versions and deleted records
require manual fix if you consider it an error.
Manual repair suggestions:
- For soft references you should investigate each case and edit the content accordingly.
- References to deleted records can theoretically be removed since a deleted record cannot be selected and hence
your website should not be affected by removal of the reference. On the other hand it does not hurt to ignore it
for now. To have this automatically fixed you must first flush the deleted records after which remaining
references will appear as pointing to Non Existing Records and can now be removed with the automatic fix.
If you want to get more detailed information, use the --verbose option.')
->addOption(
'dry-run',
null,
InputOption::VALUE_NONE,
'If this option is set, the references will not be removed, but just the output which references would be deleted are shown'
)
->addOption(
'update-refindex',
null,
InputOption::VALUE_NONE,
'Setting this option automatically updates the reference index and does not ask on command line. Alternatively, use -n to avoid the interactive mode'
);
}
/**
* Executes the command to
* - optionally update the reference index (to have clean data)
* - find data in sys_refindex (softrefs and regular references) where the reference points to a non-existing record or offline version
* - remove these files if --dry-run is not set (not possible for refindexes)
*
* @param InputInterface $input
* @param OutputInterface $output
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
// Make sure the _cli_ user is loaded
Bootstrap::initializeBackendAuthentication();
$io = new SymfonyStyle($input, $output);
$io->title($this->getDescription());
$dryRun = $input->hasOption('dry-run') && $input->getOption('dry-run') != false ? true : false;
// Update the reference index
$this->updateReferenceIndex($input, $io);
$results = $this->findRelationsToNonExistingRecords();
// Display soft references to non-existing records
if ($io->isVerbose() && count($results['nonExistingRecordsInSoftReferenceRelations'])) {
$io->note([
'Found ' . count($results['nonExistingRecordsInSoftReferenceRelations']) . ' non-existing records that are still being soft-referenced in the following locations.',
'These relations cannot be removed automatically and need manual repair.',
]);
$io->listing($results['nonExistingRecordsInSoftReferenceRelations']);
}
// Display soft references to offline version records
// These records are offline versions having a pid=-1 and references should never occur directly to their uids.
if ($io->isVerbose() && count($results['offlineVersionRecordsInSoftReferenceRelations'])) {
$io->note([
'Found ' . count($results['offlineVersionRecordsInSoftReferenceRelations']) . ' soft-references pointing to offline versions, which should never be referenced directly.',
'These relations cannot be removed automatically and need manual repair.',
]);
$io->listing($results['offlineVersionRecordsInSoftReferenceRelations']);
}
// Display references to deleted records
// These records are deleted with a flag but references are still pointing at them.
// Keeping the references is useful if you undelete the referenced records later, otherwise the references
// are lost completely when the deleted records are flushed at some point. Notice that if those records listed
// are themselves deleted (marked with "DELETED") it is not a problem.
if ($io->isVerbose() && count($results['deletedRecords'])) {
$io->note([
'Found ' . count($results['deletedRecords']) . ' references pointing to deleted records.',
'Keeping the references is useful if you undelete the referenced records later, otherwise the references' .
'are lost completely when the deleted records are flushed at some point. Notice that if those records listed' .
'are themselves deleted (marked with "DELETED") it is not a problem.',
]);
$io->listing($results['deletedRecords']);
}
// soft references which link to deleted records
if ($io->isVerbose() && count($results['deletedRecordsInSoftReferenceRelations'])) {
$io->note([
'Found ' . count($results['deletedRecordsInSoftReferenceRelations']) . ' soft references pointing to deleted records.',
'Keeping the references is useful if you undelete the referenced records later, otherwise the references' .
'are lost completely when the deleted records are flushed at some point. Notice that if those records listed' .
'are themselves deleted (marked with "DELETED") it is not a problem.',
]);
$io->listing($results['deletedRecordsInSoftReferenceRelations']);
}
// Find missing references
if (count($results['offlineVersionRecords']) || count($results['nonExistingRecords'])) {
$io->note([
'Found ' . count($results['nonExistingRecords']) . ' references to non-existing records ' .
'and ' . count($results['offlineVersionRecords']) . ' references directly linked to offline versions.',
]);
$this->removeReferencesToMissingRecords(
$results['offlineVersionRecords'],
$results['nonExistingRecords'],
$dryRun,
$io
);
$io->success('All references were updated accordingly.');
} else {
$io->success('Nothing to do, no missing relations found. Everything is in place.');
}
return 0;
}
/**
* Function to update the reference index
* - if the option --update-refindex is set, do it
* - otherwise, if in interactive mode (not having -n set), ask the user
* - otherwise assume everything is fine
*
* @param InputInterface $input holds information about entered parameters
* @param SymfonyStyle $io necessary for outputting information
*/
protected function updateReferenceIndex(InputInterface $input, SymfonyStyle $io)
{
// Check for reference index to update
$io->note('Finding missing records referenced by TYPO3 requires a clean reference index (sys_refindex)');
if ($input->hasOption('update-refindex') && $input->getOption('update-refindex')) {
$updateReferenceIndex = true;
} elseif ($input->isInteractive()) {
$updateReferenceIndex = $io->confirm('Should the reference index be updated right now?', false);
} else {
$updateReferenceIndex = false;
}
// Update the reference index
if ($updateReferenceIndex) {
$progressListener = GeneralUtility::makeInstance(ReferenceIndexProgressListener::class);
$progressListener->initialize($io);
$referenceIndex = GeneralUtility::makeInstance(ReferenceIndex::class);
$referenceIndex->updateIndex(false, $progressListener);
} else {
$io->writeln('Reference index is assumed to be up to date, continuing.');
}
}
/**
* Find relations pointing to non-existing records (in managed references or soft-references)
*
* @return array an array of records within sys_refindex
*/
protected function findRelationsToNonExistingRecords(): array
{
$deletedRecords = [];
$deletedRecordsInSoftReferenceRelations = [];
$nonExistingRecords = [];
$nonExistingRecordsInSoftReferenceRelations = [];
$offlineVersionRecords = [];
$offlineVersionRecordsInSoftReferenceRelations = [];
// Select DB relations from reference table
$queryBuilder = $this->connectionPool->getQueryBuilderForTable('sys_refindex');
$rowIterator = $queryBuilder
->select('ref_uid', 'ref_table', 'softref_key', 'hash', 'tablename', 'recuid', 'field', 'flexpointer')
->from('sys_refindex')
->where(
$queryBuilder->expr()->neq('ref_table', $queryBuilder->createNamedParameter('_FILE', Connection::PARAM_STR)),
$queryBuilder->expr()->gt('ref_uid', $queryBuilder->createNamedParameter(0, Connection::PARAM_INT))
)
->executeQuery();
$existingRecords = [];
while ($rec = $rowIterator->fetchAssociative()) {
$isSoftReference = !empty($rec['softref_key']);
$idx = $rec['ref_table'] . ':' . $rec['ref_uid'];
// Get referenced record:
if (!isset($existingRecords[$idx])) {
$queryBuilder = $this->connectionPool
->getQueryBuilderForTable($rec['ref_table']);
$queryBuilder->getRestrictions()->removeAll();
$selectFields = ['uid', 'pid'];
if (isset($GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete'])) {
$selectFields[] = $GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete'];
}
if (BackendUtility::isTableWorkspaceEnabled($rec['ref_table'])) {
$selectFields[] = 't3ver_oid';
$selectFields[] = 't3ver_wsid';
}
try {
$existingRecords[$idx] = $queryBuilder
->select(...$selectFields)
->from($rec['ref_table'])
->where(
$queryBuilder->expr()->eq(
'uid',
$queryBuilder->createNamedParameter($rec['ref_uid'], Connection::PARAM_INT)
)
)
->executeQuery()
->fetchAssociative();
} catch (TableNotFoundException $tableNotFoundException) {
// noop
}
}
// Compile info string for location of reference:
$infoString = $this->formatReferenceIndexEntryToString($rec);
// Handle missing file:
if ($existingRecords[$idx]['uid'] ?? false) {
// Record exists, but is a reference to an offline version
if ((int)($existingRecords[$idx]['t3ver_oid'] ?? 0) > 0) {
if ($isSoftReference) {
$offlineVersionRecordsInSoftReferenceRelations[] = $infoString;
} else {
$offlineVersionRecords[$idx][$rec['hash']] = $infoString;
}
// reference to a deleted record
} elseif (isset($GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete']) && $existingRecords[$idx][$GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete']]) {
if ($isSoftReference) {
$deletedRecordsInSoftReferenceRelations[] = $infoString;
} else {
$deletedRecords[] = $infoString;
}
}
} else {
if ($isSoftReference) {
$nonExistingRecordsInSoftReferenceRelations[] = $infoString;
} else {
$nonExistingRecords[$idx][$rec['hash']] = $infoString;
}
}
}
return [
// Non-existing records to which there are references (managed)
// These references can safely be removed since there is no record found in the database at all.
'nonExistingRecords' => ArrayUtility::sortByKeyRecursive($nonExistingRecords),
// Non-existing records to which there are references (softref)
'nonExistingRecordsInSoftReferenceRelations' => ArrayUtility::sortByKeyRecursive($nonExistingRecordsInSoftReferenceRelations),
// Offline version records (managed)
// These records are offline versions having a pid=-1 and references should never occur directly to their uids.
'offlineVersionRecords' => ArrayUtility::sortByKeyRecursive($offlineVersionRecords),
// Offline version records (softref)
'offlineVersionRecordsInSoftReferenceRelations' => ArrayUtility::sortByKeyRecursive($offlineVersionRecordsInSoftReferenceRelations),
// Deleted-flagged records (managed)
// These records are deleted with a flag but references are still pointing at them.
// Keeping the references is useful if you undelete the referenced records later, otherwise the references
// are lost completely when the deleted records are flushed at some point. Notice that if those records listed
// are themselves deleted (marked with "DELETED") it is not a problem.
'deletedRecords' => ArrayUtility::sortByKeyRecursive($deletedRecords),
// Deleted-flagged records (softref)
'deletedRecordsInSoftReferenceRelations' => ArrayUtility::sortByKeyRecursive($deletedRecordsInSoftReferenceRelations),
];
}
/**
* Removes all references to non-existing records or offline versions
*
* @param array $offlineVersionRecords Contains the records of offline versions of sys_refindex which need to be removed
* @param array $nonExistingRecords Contains the records non-existing records of sys_refindex which need to be removed
* @param bool $dryRun if set, the references are just displayed, but not removed
* @param SymfonyStyle $io the IO object for output
*/
protected function removeReferencesToMissingRecords(
array $offlineVersionRecords,
array $nonExistingRecords,
bool $dryRun,
SymfonyStyle $io
) {
// Remove references to offline records
foreach ($offlineVersionRecords as $fileName => $references) {
if ($io->isVeryVerbose()) {
$io->writeln('Removing references in offline versions which there are references pointing towards.');
}
foreach ($references as $hash => $recordReference) {
$io->writeln('Removing reference in record "' . $recordReference . '" (Hash: ' . $hash . ')');
if (!$dryRun) {
$sysRefObj = GeneralUtility::makeInstance(ReferenceIndex::class);
$error = $sysRefObj->setReferenceValue($hash, null);
if ($error) {
$io->error('ReferenceIndex::setReferenceValue() reported "' . $error . '"');
}
}
}
}
// Remove references to non-existing records
foreach ($nonExistingRecords as $fileName => $references) {
if ($io->isVeryVerbose()) {
$io->writeln('Removing references to non-existing records.');
}
foreach ($references as $hash => $recordReference) {
$io->writeln('Removing reference in record "' . $recordReference . '" (Hash: ' . $hash . ')');
if (!$dryRun) {
$sysRefObj = GeneralUtility::makeInstance(ReferenceIndex::class);
$error = $sysRefObj->setReferenceValue($hash, null);
if ($error) {
$io->error('ReferenceIndex::setReferenceValue() reported "' . $error . '"');
}
}
}
}
}
/**
* Formats a sys_refindex entry to something readable
*
* @param array $record
* @return string
*/
protected function formatReferenceIndexEntryToString(array $record): string
{
return $record['tablename']
. ':' . $record['recuid']
. ':' . $record['field']
. ($record['flexpointer'] ? ':' . $record['flexpointer'] : '')
. ($record['softref_key'] ? ':' . $record['softref_key'] . ' (Soft Reference) ' : '');
}
}