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