828a8d35617c82b66162be9c52886d4677ff5e68
[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 /**
18 * Looking for RTE images integrity
19 *
20 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
21 */
22 class RteImagesCommand extends CleanerCommand {
23
24 /**
25 * @var bool
26 */
27 public $checkRefIndex = TRUE;
28
29 /**
30 * Constructor
31 */
32 public function __construct() {
33 parent::__construct();
34 // Setting up help:
35 $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.';
36 $this->cli_help['description'] = trim('
37 Assumptions:
38 - a perfect integrity of the reference index table (always update the reference index table before using this tool!)
39 - that all RTEmagic image files in the database are registered with the soft reference parser "images"
40 - images found in deleted records are included (means that you might find lost RTEmagic images after flushing deleted records)
41
42 The assumptions are not requirements by the TYPO3 API but reflects the de facto implementation of most TYPO3 installations.
43 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.
44 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!
45
46 Automatic Repair of Errors:
47 - Will search for double-usages of RTEmagic images and make copies as required.
48 - 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.
49
50 Manual repair suggestions:
51 - Missing files: Re-insert missing files or edit record where the reference is found.
52 ');
53 $this->cli_help['examples'] = '/.../cli_dispatch.phpsh lowlevel_cleaner rte_images -s -r
54 Reports problems with RTE images';
55 }
56
57 /**
58 * Analyse situation with RTE magic images. (still to define what the most useful output is).
59 * Fix methods: API in \TYPO3\CMS\Core\Database\ReferenceIndex that allows to
60 * change the value of a reference (we could copy the files) or remove reference
61 *
62 * @return array
63 */
64 public function main() {
65 // Initialize result array:
66 $resultArray = array(
67 'message' => $this->cli_help['name'] . LF . LF . $this->cli_help['description'],
68 'headers' => array(
69 '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),
70 'RTEmagicFilePairs' => array('Statistical info about RTEmagic files', '(copy used as index)', 0),
71 '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),
72 'missingFiles' => array('Missing RTEmagic image files', 'These files are not found in the file system! Should be corrected!', 3),
73 '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)
74 ),
75 'RTEmagicFilePairs' => array(),
76 'doubleFiles' => array(),
77 'completeFileList' => array(),
78 'missingFiles' => array(),
79 'lostFiles' => array()
80 );
81 // Select all RTEmagic files in the reference table (only from soft references of course)
82 $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');
83 // Traverse the files and put into a large table:
84 if (is_array($recs)) {
85 foreach ($recs as $rec) {
86 $filename = basename($rec['ref_string']);
87 if (\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($filename, 'RTEmagicC_')) {
88 $original = 'RTEmagicP_' . preg_replace('/\\.[[:alnum:]]+$/', '', substr($filename, 10));
89 $infoString = $this->infoStr($rec);
90 // Build index:
91 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['exists'] = @is_file((PATH_site . $rec['ref_string']));
92 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original'] = substr($rec['ref_string'], 0, -strlen($filename)) . $original;
93 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original_exists'] = @is_file((PATH_site . $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original']));
94 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['count']++;
95 $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['usedIn'][$rec['hash']] = $infoString;
96 $resultArray['completeFileList'][$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original']]++;
97 $resultArray['completeFileList'][$rec['ref_string']]++;
98 // Missing files:
99 if (!$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['exists']) {
100 $resultArray['missingFiles'][$rec['ref_string']] = $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['usedIn'];
101 }
102 if (!$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original_exists']) {
103 $resultArray['missingFiles'][$resultArray['RTEmagicFilePairs'][$rec['ref_string']]['original']] = $resultArray['RTEmagicFilePairs'][$rec['ref_string']]['usedIn'];
104 }
105 }
106 }
107 // Searching for duplicates:
108 foreach ($resultArray['RTEmagicFilePairs'] as $fileName => $fileInfo) {
109 if ($fileInfo['count'] > 1 && $fileInfo['exists'] && $fileInfo['original_exists']) {
110 $resultArray['doubleFiles'][$fileName] = $fileInfo['usedIn'];
111 }
112 }
113 }
114 // Now, ask for RTEmagic files inside uploads/ folder:
115 $cleanerModules = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['lowlevel']['cleanerModules'];
116 $cleanerMode = \TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($cleanerModules['lost_files'][0]);
117 $resLostFiles = $cleanerMode->main(array(), FALSE, TRUE);
118 if (is_array($resLostFiles['RTEmagicFiles'])) {
119 foreach ($resLostFiles['RTEmagicFiles'] as $fileName) {
120 if (!isset($resultArray['completeFileList'][$fileName])) {
121 $resultArray['lostFiles'][$fileName] = $fileName;
122 }
123 }
124 }
125 ksort($resultArray['RTEmagicFilePairs']);
126 ksort($resultArray['completeFileList']);
127 ksort($resultArray['missingFiles']);
128 ksort($resultArray['doubleFiles']);
129 ksort($resultArray['lostFiles']);
130 return $resultArray;
131 }
132
133 /**
134 * Mandatory autofix function
135 * Will run auto-fix on the result array. Echos status during processing.
136 *
137 * @param array $resultArray Result array from main() function
138 * @return void
139 */
140 public function main_autoFix($resultArray) {
141 $limitTo = $this->cli_args['--AUTOFIX'][0];
142 if (is_array($resultArray['doubleFiles'])) {
143 if (!$limitTo || $limitTo === 'doubleFiles') {
144 echo 'FIXING double-usages of RTE files in uploads/: ' . LF;
145 foreach ($resultArray['RTEmagicFilePairs'] as $fileName => $fileInfo) {
146 // Only fix something if there is a usage count of more than 1 plus if both original and copy exists:
147 if ($fileInfo['count'] > 1 && $fileInfo['exists'] && $fileInfo['original_exists']) {
148 // Traverse all records using the file:
149 $c = 0;
150 foreach ($fileInfo['usedIn'] as $hash => $recordID) {
151 if ($c == 0) {
152 echo ' Keeping file ' . $fileName . ' for record ' . $recordID . LF;
153 } else {
154 // CODE below is adapted from \TYPO3\CMS\Impexp\ImportExport where there is support for duplication of RTE images:
155 echo ' Copying file ' . basename($fileName) . ' for record ' . $recordID . ' ';
156 // Initialize; Get directory prefix for file and set the original name:
157 $dirPrefix = dirname($fileName) . '/';
158 $rteOrigName = basename($fileInfo['original']);
159 // If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file!
160 if ($rteOrigName && \TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($dirPrefix, 'uploads/') && @is_dir((PATH_site . $dirPrefix))) {
161 // RTE:
162 // From the "original" RTE filename, produce a new "original" destination filename which is unused.
163 $fileProcObj = $this->getFileProcObj();
164 $origDestName = $fileProcObj->getUniqueName($rteOrigName, PATH_site . $dirPrefix);
165 // Create copy file name:
166 $pI = pathinfo($fileName);
167 $copyDestName = dirname($origDestName) . '/RTEmagicC_' . substr(basename($origDestName), 10) . '.' . $pI['extension'];
168 if (!@is_file($copyDestName) && !@is_file($origDestName) && $origDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($origDestName) && $copyDestName === \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($copyDestName)) {
169 echo ' to ' . basename($copyDestName);
170 if ($bypass = $this->cli_noExecutionCheck($fileName)) {
171 echo $bypass;
172 } else {
173 // Making copies:
174 \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $fileInfo['original'], $origDestName);
175 \TYPO3\CMS\Core\Utility\GeneralUtility::upload_copy_move(PATH_site . $fileName, $copyDestName);
176 clearstatcache();
177 if (@is_file($copyDestName)) {
178 $sysRefObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ReferenceIndex::class);
179 $error = $sysRefObj->setReferenceValue($hash, \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($copyDestName));
180 if ($error) {
181 echo ' - ERROR: TYPO3\\CMS\\Core\\Database\\ReferenceIndex::setReferenceValue(): ' . $error . LF;
182 die;
183 } else {
184 echo ' - DONE';
185 }
186 } else {
187 echo ' - ERROR: File "' . $copyDestName . '" was not created!';
188 }
189 }
190 } else {
191 echo ' - ERROR: Could not construct new unique names for file!';
192 }
193 } else {
194 echo ' - ERROR: Maybe directory of file was not within "uploads/"?';
195 }
196 echo LF;
197 }
198 $c++;
199 }
200 }
201 }
202 } else {
203 echo 'Bypassing fixing of double-usages since --AUTOFIX was not "doubleFiles"' . LF;
204 }
205 }
206 if (is_array($resultArray['lostFiles'])) {
207 if ($limitTo === 'lostFiles') {
208 echo 'Removing lost RTEmagic files from folders inside uploads/: ' . LF;
209 foreach ($resultArray['lostFiles'] as $key => $value) {
210 $absFileName = \TYPO3\CMS\Core\Utility\GeneralUtility::getFileAbsFileName($value);
211 echo 'Deleting file: "' . $absFileName . '": ';
212 if ($bypass = $this->cli_noExecutionCheck($absFileName)) {
213 echo $bypass;
214 } else {
215 if ($absFileName && @is_file($absFileName)) {
216 unlink($absFileName);
217 echo 'DONE';
218 } else {
219 echo ' ERROR: File "' . $absFileName . '" was not found!';
220 }
221 }
222 echo LF;
223 }
224 }
225 } else {
226 echo 'Bypassing fixing of double-usages since --AUTOFIX was not "lostFiles"' . LF;
227 }
228 }
229
230 /**
231 * Returns file processing object, initialized only once.
232 *
233 * @return object File processor object
234 */
235 public function getFileProcObj() {
236 if (!is_object($this->fileProcObj)) {
237 $this->fileProcObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Utility\File\ExtendedFileUtility::class);
238 $this->fileProcObj->init(array(), $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']);
239 $this->fileProcObj->setActionPermissions();
240 }
241 return $this->fileProcObj;
242 }
243
244 }