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