2 namespace TYPO3\CMS\Install\Updates
;
4 /***************************************************************
7 * (c) 2011-2013 Ingmar Schlecht <ingmar@typo3.org>
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 3 of the License, or
14 * (at your option) any later version.
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
19 * This script is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * This copyright notice MUST APPEAR in all copies of the script!
25 ***************************************************************/
27 use TYPO3\CMS\Core\Database\DatabaseConnection
;
28 use TYPO3\CMS\Core\Utility\GeneralUtility
;
31 * Upgrade wizard which goes through all files referenced in the tt_content.image filed
32 * and creates sys_file records as well as sys_file_reference records for the individual usages.
34 * @author Ingmar Schlecht <ingmar@typo3.org>
36 class TceformsUpdateWizard
extends AbstractUpdate
{
39 * Number of records fetched per database query
40 * Used to prevent memory overflows for huge databases
42 const RECORDS_PER_QUERY
= 1000;
47 protected $title = 'Migrate all file relations from tt_content.image and pages.media';
50 * @var \TYPO3\CMS\Core\Resource\ResourceStorage
55 * @var \TYPO3\CMS\Core\Log\Logger
60 * @var DatabaseConnection
65 * Table fields to migrate
68 protected $tables = array(
69 'tt_content' => array(
71 'sourcePath' => 'uploads/pics/',
72 // Relative to fileadmin
73 'targetPath' => '_migrated/pics/',
74 'titleTexts' => 'titleText',
75 'captions' => 'imagecaption',
76 'links' => 'image_link',
77 'alternativeTexts' => 'altText'
82 'sourcePath' => 'uploads/media/',
83 // Relative to fileadmin
84 'targetPath' => '_migrated/media/'
87 'pages_language_overlay' => array(
89 'sourcePath' => 'uploads/media/',
90 // Relative to fileadmin
91 'targetPath' => '_migrated/media/'
99 public function __construct() {
100 /** @var $logManager \TYPO3\CMS\Core\Log\LogManager */
101 $logManager = GeneralUtility
::makeInstance('TYPO3\\CMS\\Core\\Log\\LogManager');
102 $this->logger
= $logManager->getLogger(__CLASS__
);
103 $this->database
= $GLOBALS['TYPO3_DB'];
107 * Initialize the storage repository.
109 public function init() {
110 /** @var $storageRepository \TYPO3\CMS\Core\Resource\StorageRepository */
111 $storageRepository = GeneralUtility
::makeInstance('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
112 $storages = $storageRepository->findAll();
113 $this->storage
= $storages[0];
117 * Checks if an update is needed
119 * @param string &$description The description for the update
120 * @return boolean TRUE if an update is needed, FALSE otherwise
122 public function checkForUpdate(&$description) {
123 $description = 'This update wizard goes through all files that are referenced in the tt_content.image and '
124 . 'pages.media / pages_language_overlay.media field and adds the files to the new File Index.<br />'
125 . 'It also moves the files from uploads/ to the fileadmin/_migrated/ path.<br /><br />'
126 . 'This update wizard can be called multiple times in case it didn\'t finish after running once.';
128 if ($this->versionNumber
< 6000000) {
133 $finishedFields = $this->getFinishedFields();
134 if (count($finishedFields) === 0) {
135 // Nothing done yet, so there's plenty of work left
139 $numberOfFieldsToMigrate = 0;
140 foreach ($this->tables
as $table => $tableConfiguration) {
141 // find all additional fields we should get from the database
142 foreach (array_keys($tableConfiguration) as $fieldToMigrate) {
143 $fieldKey = $table . ':' . $fieldToMigrate;
144 if (!in_array($fieldKey, $finishedFields)) {
145 $numberOfFieldsToMigrate++
;
149 return $numberOfFieldsToMigrate > 0;
153 * Performs the database update.
155 * @param array &$dbQueries Queries done in this update
156 * @param mixed &$customMessages Custom messages
157 * @return boolean TRUE on success, FALSE on error
159 public function performUpdate(array &$dbQueries, &$customMessages) {
160 if ($this->versionNumber
< 6000000) {
165 $finishedFields = $this->getFinishedFields();
166 foreach ($this->tables
as $table => $tableConfiguration) {
167 // find all additional fields we should get from the database
168 foreach ($tableConfiguration as $fieldToMigrate => $fieldConfiguration) {
169 $fieldKey = $table . ':' . $fieldToMigrate;
170 if (in_array($fieldKey, $finishedFields)) {
171 // this field was already migrated
174 $fieldsToGet = array($fieldToMigrate);
175 if (isset($fieldConfiguration['titleTexts'])) {
176 $fieldsToGet[] = $fieldConfiguration['titleTexts'];
178 if (isset($fieldConfiguration['alternativeTexts'])) {
179 $fieldsToGet[] = $fieldConfiguration['alternativeTexts'];
181 if (isset($fieldConfiguration['captions'])) {
182 $fieldsToGet[] = $fieldConfiguration['captions'];
184 if (isset($fieldConfiguration['links'])) {
185 $fieldsToGet[] = $fieldConfiguration['links'];
189 $records = $this->getRecordsFromTable($table, $fieldToMigrate, $fieldsToGet, self
::RECORDS_PER_QUERY
);
190 foreach ($records as $record) {
191 $this->migrateField($table, $record, $fieldToMigrate, $fieldConfiguration, $customMessages);
193 } while (count($records) === self
::RECORDS_PER_QUERY
);
195 // add the field to the "finished fields" if things didn't fail above
196 if (is_array($records)) {
197 $finishedFields[] = $fieldKey;
201 $this->markWizardAsDone(implode(',', $finishedFields));
206 * We write down the fields that were migrated. Like this: tt_content:media
207 * so you can check whether a field was already migrated
211 protected function getFinishedFields() {
212 $className = 'TYPO3\\CMS\\Install\\Updates\\TceformsUpdateWizard';
213 return isset($GLOBALS['TYPO3_CONF_VARS']['INSTALL']['wizardDone'][$className])
214 ?
explode(',', $GLOBALS['TYPO3_CONF_VARS']['INSTALL']['wizardDone'][$className])
219 * Get records from table where the field to migrate is not empty (NOT NULL and != '')
220 * and also not numeric (which means that it is migrated)
222 * @param string $table
223 * @param string $fieldToMigrate
224 * @param array $relationFields
225 * @param int $limit Maximum number records to select
226 * @throws \RuntimeException
229 protected function getRecordsFromTable($table, $fieldToMigrate, $relationFields, $limit) {
230 $fields = implode(',', array_merge($relationFields, array('uid', 'pid')));
231 $deletedCheck = isset($GLOBALS['TCA'][$table]['ctrl']['delete'])
232 ?
' AND ' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0'
234 $where = $fieldToMigrate . ' IS NOT NULL'
235 . ' AND ' . $fieldToMigrate . ' != \'\''
236 . ' AND CAST(CAST(' . $fieldToMigrate . ' AS DECIMAL) AS CHAR) <> ' . $fieldToMigrate
238 $result = $this->database
->exec_SELECTgetRows($fields, $table, $where, '', '', $limit);
239 if ($result === NULL
) {
240 throw new \
RuntimeException('Database query failed. Error was: ' . $this->database
->sql_error());
246 * Migrates a single field.
248 * @param string $table
250 * @param string $fieldname
251 * @param array $fieldConfiguration
252 * @param string $customMessages
253 * @return array A list of performed database queries
256 protected function migrateField($table, $row, $fieldname, $fieldConfiguration, &$customMessages) {
257 $titleTextContents = array();
258 $alternativeTextContents = array();
259 $captionContents = array();
260 $linkContents = array();
262 $fieldItems = GeneralUtility
::trimExplode(',', $row[$fieldname], TRUE
);
263 if (empty($fieldItems) ||
is_numeric($row[$fieldname])) {
266 if (isset($fieldConfiguration['titleTexts'])) {
267 $titleTextField = $fieldConfiguration['titleTexts'];
268 $titleTextContents = explode(LF
, $row[$titleTextField]);
271 if (isset($fieldConfiguration['alternativeTexts'])) {
272 $alternativeTextField = $fieldConfiguration['alternativeTexts'];
273 $alternativeTextContents = explode(LF
, $row[$alternativeTextField]);
275 if (isset($fieldConfiguration['captions'])) {
276 $captionField = $fieldConfiguration['captions'];
277 $captionContents = explode(LF
, $row[$captionField]);
279 if (isset($fieldConfiguration['links'])) {
280 $linkField = $fieldConfiguration['links'];
281 $linkContents = explode(LF
, $row[$linkField]);
283 $fileadminDirectory = rtrim($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '/') . '/';
288 throw new \
Exception('PATH_site was undefined.');
291 $storageUid = (int)$this->storage
->getUid();
293 foreach ($fieldItems as $item) {
295 $sourcePath = PATH_site
. $fieldConfiguration['sourcePath'] . $item;
296 $targetDirectory = PATH_site
. $fileadminDirectory . $fieldConfiguration['targetPath'];
297 $targetPath = $targetDirectory . $item;
299 // maybe the file was already moved, so check if the original file still exists
300 if (file_exists($sourcePath)) {
301 if (!is_dir($targetDirectory)) {
302 GeneralUtility
::mkdir_deep($targetDirectory);
305 // see if the file already exists in the storage
306 $fileSha1 = sha1_file($sourcePath);
308 $existingFileRecord = $this->database
->exec_SELECTgetSingleRow(
311 'sha1=' . $this->database
->fullQuoteStr($fileSha1, 'sys_file') . ' AND storage=' . $storageUid
313 // the file exists, the file does not have to be moved again
314 if (is_array($existingFileRecord)) {
315 $fileUid = $existingFileRecord['uid'];
317 // just move the file (no duplicate)
318 rename($sourcePath, $targetPath);
322 if ($fileUid === NULL
) {
323 // get the File object if it hasn't been fetched before
325 // if the source file does not exist, we should just continue, but leave a message in the docs;
326 // ideally, the user would be informed after the update as well.
327 $file = $this->storage
->getFile($fieldConfiguration['targetPath'] . $item);
328 $fileUid = $file->getUid();
330 } catch (\Exception
$e) {
332 // no file found, no reference can be set
333 $this->logger
->notice(
334 'File ' . $fieldConfiguration['sourcePath'] . $item . ' does not exist. Reference was not migrated.',
335 array('table' => $table, 'record' => $row, 'field' => $fieldname)
338 $format = 'File \'%s\' does not exist. Referencing field: %s.%d.%s. The reference was not migrated.';
339 $message = sprintf($format, $fieldConfiguration['sourcePath'] . $item, $table, $row['uid'], $fieldname);
340 $customMessages .= PHP_EOL
. $message;
348 // TODO add sorting/sorting_foreign
349 'fieldname' => $fieldname,
350 'table_local' => 'sys_file',
351 // the sys_file_reference record should always placed on the same page
352 // as the record to link to, see issue #46497
353 'pid' => ($table === 'pages' ?
$row['uid'] : $row['pid']),
354 'uid_foreign' => $row['uid'],
355 'uid_local' => $fileUid,
356 'tablenames' => $table,
360 if (isset($titleTextField)) {
361 $fields['title'] = trim($titleTextContents[$i]);
363 if (isset($alternativeTextField)) {
364 $fields['alternative'] = trim($alternativeTextContents[$i]);
366 if (isset($captionField)) {
367 $fields['description'] = trim($captionContents[$i]);
369 if (isset($linkField)) {
370 $fields['link'] = trim($linkContents[$i]);
372 $this->database
->exec_INSERTquery('sys_file_reference', $fields);
373 $queries[] = str_replace(LF
, ' ', $this->database
->debug_lastBuiltQuery
);
378 // Update referencing table's original field to now contain the count of references,
379 // but only if all new references could be set
380 if ($i === count($fieldItems)) {
381 $this->database
->exec_UPDATEquery($table, 'uid=' . $row['uid'], array($fieldname => $i));
382 $queries[] = str_replace(LF
, ' ', $this->database
->debug_lastBuiltQuery
);