[BUGFIX] Allow importing of non-compressed t3d files again
[Packages/TYPO3.CMS.git] / typo3 / sysext / impexp / Classes / Import.php
1 <?php
2 namespace TYPO3\CMS\Impexp;
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\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\DataHandling\DataHandler;
19 use TYPO3\CMS\Core\Exception;
20 use TYPO3\CMS\Core\Resource\DuplicationBehavior;
21 use TYPO3\CMS\Core\Resource\File;
22 use TYPO3\CMS\Core\Resource\FileInterface;
23 use TYPO3\CMS\Core\Resource\ResourceFactory;
24 use TYPO3\CMS\Core\Resource\ResourceStorage;
25 use TYPO3\CMS\Core\Resource\StorageRepository;
26 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
27 use TYPO3\CMS\Core\Utility\GeneralUtility;
28 use TYPO3\CMS\Core\Utility\MathUtility;
29 use TYPO3\CMS\Core\Utility\PathUtility;
30 use TYPO3\CMS\Core\Utility\StringUtility;
31 use TYPO3\CMS\Core\Utility\VersionNumberUtility;
32
33 /**
34 * T3D file Import library (TYPO3 Record Document)
35 */
36 class Import extends ImportExport
37 {
38 /**
39 * Used to register the forged UID values for imported records that we want
40 * to create with the same UIDs as in the import file. Admin-only feature.
41 *
42 * @var array
43 */
44 public $suggestedInsertUids = array();
45
46 /**
47 * Disable logging when importing
48 *
49 * @var bool
50 */
51 public $enableLogging = false;
52
53 /**
54 * Keys are [tablename]:[new NEWxxx ids (or when updating it is uids)]
55 * while values are arrays with table/uid of the original record it is based on.
56 * With the array keys the new ids can be looked up inside tcemain
57 *
58 * @var array
59 */
60 public $import_newId = array();
61
62 /**
63 * Page id map for page tree (import)
64 *
65 * @var array
66 */
67 public $import_newId_pids = array();
68
69 /**
70 * Internal data accumulation for writing records during import
71 *
72 * @var array
73 */
74 public $import_data = array();
75
76 /**
77 * Array of current registered storage objects
78 *
79 * @var ResourceStorage[]
80 */
81 protected $storageObjects = array();
82
83 /**
84 * Is set, if the import file has a TYPO3 version below 6.0
85 *
86 * @var bool
87 */
88 protected $legacyImport = false;
89
90 /**
91 * @var \TYPO3\CMS\Core\Resource\Folder
92 */
93 protected $legacyImportFolder = null;
94
95 /**
96 * Related to the default storage root
97 *
98 * @var string
99 */
100 protected $legacyImportTargetPath = '_imported/';
101
102 /**
103 * Table fields to migrate
104 *
105 * @var array
106 */
107 protected $legacyImportMigrationTables = array(
108 'tt_content' => array(
109 'image' => array(
110 'titleTexts' => 'titleText',
111 'description' => 'imagecaption',
112 'links' => 'image_link',
113 'alternativeTexts' => 'altText'
114 ),
115 'media' => array(
116 'description' => 'imagecaption',
117 )
118 ),
119 'pages' => array(
120 'media' => array()
121 ),
122 'pages_language_overlay' => array(
123 'media' => array()
124 )
125 );
126
127 /**
128 * Records to be migrated after all
129 * Multidimensional array [table][uid][field] = array([related sys_file_reference uids])
130 *
131 * @var array
132 */
133 protected $legacyImportMigrationRecords = array();
134
135 /**
136 * @var NULL|string
137 */
138 protected $filesPathForImport = null;
139
140 /**
141 * @var array
142 */
143 protected $unlinkFiles = array();
144
145 /**
146 * @var array
147 */
148 protected $alternativeFileName = array();
149
150 /**
151 * @var array
152 */
153 protected $alternativeFilePath = array();
154
155 /**
156 * @var array
157 */
158 protected $filePathMap = array();
159
160 /**************************
161 * Initialize
162 *************************/
163
164 /**
165 * Init the object
166 *
167 * @return void
168 */
169 public function init()
170 {
171 parent::init();
172 $this->mode = 'import';
173 }
174
175 /***********************
176 * Import
177 ***********************/
178
179 /**
180 * Initialize all settings for the import
181 *
182 * @return void
183 */
184 protected function initializeImport()
185 {
186 // Set this flag to indicate that an import is being/has been done.
187 $this->doesImport = 1;
188 // Initialize:
189 // These vars MUST last for the whole section not being cleared. They are used by the method setRelations() which are called at the end of the import session.
190 $this->import_mapId = array();
191 $this->import_newId = array();
192 $this->import_newId_pids = array();
193 // Temporary files stack initialized:
194 $this->unlinkFiles = array();
195 $this->alternativeFileName = array();
196 $this->alternativeFilePath = array();
197
198 $this->initializeStorageObjects();
199 }
200
201 /**
202 * Initialize the all present storage objects
203 *
204 * @return void
205 */
206 protected function initializeStorageObjects()
207 {
208 /** @var $storageRepository StorageRepository */
209 $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
210 $this->storageObjects = $storageRepository->findAll();
211 }
212
213 /**
214 * Imports the internal data array to $pid.
215 *
216 * @param int $pid Page ID in which to import the content
217 * @return void
218 */
219 public function importData($pid)
220 {
221 $this->initializeImport();
222
223 // Write sys_file_storages first
224 $this->writeSysFileStorageRecords();
225 // Write sys_file records and write the binary file data
226 $this->writeSysFileRecords();
227 // Write records, first pages, then the rest
228 // Fields with "hard" relations to database, files and flexform fields are kept empty during this run
229 $this->writeRecords_pages($pid);
230 $this->writeRecords_records($pid);
231 // Finally all the file and DB record references must be fixed. This is done after all records have supposedly been written to database:
232 // $this->import_mapId will indicate two things: 1) that a record WAS written to db and 2) that it has got a new id-number.
233 $this->setRelations();
234 // And when all DB relations are in place, we can fix file and DB relations in flexform fields (since data structures often depends on relations to a DS record):
235 $this->setFlexFormRelations();
236 // Unlink temporary files:
237 $this->unlinkTempFiles();
238 // Finally, traverse all records and process softreferences with substitution attributes.
239 $this->processSoftReferences();
240 // After all migrate records using sys_file_reference now
241 if ($this->legacyImport) {
242 $this->migrateLegacyImportRecords();
243 }
244 }
245
246 /**
247 * Imports the sys_file_storage records from internal data array.
248 *
249 * @return void
250 */
251 protected function writeSysFileStorageRecords()
252 {
253 if (!isset($this->dat['header']['records']['sys_file_storage'])) {
254 return;
255 }
256 $sysFileStorageUidsToBeResetToDefaultStorage = array();
257 foreach ($this->dat['header']['records']['sys_file_storage'] as $sysFileStorageUid => $_) {
258 $storageRecord = $this->dat['records']['sys_file_storage:' . $sysFileStorageUid]['data'];
259 // continue with Local, writable and online storage only
260 if ($storageRecord['driver'] === 'Local' && $storageRecord['is_writable'] && $storageRecord['is_online']) {
261 foreach ($this->storageObjects as $localStorage) {
262 if ($this->isEquivalentObjectStorage($localStorage, $storageRecord)) {
263 $this->import_mapId['sys_file_storage'][$sysFileStorageUid] = $localStorage->getUid();
264 break;
265 }
266 }
267
268 if (!isset($this->import_mapId['sys_file_storage'][$sysFileStorageUid])) {
269 // Local, writable and online storage. Is allowed to be used to later write files in.
270 // Does currently not exist so add the record.
271 $this->addSingle('sys_file_storage', $sysFileStorageUid, 0);
272 }
273 } else {
274 // Storage with non Local drivers could be imported but must not be used to saves files in, because you
275 // could not be sure, that this is supported. The default storage will be used in this case.
276 // It could happen that non writable and non online storage will be created as dupes because you could not
277 // check the detailed configuration options at this point
278 $this->addSingle('sys_file_storage', $sysFileStorageUid, 0);
279 $sysFileStorageUidsToBeResetToDefaultStorage[] = $sysFileStorageUid;
280 }
281 }
282
283 // Importing the added ones
284 $tce = $this->getNewTCE();
285 // Because all records are being submitted in their correct order with positive pid numbers - and so we should reverse submission order internally.
286 $tce->reverseOrder = 1;
287 $tce->isImporting = true;
288 $tce->start($this->import_data, array());
289 $tce->process_datamap();
290 $this->addToMapId($tce->substNEWwithIDs);
291
292 $defaultStorageUid = null;
293 // get default storage
294 $defaultStorage = ResourceFactory::getInstance()->getDefaultStorage();
295 if ($defaultStorage !== null) {
296 $defaultStorageUid = $defaultStorage->getUid();
297 }
298 foreach ($sysFileStorageUidsToBeResetToDefaultStorage as $sysFileStorageUidToBeResetToDefaultStorage) {
299 $this->import_mapId['sys_file_storage'][$sysFileStorageUidToBeResetToDefaultStorage] = $defaultStorageUid;
300 }
301
302 // unset the sys_file_storage records to prevent an import in writeRecords_records
303 unset($this->dat['header']['records']['sys_file_storage']);
304 }
305
306 /**
307 * Determines whether the passed storage object and record (sys_file_storage) can be
308 * seen as equivalent during import.
309 *
310 * @param ResourceStorage $storageObject The storage object which should get compared
311 * @param array $storageRecord The storage record which should get compared
312 * @return bool Returns TRUE when both object storages can be seen as equivalent
313 */
314 protected function isEquivalentObjectStorage(ResourceStorage $storageObject, array $storageRecord)
315 {
316 // compare the properties: driver, writable and online
317 if ($storageObject->getDriverType() === $storageRecord['driver']
318 && (bool)$storageObject->isWritable() === (bool)$storageRecord['is_writable']
319 && (bool)$storageObject->isOnline() === (bool)$storageRecord['is_online']
320 ) {
321 $storageRecordConfiguration = ResourceFactory::getInstance()
322 ->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
323 $storageObjectConfiguration = $storageObject->getConfiguration();
324 // compare the properties: pathType and basePath
325 if ($storageRecordConfiguration['pathType'] === $storageObjectConfiguration['pathType']
326 && $storageRecordConfiguration['basePath'] === $storageObjectConfiguration['basePath']
327 ) {
328 return true;
329 }
330 }
331 return false;
332 }
333
334 /**
335 * Checks any prerequisites necessary to get fullfilled before import
336 *
337 * @return array Messages explaining issues which need to get resolved before import
338 */
339 public function checkImportPrerequisites()
340 {
341 $messages = array();
342
343 // Check #1: Extension dependencies
344 $extKeysToInstall = array();
345 foreach ($this->dat['header']['extensionDependencies'] as $extKey) {
346 if (!ExtensionManagementUtility::isLoaded($extKey)) {
347 $extKeysToInstall[] = $extKey;
348 }
349 }
350 if (!empty($extKeysToInstall)) {
351 $messages['missingExtensions'] = 'Before you can install this T3D file you need to install the extensions "'
352 . implode('", "', $extKeysToInstall) . '".';
353 }
354
355 // Check #2: If the path for every local storage object exists.
356 // Else files can't get moved into a newly imported storage.
357 if (!empty($this->dat['header']['records']['sys_file_storage'])) {
358 foreach ($this->dat['header']['records']['sys_file_storage'] as $sysFileStorageUid => $_) {
359 $storageRecord = $this->dat['records']['sys_file_storage:' . $sysFileStorageUid]['data'];
360 // continue with Local, writable and online storage only
361 if ($storageRecord['driver'] === 'Local'
362 && $storageRecord['is_writable']
363 && $storageRecord['is_online']
364 ) {
365 foreach ($this->storageObjects as $localStorage) {
366 if ($this->isEquivalentObjectStorage($localStorage, $storageRecord)) {
367 // There is already an existing storage
368 break;
369 }
370
371 // The storage from the import does not have an equivalent storage
372 // in the current instance (same driver, same path, etc.). Before
373 // the storage record can get inserted later on take care the path
374 // it points to really exists and is accessible.
375 $storageRecordUid = $storageRecord['uid'];
376 // Unset the storage record UID when trying to create the storage object
377 // as the record does not already exist in DB. The constructor of the
378 // storage object will check whether the target folder exists and set the
379 // isOnline flag depending on the outcome.
380 $storageRecord['uid'] = 0;
381 $resourceStorage = ResourceFactory::getInstance()->createStorageObject($storageRecord);
382 if (!$resourceStorage->isOnline()) {
383 $configuration = $resourceStorage->getConfiguration();
384 $messages['resourceStorageFolderMissing_' . $storageRecordUid] =
385 'The resource storage "'
386 . $resourceStorage->getName()
387 . $configuration['basePath']
388 . '" does not exist. Please create the directory prior to starting the import!';
389 }
390 }
391 }
392 }
393 }
394
395 return $messages;
396 }
397
398 /**
399 * Imports the sys_file records and the binary files data from internal data array.
400 *
401 * @return void
402 */
403 protected function writeSysFileRecords()
404 {
405 if (!isset($this->dat['header']['records']['sys_file'])) {
406 return;
407 }
408 $this->addGeneralErrorsByTable('sys_file');
409
410 // fetch fresh storage records from database
411 $storageRecords = $this->fetchStorageRecords();
412
413 $defaultStorage = ResourceFactory::getInstance()->getDefaultStorage();
414
415 $sanitizedFolderMappings = array();
416
417 foreach ($this->dat['header']['records']['sys_file'] as $sysFileUid => $_) {
418 $fileRecord = $this->dat['records']['sys_file:' . $sysFileUid]['data'];
419
420 $temporaryFile = null;
421 // check if there is the right file already in the local folder
422 if ($this->filesPathForImport !== null) {
423 if (is_file($this->filesPathForImport . '/' . $fileRecord['sha1']) && sha1_file($this->filesPathForImport . '/' . $fileRecord['sha1']) === $fileRecord['sha1']) {
424 $temporaryFile = $this->filesPathForImport . '/' . $fileRecord['sha1'];
425 }
426 }
427
428 // save file to disk
429 if ($temporaryFile === null) {
430 $fileId = md5($fileRecord['storage'] . ':' . $fileRecord['identifier_hash']);
431 $temporaryFile = $this->writeTemporaryFileFromData($fileId);
432 if ($temporaryFile === null) {
433 // error on writing the file. Error message was already added
434 continue;
435 }
436 }
437
438 $originalStorageUid = $fileRecord['storage'];
439 $useStorageFromStorageRecords = false;
440
441 // replace storage id, if an alternative one was registered
442 if (isset($this->import_mapId['sys_file_storage'][$fileRecord['storage']])) {
443 $fileRecord['storage'] = $this->import_mapId['sys_file_storage'][$fileRecord['storage']];
444 $useStorageFromStorageRecords = true;
445 }
446
447 if (empty($fileRecord['storage']) && !$this->isFallbackStorage($fileRecord['storage'])) {
448 // no storage for the file is defined, mostly because of a missing default storage.
449 $this->error('Error: No storage for the file "' . $fileRecord['identifier'] . '" with storage uid "' . $originalStorageUid . '"');
450 continue;
451 }
452
453 // using a storage from the local storage is only allowed, if the uid is present in the
454 // mapping. Only in this case we could be sure, that it's a local, online and writable storage.
455 if ($useStorageFromStorageRecords && isset($storageRecords[$fileRecord['storage']])) {
456 /** @var $storage \TYPO3\CMS\Core\Resource\ResourceStorage */
457 $storage = ResourceFactory::getInstance()->getStorageObject($fileRecord['storage'], $storageRecords[$fileRecord['storage']]);
458 } elseif ($this->isFallbackStorage($fileRecord['storage'])) {
459 $storage = ResourceFactory::getInstance()->getStorageObject(0);
460 } elseif ($defaultStorage !== null) {
461 $storage = $defaultStorage;
462 } else {
463 $this->error('Error: No storage available for the file "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
464 continue;
465 }
466
467 $newFile = null;
468
469 // check, if there is an identical file
470 try {
471 if ($storage->hasFile($fileRecord['identifier'])) {
472 $file = $storage->getFile($fileRecord['identifier']);
473 if ($file->getSha1() === $fileRecord['sha1']) {
474 $newFile = $file;
475 }
476 }
477 } catch (Exception $e) {
478 }
479
480 if ($newFile === null) {
481 $folderName = PathUtility::dirname(ltrim($fileRecord['identifier'], '/'));
482 if (in_array($folderName, $sanitizedFolderMappings)) {
483 $folderName = $sanitizedFolderMappings[$folderName];
484 }
485 if (!$storage->hasFolder($folderName)) {
486 try {
487 $importFolder = $storage->createFolder($folderName);
488 if ($importFolder->getIdentifier() !== $folderName && !in_array($folderName, $sanitizedFolderMappings)) {
489 $sanitizedFolderMappings[$folderName] = $importFolder->getIdentifier();
490 }
491 } catch (Exception $e) {
492 $this->error('Error: Folder "' . $folderName . '" could not be created for file "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
493 continue;
494 }
495 } else {
496 $importFolder = $storage->getFolder($folderName);
497 }
498
499 try {
500 /** @var $newFile File */
501 $newFile = $storage->addFile($temporaryFile, $importFolder, $fileRecord['name']);
502 } catch (Exception $e) {
503 $this->error('Error: File could not be added to the storage: "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
504 continue;
505 }
506
507 if ($newFile->getSha1() !== $fileRecord['sha1']) {
508 $this->error('Error: The hash of the written file is not identical to the import data! File could be corrupted! File: "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
509 }
510 }
511
512 // save the new uid in the import id map
513 $this->import_mapId['sys_file'][$fileRecord['uid']] = $newFile->getUid();
514 $this->fixUidLocalInSysFileReferenceRecords($fileRecord['uid'], $newFile->getUid());
515 }
516
517 // unset the sys_file records to prevent an import in writeRecords_records
518 unset($this->dat['header']['records']['sys_file']);
519 // remove all sys_file_reference records that point to file records which are unknown
520 // in the system to prevent exceptions
521 $this->removeSysFileReferenceRecordsFromImportDataWithRelationToMissingFile();
522 }
523
524 /**
525 * Removes all sys_file_reference records from the import data array that are pointing to sys_file records which
526 * are missing not in the import data to prevent exceptions on checking the related file started by the Datahandler.
527 *
528 * @return void
529 */
530 protected function removeSysFileReferenceRecordsFromImportDataWithRelationToMissingFile()
531 {
532 if (!isset($this->dat['header']['records']['sys_file_reference'])) {
533 return;
534 }
535
536 foreach ($this->dat['header']['records']['sys_file_reference'] as $sysFileReferenceUid => $_) {
537 $fileReferenceRecord = $this->dat['records']['sys_file_reference:' . $sysFileReferenceUid]['data'];
538 if (!in_array($fileReferenceRecord['uid_local'], $this->import_mapId['sys_file'])) {
539 unset($this->dat['header']['records']['sys_file_reference'][$sysFileReferenceUid]);
540 unset($this->dat['records']['sys_file_reference:' . $sysFileReferenceUid]);
541 $this->error('Error: sys_file_reference record ' . (int)$sysFileReferenceUid
542 . ' with relation to sys_file record ' . (int)$fileReferenceRecord['uid_local']
543 . ', which is not part of the import data, was not imported.'
544 );
545 }
546 }
547 }
548
549 /**
550 * Checks if the $storageId is the id of the fallback storage
551 *
552 * @param int|string $storageId
553 * @return bool
554 */
555 protected function isFallbackStorage($storageId)
556 {
557 return $storageId === 0 || $storageId === '0';
558 }
559
560 /**
561 * Normally the importer works like the following:
562 * Step 1: import the records with cleared field values of relation fields (see addSingle())
563 * Step 2: update the records with the right relation ids (see setRelations())
564 *
565 * In step 2 the saving fields of type "relation to sys_file_reference" checks the related sys_file_reference
566 * record (created in step 1) with the FileExtensionFilter for matching file extensions of the related file.
567 * To make this work correct, the uid_local of sys_file_reference records has to be not empty AND has to
568 * relate to the correct (imported) sys_file record uid!!!
569 *
570 * This is fixed here.
571 *
572 * @param int $oldFileUid
573 * @param int $newFileUid
574 * @return void
575 */
576 protected function fixUidLocalInSysFileReferenceRecords($oldFileUid, $newFileUid)
577 {
578 if (!isset($this->dat['header']['records']['sys_file_reference'])) {
579 return;
580 }
581
582 foreach ($this->dat['header']['records']['sys_file_reference'] as $sysFileReferenceUid => $_) {
583 $fileReferenceRecord = $this->dat['records']['sys_file_reference:' . $sysFileReferenceUid]['data'];
584 if ($fileReferenceRecord['uid_local'] == $oldFileUid) {
585 $fileReferenceRecord['uid_local'] = $newFileUid;
586 $this->dat['records']['sys_file_reference:' . $sysFileReferenceUid]['data'] = $fileReferenceRecord;
587 }
588 }
589 }
590
591 /**
592 * Initializes the folder for legacy imports as subfolder of backend users default upload folder
593 *
594 * @return void
595 */
596 protected function initializeLegacyImportFolder()
597 {
598 /** @var \TYPO3\CMS\Core\Resource\Folder $folder */
599 $folder = $this->getBackendUser()->getDefaultUploadFolder();
600 if ($folder === false) {
601 $this->error('Error: the backend users default upload folder is missing! No files will be imported!');
602 }
603 if (!$folder->hasFolder($this->legacyImportTargetPath)) {
604 try {
605 $this->legacyImportFolder = $folder->createFolder($this->legacyImportTargetPath);
606 } catch (Exception $e) {
607 $this->error('Error: the import folder in the default upload folder could not be created! No files will be imported!');
608 }
609 } else {
610 $this->legacyImportFolder = $folder->getSubfolder($this->legacyImportTargetPath);
611 }
612 }
613
614 /**
615 * Fetched fresh storage records from database because the new imported
616 * ones are not in cached data of the StorageRepository
617 *
618 * @return bool|array
619 */
620 protected function fetchStorageRecords()
621 {
622 $whereClause = BackendUtility::BEenableFields('sys_file_storage');
623 $whereClause .= BackendUtility::deleteClause('sys_file_storage');
624
625 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
626 '*',
627 'sys_file_storage',
628 '1=1' . $whereClause,
629 '',
630 '',
631 '',
632 'uid'
633 );
634
635 return $rows;
636 }
637
638 /**
639 * Writes the file from import array to temp dir and returns the filename of it.
640 *
641 * @param string $fileId
642 * @param string $dataKey
643 * @return string Absolute filename of the temporary filename of the file
644 */
645 protected function writeTemporaryFileFromData($fileId, $dataKey = 'files_fal')
646 {
647 $temporaryFilePath = null;
648 if (is_array($this->dat[$dataKey][$fileId])) {
649 $temporaryFilePathInternal = GeneralUtility::tempnam('import_temp_');
650 GeneralUtility::writeFile($temporaryFilePathInternal, $this->dat[$dataKey][$fileId]['content']);
651 clearstatcache();
652 if (@is_file($temporaryFilePathInternal)) {
653 $this->unlinkFiles[] = $temporaryFilePathInternal;
654 if (filesize($temporaryFilePathInternal) == $this->dat[$dataKey][$fileId]['filesize']) {
655 $temporaryFilePath = $temporaryFilePathInternal;
656 } else {
657 $this->error('Error: temporary file ' . $temporaryFilePathInternal . ' had a size (' . filesize($temporaryFilePathInternal) . ') different from the original (' . $this->dat[$dataKey][$fileId]['filesize'] . ')');
658 }
659 } else {
660 $this->error('Error: temporary file ' . $temporaryFilePathInternal . ' was not written as it should have been!');
661 }
662 } else {
663 $this->error('Error: No file found for ID ' . $fileId);
664 }
665 return $temporaryFilePath;
666 }
667
668 /**
669 * Writing pagetree/pages to database:
670 *
671 * @param int $pid PID in which to import. If the operation is an update operation, the root of the page tree inside will be moved to this PID unless it is the same as the root page from the import
672 * @return void
673 * @see writeRecords_records()
674 */
675 public function writeRecords_pages($pid)
676 {
677 // First, write page structure if any:
678 if (is_array($this->dat['header']['records']['pages'])) {
679 $this->addGeneralErrorsByTable('pages');
680 // $pageRecords is a copy of the pages array in the imported file. Records here are unset one by one when the addSingle function is called.
681 $pageRecords = $this->dat['header']['records']['pages'];
682 $this->import_data = array();
683 // First add page tree if any
684 if (is_array($this->dat['header']['pagetree'])) {
685 $pagesFromTree = $this->flatInversePageTree($this->dat['header']['pagetree']);
686 foreach ($pagesFromTree as $uid) {
687 $thisRec = $this->dat['header']['records']['pages'][$uid];
688 // PID: Set the main $pid, unless a NEW-id is found
689 $setPid = isset($this->import_newId_pids[$thisRec['pid']]) ? $this->import_newId_pids[$thisRec['pid']] : $pid;
690 $this->addSingle('pages', $uid, $setPid);
691 unset($pageRecords[$uid]);
692 }
693 }
694 // Then add all remaining pages not in tree on root level:
695 if (!empty($pageRecords)) {
696 $remainingPageUids = array_keys($pageRecords);
697 foreach ($remainingPageUids as $pUid) {
698 $this->addSingle('pages', $pUid, $pid);
699 }
700 }
701 // Now write to database:
702 $tce = $this->getNewTCE();
703 $tce->isImporting = true;
704 $this->callHook('before_writeRecordsPages', array(
705 'tce' => &$tce,
706 'data' => &$this->import_data
707 ));
708 $tce->suggestedInsertUids = $this->suggestedInsertUids;
709 $tce->start($this->import_data, array());
710 $tce->process_datamap();
711 $this->callHook('after_writeRecordsPages', array(
712 'tce' => &$tce
713 ));
714 // post-processing: Registering new ids (end all tcemain sessions with this)
715 $this->addToMapId($tce->substNEWwithIDs);
716 // In case of an update, order pages from the page tree correctly:
717 if ($this->update && is_array($this->dat['header']['pagetree'])) {
718 $this->writeRecords_pages_order();
719 }
720 }
721 }
722
723 /**
724 * Organize all updated pages in page tree so they are related like in the import file
725 * Only used for updates and when $this->dat['header']['pagetree'] is an array.
726 *
727 * @return void
728 * @access private
729 * @see writeRecords_pages(), writeRecords_records_order()
730 */
731 public function writeRecords_pages_order()
732 {
733 $cmd_data = array();
734 // Get uid-pid relations and traverse them in order to map to possible new IDs
735 $pidsFromTree = $this->flatInversePageTree_pid($this->dat['header']['pagetree']);
736 foreach ($pidsFromTree as $origPid => $newPid) {
737 if ($newPid >= 0 && $this->dontIgnorePid('pages', $origPid)) {
738 // If the page had a new id (because it was created) use that instead!
739 if (substr($this->import_newId_pids[$origPid], 0, 3) === 'NEW') {
740 if ($this->import_mapId['pages'][$origPid]) {
741 $mappedPid = $this->import_mapId['pages'][$origPid];
742 $cmd_data['pages'][$mappedPid]['move'] = $newPid;
743 }
744 } else {
745 $cmd_data['pages'][$origPid]['move'] = $newPid;
746 }
747 }
748 }
749 // Execute the move commands if any:
750 if (!empty($cmd_data)) {
751 $tce = $this->getNewTCE();
752 $this->callHook('before_writeRecordsPagesOrder', array(
753 'tce' => &$tce,
754 'data' => &$cmd_data
755 ));
756 $tce->start(array(), $cmd_data);
757 $tce->process_cmdmap();
758 $this->callHook('after_writeRecordsPagesOrder', array(
759 'tce' => &$tce
760 ));
761 }
762 }
763
764 /**
765 * Recursively flattening the idH array, setting PIDs as values
766 *
767 * @param array $idH Page uid hierarchy
768 * @param array $a Accumulation array of pages (internal, don't set from outside)
769 * @param int $pid PID value (internal)
770 * @return array Array with uid-pid pairs for all pages in the page tree.
771 * @see ImportExport::flatInversePageTree()
772 */
773 public function flatInversePageTree_pid($idH, $a = array(), $pid = -1)
774 {
775 if (is_array($idH)) {
776 $idH = array_reverse($idH);
777 foreach ($idH as $v) {
778 $a[$v['uid']] = $pid;
779 if (is_array($v['subrow'])) {
780 $a = $this->flatInversePageTree_pid($v['subrow'], $a, $v['uid']);
781 }
782 }
783 }
784 return $a;
785 }
786
787 /**
788 * Write all database records except pages (writtein in writeRecords_pages())
789 *
790 * @param int $pid Page id in which to import
791 * @return void
792 * @see writeRecords_pages()
793 */
794 public function writeRecords_records($pid)
795 {
796 // Write the rest of the records
797 $this->import_data = array();
798 if (is_array($this->dat['header']['records'])) {
799 foreach ($this->dat['header']['records'] as $table => $recs) {
800 $this->addGeneralErrorsByTable($table);
801 if ($table != 'pages') {
802 foreach ($recs as $uid => $thisRec) {
803 // PID: Set the main $pid, unless a NEW-id is found
804 $setPid = isset($this->import_mapId['pages'][$thisRec['pid']])
805 ? (int)$this->import_mapId['pages'][$thisRec['pid']]
806 : (int)$pid;
807 if (is_array($GLOBALS['TCA'][$table]) && isset($GLOBALS['TCA'][$table]['ctrl']['rootLevel'])) {
808 $rootLevelSetting = (int)$GLOBALS['TCA'][$table]['ctrl']['rootLevel'];
809 if ($rootLevelSetting === 1) {
810 $setPid = 0;
811 } elseif ($rootLevelSetting === 0 && $setPid === 0) {
812 $this->error('Error: Record type ' . $table . ' is not allowed on pid 0');
813 continue;
814 }
815 }
816 // Add record:
817 $this->addSingle($table, $uid, $setPid);
818 }
819 }
820 }
821 } else {
822 $this->error('Error: No records defined in internal data array.');
823 }
824 // Now write to database:
825 $tce = $this->getNewTCE();
826 $this->callHook('before_writeRecordsRecords', array(
827 'tce' => &$tce,
828 'data' => &$this->import_data
829 ));
830 $tce->suggestedInsertUids = $this->suggestedInsertUids;
831 // Because all records are being submitted in their correct order with positive pid numbers - and so we should reverse submission order internally.
832 $tce->reverseOrder = 1;
833 $tce->isImporting = true;
834 $tce->start($this->import_data, array());
835 $tce->process_datamap();
836 $this->callHook('after_writeRecordsRecords', array(
837 'tce' => &$tce
838 ));
839 // post-processing: Removing files and registering new ids (end all tcemain sessions with this)
840 $this->addToMapId($tce->substNEWwithIDs);
841 // In case of an update, order pages from the page tree correctly:
842 if ($this->update) {
843 $this->writeRecords_records_order($pid);
844 }
845 }
846
847 /**
848 * Organize all updated record to their new positions.
849 * Only used for updates
850 *
851 * @param int $mainPid Main PID into which we import.
852 * @return void
853 * @access private
854 * @see writeRecords_records(), writeRecords_pages_order()
855 */
856 public function writeRecords_records_order($mainPid)
857 {
858 $cmd_data = array();
859 if (is_array($this->dat['header']['pagetree'])) {
860 $pagesFromTree = $this->flatInversePageTree($this->dat['header']['pagetree']);
861 } else {
862 $pagesFromTree = array();
863 }
864 if (is_array($this->dat['header']['pid_lookup'])) {
865 foreach ($this->dat['header']['pid_lookup'] as $pid => $recList) {
866 $newPid = isset($this->import_mapId['pages'][$pid]) ? $this->import_mapId['pages'][$pid] : $mainPid;
867 if (MathUtility::canBeInterpretedAsInteger($newPid)) {
868 foreach ($recList as $tableName => $uidList) {
869 // If $mainPid===$newPid then we are on root level and we can consider to move pages as well!
870 // (they will not be in the page tree!)
871 if (($tableName != 'pages' || !$pagesFromTree[$pid]) && is_array($uidList)) {
872 $uidList = array_reverse(array_keys($uidList));
873 foreach ($uidList as $uid) {
874 if ($this->dontIgnorePid($tableName, $uid)) {
875 $cmd_data[$tableName][$uid]['move'] = $newPid;
876 } else {
877 }
878 }
879 }
880 }
881 }
882 }
883 }
884 // Execute the move commands if any:
885 if (!empty($cmd_data)) {
886 $tce = $this->getNewTCE();
887 $this->callHook('before_writeRecordsRecordsOrder', array(
888 'tce' => &$tce,
889 'data' => &$cmd_data
890 ));
891 $tce->start(array(), $cmd_data);
892 $tce->process_cmdmap();
893 $this->callHook('after_writeRecordsRecordsOrder', array(
894 'tce' => &$tce
895 ));
896 }
897 }
898
899 /**
900 * Adds a single record to the $importData array. Also copies files to tempfolder.
901 * However all File/DB-references and flexform field contents are set to blank for now!
902 * That is done with setRelations() later
903 *
904 * @param string $table Table name (from import memory)
905 * @param int $uid Record UID (from import memory)
906 * @param int $pid Page id
907 * @return void
908 * @see writeRecords()
909 */
910 public function addSingle($table, $uid, $pid)
911 {
912 if ($this->import_mode[$table . ':' . $uid] === 'exclude') {
913 return;
914 }
915 $record = $this->dat['records'][$table . ':' . $uid]['data'];
916 if (is_array($record)) {
917 if ($this->update && $this->doesRecordExist($table, $uid) && $this->import_mode[$table . ':' . $uid] !== 'as_new') {
918 $ID = $uid;
919 } elseif ($table === 'sys_file_metadata' && $record['sys_language_uid'] == '0' && $this->import_mapId['sys_file'][$record['file']]) {
920 // on adding sys_file records the belonging sys_file_metadata record was also created
921 // if there is one the record need to be overwritten instead of creating a new one.
922 $recordInDatabase = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
923 'uid',
924 'sys_file_metadata',
925 'file = ' . $this->import_mapId['sys_file'][$record['file']] . ' AND sys_language_uid = 0 AND pid = 0'
926 );
927 // if no record could be found, $this->import_mapId['sys_file'][$record['file']] is pointing
928 // to a file, that was already there, thus a new metadata record should be created
929 if (is_array($recordInDatabase)) {
930 $this->import_mapId['sys_file_metadata'][$record['uid']] = $recordInDatabase['uid'];
931 $ID = $recordInDatabase['uid'];
932 } else {
933 $ID = StringUtility::getUniqueId('NEW');
934 }
935 } else {
936 $ID = StringUtility::getUniqueId('NEW');
937 }
938 $this->import_newId[$table . ':' . $ID] = array('table' => $table, 'uid' => $uid);
939 if ($table == 'pages') {
940 $this->import_newId_pids[$uid] = $ID;
941 }
942 // Set main record data:
943 $this->import_data[$table][$ID] = $record;
944 $this->import_data[$table][$ID]['tx_impexp_origuid'] = $this->import_data[$table][$ID]['uid'];
945 // Reset permission data:
946 if ($table === 'pages') {
947 // Have to reset the user/group IDs so pages are owned by importing user. Otherwise strange things may happen for non-admins!
948 unset($this->import_data[$table][$ID]['perms_userid']);
949 unset($this->import_data[$table][$ID]['perms_groupid']);
950 }
951 // PID and UID:
952 unset($this->import_data[$table][$ID]['uid']);
953 // Updates:
954 if (MathUtility::canBeInterpretedAsInteger($ID)) {
955 unset($this->import_data[$table][$ID]['pid']);
956 } else {
957 // Inserts:
958 $this->import_data[$table][$ID]['pid'] = $pid;
959 if (($this->import_mode[$table . ':' . $uid] === 'force_uid' && $this->update || $this->force_all_UIDS) && $this->getBackendUser()->isAdmin()) {
960 $this->import_data[$table][$ID]['uid'] = $uid;
961 $this->suggestedInsertUids[$table . ':' . $uid] = 'DELETE';
962 }
963 }
964 // Setting db/file blank:
965 foreach ($this->dat['records'][$table . ':' . $uid]['rels'] as $field => $config) {
966 switch ((string)$config['type']) {
967 case 'db':
968
969 case 'file':
970 // Fixed later in ->setRelations() [because we need to know ALL newly created IDs before we can map relations!]
971 // In the meantime we set NO values for relations.
972 //
973 // BUT for field uid_local of table sys_file_reference the relation MUST not be cleared here,
974 // because the value is already the uid of the right imported sys_file record.
975 // @see fixUidLocalInSysFileReferenceRecords()
976 // If it's empty or a uid to another record the FileExtensionFilter will throw an exception or
977 // delete the reference record if the file extension of the related record doesn't match.
978 if ($table !== 'sys_file_reference' && $field !== 'uid_local') {
979 $this->import_data[$table][$ID][$field] = '';
980 }
981 break;
982 case 'flex':
983 // Fixed later in setFlexFormRelations()
984 // In the meantime we set NO value for flexforms - this is mainly because file references
985 // inside will not be processed properly; In fact references will point to no file
986 // or existing files (in which case there will be double-references which is a big problem of course!)
987 $this->import_data[$table][$ID][$field] = '';
988 break;
989 }
990 }
991 } elseif ($table . ':' . $uid != 'pages:0') {
992 // On root level we don't want this error message.
993 $this->error('Error: no record was found in data array!');
994 }
995 }
996
997 /**
998 * Registers the substNEWids in memory.
999 *
1000 * @param array $substNEWwithIDs From tcemain to be merged into internal mapping variable in this object
1001 * @return void
1002 * @see writeRecords()
1003 */
1004 public function addToMapId($substNEWwithIDs)
1005 {
1006 foreach ($this->import_data as $table => $recs) {
1007 foreach ($recs as $id => $value) {
1008 $old_uid = $this->import_newId[$table . ':' . $id]['uid'];
1009 if (isset($substNEWwithIDs[$id])) {
1010 $this->import_mapId[$table][$old_uid] = $substNEWwithIDs[$id];
1011 } elseif ($this->update) {
1012 // Map same ID to same ID....
1013 $this->import_mapId[$table][$old_uid] = $id;
1014 } else {
1015 // if $this->import_mapId contains already the right mapping, skip the error msg.
1016 // See special handling of sys_file_metadata in addSingle() => nothing to do
1017 if (!($table === 'sys_file_metadata' && isset($this->import_mapId[$table][$old_uid]) && $this->import_mapId[$table][$old_uid] == $id)) {
1018 $this->error('Possible error: ' . $table . ':' . $old_uid . ' had no new id assigned to it. This indicates that the record was not added to database during import. Please check changelog!');
1019 }
1020 }
1021 }
1022 }
1023 }
1024
1025 /**
1026 * Returns a new $TCE object
1027 *
1028 * @return DataHandler $TCE object
1029 */
1030 public function getNewTCE()
1031 {
1032 $tce = GeneralUtility::makeInstance(DataHandler::class);
1033 $tce->stripslashes_values = false;
1034 $tce->dontProcessTransformations = 1;
1035 $tce->enableLogging = $this->enableLogging;
1036 $tce->alternativeFileName = $this->alternativeFileName;
1037 $tce->alternativeFilePath = $this->alternativeFilePath;
1038 return $tce;
1039 }
1040
1041 /**
1042 * Cleaning up all the temporary files stored in typo3temp/ folder
1043 *
1044 * @return void
1045 */
1046 public function unlinkTempFiles()
1047 {
1048 foreach ($this->unlinkFiles as $fileName) {
1049 if (GeneralUtility::isFirstPartOfStr($fileName, PATH_site . 'typo3temp/')) {
1050 GeneralUtility::unlink_tempfile($fileName);
1051 clearstatcache();
1052 if (is_file($fileName)) {
1053 $this->error('Error: ' . $fileName . ' was NOT unlinked as it should have been!');
1054 }
1055 } else {
1056 $this->error('Error: ' . $fileName . ' was not in temp-path. Not removed!');
1057 }
1058 }
1059 $this->unlinkFiles = array();
1060 }
1061
1062 /***************************
1063 * Import / Relations setting
1064 ***************************/
1065
1066 /**
1067 * At the end of the import process all file and DB relations should be set properly (that is relations
1068 * to imported records are all re-created so imported records are correctly related again)
1069 * Relations in flexform fields are processed in setFlexFormRelations() after this function
1070 *
1071 * @return void
1072 * @see setFlexFormRelations()
1073 */
1074 public function setRelations()
1075 {
1076 $updateData = array();
1077 // import_newId contains a register of all records that was in the import memorys "records" key
1078 foreach ($this->import_newId as $nId => $dat) {
1079 $table = $dat['table'];
1080 $uid = $dat['uid'];
1081 // original UID - NOT the new one!
1082 // If the record has been written and received a new id, then proceed:
1083 if (is_array($this->import_mapId[$table]) && isset($this->import_mapId[$table][$uid])) {
1084 $thisNewUid = BackendUtility::wsMapId($table, $this->import_mapId[$table][$uid]);
1085 if (is_array($this->dat['records'][$table . ':' . $uid]['rels'])) {
1086 $thisNewPageUid = 0;
1087 if ($this->legacyImport) {
1088 if ($table != 'pages') {
1089 $oldPid = $this->dat['records'][$table . ':' . $uid]['data']['pid'];
1090 $thisNewPageUid = BackendUtility::wsMapId($table, $this->import_mapId['pages'][$oldPid]);
1091 } else {
1092 $thisNewPageUid = $thisNewUid;
1093 }
1094 }
1095 // Traverse relation fields of each record
1096 foreach ($this->dat['records'][$table . ':' . $uid]['rels'] as $field => $config) {
1097 // uid_local of sys_file_reference needs no update because the correct reference uid was already written
1098 // @see ImportExport::fixUidLocalInSysFileReferenceRecords()
1099 if ($table === 'sys_file_reference' && $field === 'uid_local') {
1100 continue;
1101 }
1102 switch ((string)$config['type']) {
1103 case 'db':
1104 if (is_array($config['itemArray']) && !empty($config['itemArray'])) {
1105 $itemConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1106 $valArray = $this->setRelations_db($config['itemArray'], $itemConfig);
1107 $updateData[$table][$thisNewUid][$field] = implode(',', $valArray);
1108 }
1109 break;
1110 case 'file':
1111 if (is_array($config['newValueFiles']) && !empty($config['newValueFiles'])) {
1112 $valArr = array();
1113 foreach ($config['newValueFiles'] as $fI) {
1114 $valArr[] = $this->import_addFileNameToBeCopied($fI);
1115 }
1116 if ($this->legacyImport && $this->legacyImportFolder === null && isset($this->legacyImportMigrationTables[$table][$field])) {
1117 // Do nothing - the legacy import folder is missing
1118 } elseif ($this->legacyImport && $this->legacyImportFolder !== null && isset($this->legacyImportMigrationTables[$table][$field])) {
1119 $refIds = array();
1120 foreach ($valArr as $tempFile) {
1121 $fileName = $this->alternativeFileName[$tempFile];
1122 $fileObject = null;
1123
1124 try {
1125 // check, if there is alreay the same file in the folder
1126 if ($this->legacyImportFolder->hasFile($fileName)) {
1127 $fileStorage = $this->legacyImportFolder->getStorage();
1128 $file = $fileStorage->getFile($this->legacyImportFolder->getIdentifier() . $fileName);
1129 if ($file->getSha1() === sha1_file($tempFile)) {
1130 $fileObject = $file;
1131 }
1132 }
1133 } catch (Exception $e) {
1134 }
1135
1136 if ($fileObject === null) {
1137 try {
1138 $fileObject = $this->legacyImportFolder->addFile($tempFile, $fileName, DuplicationBehavior::RENAME);
1139 } catch (Exception $e) {
1140 $this->error('Error: no file could be added to the storage for file name' . $this->alternativeFileName[$tempFile]);
1141 }
1142 }
1143 if ($fileObject !== null) {
1144 $refId = StringUtility::getUniqueId('NEW');
1145 $refIds[] = $refId;
1146 $updateData['sys_file_reference'][$refId] = array(
1147 'uid_local' => $fileObject->getUid(),
1148 'uid_foreign' => $thisNewUid, // uid of your content record
1149 'tablenames' => $table,
1150 'fieldname' => $field,
1151 'pid' => $thisNewPageUid, // parent id of the parent page
1152 'table_local' => 'sys_file',
1153 );
1154 }
1155 }
1156 $updateData[$table][$thisNewUid][$field] = implode(',', $refIds);
1157 if (!empty($this->legacyImportMigrationTables[$table][$field])) {
1158 $this->legacyImportMigrationRecords[$table][$thisNewUid][$field] = $refIds;
1159 }
1160 } else {
1161 $updateData[$table][$thisNewUid][$field] = implode(',', $valArr);
1162 }
1163 }
1164 break;
1165 }
1166 }
1167 } else {
1168 $this->error('Error: no record was found in data array!');
1169 }
1170 } else {
1171 $this->error('Error: this records is NOT created it seems! (' . $table . ':' . $uid . ')');
1172 }
1173 }
1174 if (!empty($updateData)) {
1175 $tce = $this->getNewTCE();
1176 $tce->isImporting = true;
1177 $this->callHook('before_setRelation', array(
1178 'tce' => &$tce,
1179 'data' => &$updateData
1180 ));
1181 $tce->start($updateData, array());
1182 $tce->process_datamap();
1183 // Replace the temporary "NEW" ids with the final ones.
1184 foreach ($this->legacyImportMigrationRecords as $table => $records) {
1185 foreach ($records as $uid => $fields) {
1186 foreach ($fields as $field => $referenceIds) {
1187 foreach ($referenceIds as $key => $referenceId) {
1188 $this->legacyImportMigrationRecords[$table][$uid][$field][$key] = $tce->substNEWwithIDs[$referenceId];
1189 }
1190 }
1191 }
1192 }
1193 $this->callHook('after_setRelations', array(
1194 'tce' => &$tce
1195 ));
1196 }
1197 }
1198
1199 /**
1200 * Maps relations for database
1201 *
1202 * @param array $itemArray Array of item sets (table/uid) from a dbAnalysis object
1203 * @param array $itemConfig Array of TCA config of the field the relation to be set on
1204 * @return array Array with values [table]_[uid] or [uid] for field of type group / internal_type file_reference. These values have the regular tcemain-input group/select type which means they will automatically be processed into a uid-list or MM relations.
1205 */
1206 public function setRelations_db($itemArray, $itemConfig)
1207 {
1208 $valArray = array();
1209 foreach ($itemArray as $relDat) {
1210 if (is_array($this->import_mapId[$relDat['table']]) && isset($this->import_mapId[$relDat['table']][$relDat['id']])) {
1211 // Since non FAL file relation type group internal_type file_reference are handled as reference to
1212 // sys_file records Datahandler requires the value as uid of the the related sys_file record only
1213 if ($itemConfig['type'] === 'group' && $itemConfig['internal_type'] === 'file_reference') {
1214 $value = $this->import_mapId[$relDat['table']][$relDat['id']];
1215 } elseif ($itemConfig['type'] === 'input' && isset($itemConfig['wizards']['link'])) {
1216 // If an input field has a relation to a sys_file record this need to be converted back to
1217 // the public path. But use getPublicUrl here, because could normally only be a local file path.
1218 $fileUid = $this->import_mapId[$relDat['table']][$relDat['id']];
1219 // Fallback value
1220 $value = 'file:' . $fileUid;
1221 try {
1222 $file = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileUid);
1223 } catch (\Exception $e) {
1224 $file = null;
1225 }
1226 if ($file instanceof FileInterface) {
1227 $value = $file->getPublicUrl();
1228 }
1229 } else {
1230 $value = $relDat['table'] . '_' . $this->import_mapId[$relDat['table']][$relDat['id']];
1231 }
1232 $valArray[] = $value;
1233 } elseif ($this->isTableStatic($relDat['table']) || $this->isExcluded($relDat['table'], $relDat['id']) || $relDat['id'] < 0) {
1234 // Checking for less than zero because some select types could contain negative values,
1235 // eg. fe_groups (-1, -2) and sys_language (-1 = ALL languages). This must be handled on both export and import.
1236 $valArray[] = $relDat['table'] . '_' . $relDat['id'];
1237 } else {
1238 $this->error('Lost relation: ' . $relDat['table'] . ':' . $relDat['id']);
1239 }
1240 }
1241 return $valArray;
1242 }
1243
1244 /**
1245 * Writes the file from import array to temp dir and returns the filename of it.
1246 *
1247 * @param array $fI File information with three keys: "filename" = filename without path, "ID_absFile" = absolute filepath to the file (including the filename), "ID" = md5 hash of "ID_absFile
1248 * @return string|NULL Absolute filename of the temporary filename of the file. In ->alternativeFileName the original name is set.
1249 */
1250 public function import_addFileNameToBeCopied($fI)
1251 {
1252 if (is_array($this->dat['files'][$fI['ID']])) {
1253 $tmpFile = null;
1254 // check if there is the right file already in the local folder
1255 if ($this->filesPathForImport !== null) {
1256 if (is_file($this->filesPathForImport . '/' . $this->dat['files'][$fI['ID']]['content_md5']) &&
1257 md5_file($this->filesPathForImport . '/' . $this->dat['files'][$fI['ID']]['content_md5']) === $this->dat['files'][$fI['ID']]['content_md5']) {
1258 $tmpFile = $this->filesPathForImport . '/' . $this->dat['files'][$fI['ID']]['content_md5'];
1259 }
1260 }
1261 if ($tmpFile === null) {
1262 $tmpFile = GeneralUtility::tempnam('import_temp_');
1263 GeneralUtility::writeFile($tmpFile, $this->dat['files'][$fI['ID']]['content']);
1264 }
1265 clearstatcache();
1266 if (@is_file($tmpFile)) {
1267 $this->unlinkFiles[] = $tmpFile;
1268 if (filesize($tmpFile) == $this->dat['files'][$fI['ID']]['filesize']) {
1269 $this->alternativeFileName[$tmpFile] = $fI['filename'];
1270 $this->alternativeFilePath[$tmpFile] = $this->dat['files'][$fI['ID']]['relFileRef'];
1271 return $tmpFile;
1272 } else {
1273 $this->error('Error: temporary file ' . $tmpFile . ' had a size (' . filesize($tmpFile) . ') different from the original (' . $this->dat['files'][$fI['ID']]['filesize'] . ')');
1274 }
1275 } else {
1276 $this->error('Error: temporary file ' . $tmpFile . ' was not written as it should have been!');
1277 }
1278 } else {
1279 $this->error('Error: No file found for ID ' . $fI['ID']);
1280 }
1281 return null;
1282 }
1283
1284 /**
1285 * After all DB relations has been set in the end of the import (see setRelations()) then it is time to correct all relations inside of FlexForm fields.
1286 * The reason for doing this after is that the setting of relations may affect (quite often!) which data structure is used for the flexforms field!
1287 *
1288 * @return void
1289 * @see setRelations()
1290 */
1291 public function setFlexFormRelations()
1292 {
1293 $updateData = array();
1294 // import_newId contains a register of all records that was in the import memorys "records" key
1295 foreach ($this->import_newId as $nId => $dat) {
1296 $table = $dat['table'];
1297 $uid = $dat['uid'];
1298 // original UID - NOT the new one!
1299 // If the record has been written and received a new id, then proceed:
1300 if (!isset($this->import_mapId[$table][$uid])) {
1301 $this->error('Error: this records is NOT created it seems! (' . $table . ':' . $uid . ')');
1302 continue;
1303 }
1304
1305 if (!is_array($this->dat['records'][$table . ':' . $uid]['rels'])) {
1306 $this->error('Error: no record was found in data array!');
1307 continue;
1308 }
1309 $thisNewUid = BackendUtility::wsMapId($table, $this->import_mapId[$table][$uid]);
1310 // Traverse relation fields of each record
1311 foreach ($this->dat['records'][$table . ':' . $uid]['rels'] as $field => $config) {
1312 switch ((string)$config['type']) {
1313 case 'flex':
1314 // Get XML content and set as default value (string, non-processed):
1315 $updateData[$table][$thisNewUid][$field] = $this->dat['records'][$table . ':' . $uid]['data'][$field];
1316 // If there has been registered relations inside the flex form field, run processing on the content:
1317 if (!empty($config['flexFormRels']['db']) || !empty($config['flexFormRels']['file'])) {
1318 $origRecordRow = BackendUtility::getRecord($table, $thisNewUid, '*');
1319 // This will fetch the new row for the element (which should be updated with any references to data structures etc.)
1320 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1321 if (is_array($origRecordRow) && is_array($conf) && $conf['type'] === 'flex') {
1322 // Get current data structure and value array:
1323 $dataStructArray = BackendUtility::getFlexFormDS($conf, $origRecordRow, $table, $field);
1324 $currentValueArray = GeneralUtility::xml2array($updateData[$table][$thisNewUid][$field]);
1325 // Do recursive processing of the XML data:
1326 $iteratorObj = GeneralUtility::makeInstance(DataHandler::class);
1327 $iteratorObj->callBackObj = $this;
1328 $currentValueArray['data'] = $iteratorObj->checkValue_flex_procInData(
1329 $currentValueArray['data'],
1330 array(),
1331 array(),
1332 $dataStructArray,
1333 array($table, $thisNewUid, $field, $config),
1334 'remapListedDBRecords_flexFormCallBack'
1335 );
1336 // The return value is set as an array which means it will be processed by tcemain for file and DB references!
1337 if (is_array($currentValueArray['data'])) {
1338 $updateData[$table][$thisNewUid][$field] = $currentValueArray;
1339 }
1340 }
1341 }
1342 break;
1343 }
1344 }
1345 }
1346 if (!empty($updateData)) {
1347 $tce = $this->getNewTCE();
1348 $tce->isImporting = true;
1349 $this->callHook('before_setFlexFormRelations', array(
1350 'tce' => &$tce,
1351 'data' => &$updateData
1352 ));
1353 $tce->start($updateData, array());
1354 $tce->process_datamap();
1355 $this->callHook('after_setFlexFormRelations', array(
1356 'tce' => &$tce
1357 ));
1358 }
1359 }
1360
1361 /**
1362 * Callback function for traversing the FlexForm structure in relation to remapping database relations
1363 *
1364 * @param array $pParams Set of parameters in numeric array: table, uid, field
1365 * @param array $dsConf TCA config for field (from Data Structure of course)
1366 * @param string $dataValue Field value (from FlexForm XML)
1367 * @param string $dataValue_ext1 Not used
1368 * @param string $dataValue_ext2 Not used
1369 * @param string $path Path of where the data structure of the element is found
1370 * @return array Array where the "value" key carries the value.
1371 * @see setFlexFormRelations()
1372 */
1373 public function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path)
1374 {
1375 // Extract parameters:
1376 list(, , , $config) = $pParams;
1377 // In case the $path is used as index without a trailing slash we will remove that
1378 if (!is_array($config['flexFormRels']['db'][$path]) && is_array($config['flexFormRels']['db'][rtrim($path, '/')])) {
1379 $path = rtrim($path, '/');
1380 }
1381 if (is_array($config['flexFormRels']['db'][$path])) {
1382 $valArray = $this->setRelations_db($config['flexFormRels']['db'][$path], $dsConf);
1383 $dataValue = implode(',', $valArray);
1384 }
1385 if (is_array($config['flexFormRels']['file'][$path])) {
1386 $valArr = array();
1387 foreach ($config['flexFormRels']['file'][$path] as $fI) {
1388 $valArr[] = $this->import_addFileNameToBeCopied($fI);
1389 }
1390 $dataValue = implode(',', $valArr);
1391 }
1392 return array('value' => $dataValue);
1393 }
1394
1395 /**************************
1396 * Import / Soft References
1397 *************************/
1398
1399 /**
1400 * Processing of soft references
1401 *
1402 * @return void
1403 */
1404 public function processSoftReferences()
1405 {
1406 // Initialize:
1407 $inData = array();
1408 // Traverse records:
1409 if (is_array($this->dat['header']['records'])) {
1410 foreach ($this->dat['header']['records'] as $table => $recs) {
1411 foreach ($recs as $uid => $thisRec) {
1412 // If there are soft references defined, traverse those:
1413 if (isset($GLOBALS['TCA'][$table]) && is_array($thisRec['softrefs'])) {
1414 // First traversal is to collect softref configuration and split them up based on fields.
1415 // This could probably also have been done with the "records" key instead of the header.
1416 $fieldsIndex = array();
1417 foreach ($thisRec['softrefs'] as $softrefDef) {
1418 // If a substitution token is set:
1419 if ($softrefDef['field'] && is_array($softrefDef['subst']) && $softrefDef['subst']['tokenID']) {
1420 $fieldsIndex[$softrefDef['field']][$softrefDef['subst']['tokenID']] = $softrefDef;
1421 }
1422 }
1423 // The new id:
1424 $thisNewUid = BackendUtility::wsMapId($table, $this->import_mapId[$table][$uid]);
1425 // Now, if there are any fields that require substitution to be done, lets go for that:
1426 foreach ($fieldsIndex as $field => $softRefCfgs) {
1427 if (is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
1428 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1429 if ($conf['type'] === 'flex') {
1430 // This will fetch the new row for the element (which should be updated with any references to data structures etc.)
1431 $origRecordRow = BackendUtility::getRecord($table, $thisNewUid, '*');
1432 if (is_array($origRecordRow)) {
1433 // Get current data structure and value array:
1434 $dataStructArray = BackendUtility::getFlexFormDS($conf, $origRecordRow, $table, $field);
1435 $currentValueArray = GeneralUtility::xml2array($origRecordRow[$field]);
1436 // Do recursive processing of the XML data:
1437 /** @var $iteratorObj DataHandler */
1438 $iteratorObj = GeneralUtility::makeInstance(DataHandler::class);
1439 $iteratorObj->callBackObj = $this;
1440 $currentValueArray['data'] = $iteratorObj->checkValue_flex_procInData($currentValueArray['data'], array(), array(), $dataStructArray, array($table, $uid, $field, $softRefCfgs), 'processSoftReferences_flexFormCallBack');
1441 // The return value is set as an array which means it will be processed by tcemain for file and DB references!
1442 if (is_array($currentValueArray['data'])) {
1443 $inData[$table][$thisNewUid][$field] = $currentValueArray;
1444 }
1445 }
1446 } else {
1447 // Get tokenizedContent string and proceed only if that is not blank:
1448 $tokenizedContent = $this->dat['records'][$table . ':' . $uid]['rels'][$field]['softrefs']['tokenizedContent'];
1449 if (strlen($tokenizedContent) && is_array($softRefCfgs)) {
1450 $inData[$table][$thisNewUid][$field] = $this->processSoftReferences_substTokens($tokenizedContent, $softRefCfgs, $table, $uid);
1451 }
1452 }
1453 }
1454 }
1455 }
1456 }
1457 }
1458 }
1459 // Now write to database:
1460 $tce = $this->getNewTCE();
1461 $tce->isImporting = true;
1462 $this->callHook('before_processSoftReferences', array(
1463 'tce' => $tce,
1464 'data' => &$inData
1465 ));
1466 $tce->enableLogging = true;
1467 $tce->start($inData, array());
1468 $tce->process_datamap();
1469 $this->callHook('after_processSoftReferences', array(
1470 'tce' => $tce
1471 ));
1472 }
1473
1474 /**
1475 * Callback function for traversing the FlexForm structure in relation to remapping softreference relations
1476 *
1477 * @param array $pParams Set of parameters in numeric array: table, uid, field
1478 * @param array $dsConf TCA config for field (from Data Structure of course)
1479 * @param string $dataValue Field value (from FlexForm XML)
1480 * @param string $dataValue_ext1 Not used
1481 * @param string $dataValue_ext2 Not used
1482 * @param string $path Path of where the data structure where the element is found
1483 * @return array Array where the "value" key carries the value.
1484 * @see setFlexFormRelations()
1485 */
1486 public function processSoftReferences_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path)
1487 {
1488 // Extract parameters:
1489 list($table, $origUid, $field, $softRefCfgs) = $pParams;
1490 if (is_array($softRefCfgs)) {
1491 // First, find all soft reference configurations for this structure path (they are listed flat in the header):
1492 $thisSoftRefCfgList = array();
1493 foreach ($softRefCfgs as $sK => $sV) {
1494 if ($sV['structurePath'] === $path) {
1495 $thisSoftRefCfgList[$sK] = $sV;
1496 }
1497 }
1498 // If any was found, do processing:
1499 if (!empty($thisSoftRefCfgList)) {
1500 // Get tokenizedContent string and proceed only if that is not blank:
1501 $tokenizedContent = $this->dat['records'][$table . ':' . $origUid]['rels'][$field]['flexFormRels']['softrefs'][$path]['tokenizedContent'];
1502 if (strlen($tokenizedContent)) {
1503 $dataValue = $this->processSoftReferences_substTokens($tokenizedContent, $thisSoftRefCfgList, $table, $origUid);
1504 }
1505 }
1506 }
1507 // Return
1508 return array('value' => $dataValue);
1509 }
1510
1511 /**
1512 * Substition of softreference tokens
1513 *
1514 * @param string $tokenizedContent Content of field with soft reference tokens in.
1515 * @param array $softRefCfgs Soft reference configurations
1516 * @param string $table Table for which the processing occurs
1517 * @param string $uid UID of record from table
1518 * @return string The input content with tokens substituted according to entries in softRefCfgs
1519 */
1520 public function processSoftReferences_substTokens($tokenizedContent, $softRefCfgs, $table, $uid)
1521 {
1522 // traverse each softref type for this field:
1523 foreach ($softRefCfgs as $cfg) {
1524 // Get token ID:
1525 $tokenID = $cfg['subst']['tokenID'];
1526 // Default is current token value:
1527 $insertValue = $cfg['subst']['tokenValue'];
1528 // Based on mode:
1529 switch ((string)$this->softrefCfg[$tokenID]['mode']) {
1530 case 'exclude':
1531 // Exclude is a simple passthrough of the value
1532 break;
1533 case 'editable':
1534 // Editable always picks up the value from this input array:
1535 $insertValue = $this->softrefInputValues[$tokenID];
1536 break;
1537 default:
1538 // Mapping IDs/creating files: Based on type, look up new value:
1539 switch ((string)$cfg['subst']['type']) {
1540 case 'file':
1541 // Create / Overwrite file:
1542 $insertValue = $this->processSoftReferences_saveFile($cfg['subst']['relFileName'], $cfg, $table, $uid);
1543 break;
1544 case 'db':
1545 default:
1546 // Trying to map database element if found in the mapID array:
1547 list($tempTable, $tempUid) = explode(':', $cfg['subst']['recordRef']);
1548 if (isset($this->import_mapId[$tempTable][$tempUid])) {
1549 $insertValue = BackendUtility::wsMapId($tempTable, $this->import_mapId[$tempTable][$tempUid]);
1550 // Look if reference is to a page and the original token value was NOT an integer - then we assume is was an alias and try to look up the new one!
1551 if ($tempTable === 'pages' && !MathUtility::canBeInterpretedAsInteger($cfg['subst']['tokenValue'])) {
1552 $recWithUniqueValue = BackendUtility::getRecord($tempTable, $insertValue, 'alias');
1553 if ($recWithUniqueValue['alias']) {
1554 $insertValue = $recWithUniqueValue['alias'];
1555 }
1556 } elseif (strpos($cfg['subst']['tokenValue'], ':') !== false) {
1557 list($tokenKey) = explode(':', $cfg['subst']['tokenValue']);
1558 $insertValue = $tokenKey . ':' . $insertValue;
1559 }
1560 }
1561 }
1562 }
1563 // Finally, swap the soft reference token in tokenized content with the insert value:
1564 $tokenizedContent = str_replace('{softref:' . $tokenID . '}', $insertValue, $tokenizedContent);
1565 }
1566 return $tokenizedContent;
1567 }
1568
1569 /**
1570 * Process a soft reference file
1571 *
1572 * @param string $relFileName Old Relative filename
1573 * @param array $cfg soft reference configuration array
1574 * @param string $table Table for which the processing occurs
1575 * @param string $uid UID of record from table
1576 * @return string New relative filename (value to insert instead of the softref token)
1577 */
1578 public function processSoftReferences_saveFile($relFileName, $cfg, $table, $uid)
1579 {
1580 if ($fileHeaderInfo = $this->dat['header']['files'][$cfg['file_ID']]) {
1581 // Initialize; Get directory prefix for file and find possible RTE filename
1582 $dirPrefix = PathUtility::dirname($relFileName) . '/';
1583 $rteOrigName = $this->getRTEoriginalFilename(PathUtility::basename($relFileName));
1584 // If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file!
1585 if ($rteOrigName && GeneralUtility::isFirstPartOfStr($dirPrefix, 'uploads/')) {
1586 // RTE:
1587 // First, find unique RTE file name:
1588 if (@is_dir((PATH_site . $dirPrefix))) {
1589 // From the "original" RTE filename, produce a new "original" destination filename which is unused.
1590 // Even if updated, the image should be unique. Currently the problem with this is that it leaves a lot of unused RTE images...
1591 $fileProcObj = $this->getFileProcObj();
1592 $origDestName = $fileProcObj->getUniqueName($rteOrigName, PATH_site . $dirPrefix);
1593 // Create copy file name:
1594 $pI = pathinfo($relFileName);
1595 $copyDestName = PathUtility::dirname($origDestName) . '/RTEmagicC_' . substr(PathUtility::basename($origDestName), 10) . '.' . $pI['extension'];
1596 if (
1597 !@is_file($copyDestName) && !@is_file($origDestName)
1598 && $origDestName === GeneralUtility::getFileAbsFileName($origDestName)
1599 && $copyDestName === GeneralUtility::getFileAbsFileName($copyDestName)
1600 ) {
1601 if ($this->dat['header']['files'][$fileHeaderInfo['RTE_ORIG_ID']]) {
1602 if ($this->legacyImport) {
1603 $fileName = PathUtility::basename($copyDestName);
1604 $this->writeSysFileResourceForLegacyImport($fileName, $cfg['file_ID']);
1605 $relFileName = $this->filePathMap[$cfg['file_ID']] . '" data-htmlarea-file-uid="' . $fileName . '" data-htmlarea-file-table="sys_file';
1606 // Also save the original file
1607 $originalFileName = PathUtility::basename($origDestName);
1608 $this->writeSysFileResourceForLegacyImport($originalFileName, $fileHeaderInfo['RTE_ORIG_ID']);
1609 } else {
1610 // Write the copy and original RTE file to the respective filenames:
1611 $this->writeFileVerify($copyDestName, $cfg['file_ID'], true);
1612 $this->writeFileVerify($origDestName, $fileHeaderInfo['RTE_ORIG_ID'], true);
1613 // Return the relative path of the copy file name:
1614 return PathUtility::stripPathSitePrefix($copyDestName);
1615 }
1616 } else {
1617 $this->error('ERROR: Could not find original file ID');
1618 }
1619 } else {
1620 $this->error('ERROR: The destination filenames "' . $copyDestName . '" and "' . $origDestName . '" either existed or have non-valid names');
1621 }
1622 } else {
1623 $this->error('ERROR: "' . PATH_site . $dirPrefix . '" was not a directory, so could not process file "' . $relFileName . '"');
1624 }
1625 } elseif (GeneralUtility::isFirstPartOfStr($dirPrefix, $this->fileadminFolderName . '/')) {
1626 // File in fileadmin/ folder:
1627 // Create file (and possible resources)
1628 $newFileName = $this->processSoftReferences_saveFile_createRelFile($dirPrefix, PathUtility::basename($relFileName), $cfg['file_ID'], $table, $uid);
1629 if (strlen($newFileName)) {
1630 $relFileName = $newFileName;
1631 } else {
1632 $this->error('ERROR: No new file created for "' . $relFileName . '"');
1633 }
1634 } else {
1635 $this->error('ERROR: Sorry, cannot operate on non-RTE files which are outside the fileadmin folder.');
1636 }
1637 } else {
1638 $this->error('ERROR: Could not find file ID in header.');
1639 }
1640 // Return (new) filename relative to PATH_site:
1641 return $relFileName;
1642 }
1643
1644 /**
1645 * Create file in directory and return the new (unique) filename
1646 *
1647 * @param string $origDirPrefix Directory prefix, relative, with trailing slash
1648 * @param string $fileName Filename (without path)
1649 * @param string $fileID File ID from import memory
1650 * @param string $table Table for which the processing occurs
1651 * @param string $uid UID of record from table
1652 * @return string|NULL New relative filename, if any
1653 */
1654 public function processSoftReferences_saveFile_createRelFile($origDirPrefix, $fileName, $fileID, $table, $uid)
1655 {
1656 // If the fileID map contains an entry for this fileID then just return the relative filename of that entry;
1657 // we don't want to write another unique filename for this one!
1658 if (isset($this->fileIDMap[$fileID])) {
1659 return PathUtility::stripPathSitePrefix($this->fileIDMap[$fileID]);
1660 }
1661 if ($this->legacyImport) {
1662 // set dirPrefix to fileadmin because the right target folder is set and checked for permissions later
1663 $dirPrefix = $this->fileadminFolderName . '/';
1664 } else {
1665 // Verify FileMount access to dir-prefix. Returns the best alternative relative path if any
1666 $dirPrefix = $this->verifyFolderAccess($origDirPrefix);
1667 }
1668 if ($dirPrefix && (!$this->update || $origDirPrefix === $dirPrefix) && $this->checkOrCreateDir($dirPrefix)) {
1669 $fileHeaderInfo = $this->dat['header']['files'][$fileID];
1670 $updMode = $this->update && $this->import_mapId[$table][$uid] === $uid && $this->import_mode[$table . ':' . $uid] !== 'as_new';
1671 // Create new name for file:
1672 // Must have same ID in map array (just for security, is not really needed) and NOT be set "as_new".
1673
1674 // Write main file:
1675 if ($this->legacyImport) {
1676 $fileWritten = $this->writeSysFileResourceForLegacyImport($fileName, $fileID);
1677 if ($fileWritten) {
1678 $newName = 'file:' . $fileName;
1679 return $newName;
1680 // no support for HTML/CSS file resources attached ATM - see below
1681 }
1682 } else {
1683 if ($updMode) {
1684 $newName = PATH_site . $dirPrefix . $fileName;
1685 } else {
1686 // Create unique filename:
1687 $fileProcObj = $this->getFileProcObj();
1688 $newName = $fileProcObj->getUniqueName($fileName, PATH_site . $dirPrefix);
1689 }
1690 if ($this->writeFileVerify($newName, $fileID)) {
1691 // If the resource was an HTML/CSS file with resources attached, we will write those as well!
1692 if (is_array($fileHeaderInfo['EXT_RES_ID'])) {
1693 $tokenizedContent = $this->dat['files'][$fileID]['tokenizedContent'];
1694 $tokenSubstituted = false;
1695 $fileProcObj = $this->getFileProcObj();
1696 if ($updMode) {
1697 foreach ($fileHeaderInfo['EXT_RES_ID'] as $res_fileID) {
1698 if ($this->dat['files'][$res_fileID]['filename']) {
1699 // Resolve original filename:
1700 $relResourceFileName = $this->dat['files'][$res_fileID]['parentRelFileName'];
1701 $absResourceFileName = GeneralUtility::resolveBackPath(PATH_site . $origDirPrefix . $relResourceFileName);
1702 $absResourceFileName = GeneralUtility::getFileAbsFileName($absResourceFileName);
1703 if ($absResourceFileName && GeneralUtility::isFirstPartOfStr($absResourceFileName, PATH_site . $this->fileadminFolderName . '/')) {
1704 $destDir = PathUtility::stripPathSitePrefix(PathUtility::dirname($absResourceFileName) . '/');
1705 if ($this->verifyFolderAccess($destDir, true) && $this->checkOrCreateDir($destDir)) {
1706 $this->writeFileVerify($absResourceFileName, $res_fileID);
1707 } else {
1708 $this->error('ERROR: Could not create file in directory "' . $destDir . '"');
1709 }
1710 } else {
1711 $this->error('ERROR: Could not resolve path for "' . $relResourceFileName . '"');
1712 }
1713 $tokenizedContent = str_replace('{EXT_RES_ID:' . $res_fileID . '}', $relResourceFileName, $tokenizedContent);
1714 $tokenSubstituted = true;
1715 }
1716 }
1717 } else {
1718 // Create the resouces directory name (filename without extension, suffixed "_FILES")
1719 $resourceDir = PathUtility::dirname($newName) . '/' . preg_replace('/\\.[^.]*$/', '', PathUtility::basename($newName)) . '_FILES';
1720 if (GeneralUtility::mkdir($resourceDir)) {
1721 foreach ($fileHeaderInfo['EXT_RES_ID'] as $res_fileID) {
1722 if ($this->dat['files'][$res_fileID]['filename']) {
1723 $absResourceFileName = $fileProcObj->getUniqueName($this->dat['files'][$res_fileID]['filename'], $resourceDir);
1724 $relResourceFileName = substr($absResourceFileName, strlen(PathUtility::dirname($resourceDir)) + 1);
1725 $this->writeFileVerify($absResourceFileName, $res_fileID);
1726 $tokenizedContent = str_replace('{EXT_RES_ID:' . $res_fileID . '}', $relResourceFileName, $tokenizedContent);
1727 $tokenSubstituted = true;
1728 }
1729 }
1730 }
1731 }
1732 // If substitutions has been made, write the content to the file again:
1733 if ($tokenSubstituted) {
1734 GeneralUtility::writeFile($newName, $tokenizedContent);
1735 }
1736 }
1737 return PathUtility::stripPathSitePrefix($newName);
1738 }
1739 }
1740 }
1741 return null;
1742 }
1743
1744 /**
1745 * Writes a file from the import memory having $fileID to file name $fileName which must be an absolute path inside PATH_site
1746 *
1747 * @param string $fileName Absolute filename inside PATH_site to write to
1748 * @param string $fileID File ID from import memory
1749 * @param bool $bypassMountCheck Bypasses the checking against filemounts - only for RTE files!
1750 * @return bool Returns TRUE if it went well. Notice that the content of the file is read again, and md5 from import memory is validated.
1751 */
1752 public function writeFileVerify($fileName, $fileID, $bypassMountCheck = false)
1753 {
1754 $fileProcObj = $this->getFileProcObj();
1755 if (!$fileProcObj->actionPerms['addFile']) {
1756 $this->error('ERROR: You did not have sufficient permissions to write the file "' . $fileName . '"');
1757 return false;
1758 }
1759 // Just for security, check again. Should actually not be necessary.
1760 if (!$fileProcObj->checkPathAgainstMounts($fileName) && !$bypassMountCheck) {
1761 $this->error('ERROR: Filename "' . $fileName . '" was not allowed in destination path!');
1762 return false;
1763 }
1764 $fI = GeneralUtility::split_fileref($fileName);
1765 if (!$fileProcObj->checkIfAllowed($fI['fileext'], $fI['path'], $fI['file']) && (!$this->allowPHPScripts || !$this->getBackendUser()->isAdmin())) {
1766 $this->error('ERROR: Filename "' . $fileName . '" failed against extension check or deny-pattern!');
1767 return false;
1768 }
1769 if (!GeneralUtility::getFileAbsFileName($fileName)) {
1770 $this->error('ERROR: Filename "' . $fileName . '" was not a valid relative file path!');
1771 return false;
1772 }
1773 if (!$this->dat['files'][$fileID]) {
1774 $this->error('ERROR: File ID "' . $fileID . '" could not be found');
1775 return false;
1776 }
1777 GeneralUtility::writeFile($fileName, $this->dat['files'][$fileID]['content']);
1778 $this->fileIDMap[$fileID] = $fileName;
1779 if (md5(GeneralUtility::getUrl($fileName)) == $this->dat['files'][$fileID]['content_md5']) {
1780 return true;
1781 } else {
1782 $this->error('ERROR: File content "' . $fileName . '" was corrupted');
1783 return false;
1784 }
1785 }
1786
1787 /**
1788 * Writes the file with the is $fileId to the legacy import folder. The file name will used from
1789 * argument $fileName and the file was successfully created or an identical file was already found,
1790 * $fileName will held the uid of the new created file record.
1791 *
1792 * @param string $fileName The file name for the new file. Value would be changed to the uid of the new created file record.
1793 * @param int $fileId The id of the file in data array
1794 * @return bool
1795 */
1796 protected function writeSysFileResourceForLegacyImport(&$fileName, $fileId)
1797 {
1798 if ($this->legacyImportFolder === null) {
1799 return false;
1800 }
1801
1802 if (!isset($this->dat['files'][$fileId])) {
1803 $this->error('ERROR: File ID "' . $fileId . '" could not be found');
1804 return false;
1805 }
1806
1807 $temporaryFile = $this->writeTemporaryFileFromData($fileId, 'files');
1808 if ($temporaryFile === null) {
1809 // error on writing the file. Error message was already added
1810 return false;
1811 }
1812
1813 $importFolder = $this->legacyImportFolder;
1814
1815 if (isset($this->dat['files'][$fileId]['relFileName'])) {
1816 $relativeFilePath = PathUtility::dirname($this->dat['files'][$fileId]['relFileName']);
1817
1818 if (!$this->legacyImportFolder->hasFolder($relativeFilePath)) {
1819 $this->legacyImportFolder->createFolder($relativeFilePath);
1820 }
1821 $importFolder = $this->legacyImportFolder->getSubfolder($relativeFilePath);
1822 }
1823
1824 $fileObject = null;
1825
1826 try {
1827 // check, if there is alreay the same file in the folder
1828 if ($importFolder->hasFile($fileName)) {
1829 $fileStorage = $importFolder->getStorage();
1830 $file = $fileStorage->getFile($importFolder->getIdentifier() . $fileName);
1831 if ($file->getSha1() === sha1_file($temporaryFile)) {
1832 $fileObject = $file;
1833 }
1834 }
1835 } catch (Exception $e) {
1836 }
1837
1838 if ($fileObject === null) {
1839 try {
1840 $fileObject = $importFolder->addFile($temporaryFile, $fileName, DuplicationBehavior::RENAME);
1841 } catch (Exception $e) {
1842 $this->error('Error: no file could be added to the storage for file name ' . $this->alternativeFileName[$temporaryFile]);
1843 }
1844 }
1845
1846 if (md5_file(PATH_site . $fileObject->getPublicUrl()) == $this->dat['files'][$fileId]['content_md5']) {
1847 $fileName = $fileObject->getUid();
1848 $this->fileIDMap[$fileId] = $fileName;
1849 $this->filePathMap[$fileId] = $fileObject->getPublicUrl();
1850 return true;
1851 } else {
1852 $this->error('ERROR: File content "' . $this->dat['files'][$fileId]['relFileName'] . '" was corrupted');
1853 }
1854
1855 return false;
1856 }
1857
1858 /**
1859 * Migrate legacy import records
1860 *
1861 * @return void
1862 */
1863 protected function migrateLegacyImportRecords()
1864 {
1865 $updateData= array();
1866
1867 foreach ($this->legacyImportMigrationRecords as $table => $records) {
1868 foreach ($records as $uid => $fields) {
1869 $row = BackendUtility::getRecord($table, $uid);
1870 if (empty($row)) {
1871 continue;
1872 }
1873
1874 foreach ($fields as $field => $referenceIds) {
1875 $fieldConfiguration = $this->legacyImportMigrationTables[$table][$field];
1876
1877 if (isset($fieldConfiguration['titleTexts'])) {
1878 $titleTextField = $fieldConfiguration['titleTexts'];
1879 if (isset($row[$titleTextField]) && $row[$titleTextField] !== '') {
1880 $titleTextContents = explode(LF, $row[$titleTextField]);
1881 $updateData[$table][$uid][$titleTextField] = '';
1882 }
1883 }
1884
1885 if (isset($fieldConfiguration['alternativeTexts'])) {
1886 $alternativeTextField = $fieldConfiguration['alternativeTexts'];
1887 if (isset($row[$alternativeTextField]) && $row[$alternativeTextField] !== '') {
1888 $alternativeTextContents = explode(LF, $row[$alternativeTextField]);
1889 $updateData[$table][$uid][$alternativeTextField] = '';
1890 }
1891 }
1892 if (isset($fieldConfiguration['description'])) {
1893 $descriptionField = $fieldConfiguration['description'];
1894 if ($row[$descriptionField] !== '') {
1895 $descriptionContents = explode(LF, $row[$descriptionField]);
1896 $updateData[$table][$uid][$descriptionField] = '';
1897 }
1898 }
1899 if (isset($fieldConfiguration['links'])) {
1900 $linkField = $fieldConfiguration['links'];
1901 if ($row[$linkField] !== '') {
1902 $linkContents = explode(LF, $row[$linkField]);
1903 $updateData[$table][$uid][$linkField] = '';
1904 }
1905 }
1906
1907 foreach ($referenceIds as $key => $referenceId) {
1908 if (isset($titleTextContents[$key])) {
1909 $updateData['sys_file_reference'][$referenceId]['title'] = trim($titleTextContents[$key]);
1910 }
1911 if (isset($alternativeTextContents[$key])) {
1912 $updateData['sys_file_reference'][$referenceId]['alternative'] = trim($alternativeTextContents[$key]);
1913 }
1914 if (isset($descriptionContents[$key])) {
1915 $updateData['sys_file_reference'][$referenceId]['description'] = trim($descriptionContents[$key]);
1916 }
1917 if (isset($linkContents[$key])) {
1918 $updateData['sys_file_reference'][$referenceId]['link'] = trim($linkContents[$key]);
1919 }
1920 }
1921 }
1922 }
1923 }
1924
1925 // update
1926 $tce = $this->getNewTCE();
1927 $tce->isImporting = true;
1928 $tce->start($updateData, array());
1929 $tce->process_datamap();
1930 }
1931
1932 /**
1933 * Returns TRUE if directory exists and if it doesn't it will create directory and return TRUE if that succeeded.
1934 *
1935 * @param string $dirPrefix Directory to create. Having a trailing slash. Must be in fileadmin/. Relative to PATH_site
1936 * @return bool TRUE, if directory exists (was created)
1937 */
1938 public function checkOrCreateDir($dirPrefix)
1939 {
1940 // Split dir path and remove first directory (which should be "fileadmin")
1941 $filePathParts = explode('/', $dirPrefix);
1942 $firstDir = array_shift($filePathParts);
1943 if ($firstDir === $this->fileadminFolderName && GeneralUtility::getFileAbsFileName($dirPrefix)) {
1944 $pathAcc = '';
1945 foreach ($filePathParts as $dirname) {
1946 $pathAcc .= '/' . $dirname;
1947 if (strlen($dirname)) {
1948 if (!@is_dir((PATH_site . $this->fileadminFolderName . $pathAcc))) {
1949 if (!GeneralUtility::mkdir((PATH_site . $this->fileadminFolderName . $pathAcc))) {
1950 $this->error('ERROR: Directory could not be created....B');
1951 return false;
1952 }
1953 }
1954 } elseif ($dirPrefix === $this->fileadminFolderName . $pathAcc) {
1955 return true;
1956 } else {
1957 $this->error('ERROR: Directory could not be created....A');
1958 }
1959 }
1960 }
1961 return false;
1962 }
1963
1964 /**************************
1965 * File Input
1966 *************************/
1967
1968 /**
1969 * Loads the header section/all of the $filename into memory
1970 *
1971 * @param string $filename Filename, absolute
1972 * @param bool $all If set, all information is loaded (header, records and files). Otherwise the default is to read only the header information
1973 * @return bool TRUE if the operation went well
1974 */
1975 public function loadFile($filename, $all = false)
1976 {
1977 if (!@is_file($filename)) {
1978 $this->error('Filename not found: ' . $filename);
1979 return false;
1980 }
1981 $fI = pathinfo($filename);
1982 if (@is_dir($filename . '.files')) {
1983 if (GeneralUtility::isAllowedAbsPath($filename . '.files')) {
1984 // copy the folder lowlevel to typo3temp, because the files would be deleted after import
1985 $temporaryFolderName = $this->getTemporaryFolderName();
1986 GeneralUtility::copyDirectory($filename . '.files', $temporaryFolderName);
1987 $this->filesPathForImport = $temporaryFolderName;
1988 } else {
1989 $this->error('External import files for the given import source is currently not supported.');
1990 }
1991 }
1992 if (strtolower($fI['extension']) == 'xml') {
1993 // XML:
1994 $xmlContent = GeneralUtility::getUrl($filename);
1995 if (strlen($xmlContent)) {
1996 $this->dat = GeneralUtility::xml2array($xmlContent, '', true);
1997 if (is_array($this->dat)) {
1998 if ($this->dat['_DOCUMENT_TAG'] === 'T3RecordDocument' && is_array($this->dat['header']) && is_array($this->dat['records'])) {
1999 $this->loadInit();
2000 return true;
2001 } else {
2002 $this->error('XML file did not contain proper XML for TYPO3 Import');
2003 }
2004 } else {
2005 $this->error('XML could not be parsed: ' . $this->dat);
2006 }
2007 } else {
2008 $this->error('Error opening file: ' . $filename);
2009 }
2010 } else {
2011 // T3D
2012 if ($fd = fopen($filename, 'rb')) {
2013 $this->dat['header'] = $this->getNextFilePart($fd, 1, 'header');
2014 if ($all) {
2015 $this->dat['records'] = $this->getNextFilePart($fd, 1, 'records');
2016 $this->dat['files'] = $this->getNextFilePart($fd, 1, 'files');
2017 $this->dat['files_fal'] = $this->getNextFilePart($fd, 1, 'files_fal');
2018 }
2019 $this->loadInit();
2020 return true;
2021 } else {
2022 $this->error('Error opening file: ' . $filename);
2023 }
2024 fclose($fd);
2025 }
2026 return false;
2027 }
2028
2029 /**
2030 * Returns the next content part form the fileresource (t3d), $fd
2031 *
2032 * @param resource $fd File pointer
2033 * @param bool $unserialize If set, the returned content is unserialized into an array, otherwise you get the raw string
2034 * @param string $name For error messages this indicates the section of the problem.
2035 * @return string|NULL Data string or NULL in case of an error
2036 * @access private
2037 * @see loadFile()
2038 */
2039 public function getNextFilePart($fd, $unserialize = false, $name = '')
2040 {
2041 $initStrLen = 32 + 1 + 1 + 1 + 10 + 1;
2042 // Getting header data
2043 $initStr = fread($fd, $initStrLen);
2044 if (empty($initStr)) {
2045 $this->error('File does not contain data for "' . $name . '"');
2046 return null;
2047 }
2048 $initStrDat = explode(':', $initStr);
2049 if (strstr($initStrDat[0], 'Warning')) {
2050 $this->error('File read error: Warning message in file. (' . $initStr . fgets($fd) . ')');
2051 return null;
2052 }
2053 if ((string)$initStrDat[3] !== '') {
2054 $this->error('File read error: InitString had a wrong length. (' . $name . ')');
2055 return null;
2056 }
2057 $datString = fread($fd, (int)$initStrDat[2]);
2058 fread($fd, 1);
2059 if (md5($datString) === $initStrDat[0]) {
2060 if ($initStrDat[1]) {
2061 if ($this->compress) {
2062 $datString = gzuncompress($datString);
2063 } else {
2064 $this->error('Content read error: This file requires decompression, but this server does not offer gzcompress()/gzuncompress() functions.');
2065 return null;
2066 }
2067 }
2068 return $unserialize ? unserialize($datString) : $datString;
2069 } else {
2070 $this->error('MD5 check failed (' . $name . ')');
2071 }
2072 return null;
2073 }
2074
2075 /**
2076 * Loads T3D file content into the $this->dat array
2077 * (This function can be used to test the output strings from ->compileMemoryToFileContent())
2078 *
2079 * @param string $filecontent File content
2080 * @return void
2081 */
2082 public function loadContent($filecontent)
2083 {
2084 $pointer = 0;
2085 $this->dat['header'] = $this->getNextContentPart($filecontent, $pointer, 1, 'header');
2086 $this->dat['records'] = $this->getNextContentPart($filecontent, $pointer, 1, 'records');
2087 $this->dat['files'] = $this->getNextContentPart($filecontent, $pointer, 1, 'files');
2088 $this->loadInit();
2089 }
2090
2091 /**
2092 * Returns the next content part from the $filecontent
2093 *
2094 * @param string $filecontent File content string
2095 * @param int $pointer File pointer (where to read from)
2096 * @param bool $unserialize If set, the returned content is unserialized into an array, otherwise you get the raw string
2097 * @param string $name For error messages this indicates the section of the problem.
2098 * @return string|NULL Data string
2099 */
2100 public function getNextContentPart($filecontent, &$pointer, $unserialize = false, $name = '')
2101 {
2102 $initStrLen = 32 + 1 + 1 + 1 + 10 + 1;
2103 // getting header data
2104 $initStr = substr($filecontent, $pointer, $initStrLen);
2105 $pointer += $initStrLen;
2106 $initStrDat = explode(':', $initStr);
2107 if ((string)$initStrDat[3] !== '') {
2108 $this->error('Content read error: InitString had a wrong length. (' . $name . ')');
2109 return null;
2110 }
2111 $datString = substr($filecontent, $pointer, (int)$initStrDat[2]);
2112 $pointer += (int)$initStrDat[2] + 1;
2113 if (md5($datString) === $initStrDat[0]) {
2114 if ($initStrDat[1]) {
2115 if ($this->compress) {
2116 $datString = gzuncompress($datString);
2117 return $unserialize ? unserialize($datString) : $datString;
2118 } else {
2119 $this->error('Content read error: This file requires decompression, but this server does not offer gzcompress()/gzuncompress() functions.');
2120 }
2121 }
2122 } else {
2123 $this->error('MD5 check failed (' . $name . ')');
2124 }
2125 return null;
2126 }
2127
2128 /**
2129 * Setting up the object based on the recently loaded ->dat array
2130 *
2131 * @return void
2132 */
2133 public function loadInit()
2134 {
2135 $this->cleanupImportData();
2136 $this->relStaticTables = (array)$this->dat['header']['relStaticTables'];
2137 $this->excludeMap = (array)$this->dat['header']['excludeMap'];
2138 $this->softrefCfg = (array)$this->dat['header']['softrefCfg'];
2139 $this->fixCharsets();
2140 if (
2141 isset($this->dat['header']['meta']['TYPO3_version'])
2142 && VersionNumberUtility::convertVersionNumberToInteger($this->dat['header']['meta']['TYPO3_version']) < 6000000
2143 ) {
2144 $this->legacyImport = true;
2145 $this->initializeLegacyImportFolder();
2146 }
2147 }
2148
2149 /**
2150 * Cleanses any inconsistent states which can occur in imported T3D/XML
2151 *
2152 * @return void
2153 */
2154 protected function cleanupImportData()
2155 {
2156 if (isset($this->dat['header']['extensionDependencies']) && is_array($this->dat['header']['extensionDependencies'])) {
2157 $this->dat['header']['extensionDependencies'] = array_filter($this->dat['header']['extensionDependencies']);
2158 } else {
2159 $this->dat['header']['extensionDependencies'] = array();
2160 }
2161 }
2162
2163 /**
2164 * Fix charset of import memory if different from system charset
2165 *
2166 * @return void
2167 * @see loadInit()
2168 */
2169 public function fixCharsets()
2170 {
2171 $importCharset = $this->dat['header']['charset'];
2172 if ($importCharset) {
2173 if ($importCharset !== $this->getLanguageService()->charSet) {
2174 $this->error('CHARSET: Converting charset of input file (' . $importCharset . ') to the system charset (' . $this->getLanguageService()->charSet . ')');
2175 // Convert meta data:
2176 if (is_array($this->dat['header']['meta'])) {
2177 $this->getLanguageService()->csConvObj->convArray($this->dat['header']['meta'], $importCharset, $this->getLanguageService()->charSet);
2178 }
2179 // Convert record headers:
2180 if (is_array($this->dat['header']['records'])) {
2181 $this->getLanguageService()->csConvObj->convArray($this->dat['header']['records'], $importCharset, $this->getLanguageService()->charSet);
2182 }
2183 // Convert records themselves:
2184 if (is_array($this->dat['records'])) {
2185 $this->getLanguageService()->csConvObj->convArray($this->dat['records'], $importCharset, $this->getLanguageService()->charSet);
2186 }
2187 }
2188 } else {
2189 $this->error('CHARSET: No charset found in import file!');
2190 }
2191 }
2192 }