‪TYPO3CMS  10.4
MissingRelationsCommand.php
Go to the documentation of this file.
1 <?php
2 
3 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 
19 
20 use Symfony\Component\Console\Command\Command;
21 use Symfony\Component\Console\Input\InputInterface;
22 use Symfony\Component\Console\Input\InputOption;
23 use Symfony\Component\Console\Output\OutputInterface;
24 use Symfony\Component\Console\Style\SymfonyStyle;
32 
42 class ‪MissingRelationsCommand extends Command
43 {
44 
48  public function ‪configure()
49  {
50  $this
51  ->setDescription('Find all record references pointing to a non-existing record')
52  ->setHelp('
53 Assumptions:
54 - a perfect integrity of the reference index table (always update the reference index table before using this tool!)
55 - all database references to check are integers greater than zero
56 - 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
57 Records may be missing for these reasons (except software bugs):
58 - someone deleted the record which is technically not an error although it might be a mistake that someone did so.
59 - after flushing published versions and/or deleted-flagged records a number of new missing references might appear; those were pointing to records just flushed.
60 
61 An automatic repair is only possible for managed references are (not for soft references), for
62 offline versions records and non-existing records. If you just want to list them, use the --dry-run option.
63 The references in this case are removed.
64 
65 If the option "--dry-run" is not set, all managed files (TCA/FlexForm attachments) will silently remove the references
66 to non-existing and offline version records.
67 All soft references with relations to non-existing records, offline versions and deleted records
68 require manual fix if you consider it an error.
69 
70 Manual repair suggestions:
71 - For soft references you should investigate each case and edit the content accordingly.
72 - References to deleted records can theoretically be removed since a deleted record cannot be selected and hence
73 your website should not be affected by removal of the reference. On the other hand it does not hurt to ignore it
74 for now. To have this automatically fixed you must first flush the deleted records after which remaining
75 references will appear as pointing to Non Existing Records and can now be removed with the automatic fix.
76 
77 If you want to get more detailed information, use the --verbose option.')
78  ->addOption(
79  'dry-run',
80  null,
81  InputOption::VALUE_NONE,
82  'If this option is set, the references will not be removed, but just the output which references would be deleted are shown'
83  )
84  ->addOption(
85  'update-refindex',
86  null,
87  InputOption::VALUE_NONE,
88  'Setting this option automatically updates the reference index and does not ask on command line. Alternatively, use -n to avoid the interactive mode'
89  );
90  }
91 
102  protected function ‪execute(InputInterface $input, OutputInterface ‪$output)
103  {
104  // Make sure the _cli_ user is loaded
106 
107  $io = new SymfonyStyle($input, ‪$output);
108  $io->title($this->getDescription());
109 
110  $dryRun = $input->hasOption('dry-run') && $input->getOption('dry-run') != false ? true : false;
111 
112  // Update the reference index
113  $this->‪updateReferenceIndex($input, $io);
114 
115  $results = $this->‪findRelationsToNonExistingRecords();
116 
117  // Display soft references to non-existing records
118  if ($io->isVerbose() && count($results['nonExistingRecordsInSoftReferenceRelations'])) {
119  $io->note([
120  'Found ' . count($results['nonExistingRecordsInSoftReferenceRelations']) . ' non-existing records that are still being soft-referenced in the following locations.',
121  'These relations cannot be removed automatically and need manual repair.'
122  ]);
123  $io->listing($results['nonExistingRecordsInSoftReferenceRelations']);
124  }
125 
126  // Display soft references to offline version records
127  // These records are offline versions having a pid=-1 and references should never occur directly to their uids.
128  if ($io->isVerbose() && count($results['offlineVersionRecordsInSoftReferenceRelations'])) {
129  $io->note([
130  'Found ' . count($results['offlineVersionRecordsInSoftReferenceRelations']) . ' soft-references pointing to offline versions, which should never be referenced directly.',
131  'These relations cannot be removed automatically and need manual repair.'
132  ]);
133  $io->listing($results['offlineVersionRecordsInSoftReferenceRelations']);
134  }
135 
136  // Display references to deleted records
137  // These records are deleted with a flag but references are still pointing at them.
138  // Keeping the references is useful if you undelete the referenced records later, otherwise the references
139  // are lost completely when the deleted records are flushed at some point. Notice that if those records listed
140  // are themselves deleted (marked with "DELETED") it is not a problem.
141  if ($io->isVerbose() && count($results['deletedRecords'])) {
142  $io->note([
143  'Found ' . count($results['deletedRecords']) . ' references pointing to deleted records.',
144  'Keeping the references is useful if you undelete the referenced records later, otherwise the references' .
145  'are lost completely when the deleted records are flushed at some point. Notice that if those records listed' .
146  'are themselves deleted (marked with "DELETED") it is not a problem.',
147  ]);
148  $io->listing($results['deletedRecords']);
149  }
150 
151  // soft references which link to deleted records
152  if ($io->isVerbose() && count($results['deletedRecordsInSoftReferenceRelations'])) {
153  $io->note([
154  'Found ' . count($results['deletedRecordsInSoftReferenceRelations']) . ' soft references pointing to deleted records.',
155  'Keeping the references is useful if you undelete the referenced records later, otherwise the references' .
156  'are lost completely when the deleted records are flushed at some point. Notice that if those records listed' .
157  'are themselves deleted (marked with "DELETED") it is not a problem.',
158  ]);
159  $io->listing($results['deletedRecordsInSoftReferenceRelations']);
160  }
161 
162  // Find missing references
163  if (count($results['offlineVersionRecords']) || count($results['nonExistingRecords'])) {
164  $io->note([
165  'Found ' . count($results['nonExistingRecords']) . ' references to non-existing records ' .
166  'and ' . count($results['offlineVersionRecords']) . ' references directly linked to offline versions.'
167  ]);
168 
170  $results['offlineVersionRecords'],
171  $results['nonExistingRecords'],
172  $dryRun,
173  $io
174  );
175  $io->success('All references were updated accordingly.');
176  } else {
177  $io->success('Nothing to do, no missing relations found. Everything is in place.');
178  }
179  return 0;
180  }
181 
191  protected function ‪updateReferenceIndex(InputInterface $input, SymfonyStyle $io)
192  {
193  // Check for reference index to update
194  $io->note('Finding missing records referenced by TYPO3 requires a clean reference index (sys_refindex)');
195  if ($input->hasOption('update-refindex') && $input->getOption('update-refindex')) {
196  $updateReferenceIndex = true;
197  } elseif ($input->isInteractive()) {
198  $updateReferenceIndex = $io->confirm('Should the reference index be updated right now?', false);
199  } else {
200  $updateReferenceIndex = false;
201  }
202 
203  // Update the reference index
204  if ($updateReferenceIndex) {
205  $progressListener = GeneralUtility::makeInstance(ReferenceIndexProgressListener::class);
206  $progressListener->initialize($io);
207  $referenceIndex = GeneralUtility::makeInstance(ReferenceIndex::class);
208  $referenceIndex->updateIndex(false, $progressListener);
209  } else {
210  $io->writeln('Reference index is assumed to be up to date, continuing.');
211  }
212  }
213 
219  protected function ‪findRelationsToNonExistingRecords(): array
220  {
221  $deletedRecords = [];
222  $deletedRecordsInSoftReferenceRelations = [];
223  $nonExistingRecords = [];
224  $nonExistingRecordsInSoftReferenceRelations = [];
225  $offlineVersionRecords = [];
226  $offlineVersionRecordsInSoftReferenceRelations = [];
227 
228  // Select DB relations from reference table
229  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_refindex');
230  $rowIterator = $queryBuilder
231  ->select('ref_uid', 'ref_table', 'softref_key', 'hash', 'tablename', 'recuid', 'field', 'flexpointer', 'deleted')
232  ->from('sys_refindex')
233  ->where(
234  $queryBuilder->expr()->neq('ref_table', $queryBuilder->createNamedParameter('_FILE', \PDO::PARAM_STR)),
235  $queryBuilder->expr()->gt('ref_uid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
236  )
237  ->execute();
238 
239  $existingRecords = [];
240  while ($rec = $rowIterator->fetch()) {
241  $isSoftReference = !empty($rec['softref_key']);
242  $idx = $rec['ref_table'] . ':' . $rec['ref_uid'];
243  // Get referenced record:
244  if (!isset($existingRecords[$idx])) {
245  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
246  ->getQueryBuilderForTable($rec['ref_table']);
247  $queryBuilder->getRestrictions()->removeAll();
248 
249  $selectFields = ['uid', 'pid'];
250  if (isset(‪$GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete'])) {
251  $selectFields[] = ‪$GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete'];
252  }
253  if (‪BackendUtility::isTableWorkspaceEnabled($rec['ref_table'])) {
254  $selectFields[] = 't3ver_oid';
255  $selectFields[] = 't3ver_wsid';
256  }
257 
258  $existingRecords[$idx] = $queryBuilder
259  ->select(...$selectFields)
260  ->from($rec['ref_table'])
261  ->where(
262  $queryBuilder->expr()->eq(
263  'uid',
264  $queryBuilder->createNamedParameter($rec['ref_uid'], \PDO::PARAM_INT)
265  )
266  )
267  ->execute()
268  ->fetch();
269  }
270  // Compile info string for location of reference:
271  $infoString = $this->‪formatReferenceIndexEntryToString($rec);
272  // Handle missing file:
273  if ($existingRecords[$idx]['uid']) {
274  // Record exists, but is a reference to an offline version
275  if ((int)($existingRecords[$idx]['t3ver_oid'] ?? 0) > 0) {
276  if ($isSoftReference) {
277  $offlineVersionRecordsInSoftReferenceRelations[] = $infoString;
278  } else {
279  $offlineVersionRecords[$idx][$rec['hash']] = $infoString;
280  }
281  // reference to a deleted record
282  } elseif (isset(‪$GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete']) && $existingRecords[$idx][‪$GLOBALS['TCA'][$rec['ref_table']]['ctrl']['delete']]) {
283  if ($isSoftReference) {
284  $deletedRecordsInSoftReferenceRelations[] = $infoString;
285  } else {
286  $deletedRecords[] = $infoString;
287  }
288  }
289  } else {
290  if ($isSoftReference) {
291  $nonExistingRecordsInSoftReferenceRelations[] = $infoString;
292  } else {
293  $nonExistingRecords[$idx][$rec['hash']] = $infoString;
294  }
295  }
296  }
297 
298  return [
299  // Non-existing records to which there are references (managed)
300  // These references can safely be removed since there is no record found in the database at all.
301  'nonExistingRecords' => ‪ArrayUtility::sortByKeyRecursive($nonExistingRecords),
302  // Non-existing records to which there are references (softref)
303  'nonExistingRecordsInSoftReferenceRelations' => ‪ArrayUtility::sortByKeyRecursive($nonExistingRecordsInSoftReferenceRelations),
304  // Offline version records (managed)
305  // These records are offline versions having a pid=-1 and references should never occur directly to their uids.
306  'offlineVersionRecords' => ‪ArrayUtility::sortByKeyRecursive($offlineVersionRecords),
307  // Offline version records (softref)
308  'offlineVersionRecordsInSoftReferenceRelations' => ‪ArrayUtility::sortByKeyRecursive($offlineVersionRecordsInSoftReferenceRelations),
309  // Deleted-flagged records (managed)
310  // These records are deleted with a flag but references are still pointing at them.
311  // Keeping the references is useful if you undelete the referenced records later, otherwise the references
312  // are lost completely when the deleted records are flushed at some point. Notice that if those records listed
313  // are themselves deleted (marked with "DELETED") it is not a problem.
314  'deletedRecords' => ‪ArrayUtility::sortByKeyRecursive($deletedRecords),
315  // Deleted-flagged records (softref)
316  'deletedRecordsInSoftReferenceRelations' => ‪ArrayUtility::sortByKeyRecursive($deletedRecordsInSoftReferenceRelations),
317  ];
318  }
319 
329  array $offlineVersionRecords,
330  array $nonExistingRecords,
331  bool $dryRun,
332  SymfonyStyle $io
333  ) {
334  // Remove references to offline records
335  foreach ($offlineVersionRecords as $fileName => $references) {
336  if ($io->isVeryVerbose()) {
337  $io->writeln('Removing references in offline versions which there are references pointing towards.');
338  }
339  foreach ($references as $hash => $recordReference) {
340  $io->writeln('Removing reference in record "' . $recordReference . '" (Hash: ' . $hash . ')');
341  if (!$dryRun) {
342  $sysRefObj = GeneralUtility::makeInstance(ReferenceIndex::class);
343  $error = $sysRefObj->setReferenceValue($hash, null);
344  if ($error) {
345  $io->error('ReferenceIndex::setReferenceValue() reported "' . $error . '"');
346  }
347  }
348  }
349  }
350 
351  // Remove references to non-existing records
352  foreach ($nonExistingRecords as $fileName => $references) {
353  if ($io->isVeryVerbose()) {
354  $io->writeln('Removing references to non-existing records.');
355  }
356  foreach ($references as $hash => $recordReference) {
357  $io->writeln('Removing reference in record "' . $recordReference . '" (Hash: ' . $hash . ')');
358  if (!$dryRun) {
359  $sysRefObj = GeneralUtility::makeInstance(ReferenceIndex::class);
360  $error = $sysRefObj->setReferenceValue($hash, null);
361  if ($error) {
362  $io->error('ReferenceIndex::setReferenceValue() reported "' . $error . '"');
363  }
364  }
365  }
366  }
367  }
368 
375  protected function ‪formatReferenceIndexEntryToString(array $record): string
376  {
377  return $record['tablename']
378  . ':' . $record['recuid']
379  . ':' . $record['field']
380  . ($record['flexpointer'] ? ':' . $record['flexpointer'] : '')
381  . ($record['softref_key'] ? ':' . $record['softref_key'] . ' (Soft Reference) ' : '')
382  . ($record['deleted'] ? ' (DELETED)' : '');
383  }
384 }
‪TYPO3\CMS\Lowlevel\Command\MissingRelationsCommand\configure
‪configure()
Definition: MissingRelationsCommand.php:48
‪TYPO3\CMS\Lowlevel\Command\MissingRelationsCommand\findRelationsToNonExistingRecords
‪array findRelationsToNonExistingRecords()
Definition: MissingRelationsCommand.php:219
‪TYPO3\CMS\Backend\Command\ProgressListener\ReferenceIndexProgressListener
Definition: ReferenceIndexProgressListener.php:30
‪TYPO3\CMS\Core\Database\ReferenceIndex
Definition: ReferenceIndex.php:48
‪TYPO3\CMS\Core\Core\Bootstrap\initializeBackendAuthentication
‪static initializeBackendAuthentication($proceedIfNoUserIsLoggedIn=false)
Definition: Bootstrap.php:607
‪TYPO3\CMS\Core\Utility\ArrayUtility\sortByKeyRecursive
‪static array sortByKeyRecursive(array $array)
Definition: ArrayUtility.php:354
‪TYPO3\CMS\Backend\Utility\BackendUtility\isTableWorkspaceEnabled
‪static bool isTableWorkspaceEnabled($table)
Definition: BackendUtility.php:4021
‪TYPO3\CMS\Lowlevel\Command\MissingRelationsCommand\updateReferenceIndex
‪updateReferenceIndex(InputInterface $input, SymfonyStyle $io)
Definition: MissingRelationsCommand.php:191
‪TYPO3\CMS\Lowlevel\Command\MissingRelationsCommand\removeReferencesToMissingRecords
‪removeReferencesToMissingRecords(array $offlineVersionRecords, array $nonExistingRecords, bool $dryRun, SymfonyStyle $io)
Definition: MissingRelationsCommand.php:328
‪TYPO3\CMS\Lowlevel\Command\MissingRelationsCommand\formatReferenceIndexEntryToString
‪string formatReferenceIndexEntryToString(array $record)
Definition: MissingRelationsCommand.php:375
‪TYPO3\CMS\Backend\Utility\BackendUtility
Definition: BackendUtility.php:75
‪TYPO3\CMS\Lowlevel\Command\MissingRelationsCommand
Definition: MissingRelationsCommand.php:43
‪$output
‪$output
Definition: annotationChecker.php:119
‪TYPO3\CMS\Lowlevel\Command\MissingRelationsCommand\execute
‪int execute(InputInterface $input, OutputInterface $output)
Definition: MissingRelationsCommand.php:102
‪TYPO3\CMS\Core\Utility\ArrayUtility
Definition: ArrayUtility.php:24
‪$GLOBALS
‪$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['adminpanel']['modules']
Definition: ext_localconf.php:5
‪TYPO3\CMS\Core\Core\Bootstrap
Definition: Bootstrap.php:66
‪TYPO3\CMS\Lowlevel\Command
Definition: CleanFlexFormsCommand.php:18
‪TYPO3\CMS\Core\Database\ConnectionPool
Definition: ConnectionPool.php:46
‪TYPO3\CMS\Core\Utility\GeneralUtility
Definition: GeneralUtility.php:46