‪TYPO3CMS  ‪main
OrphanRecordsCommand.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;
25 use TYPO3\CMS\Backend\Utility\BackendUtility;
31 
35 class ‪OrphanRecordsCommand extends Command
36 {
37  public function ‪__construct(private readonly ‪ConnectionPool $connectionPool)
38  {
39  parent::__construct();
40  }
41 
45  public function ‪configure()
46  {
47  $this
48  ->setHelp('Assumption: All actively used records on the website from TCA configured tables are located in the page tree exclusively.
49 
50 All records managed by TYPO3 via the TCA array configuration has to belong to a page in the page tree, either directly or indirectly as a version of another record.
51 VERY TIME, CPU and MEMORY intensive operation since the full page tree is looked up!
52 
53 Automatic Repair of Errors:
54 - Silently deleting the orphaned records. In theory they should not be used anywhere in the system, but there could be references. See below for more details on this matter.
55 
56 Manual repair suggestions:
57 - Possibly re-connect orphaned records to page tree by setting their "pid" field to a valid page id. A lookup in the sys_refindex table can reveal if there are references to an orphaned record. If there are such references (from records that are not themselves orphans) you might consider to re-connect the record to the page tree, otherwise it should be safe to delete it.
58 
59  If you want to get more detailed information, use the --verbose option.')
60  ->addOption(
61  'dry-run',
62  null,
63  InputOption::VALUE_NONE,
64  'If this option is set, the records will not actually be deleted, but just the output which records would be deleted are shown'
65  );
66  }
67 
72  protected function ‪execute(InputInterface $input, OutputInterface ‪$output): int
73  {
74  // Make sure the _cli_ user is loaded
76 
77  $io = new SymfonyStyle($input, ‪$output);
78  $io->title($this->getDescription());
79 
80  if ($io->isVerbose()) {
81  $io->section('Searching the database now for orphaned records.');
82  }
83 
84  $dryRun = $input->hasOption('dry-run') && (bool)$input->getOption('dry-run') !== false;
85 
86  // find all records that should be deleted
87  $allRecords = $this->‪findAllConnectedRecordsInPage(0, 10000);
88 
89  // Find orphans
90  $orphans = [];
91  foreach (array_keys(‪$GLOBALS['TCA']) as $tableName) {
92  $idList = [0];
93  if (is_array($allRecords[$tableName] ?? false) && !empty($allRecords[$tableName])) {
94  $idList = $allRecords[$tableName];
95  }
96  // Select all records that are NOT connected
97  $queryBuilder = $this->connectionPool
98  ->getQueryBuilderForTable($tableName);
99  $queryBuilder->getRestrictions()->removeAll();
100  $queryBuilder
101  ->from($tableName)
102  ->where(
103  $queryBuilder->expr()->notIn(
104  'uid',
105  // do not use named parameter here as the list can get too long
106  array_map('intval', $idList)
107  )
108  );
109 
110  $countQueryBuilder = clone $queryBuilder;
111  $rowCount = $countQueryBuilder->count('uid')->executeQuery()->fetchOne();
112  if ($rowCount) {
113  $queryBuilder->select('uid')->orderBy('uid');
114  $result = $queryBuilder->executeQuery();
115 
116  $orphans[$tableName] = [];
117  while ($orphanRecord = $result->fetchAssociative()) {
118  $orphans[$tableName][$orphanRecord['uid']] = $orphanRecord['uid'];
119  }
120 
121  if (count($orphans[$tableName])) {
122  $io->note('Found ' . count($orphans[$tableName]) . ' orphan records in table "' . $tableName . '" with following ids: ' . implode(', ', $orphans[$tableName]));
123  }
124  }
125  }
126 
127  if (count($orphans)) {
128  $io->section('Deletion process starting now.' . ($dryRun ? ' (Not deleting now, just a dry run)' : ''));
129 
130  // Actually permanently delete them
131  $this->‪deleteRecords($orphans, $dryRun, $io);
132 
133  $io->success('All done!');
134  } else {
135  $io->success('No orphan records found.');
136  }
137  return Command::SUCCESS;
138  }
139 
151  protected function ‪findAllConnectedRecordsInPage(int $pageId, int $depth, array $allRecords = []): array
152  {
153  // Register page
154  if ($pageId > 0) {
155  $allRecords['pages'][$pageId] = $pageId;
156  }
157  // Traverse tables of records that belongs to page
158  foreach (array_keys(‪$GLOBALS['TCA']) as $tableName) {
160  if ($tableName !== 'pages') {
161  // Select all records belonging to page:
162  $queryBuilder = $this->connectionPool
163  ->getQueryBuilderForTable($tableName);
164 
165  $queryBuilder->getRestrictions()->removeAll();
166 
167  $result = $queryBuilder
168  ->select('uid')
169  ->from($tableName)
170  ->where(
171  $queryBuilder->expr()->eq(
172  'pid',
173  $queryBuilder->createNamedParameter($pageId, ‪Connection::PARAM_INT)
174  )
175  )
176  ->executeQuery();
177 
178  while ($rowSub = $result->fetchAssociative()) {
179  $allRecords[$tableName][$rowSub['uid']] = $rowSub['uid'];
180  // Add any versions of those records:
181  $versions = BackendUtility::selectVersionsOfRecord($tableName, $rowSub['uid'], 'uid,t3ver_wsid', null, true);
182  if (is_array($versions)) {
183  foreach ($versions as $verRec) {
184  if (!($verRec['_CURRENT_VERSION'] ?? false)) {
185  $allRecords[$tableName][$verRec['uid']] = $verRec['uid'];
186  }
187  }
188  }
189  }
190  }
191  }
192  // Find subpages to root ID and traverse (only when rootID is not a version or is a branch-version):
193  if ($depth > 0) {
194  $depth--;
195  $queryBuilder = $this->connectionPool
196  ->getQueryBuilderForTable('pages');
197 
198  $queryBuilder->getRestrictions()->removeAll();
199 
200  $result = $queryBuilder
201  ->select('uid')
202  ->from('pages')
203  ->where(
204  $queryBuilder->expr()->eq(
205  'pid',
206  $queryBuilder->createNamedParameter($pageId, ‪Connection::PARAM_INT)
207  )
208  )
209  ->orderBy('sorting')
210  ->executeQuery();
211 
212  while ($row = $result->fetchAssociative()) {
213  $allRecords = $this->‪findAllConnectedRecordsInPage((int)$row['uid'], $depth, $allRecords);
214  }
215  }
216 
217  // Add any versions of pages
218  if ($pageId > 0) {
219  $versions = BackendUtility::selectVersionsOfRecord('pages', $pageId, 'uid,t3ver_oid,t3ver_wsid', null, true);
220  if (is_array($versions)) {
221  foreach ($versions as $verRec) {
222  if (!($verRec['_CURRENT_VERSION'] ?? false)) {
223  $allRecords = $this->‪findAllConnectedRecordsInPage((int)$verRec['uid'], $depth, $allRecords);
224  }
225  }
226  }
227  }
228  return $allRecords;
229  }
230 
237  protected function ‪deleteRecords(array $orphanedRecords, bool $dryRun, SymfonyStyle $io): void
238  {
239  // Putting "pages" table in the bottom
240  if (isset($orphanedRecords['pages'])) {
241  $_pages = $orphanedRecords['pages'];
242  unset($orphanedRecords['pages']);
243  // To delete sub pages first assuming they are accumulated from top of page tree.
244  $orphanedRecords['pages'] = array_reverse($_pages);
245  }
246 
247  // set up the data handler instance
248  $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
249  $dataHandler->start([], []);
250 
251  // Loop through all tables and their records
252  foreach ($orphanedRecords as $table => $list) {
253  if ($io->isVerbose()) {
254  $io->writeln('Flushing ' . count($list) . ' orphaned records from table "' . $table . '"');
255  }
256  foreach ($list as ‪$uid) {
257  if ($io->isVeryVerbose()) {
258  $io->writeln('Flushing record "' . $table . ':' . ‪$uid . '"');
259  }
260  if (!$dryRun) {
261  // Notice, we are deleting pages with no regard to subpages/subrecords - we do this since they
262  // should also be included in the set of deleted pages of course (no un-deleted record can exist
263  // under a deleted page...)
264  $dataHandler->deleteRecord($table, ‪$uid, true, true);
265  // Return errors if any:
266  if (!empty($dataHandler->errorLog)) {
267  $errorMessage = array_merge(['DataHandler reported an error'], $dataHandler->errorLog);
268  $io->error($errorMessage);
269  } elseif (!$io->isQuiet()) {
270  $io->writeln('Permanently deleted orphaned record "' . $table . ':' . ‪$uid . '".');
271  }
272  }
273  }
274  }
275  }
276 }
‪TYPO3\CMS\Core\DataHandling\DataHandler
Definition: DataHandler.php:95
‪TYPO3\CMS\Core\Database\Connection\PARAM_INT
‪const PARAM_INT
Definition: Connection.php:50
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand\configure
‪configure()
Definition: OrphanRecordsCommand.php:45
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand
Definition: OrphanRecordsCommand.php:36
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand\deleteRecords
‪deleteRecords(array $orphanedRecords, bool $dryRun, SymfonyStyle $io)
Definition: OrphanRecordsCommand.php:237
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand\findAllConnectedRecordsInPage
‪array findAllConnectedRecordsInPage(int $pageId, int $depth, array $allRecords=[])
Definition: OrphanRecordsCommand.php:151
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand\__construct
‪__construct(private readonly ConnectionPool $connectionPool)
Definition: OrphanRecordsCommand.php:37
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand\execute
‪execute(InputInterface $input, OutputInterface $output)
Definition: OrphanRecordsCommand.php:72
‪$output
‪$output
Definition: annotationChecker.php:119
‪TYPO3\CMS\Core\Database\Connection
Definition: Connection.php:39
‪TYPO3\CMS\Webhooks\Message\$uid
‪identifier readonly int $uid
Definition: PageModificationMessage.php:35
‪$GLOBALS
‪$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['adminpanel']['modules']
Definition: ext_localconf.php:25
‪TYPO3\CMS\Core\Core\Bootstrap
Definition: Bootstrap.php:64
‪TYPO3\CMS\Lowlevel\Command
Definition: CleanFlexFormsCommand.php:18
‪TYPO3\CMS\Core\Database\ConnectionPool
Definition: ConnectionPool.php:48
‪TYPO3\CMS\Core\Utility\GeneralUtility
Definition: GeneralUtility.php:51
‪TYPO3\CMS\Core\Core\Bootstrap\initializeBackendAuthentication
‪static initializeBackendAuthentication()
Definition: Bootstrap.php:529