TYPO3 CMS  TYPO3_8-7
MissingRelationsCommand.php
Go to the documentation of this file.
1 <?php
2 declare(strict_types = 1);
4 
5 /*
6  * This file is part of the TYPO3 CMS project.
7  *
8  * It is free software; you can redistribute it and/or modify it under
9  * the terms of the GNU General Public License, either version 2
10  * of the License, or any later version.
11  *
12  * For the full copyright and license information, please read the
13  * LICENSE.txt file that was distributed with this source code.
14  *
15  * The TYPO3 project - inspiring people to share!
16  */
17 
28 
38 class MissingRelationsCommand extends Command
39 {
40 
44  public function configure()
45  {
46  $this
47  ->setDescription('Find all record references pointing to a non-existing record')
48  ->setHelp('
49 Assumptions:
50 - a perfect integrity of the reference index table (always update the reference index table before using this tool!)
51 - all database references to check are integers greater than zero
52 - 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
53 Records may be missing for these reasons (except software bugs):
54 - someone deleted the record which is technically not an error although it might be a mistake that someone did so.
55 - after flushing published versions and/or deleted-flagged records a number of new missing references might appear; those were pointing to records just flushed.
56 
57 An automatic repair is only possible for managed references are (not for soft references), for
58 offline versions records and non-existing records. If you just want to list them, use the --dry-run option.
59 The references in this case are removed.
60 
61 If the option "--dry-run" is not set, all managed files (TCA/FlexForm attachments) will silently remove the references
62 to non-existing and offline version records.
63 All soft references with relations to non-existing records, offline versions and deleted records
64 require manual fix if you consider it an error.
65 
66 Manual repair suggestions:
67 - For soft references you should investigate each case and edit the content accordingly.
68 - References to deleted records can theoretically be removed since a deleted record cannot be selected and hence
69 your website should not be affected by removal of the reference. On the other hand it does not hurt to ignore it
70 for now. To have this automatically fixed you must first flush the deleted records after which remaining
71 references will appear as pointing to Non Existing Records and can now be removed with the automatic fix.
72 
73 If you want to get more detailed information, use the --verbose option.')
74  ->addOption(
75  'dry-run',
76  null,
77  InputOption::VALUE_NONE,
78  'If this option is set, the references will not be removed, but just the output which references would be deleted are shown'
79  )
80  ->addOption(
81  'update-refindex',
82  null,
83  InputOption::VALUE_NONE,
84  'Setting this option automatically updates the reference index and does not ask on command line. Alternatively, use -n to avoid the interactive mode'
85  );
86  }
87 
97  protected function execute(InputInterface $input, OutputInterface $output)
98  {
99  // Make sure the _cli_ user is loaded
100  Bootstrap::getInstance()->initializeBackendAuthentication();
101 
102  $io = new SymfonyStyle($input, $output);
103  $io->title($this->getDescription());
104 
105  $dryRun = $input->hasOption('dry-run') && $input->getOption('dry-run') != false ? true : false;
106 
107  // Update the reference index
108  $this->updateReferenceIndex($input, $io);
109 
110  $results = $this->findRelationsToNonExistingRecords();
111 
112  // Display soft references to non-existing records
113  if ($io->isVerbose() && count($results['nonExistingRecordsInSoftReferenceRelations'])) {
114  $io->note([
115  'Found ' . count($results['nonExistingRecordsInSoftReferenceRelations']) . ' non-existing records that are still being soft-referenced in the following locations.',
116  'These relations cannot be removed automatically and need manual repair.'
117  ]);
118  $io->listing($results['nonExistingRecordsInSoftReferenceRelations']);
119  }
120 
121  // Display soft references to offline version records
122  // These records are offline versions having a pid=-1 and references should never occur directly to their uids.
123  if ($io->isVerbose() && count($results['offlineVersionRecordsInSoftReferenceRelations'])) {
124  $io->note([
125  'Found ' . count($results['offlineVersionRecordsInSoftReferenceRelations']) . ' soft-references pointing to offline versions, which should never be referenced directly.',
126  'These relations cannot be removed automatically and need manual repair.'
127  ]);
128  $io->listing($results['offlineVersionRecordsInSoftReferenceRelations']);
129  }
130 
131  // Display references to deleted records
132  // These records are deleted with a flag but references are still pointing at them.
133  // Keeping the references is useful if you undelete the referenced records later, otherwise the references
134  // are lost completely when the deleted records are flushed at some point. Notice that if those records listed
135  // are themselves deleted (marked with "DELETED") it is not a problem.
136  if ($io->isVerbose() && count($results['deletedRecords'])) {
137  $io->note([
138  'Found ' . count($results['deletedRecords']) . ' references pointing to deleted records.',
139  'Keeping the references is useful if you undelete the referenced records later, otherwise the references' .
140  'are lost completely when the deleted records are flushed at some point. Notice that if those records listed' .
141  'are themselves deleted (marked with "DELETED") it is not a problem.',
142  ]);
143  $io->listing($results['deletedRecords']);
144  }
145 
146  // soft references which link to deleted records
147  if ($io->isVerbose() && count($results['deletedRecordsInSoftReferenceRelations'])) {
148  $io->note([
149  'Found ' . count($results['deletedRecordsInSoftReferenceRelations']) . ' soft references pointing to deleted records.',
150  'Keeping the references is useful if you undelete the referenced records later, otherwise the references' .
151  'are lost completely when the deleted records are flushed at some point. Notice that if those records listed' .
152  'are themselves deleted (marked with "DELETED") it is not a problem.',
153  ]);
154  $io->listing($results['deletedRecordsInSoftReferenceRelations']);
155  }
156 
157  // Find missing references
158  if (count($results['offlineVersionRecords']) || count($results['nonExistingRecords'])) {
159  $io->note([
160  'Found ' . count($results['nonExistingRecords']) . ' references to non-existing records ' .
161  'and ' . count($results['offlineVersionRecords']) . ' references directly linked to offline versions.'
162  ]);
163 
165  $results['offlineVersionRecords'],
166  $results['nonExistingRecords'],
167  $dryRun,
168  $io
169  );
170  $io->success('All references were updated accordingly.');
171  } else {
172  $io->success('Nothing to do, no missing relations found. Everything is in place.');
173  }
174  }
175 
185  protected function updateReferenceIndex(InputInterface $input, SymfonyStyle $io)
186  {
187  // Check for reference index to update
188  $io->note('Finding missing records referenced by TYPO3 requires a clean reference index (sys_refindex)');
189  if ($input->hasOption('update-refindex') && $input->getOption('update-refindex')) {
190  $updateReferenceIndex = true;
191  } elseif ($input->isInteractive()) {
192  $updateReferenceIndex = $io->confirm('Should the reference index be updated right now?', false);
193  } else {
194  $updateReferenceIndex = false;
195  }
196 
197  // Update the reference index
198  if ($updateReferenceIndex) {
199  $referenceIndex = GeneralUtility::makeInstance(ReferenceIndex::class);
200  $referenceIndex->updateIndex(false, !$io->isQuiet());
201  } else {
202  $io->writeln('Reference index is assumed to be up to date, continuing.');
203  }
204  }
205 
211  protected function findRelationsToNonExistingRecords(): array
212  {
213  $deletedRecords = [];
214  $deletedRecordsInSoftReferenceRelations = [];
215  $nonExistingRecords = [];
216  $nonExistingRecordsInSoftReferenceRelations = [];
217  $offlineVersionRecords = [];
218  $offlineVersionRecordsInSoftReferenceRelations = [];
219 
220  // Select DB relations from reference table
221  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
222  $rowIterator = $queryBuilder
223  ->select('ref_uid', 'ref_table', 'softref_key', 'hash', 'tablename', 'recuid', 'field', 'flexpointer', 'deleted')
224  ->from('sys_refindex')
225  ->where(
226  $queryBuilder->expr()->neq('ref_table', $queryBuilder->createNamedParameter('_FILE', \PDO::PARAM_STR)),
227  $queryBuilder->expr()->gt('ref_uid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
228  )
229  ->execute();
230 
231  $existingRecords = [];
232  while ($rec = $rowIterator->fetch()) {
233  $isSoftReference = !empty($rec['softref_key']);
234  $idx = $rec['ref_table'] . ':' . $rec['ref_uid'];
235  // Get referenced record:
236  if (!isset($existingRecords[$idx])) {
237  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
238  ->getQueryBuilderForTable($rec['ref_table']);
239  $queryBuilder->getRestrictions()->removeAll();
240 
241  $selectFields = ['uid', 'pid'];
242  if (isset($GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete'])) {
243  $selectFields[] = $GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete'];
244  }
245 
246  $existingRecords[$idx] = $queryBuilder
247  ->select(...$selectFields)
248  ->from($rec['ref_table'])
249  ->where(
250  $queryBuilder->expr()->eq(
251  'uid',
252  $queryBuilder->createNamedParameter($rec['ref_uid'], \PDO::PARAM_INT)
253  )
254  )
255  ->execute()
256  ->fetch();
257  }
258  // Compile info string for location of reference:
259  $infoString = $this->formatReferenceIndexEntryToString($rec);
260  // Handle missing file:
261  if ($existingRecords[$idx]['uid']) {
262  // Record exists, but is a reference to an offline version
263  if ((int)$existingRecords[$idx]['pid'] === -1) {
264  if ($isSoftReference) {
265  $offlineVersionRecordsInSoftReferenceRelations[] = $infoString;
266  } else {
267  $offlineVersionRecords[$idx][$rec['hash']] = $infoString;
268  }
269  // reference to a deleted record
270  } elseif (isset($GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete']) && $existingRecords[$idx][$GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete']]) {
271  if ($isSoftReference) {
272  $deletedRecordsInSoftReferenceRelations[] = $infoString;
273  } else {
274  $deletedRecords[] = $infoString;
275  }
276  }
277  } else {
278  if ($isSoftReference) {
279  $nonExistingRecordsInSoftReferenceRelations[] = $infoString;
280  } else {
281  $nonExistingRecords[$idx][$rec['hash']] = $infoString;
282  }
283  }
284  }
285 
286  return [
287  // Non-existing records to which there are references (managed)
288  // These references can safely be removed since there is no record found in the database at all.
289  'nonExistingRecords' => ArrayUtility::sortByKeyRecursive($nonExistingRecords),
290  // Non-existing records to which there are references (softref)
291  'nonExistingRecordsInSoftReferenceRelations' => ArrayUtility::sortByKeyRecursive($nonExistingRecordsInSoftReferenceRelations),
292  // Offline version records (managed)
293  // These records are offline versions having a pid=-1 and references should never occur directly to their uids.
294  'offlineVersionRecords' => ArrayUtility::sortByKeyRecursive($offlineVersionRecords),
295  // Offline version records (softref)
296  'offlineVersionRecordsInSoftReferenceRelations' => ArrayUtility::sortByKeyRecursive($offlineVersionRecordsInSoftReferenceRelations),
297  // Deleted-flagged records (managed)
298  // These records are deleted with a flag but references are still pointing at them.
299  // Keeping the references is useful if you undelete the referenced records later, otherwise the references
300  // are lost completely when the deleted records are flushed at some point. Notice that if those records listed
301  // are themselves deleted (marked with "DELETED") it is not a problem.
302  'deletedRecords' => ArrayUtility::sortByKeyRecursive($deletedRecords),
303  // Deleted-flagged records (softref)
304  'deletedRecordsInSoftReferenceRelations' => ArrayUtility::sortByKeyRecursive($deletedRecordsInSoftReferenceRelations),
305  ];
306  }
307 
317  array $offlineVersionRecords,
318  array $nonExistingRecords,
319  bool $dryRun,
320  SymfonyStyle $io
321  ) {
322  // Remove references to offline records
323  foreach ($offlineVersionRecords as $fileName => $references) {
324  if ($io->isVeryVerbose()) {
325  $io->writeln('Removing references in offline versions which there are references pointing towards.');
326  }
327  foreach ($references as $hash => $recordReference) {
328  $io->writeln('Removing reference in record "' . $recordReference . '" (Hash: ' . $hash . ')');
329  if (!$dryRun) {
330  $sysRefObj = GeneralUtility::makeInstance(ReferenceIndex::class);
331  $error = $sysRefObj->setReferenceValue($hash, null);
332  if ($error) {
333  $io->error('ReferenceIndex::setReferenceValue() reported "' . $error . '"');
334  }
335  }
336  }
337  }
338 
339  // Remove references to non-existing records
340  foreach ($nonExistingRecords as $fileName => $references) {
341  if ($io->isVeryVerbose()) {
342  $io->writeln('Removing references to non-existing records.');
343  }
344  foreach ($references as $hash => $recordReference) {
345  $io->writeln('Removing reference in record "' . $recordReference . '" (Hash: ' . $hash . ')');
346  if (!$dryRun) {
347  $sysRefObj = GeneralUtility::makeInstance(ReferenceIndex::class);
348  $error = $sysRefObj->setReferenceValue($hash, null);
349  if ($error) {
350  $io->error('ReferenceIndex::setReferenceValue() reported "' . $error . '"');
351  }
352  }
353  }
354  }
355  }
356 
363  protected function formatReferenceIndexEntryToString(array $record): string
364  {
365  return $record['tablename']
366  . ':' . $record['recuid']
367  . ':' . $record['field']
368  . ($record['flexpointer'] ? ':' . $record['flexpointer'] : '')
369  . ($record['softref_key'] ? ':' . $record['softref_key'] . ' (Soft Reference) ' : '')
370  . ($record['deleted'] ? ' (DELETED)' : '');
371  }
372 }
execute(InputInterface $input, OutputInterface $output)
removeReferencesToMissingRecords(array $offlineVersionRecords, array $nonExistingRecords, bool $dryRun, SymfonyStyle $io)
static makeInstance($className,... $constructorArguments)
static sortByKeyRecursive(array $array)
updateReferenceIndex(InputInterface $input, SymfonyStyle $io)
if(TYPO3_MODE==='BE') $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tsfebeuserauth.php']['frontendEditingController']['default']