[CLEANUP] Improve the @param/@return/@var PHPDoc
[Packages/TYPO3.CMS.git] / typo3 / sysext / lowlevel / Classes / RteImagesCommand.php
1 <?php
2 namespace TYPO3\CMS\Lowlevel;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
18
19 /**
20 * Looking for RTE images integrity
21 *
22 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
23 */
24 class RteImagesCommand extends CleanerCommand {
25
26 /**
27 * @var bool
28 */
29 public $checkRefIndex = TRUE;
30
31 /**
32 * @var ExtendedFileUtility
33 */
34 protected $fileProcObj = NULL;
35
36 /**
37 * Constructor
38 */
39 public function __construct() {
40 parent::__construct();
41 // Setting up help:
42 $this->cli_help['name'] = 'rte_images -- Looking up all occurencies of RTEmagic images in the database and check existence of parent and copy files on the file system plus report possibly lost files of this type.';
43 $this->cli_help['description'] = trim('
44 Assumptions:
45 - a perfect integrity of the reference index table (always update the reference index table before using this tool!)
46 - that all RTEmagic image files in the database are registered with the soft reference parser "images"
47 - images found in deleted records are included (means that you might find lost RTEmagic images after flushing deleted records)
48
49 The assumptions are not requirements by the TYPO3 API but reflects the de facto implementation of most TYPO3 installations.
50 However, many custom fields using an RTE will probably not have the "images" soft reference parser registered and so the index will be incomplete and not listing all RTEmagic image files.
51 The consequence of this limitation is that you should be careful if you wish to delete lost RTEmagic images - they could be referenced from a field not parsed by the "images" soft reference parser!
52
53 Automatic Repair of Errors:
54 - Will search for double-usages of RTEmagic images and make copies as required.
55 - Lost files can be deleted automatically by setting the value "lostFiles" as an optional parameter to --AUTOFIX, but otherwise delete them manually if you do not recognize them as used somewhere the system does not know about.
56
57 Manual repair suggestions:
58 - Missing files: Re-insert missing files or edit record where the reference is found.
59 ');
60 $this->cli_help['examples'] = '/.../cli_dispatch.phpsh lowlevel_cleaner rte_images -s -r
61 Reports problems with RTE images';
62 }
63
64 /**
65 * Analyse situation with RTE magic images. (still to define what the most useful output is).
66 * Fix methods: API in \TYPO3\CMS\Core\Database\ReferenceIndex that allows to
67 * change the value of a reference (we could copy the files) or remove reference
68 *
69 * @return array
70 */
71 public function main() {
72 // Initialize result array:
73 $resultArray = array(
74 'message' => $this->cli_help['name'] . LF . LF . $this->cli_help['description'],
75 'headers' => array(
76 'completeFileList' => array('Complete list of used RTEmagic files', 'Both parent and copy are listed here including usage count (which should in theory all be "1"). This list does not exclude files that might be missing.', 1),
77 'RTEmagicFilePairs' => array('Statistical info about RTEmagic files', '(copy used as index)', 0),
78 'doubleFiles' => array('Duplicate RTEmagic image files', 'These files are RTEmagic images found used in multiple records! RTEmagic images should be used by only one record at a time. A large amount of such images probably stems from previous versions of TYPO3 (before 4.2) which did not support making copies automatically of RTEmagic images in case of new copies / versions.', 3),
79 'missingFiles' => array('Missing RTEmagic image files', 'These files are not found in the file system! Should be corrected!', 3),
80 'lostFiles' => array('Lost RTEmagic files from uploads/', 'These files you might be able to delete but only if _all_ RTEmagic images are found by the soft reference parser. If you are using the RTE in third-party extensions it is likely that the soft reference parser is not applied correctly to their RTE and thus these "lost" files actually represent valid RTEmagic images, just not registered. Lost files can be auto-fixed but only if you specifically set "lostFiles" as parameter to the --AUTOFIX option.', 2)
81 ),
82 'RTEmagicFilePairs' => array(),
83 'doubleFiles' => array(),
84 'completeFileList' => array(),
85 'missingFiles' => array(),
86 'lostFiles' => array()
87 );
88 // Select all RTEmagic files in the reference table (only from soft references of course)
89 $recs = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'sys_refindex', 'ref_table=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('_FILE', 'sys_refindex') . ' AND ref_string LIKE ' . $GLOBALS['TYPO3_DB']->fullQuoteStr('%/RTEmagic%', 'sys_refindex') . ' AND softref_key=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('images', 'sys_refindex'), '', 'sorting DESC');
90 // Traverse the files and put into a large table:
91 if (is_array($recs)) {
92 foreach ($recs as $rec) {
93 $filename = basename($rec['ref_string']);
94 if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($filename, 'RTEmagicC_')) {
95 $original = 'RTEmagicP_' . preg_replace('/\\.[[:alnum:]]+$/', '', substr($filename, 10));
96 $infoString = $this->infoStr($rec);
97 // Build index:
98 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['exists'] = @is_file((PATH_site . $rec['ref_string']));
99 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original'] = substr($rec['ref_string'], 0, -strlen($filename)) . $original;
100 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original_exists'] = @is_file((PATH_site . $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original']));
101 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['count']++;
102 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['usedIn'][$rec['hash']] = $infoString;
103 $resultArray['completeFileList'][$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original']]++;
104 $resultArray['completeFileList'][$rec['ref_string']]++;
105 // Missing files:
106 if (!$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['exists']) {
107 $resultArray['missingFiles'][$rec['ref_string']] = $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['usedIn'];
108 }
109 if (!$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original_exists']) {
110 $resultArray['missingFiles'][$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original']] = $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['usedIn'];
111 }
112 }
113 }
114 // Searching for duplicates:
115 foreach ($resultArray['RTEmagicFilePairs'] as $fileName => $fileInfo) {
116 if ($fileInfo['count'] > 1 && $fileInfo['exists'] && $fileInfo['original_exists']) {
117 $resultArray['doubleFiles'][$fileName] = $fileInfo['usedIn'];
118 }
119 }
120 }
121 // Now, ask for RTEmagic files inside uploads/ folder:
122 $cleanerModules = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['lowlevel']['cleanerModules'];
123 $cleanerMode = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($cleanerModules['lost_files'][0]);
124 $resLostFiles = $cleanerMode->main(array(), FALSE, TRUE);
125 if (is_array($resLostFiles['RTEmagicFiles'])) {
126 foreach ($resLostFiles['RTEmagicFiles'] as $fileName) {
127 if (!isset($resultArray['completeFileList'][$fileName])) {
128 $resultArray['lostFiles'][$fileName] = $fileName;
129 }
130 }
131 }
132 ksort($resultArray['RTEmagicFilePairs']);
133 ksort($resultArray['completeFileList']);
134 ksort($resultArray['missingFiles']);
135 ksort($resultArray['doubleFiles']);
136 ksort($resultArray['lostFiles']);
137 return $resultArray;
138 }
139
140 /**
141 * Mandatory autofix function
142 * Will run auto-fix on the result array. Echos status during processing.
143 *
144 * @param array $resultArray Result array from main() function
145 * @return void
146 */
147 public function main_autoFix($resultArray) {
148 $limitTo = $this->cli_args['--AUTOFIX'][0];
149 if (is_array($resultArray['doubleFiles'])) {
150 if (!$limitTo || $limitTo === 'doubleFiles') {
151 echo 'FIXING double-usages of RTE files in uploads/: ' . LF;
152 foreach ($resultArray['RTEmagicFilePairs'] as $fileName => $fileInfo) {
153 // Only fix something if there is a usage count of more than 1 plus if both original and copy exists:
154 if ($fileInfo['count'] > 1 && $fileInfo['exists'] && $fileInfo['original_exists']) {
155 // Traverse all records using the file:
156 $c = 0;
157 foreach ($fileInfo['usedIn'] as $hash => $recordID) {
158 if ($c == 0) {
159 echo ' Keeping file ' . $fileName . ' for record ' . $recordID . LF;
160 } else {
161 // CODE below is adapted from \TYPO3\CMS\Impexp\ImportExport where there is support for duplication of RTE images:
162 echo ' Copying file ' . basename($fileName) . ' for record ' . $recordID . ' ';
163 // Initialize; Get directory prefix for file and set the original name:
164 $dirPrefix = dirname($fileName) . '/';
165 $rteOrigName = basename($fileInfo['original']);
166 // If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file!
167 if ($rteOrigName && \TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($dirPrefix, 'uploads/') && @is_dir((PATH_site . $dirPrefix))) {
168 // RTE:
169 // From the "original" RTE filename, produce a new "original" destination filename which is unused.
170 $fileProcObj = $this->getFileProcObj();
171 $origDestName = $fileProcObj->getUniqueName($rteOrigName, PATH_site . $dirPrefix);
172 // Create copy file name:
173 $pI = pathinfo($fileName);
174 $copyDestName = dirname($origDestName) . '/RTEmagicC_' . substr(basename($origDestName), 10) . '.' . $pI['extension'];
175 if (!@is_file($copyDestName) && !@is_file($origDestName) && $origDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($origDestName) && $copyDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($copyDestName)) {
176 echo ' to ' . basename($copyDestName);
177 if ($bypass = $this->cli_noExecutionCheck($fileName)) {
178 echo $bypass;
179 } else {
180 // Making copies:
181 \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $fileInfo['original'], $origDestName);
182 \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $fileName, $copyDestName);
183 clearstatcache();
184 if (@is_file($copyDestName)) {
185 $sysRefObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ReferenceIndex::class);
186 $error = $sysRefObj->setReferenceValue($hash, \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($copyDestName));
187 if ($error) {
188 echo ' - ERROR: TYPO3\\CMS\\Core\\Database\\ReferenceIndex::setReferenceValue(): ' . $error . LF;
189 die;
190 } else {
191 echo ' - DONE';
192 }
193 } else {
194 echo ' - ERROR: File "' . $copyDestName . '" was not created!';
195 }
196 }
197 } else {
198 echo ' - ERROR: Could not construct new unique names for file!';
199 }
200 } else {
201 echo ' - ERROR: Maybe directory of file was not within "uploads/"?';
202 }
203 echo LF;
204 }
205 $c++;
206 }
207 }
208 }
209 } else {
210 echo 'Bypassing fixing of double-usages since --AUTOFIX was not "doubleFiles"' . LF;
211 }
212 }
213 if (is_array($resultArray['lostFiles'])) {
214 if ($limitTo === 'lostFiles') {
215 echo 'Removing lost RTEmagic files from folders inside uploads/: ' . LF;
216 foreach ($resultArray['lostFiles'] as $key => $value) {
217 $absFileName = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($value);
218 echo 'Deleting file: "' . $absFileName . '": ';
219 if ($bypass = $this->cli_noExecutionCheck($absFileName)) {
220 echo $bypass;
221 } else {
222 if ($absFileName && @is_file($absFileName)) {
223 unlink($absFileName);
224 echo 'DONE';
225 } else {
226 echo ' ERROR: File "' . $absFileName . '" was not found!';
227 }
228 }
229 echo LF;
230 }
231 }
232 } else {
233 echo 'Bypassing fixing of double-usages since --AUTOFIX was not "lostFiles"' . LF;
234 }
235 }
236
237 /**
238 * Returns file processing object, initialized only once.
239 *
240 * @return ExtendedFileUtility File processor object
241 */
242 public function getFileProcObj() {
243 if (!is_object($this->fileProcObj)) {
244 $this->fileProcObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(ExtendedFileUtility::class);
245 $this->fileProcObj->init(array(), $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']);
246 $this->fileProcObj->setActionPermissions();
247 }
248 return $this->fileProcObj;
249 }
250
251 }