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