TYPO3CMS  8
 All Classes Namespaces Files Functions Variables Pages
LostFilesCommand.php
Go to the documentation of this file.
1 <?php
2 declare(strict_types=1);
3 namespace TYPO3\CMS\Lowlevel\Command;
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 
18 use Symfony\Component\Console\Command\Command;
19 use Symfony\Component\Console\Input\InputInterface;
20 use Symfony\Component\Console\Input\InputOption;
21 use Symfony\Component\Console\Output\OutputInterface;
22 use Symfony\Component\Console\Style\SymfonyStyle;
26 
30 class LostFilesCommand extends Command
31 {
32 
36  public function configure()
37  {
38  $this
39  ->setDescription('Looking for files in the uploads/ folder which does not have a reference in TYPO3 managed records.')
40  ->setHelp('
41 Assumptions:
42 - a perfect integrity of the reference index table (always update the reference index table before using this tool!)
43 - that all contents in the uploads folder are files attached to TCA records and exclusively managed by DataHandler through "group" type fields
44 - index.html, .htaccess files and RTEmagic* image files (ignored)
45 - Files found in deleted records are included (otherwise you would see a false list of lost files)
46 
47 The assumptions are not requirements by the TYPO3 API but reflects the de facto implementation of most TYPO3 installations and therefore a practical approach to cleaning up the uploads/ folder.
48 Therefore, if all "group" type fields in TCA and flexforms are positioned inside the uploads/ folder and if no files inside are managed manually it should be safe to clean out files with no relations found in the system.
49 Under such circumstances there should theoretically be no lost files in the uploads/ folder since DataHandler should have managed relations automatically including adding and deleting files.
50 However, there is at least one reason known to why files might be found lost and that is when FlexForms are used. In such a case a change of/in the Data Structure XML (or the ability of the system to find the Data Structure definition!) used for the flexform could leave lost files behind. This is not unlikely to happen when records are deleted. More details can be found in a note to the function FlexFormTools->getDataStructureIdentifier()
51 Another scenario could of course be de-installation of extensions which managed files in the uploads/ folders.
52 
53 If the option "--dry-run" is not set, the files are then deleted automatically.
54 Warning: First, make sure those files are not used somewhere TYPO3 does not know about! See the assumptions above.
55 
56 If you want to get more detailed information, use the --verbose option.')
57  ->addOption(
58  'exclude',
59  null,
60  InputOption::VALUE_REQUIRED,
61  'Comma-separated list of paths that should be excluded, e.g. "uploads/pics,uploads/media"'
62  )
63  ->addOption(
64  'dry-run',
65  null,
66  InputOption::VALUE_NONE,
67  'If this option is set, the files will not actually be deleted, but just the output which files would be deleted are shown'
68  )
69  ->addOption(
70  'update-refindex',
71  null,
72  InputOption::VALUE_NONE,
73  'Setting this option automatically updates the reference index and does not ask on command line. Alternatively, use -n to avoid the interactive mode'
74  );
75  }
76 
88  protected function execute(InputInterface $input, OutputInterface $output)
89  {
90  $io = new SymfonyStyle($input, $output);
91  $io->title($this->getDescription());
92 
93  $dryRun = $input->hasOption('dry-run') && $input->getOption('dry-run') != false ? true : false;
94 
95  $this->updateReferenceIndex($input, $io);
96 
97  // Find the lost files
98  if ($input->hasOption('exclude') && !empty($input->getOption('exclude'))) {
99  $excludedPaths = GeneralUtility::trimExplode(',', $input->getOption('exclude'), true);
100  } else {
101  $excludedPaths = [];
102  }
103  $lostFiles = $this->findLostFiles($excludedPaths);
104 
105  if (count($lostFiles)) {
106  if (!$io->isQuiet()) {
107  $io->note('Found ' . count($lostFiles) . ' lost files, ready to be deleted.');
108  if ($io->isVerbose()) {
109  $io->listing($lostFiles);
110  }
111  }
112 
113  // Delete them
114  $this->deleteLostFiles($lostFiles, $dryRun, $io);
115 
116  $io->success('Deleted ' . count($lostFiles) . ' lost files.');
117  } else {
118  $io->success('Nothing to do, no lost files found');
119  }
120  }
121 
132  protected function updateReferenceIndex(InputInterface $input, SymfonyStyle $io)
133  {
134  // Check for reference index to update
135  $io->note('Finding lost files managed by TYPO3 requires a clean reference index (sys_refindex)');
136  $updateReferenceIndex = false;
137  if ($input->hasOption('update-refindex') && $input->getOption('update-refindex')) {
138  $updateReferenceIndex = true;
139  } elseif ($input->isInteractive()) {
140  $updateReferenceIndex = $io->confirm('Should the reference index be updated right now?', false);
141  }
142 
143  // Update the reference index
144  if ($updateReferenceIndex) {
145  $referenceIndex = GeneralUtility::makeInstance(ReferenceIndex::class);
146  $referenceIndex->updateIndex(false, !$io->isQuiet());
147  } else {
148  $io->writeln('Reference index is assumed to be up to date, continuing.');
149  }
150  }
151 
158  protected function findLostFiles($excludedPaths = []): array
159  {
160  $lostFiles = [];
161 
162  // Get all files
163  $files = [];
164  $files = GeneralUtility::getAllFilesAndFoldersInPath($files, PATH_site . 'uploads/');
165  $files = GeneralUtility::removePrefixPathFromList($files, PATH_site);
166 
167  $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
168  ->getQueryBuilderForTable('sys_refindex');
169 
170  // Traverse files and for each, look up if its found in the reference index.
171  foreach ($files as $key => $value) {
172 
173  // First, allow "index.html", ".htaccess" files since they are often used for good reasons
174  if (substr($value, -11) === '/index.html' || substr($value, -10) === '/.htaccess') {
175  continue;
176  }
177 
178  // If the file is a RTEmagic-image name and if so, we allow it
179  if (preg_match('/^RTEmagic[P|C]_/', basename($value))) {
180  continue;
181  }
182 
183  $fileIsInExcludedPath = false;
184  foreach ($excludedPaths as $exclPath) {
185  if (GeneralUtility::isFirstPartOfStr($value, $exclPath)) {
186  $fileIsInExcludedPath = true;
187  break;
188  }
189  }
190 
191  if ($fileIsInExcludedPath) {
192  continue;
193  }
194 
195  // Looking for a reference from a field which is NOT a soft reference (thus, only fields with a proper TCA/Flexform configuration)
196  $result = $queryBuilder
197  ->select('hash')
198  ->from('sys_refindex')
199  ->where(
200  $queryBuilder->expr()->eq(
201  'ref_table',
202  $queryBuilder->createNamedParameter('_FILE', \PDO::PARAM_STR)
203  ),
204  $queryBuilder->expr()->eq(
205  'ref_string',
206  $queryBuilder->createNamedParameter($value, \PDO::PARAM_STR)
207  ),
208  $queryBuilder->expr()->eq(
209  'softref_key',
210  $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
211  )
212  )
213  ->orderBy('sorting', 'DESC')
214  ->execute();
215 
216  // We conclude that the file is lost
217  if ($result->rowCount() === 0) {
218  $lostFiles[] = $value;
219  }
220  }
221 
222  return $lostFiles;
223  }
224 
233  protected function deleteLostFiles(array $lostFiles, bool $dryRun, SymfonyStyle $io)
234  {
235  foreach ($lostFiles as $lostFile) {
236  $absoluteFileName = GeneralUtility::getFileAbsFileName($lostFile);
237  if ($io->isVeryVerbose()) {
238  $io->writeln('Deleting file "' . $absoluteFileName . '"');
239  }
240  if (!$dryRun) {
241  if ($absoluteFileName && @is_file($absoluteFileName)) {
242  unlink($absoluteFileName);
243  if (!$io->isQuiet()) {
244  $io->writeln('Permanently deleted file record "' . $absoluteFileName . '".');
245  }
246  } else {
247  $io->error('File "' . $absoluteFileName . '" was not found!');
248  }
249  }
250  }
251  }
252 }
execute(InputInterface $input, OutputInterface $output)
static isFirstPartOfStr($str, $partStr)
static trimExplode($delim, $string, $removeEmptyValues=false, $limit=0)
static removePrefixPathFromList(array $fileArr, $prefixToRemove)
updateReferenceIndex(InputInterface $input, SymfonyStyle $io)
static makeInstance($className,...$constructorArguments)
static getFileAbsFileName($filename, $_=null, $_2=null)
deleteLostFiles(array $lostFiles, bool $dryRun, SymfonyStyle $io)
static getAllFilesAndFoldersInPath(array $fileArr, $path, $extList= '', $regDirs=false, $recursivityLevels=99, $excludePattern= '')