‪TYPO3CMS  10.4
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;
30 
34 class ‪OrphanRecordsCommand extends Command
35 {
36 
40  public function ‪configure()
41  {
42  $this
43  ->setDescription('Find and delete records that have lost their connection with the page tree.')
44  ->setHelp('Assumption: All actively used records on the website from TCA configured tables are located in the page tree exclusively.
45 
46 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.
47 VERY TIME, CPU and MEMORY intensive operation since the full page tree is looked up!
48 
49 Automatic Repair of Errors:
50 - 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.
51 
52 Manual repair suggestions:
53 - 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 a 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.
54 
55  If you want to get more detailed information, use the --verbose option.')
56  ->addOption(
57  'dry-run',
58  null,
59  InputOption::VALUE_NONE,
60  'If this option is set, the records will not actually be deleted, but just the output which records would be deleted are shown'
61  );
62  }
63 
72  protected function ‪execute(InputInterface $input, OutputInterface ‪$output)
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  // type unsafe comparison and explicit boolean setting on purpose
85  $dryRun = $input->hasOption('dry-run') && $input->getOption('dry-run') != false ? true : false;
86 
87  // find all records that should be deleted
88  $allRecords = $this->‪findAllConnectedRecordsInPage(0, 10000);
89 
90  // Find orphans
91  $orphans = [];
92  foreach (array_keys(‪$GLOBALS['TCA']) as $tableName) {
93  $idList = [0];
94  if (is_array($allRecords[$tableName]) && !empty($allRecords[$tableName])) {
95  $idList = $allRecords[$tableName];
96  }
97  // Select all records that are NOT connected
98  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
99  ->getQueryBuilderForTable($tableName);
100  $queryBuilder->getRestrictions()->removeAll();
101  $queryBuilder
102  ->from($tableName)
103  ->where(
104  $queryBuilder->expr()->notIn(
105  'uid',
106  // do not use named parameter here as the list can get too long
107  array_map('intval', $idList)
108  )
109  );
110 
111  $countQueryBuilder = clone $queryBuilder;
112  $rowCount = $countQueryBuilder->count('uid')->execute()->fetchColumn(0);
113  if ($rowCount) {
114  $queryBuilder->select('uid')->orderBy('uid');
115  $result = $queryBuilder->execute();
116 
117  $orphans[$tableName] = [];
118  while ($orphanRecord = $result->fetch()) {
119  $orphans[$tableName][$orphanRecord['uid']] = $orphanRecord['uid'];
120  }
121 
122  if (count($orphans[$tableName])) {
123  $io->note('Found ' . count($orphans[$tableName]) . ' orphan records in table "' . $tableName . '" with following ids: ' . implode(', ', $orphans[$tableName]));
124  }
125  }
126  }
127 
128  if (count($orphans)) {
129  $io->section('Deletion process starting now.' . ($dryRun ? ' (Not deleting now, just a dry run)' : ''));
130 
131  // Actually permanently delete them
132  $this->‪deleteRecords($orphans, $dryRun, $io);
133 
134  $io->success('All done!');
135  } else {
136  $io->success('No orphan records found.');
137  }
138  return 0;
139  }
140 
152  protected function ‪findAllConnectedRecordsInPage(int $pageId, int $depth, array $allRecords = []): array
153  {
154  // Register page
155  if ($pageId > 0) {
156  $allRecords['pages'][$pageId] = $pageId;
157  }
158  // Traverse tables of records that belongs to page
159  foreach (array_keys(‪$GLOBALS['TCA']) as $tableName) {
161  if ($tableName !== 'pages') {
162  // Select all records belonging to page:
163  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
164  ->getQueryBuilderForTable($tableName);
165 
166  $queryBuilder->getRestrictions()->removeAll();
167 
168  $result = $queryBuilder
169  ->select('uid')
170  ->from($tableName)
171  ->where(
172  $queryBuilder->expr()->eq(
173  'pid',
174  $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
175  )
176  )
177  ->execute();
178 
179  while ($rowSub = $result->fetch()) {
180  $allRecords[$tableName][$rowSub['uid']] = $rowSub['uid'];
181  // Add any versions of those records:
182  $versions = ‪BackendUtility::selectVersionsOfRecord($tableName, $rowSub['uid'], 'uid,t3ver_wsid,t3ver_count', null, true);
183  if (is_array($versions)) {
184  foreach ($versions as $verRec) {
185  if (!$verRec['_CURRENT_VERSION']) {
186  $allRecords[$tableName][$verRec['uid']] = $verRec['uid'];
187  }
188  }
189  }
190  }
191  }
192  }
193  // Find subpages to root ID and traverse (only when rootID is not a version or is a branch-version):
194  if ($depth > 0) {
195  $depth--;
196  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
197  ->getQueryBuilderForTable('pages');
198 
199  $queryBuilder->getRestrictions()->removeAll();
200 
201  $result = $queryBuilder
202  ->select('uid')
203  ->from('pages')
204  ->where(
205  $queryBuilder->expr()->eq(
206  'pid',
207  $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT)
208  )
209  )
210  ->orderBy('sorting')
211  ->execute();
212 
213  while ($row = $result->fetch()) {
214  $allRecords = $this->‪findAllConnectedRecordsInPage((int)$row['uid'], $depth, $allRecords);
215  }
216  }
217 
218  // Add any versions of pages
219  if ($pageId > 0) {
220  $versions = ‪BackendUtility::selectVersionsOfRecord('pages', $pageId, 'uid,t3ver_oid,t3ver_wsid,t3ver_count', null, true);
221  if (is_array($versions)) {
222  foreach ($versions as $verRec) {
223  if (!$verRec['_CURRENT_VERSION']) {
224  $allRecords = $this->‪findAllConnectedRecordsInPage((int)$verRec['uid'], $depth, $allRecords);
225  }
226  }
227  }
228  }
229  return $allRecords;
230  }
231 
239  protected function ‪deleteRecords(array $orphanedRecords, bool $dryRun, SymfonyStyle $io)
240  {
241  // Putting "pages" table in the bottom
242  if (isset($orphanedRecords['pages'])) {
243  $_pages = $orphanedRecords['pages'];
244  unset($orphanedRecords['pages']);
245  // To delete sub pages first assuming they are accumulated from top of page tree.
246  $orphanedRecords['pages'] = array_reverse($_pages);
247  }
248 
249  // set up the data handler instance
250  $dataHandler = GeneralUtility::makeInstance(DataHandler::class);
251  $dataHandler->start([], []);
252 
253  // Loop through all tables and their records
254  foreach ($orphanedRecords as $table => $list) {
255  if ($io->isVerbose()) {
256  $io->writeln('Flushing ' . count($list) . ' orphaned records from table "' . $table . '"');
257  }
258  foreach ($list as $uid) {
259  if ($io->isVeryVerbose()) {
260  $io->writeln('Flushing record "' . $table . ':' . $uid . '"');
261  }
262  if (!$dryRun) {
263  // Notice, we are deleting pages with no regard to subpages/subrecords - we do this since they
264  // should also be included in the set of deleted pages of course (no un-deleted record can exist
265  // under a deleted page...)
266  $dataHandler->deleteRecord($table, $uid, true, true);
267  // Return errors if any:
268  if (!empty($dataHandler->errorLog)) {
269  $errorMessage = array_merge(['DataHandler reported an error'], $dataHandler->errorLog);
270  $io->error($errorMessage);
271  } elseif (!$io->isQuiet()) {
272  $io->writeln('Permanently deleted orphaned record "' . $table . ':' . $uid . '".');
273  }
274  }
275  }
276  }
277  }
278 }
‪TYPO3\CMS\Core\DataHandling\DataHandler
Definition: DataHandler.php:84
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand\configure
‪configure()
Definition: OrphanRecordsCommand.php:40
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand
Definition: OrphanRecordsCommand.php:35
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand\execute
‪int execute(InputInterface $input, OutputInterface $output)
Definition: OrphanRecordsCommand.php:72
‪TYPO3\CMS\Core\Core\Bootstrap\initializeBackendAuthentication
‪static initializeBackendAuthentication($proceedIfNoUserIsLoggedIn=false)
Definition: Bootstrap.php:607
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand\deleteRecords
‪deleteRecords(array $orphanedRecords, bool $dryRun, SymfonyStyle $io)
Definition: OrphanRecordsCommand.php:239
‪TYPO3\CMS\Lowlevel\Command\OrphanRecordsCommand\findAllConnectedRecordsInPage
‪array findAllConnectedRecordsInPage(int $pageId, int $depth, array $allRecords=[])
Definition: OrphanRecordsCommand.php:152
‪TYPO3\CMS\Backend\Utility\BackendUtility
Definition: BackendUtility.php:75
‪$output
‪$output
Definition: annotationChecker.php:119
‪$GLOBALS
‪$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['adminpanel']['modules']
Definition: ext_localconf.php:5
‪TYPO3\CMS\Core\Core\Bootstrap
Definition: Bootstrap.php:66
‪TYPO3\CMS\Backend\Utility\BackendUtility\selectVersionsOfRecord
‪static array null selectVersionsOfRecord( $table, $uid, $fields=' *', $workspace=0, $includeDeletedRecords=false, $row=null)
Definition: BackendUtility.php:3416
‪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