[!!!][TASK] Remove deprecated code from database and query functions
[Packages/TYPO3.CMS.git] / typo3 / sysext / impexp / Classes / ImportExport.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\Authentication\BackendUserAuthentication;
19 use TYPO3\CMS\Core\Database\DatabaseConnection;
20 use TYPO3\CMS\Core\Database\ReferenceIndex;
21 use TYPO3\CMS\Core\DataHandling\DataHandler;
22 use TYPO3\CMS\Core\Exception;
23 use TYPO3\CMS\Core\Html\HtmlParser;
24 use TYPO3\CMS\Core\Imaging\Icon;
25 use TYPO3\CMS\Core\Imaging\IconFactory;
26 use TYPO3\CMS\Core\Resource\DuplicationBehavior;
27 use TYPO3\CMS\Core\Resource\File;
28 use TYPO3\CMS\Core\Resource\FileInterface;
29 use TYPO3\CMS\Core\Resource\ResourceFactory;
30 use TYPO3\CMS\Core\Resource\StorageRepository;
31 use TYPO3\CMS\Core\Utility\DebugUtility;
32 use TYPO3\CMS\Core\Utility\DiffUtility;
33 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
34 use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
35 use TYPO3\CMS\Core\Utility\GeneralUtility;
36 use TYPO3\CMS\Core\Utility\MathUtility;
37 use TYPO3\CMS\Core\Utility\PathUtility;
38 use TYPO3\CMS\Core\Utility\StringUtility;
39 use TYPO3\CMS\Core\Utility\VersionNumberUtility;
40 use TYPO3\CMS\Lang\LanguageService;
41
42 /**
43 * EXAMPLE for using the impexp-class for exporting stuff:
44 *
45 * Create and initialize:
46 * $this->export = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Impexp\ImportExport::class);
47 * $this->export->init();
48 * Set which tables relations we will allow:
49 * $this->export->relOnlyTables[]="tt_news"; // exclusively includes. See comment in the class
50 *
51 * Adding records:
52 * $this->export->export_addRecord("pages", $this->pageinfo);
53 * $this->export->export_addRecord("pages", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("pages", 38));
54 * $this->export->export_addRecord("pages", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("pages", 39));
55 * $this->export->export_addRecord("tt_content", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("tt_content", 12));
56 * $this->export->export_addRecord("tt_content", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("tt_content", 74));
57 * $this->export->export_addRecord("sys_template", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("sys_template", 20));
58 *
59 * Adding all the relations (recursively in 5 levels so relations has THEIR relations registered as well)
60 * for($a=0;$a<5;$a++) {
61 * $addR = $this->export->export_addDBRelations($a);
62 * if (empty($addR)) break;
63 * }
64 *
65 * Finally load all the files.
66 * $this->export->export_addFilesFromRelations(); // MUST be after the DBrelations are set so that file from ALL added records are included!
67 *
68 * Write export
69 * $out = $this->export->compileMemoryToFileContent();
70 */
71
72 /**
73 * T3D file Import/Export library (TYPO3 Record Document)
74 */
75 class ImportExport
76 {
77 /**
78 * If set, static relations (not exported) will be shown in overview as well
79 *
80 * @var bool
81 */
82 public $showStaticRelations = false;
83
84 /**
85 * Name of the "fileadmin" folder where files for export/import should be located
86 *
87 * @var string
88 */
89 public $fileadminFolderName = '';
90
91 /**
92 * Whether "import" or "export" mode of object. Set through init() function
93 *
94 * @var string
95 */
96 public $mode = '';
97
98 /**
99 * Updates all records that has same UID instead of creating new!
100 *
101 * @var bool
102 */
103 public $update = false;
104
105 /**
106 * Is set by importData() when an import has been done.
107 *
108 * @var bool
109 */
110 public $doesImport = false;
111
112 /**
113 * If set to a page-record, then the preview display of the content will expect this page-record to be the target
114 * for the import and accordingly display validation information. This triggers the visual view of the
115 * import/export memory to validate if import is possible
116 *
117 * @var array
118 */
119 public $display_import_pid_record = array();
120
121 /**
122 * Used to register the forged UID values for imported records that we want
123 * to create with the same UIDs as in the import file. Admin-only feature.
124 *
125 * @var array
126 */
127 public $suggestedInsertUids = array();
128
129 /**
130 * Setting import modes during update state: as_new, exclude, force_uid
131 *
132 * @var array
133 */
134 public $import_mode = array();
135
136 /**
137 * If set, PID correct is ignored globally
138 *
139 * @var bool
140 */
141 public $global_ignore_pid = false;
142
143 /**
144 * If set, all UID values are forced! (update or import)
145 *
146 * @var bool
147 */
148 public $force_all_UIDS = false;
149
150 /**
151 * If set, a diff-view column is added to the overview.
152 *
153 * @var bool
154 */
155 public $showDiff = false;
156
157 /**
158 * If set, and if the user is admin, allow the writing of PHP scripts to fileadmin/ area.
159 *
160 * @var bool
161 */
162 public $allowPHPScripts = false;
163
164 /**
165 * Disable logging when importing
166 *
167 * @var bool
168 */
169 public $enableLogging = false;
170
171 /**
172 * Array of values to substitute in editable softreferences.
173 *
174 * @var array
175 */
176 public $softrefInputValues = array();
177
178 /**
179 * Mapping between the fileID from import memory and the final filenames they are written to.
180 *
181 * @var array
182 */
183 public $fileIDMap = array();
184
185 /**
186 * 1MB max file size
187 *
188 * @var int
189 */
190 public $maxFileSize = 1000000;
191
192 /**
193 * 1MB max record size
194 *
195 * @var int
196 */
197 public $maxRecordSize = 1000000;
198
199 /**
200 * 10MB max export size
201 *
202 * @var int
203 */
204 public $maxExportSize = 10000000;
205
206 /**
207 * Add table names here which are THE ONLY ones which will be included
208 * into export if found as relations. '_ALL' will allow all tables.
209 *
210 * @var array
211 */
212 public $relOnlyTables = array();
213
214 /**
215 * Add tables names here which should not be exported with the file.
216 * (Where relations should be mapped to same UIDs in target system).
217 *
218 * @var array
219 */
220 public $relStaticTables = array();
221
222 /**
223 * Exclude map. Keys are table:uid pairs and if set, records are not added to the export.
224 *
225 * @var array
226 */
227 public $excludeMap = array();
228
229 /**
230 * Soft Reference Token ID modes.
231 *
232 * @var array
233 */
234 public $softrefCfg = array();
235
236 /**
237 * Listing extension dependencies.
238 *
239 * @var array
240 */
241 public $extensionDependencies = array();
242
243 /**
244 * Set by user: If set, compression in t3d files is disabled
245 *
246 * @var bool
247 */
248 public $dontCompress = false;
249
250 /**
251 * If set, HTML file resources are included.
252 *
253 * @var bool
254 */
255 public $includeExtFileResources = false;
256
257 /**
258 * Files with external media (HTML/css style references inside)
259 *
260 * @var string
261 */
262 public $extFileResourceExtensions = 'html,htm,css';
263
264 /**
265 * After records are written this array is filled with [table][original_uid] = [new_uid]
266 *
267 * @var array
268 */
269 public $import_mapId = array();
270
271 /**
272 * Keys are [tablename]:[new NEWxxx ids (or when updating it is uids)]
273 * while values are arrays with table/uid of the original record it is based on.
274 * With the array keys the new ids can be looked up inside tcemain
275 *
276 * @var array
277 */
278 public $import_newId = array();
279
280 /**
281 * Page id map for page tree (import)
282 *
283 * @var array
284 */
285 public $import_newId_pids = array();
286
287 /**
288 * Internal data accumulation for writing records during import
289 *
290 * @var array
291 */
292 public $import_data = array();
293
294 /**
295 * Error log.
296 *
297 * @var array
298 */
299 public $errorLog = array();
300
301 /**
302 * Cache for record paths
303 *
304 * @var array
305 */
306 public $cache_getRecordPath = array();
307
308 /**
309 * Cache of checkPID values.
310 *
311 * @var array
312 */
313 public $checkPID_cache = array();
314
315 /**
316 * Set internally if the gzcompress function exists
317 * Used by ImportExportController
318 *
319 * @var bool
320 */
321 public $compress = false;
322
323 /**
324 * Internal import/export memory
325 *
326 * @var array
327 */
328 public $dat = array();
329
330 /**
331 * File processing object
332 *
333 * @var ExtendedFileUtility
334 */
335 protected $fileProcObj = null;
336
337 /**
338 * Keys are [recordname], values are an array of fields to be included
339 * in the export
340 *
341 * @var array
342 */
343 protected $recordTypesIncludeFields = array();
344
345 /**
346 * Default array of fields to be included in the export
347 *
348 * @var array
349 */
350 protected $defaultRecordIncludeFields = array('uid', 'pid');
351
352 /**
353 * Array of current registered storage objects
354 *
355 * @var array
356 */
357 protected $storageObjects = array();
358
359 /**
360 * Is set, if the import file has a TYPO3 version below 6.0
361 *
362 * @var bool
363 */
364 protected $legacyImport = false;
365
366 /**
367 * @var \TYPO3\CMS\Core\Resource\Folder
368 */
369 protected $legacyImportFolder = null;
370
371 /**
372 * Related to the default storage root
373 *
374 * @var string
375 */
376 protected $legacyImportTargetPath = '_imported/';
377
378 /**
379 * Table fields to migrate
380 *
381 * @var array
382 */
383 protected $legacyImportMigrationTables = array(
384 'tt_content' => array(
385 'image' => array(
386 'titleTexts' => 'titleText',
387 'description' => 'imagecaption',
388 'links' => 'image_link',
389 'alternativeTexts' => 'altText'
390 ),
391 'media' => array(
392 'description' => 'imagecaption',
393 )
394 ),
395 'pages' => array(
396 'media' => array()
397 ),
398 'pages_language_overlay' => array(
399 'media' => array()
400 )
401 );
402
403 /**
404 * Records to be migrated after all
405 * Multidimensional array [table][uid][field] = array([related sys_file_reference uids])
406 *
407 * @var array
408 */
409 protected $legacyImportMigrationRecords = array();
410
411 /**
412 * @var bool
413 */
414 protected $saveFilesOutsideExportFile = false;
415
416 /**
417 * @var NULL|string
418 */
419 protected $temporaryFilesPathForExport = null;
420
421 /**
422 * @var NULL|string
423 */
424 protected $filesPathForImport = null;
425
426 /**
427 * @var array
428 */
429 protected $unlinkFiles = array();
430
431 /**
432 * @var array
433 */
434 protected $alternativeFileName = array();
435
436 /**
437 * @var array
438 */
439 protected $alternativeFilePath = array();
440
441 /**
442 * @var array
443 */
444 protected $filePathMap = array();
445
446 /**
447 * @var array
448 */
449 protected $remainHeader = array();
450
451 /**
452 * @var IconFactory
453 */
454 protected $iconFactory;
455
456 /**
457 * The constructor
458 */
459 public function __construct()
460 {
461 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
462 }
463
464 /**************************
465 * Initialize
466 *************************/
467
468 /**
469 * Init the object, both import and export
470 *
471 * @param bool $dontCompress If set, compression of t3d files is disabled
472 * @param string $mode Mode of usage, either "import" or "export
473 * @return void
474 */
475 public function init($dontCompress = false, $mode = '')
476 {
477 $this->compress = function_exists('gzcompress');
478 $this->dontCompress = $dontCompress;
479 $this->mode = $mode;
480 $this->fileadminFolderName = !empty($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) ? rtrim($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '/') : 'fileadmin';
481 }
482
483 /**************************
484 * Export / Init + Meta Data
485 *************************/
486
487 /**
488 * Set header basics
489 *
490 * @return void
491 */
492 public function setHeaderBasics()
493 {
494 // Initializing:
495 if (is_array($this->softrefCfg)) {
496 foreach ($this->softrefCfg as $key => $value) {
497 if (!strlen($value['mode'])) {
498 unset($this->softrefCfg[$key]);
499 }
500 }
501 }
502 // Setting in header memory:
503 // Version of file format
504 $this->dat['header']['XMLversion'] = '1.0';
505 // Initialize meta data array (to put it in top of file)
506 $this->dat['header']['meta'] = array();
507 // Add list of tables to consider static
508 $this->dat['header']['relStaticTables'] = $this->relStaticTables;
509 // The list of excluded records
510 $this->dat['header']['excludeMap'] = $this->excludeMap;
511 // Soft Reference mode for elements
512 $this->dat['header']['softrefCfg'] = $this->softrefCfg;
513 // List of extensions the import depends on.
514 $this->dat['header']['extensionDependencies'] = $this->extensionDependencies;
515 }
516
517 /**
518 * Set charset
519 *
520 * @param string $charset Charset for the content in the export. During import the character set will be converted if the target system uses another charset.
521 * @return void
522 */
523 public function setCharset($charset)
524 {
525 $this->dat['header']['charset'] = $charset;
526 }
527
528 /**
529 * Sets meta data
530 *
531 * @param string $title Title of the export
532 * @param string $description Description of the export
533 * @param string $notes Notes about the contents
534 * @param string $packager_username Backend Username of the packager (the guy making the export)
535 * @param string $packager_name Real name of the packager
536 * @param string $packager_email Email of the packager
537 * @return void
538 */
539 public function setMetaData($title, $description, $notes, $packager_username, $packager_name, $packager_email)
540 {
541 $this->dat['header']['meta'] = array(
542 'title' => $title,
543 'description' => $description,
544 'notes' => $notes,
545 'packager_username' => $packager_username,
546 'packager_name' => $packager_name,
547 'packager_email' => $packager_email,
548 'TYPO3_version' => TYPO3_version,
549 'created' => strftime('%A %e. %B %Y', $GLOBALS['EXEC_TIME'])
550 );
551 }
552
553 /**
554 * Option to enable having the files not included in the export file.
555 * The files are saved to a temporary folder instead.
556 *
557 * @param bool $saveFilesOutsideExportFile
558 * @see getTemporaryFilesPathForExport()
559 */
560 public function setSaveFilesOutsideExportFile($saveFilesOutsideExportFile)
561 {
562 $this->saveFilesOutsideExportFile = $saveFilesOutsideExportFile;
563 }
564
565 /**
566 * Sets a thumbnail image to the exported file
567 *
568 * @param string $imgFilepath Filename reference, gif, jpg, png. Absolute path.
569 * @return void
570 */
571 public function addThumbnail($imgFilepath)
572 {
573 if (@is_file($imgFilepath)) {
574 $imgInfo = @getimagesize($imgFilepath);
575 if (is_array($imgInfo)) {
576 $fileContent = GeneralUtility::getUrl($imgFilepath);
577 $this->dat['header']['thumbnail'] = array(
578 'imgInfo' => $imgInfo,
579 'content' => $fileContent,
580 'filesize' => strlen($fileContent),
581 'filemtime' => filemtime($imgFilepath),
582 'filename' => PathUtility::basename($imgFilepath)
583 );
584 }
585 }
586 }
587
588 /**************************
589 * Export / Init Page tree
590 *************************/
591
592 /**
593 * Sets the page-tree array in the export header and returns the array in a flattened version
594 *
595 * @param array $idH Hierarchy of ids, the page tree: array([uid] => array("uid" => [uid], "subrow" => array(.....)), [uid] => ....)
596 * @return array The hierarchical page tree converted to a one-dimensional list of pages
597 */
598 public function setPageTree($idH)
599 {
600 $this->dat['header']['pagetree'] = $this->unsetExcludedSections($idH);
601 return $this->flatInversePageTree($this->dat['header']['pagetree']);
602 }
603
604 /**
605 * Removes entries in the page tree which are found in ->excludeMap[]
606 *
607 * @param array $idH Page uid hierarchy
608 * @return array Modified input array
609 * @access private
610 * @see setPageTree()
611 */
612 public function unsetExcludedSections($idH)
613 {
614 if (is_array($idH)) {
615 foreach ($idH as $k => $v) {
616 if ($this->excludeMap['pages:' . $idH[$k]['uid']]) {
617 unset($idH[$k]);
618 } elseif (is_array($idH[$k]['subrow'])) {
619 $idH[$k]['subrow'] = $this->unsetExcludedSections($idH[$k]['subrow']);
620 }
621 }
622 }
623 return $idH;
624 }
625
626 /**
627 * Recursively flattening the idH array (for setPageTree() function)
628 *
629 * @param array $idH Page uid hierarchy
630 * @param array $a Accumulation array of pages (internal, don't set from outside)
631 * @return array Array with uid-uid pairs for all pages in the page tree.
632 * @see flatInversePageTree_pid()
633 */
634 public function flatInversePageTree($idH, $a = array())
635 {
636 if (is_array($idH)) {
637 $idH = array_reverse($idH);
638 foreach ($idH as $k => $v) {
639 $a[$v['uid']] = $v['uid'];
640 if (is_array($v['subrow'])) {
641 $a = $this->flatInversePageTree($v['subrow'], $a);
642 }
643 }
644 }
645 return $a;
646 }
647
648 /**
649 * Recursively flattening the idH array (for setPageTree() function), setting PIDs as values
650 *
651 * @param array $idH Page uid hierarchy
652 * @param array $a Accumulation array of pages (internal, don't set from outside)
653 * @param int $pid PID value (internal)
654 * @return array Array with uid-pid pairs for all pages in the page tree.
655 * @see flatInversePageTree()
656 */
657 public function flatInversePageTree_pid($idH, $a = array(), $pid = -1)
658 {
659 if (is_array($idH)) {
660 $idH = array_reverse($idH);
661 foreach ($idH as $v) {
662 $a[$v['uid']] = $pid;
663 if (is_array($v['subrow'])) {
664 $a = $this->flatInversePageTree_pid($v['subrow'], $a, $v['uid']);
665 }
666 }
667 }
668 return $a;
669 }
670
671 /**************************
672 * Export
673 *************************/
674
675 /**
676 * Sets the fields of record types to be included in the export
677 *
678 * @param array $recordTypesIncludeFields Keys are [recordname], values are an array of fields to be included in the export
679 * @throws Exception if an array value is not type of array
680 * @return void
681 */
682 public function setRecordTypesIncludeFields(array $recordTypesIncludeFields)
683 {
684 foreach ($recordTypesIncludeFields as $table => $fields) {
685 if (!is_array($fields)) {
686 throw new Exception('The include fields for record type ' . htmlspecialchars($table) . ' are not defined by an array.', 1391440658);
687 }
688 $this->setRecordTypeIncludeFields($table, $fields);
689 }
690 }
691
692 /**
693 * Sets the fields of a record type to be included in the export
694 *
695 * @param string $table The record type
696 * @param array $fields The fields to be included
697 * @return void
698 */
699 public function setRecordTypeIncludeFields($table, array $fields)
700 {
701 $this->recordTypesIncludeFields[$table] = $fields;
702 }
703
704 /**
705 * Adds the record $row from $table.
706 * No checking for relations done here. Pure data.
707 *
708 * @param string $table Table name
709 * @param array $row Record row.
710 * @param int $relationLevel (Internal) if the record is added as a relation, this is set to the "level" it was on.
711 * @return void
712 */
713 public function export_addRecord($table, $row, $relationLevel = 0)
714 {
715 BackendUtility::workspaceOL($table, $row);
716 if ((string)$table !== '' && is_array($row) && $row['uid'] > 0 && !$this->excludeMap[$table . ':' . $row['uid']]) {
717 if ($this->checkPID($table === 'pages' ? $row['uid'] : $row['pid'])) {
718 if (!isset($this->dat['records'][$table . ':' . $row['uid']])) {
719 // Prepare header info:
720 $row = $this->filterRecordFields($table, $row);
721 $headerInfo = array();
722 $headerInfo['uid'] = $row['uid'];
723 $headerInfo['pid'] = $row['pid'];
724 $headerInfo['title'] = GeneralUtility::fixed_lgd_cs(BackendUtility::getRecordTitle($table, $row), 40);
725 $headerInfo['size'] = strlen(serialize($row));
726 if ($relationLevel) {
727 $headerInfo['relationLevel'] = $relationLevel;
728 }
729 // If record content is not too large in size, set the header content and add the rest:
730 if ($headerInfo['size'] < $this->maxRecordSize) {
731 // Set the header summary:
732 $this->dat['header']['records'][$table][$row['uid']] = $headerInfo;
733 // Create entry in the PID lookup:
734 $this->dat['header']['pid_lookup'][$row['pid']][$table][$row['uid']] = 1;
735 // Initialize reference index object:
736 $refIndexObj = GeneralUtility::makeInstance(ReferenceIndex::class);
737 // Yes to workspace overlays for exporting....
738 $refIndexObj->WSOL = true;
739 $relations = $refIndexObj->getRelations($table, $row);
740 $relations = $this->fixFileIDsInRelations($relations);
741 $relations = $this->removeSoftrefsHavingTheSameDatabaseRelation($relations);
742 // Data:
743 $this->dat['records'][$table . ':' . $row['uid']] = array();
744 $this->dat['records'][$table . ':' . $row['uid']]['data'] = $row;
745 $this->dat['records'][$table . ':' . $row['uid']]['rels'] = $relations;
746 // Add information about the relations in the record in the header:
747 $this->dat['header']['records'][$table][$row['uid']]['rels'] = $this->flatDBrels($this->dat['records'][$table . ':' . $row['uid']]['rels']);
748 // Add information about the softrefs to header:
749 $this->dat['header']['records'][$table][$row['uid']]['softrefs'] = $this->flatSoftRefs($this->dat['records'][$table . ':' . $row['uid']]['rels']);
750 } else {
751 $this->error('Record ' . $table . ':' . $row['uid'] . ' was larger than maxRecordSize (' . GeneralUtility::formatSize($this->maxRecordSize) . ')');
752 }
753 } else {
754 $this->error('Record ' . $table . ':' . $row['uid'] . ' already added.');
755 }
756 } else {
757 $this->error('Record ' . $table . ':' . $row['uid'] . ' was outside your DB mounts!');
758 }
759 }
760 }
761
762 /**
763 * This changes the file reference ID from a hash based on the absolute file path
764 * (coming from ReferenceIndex) to a hash based on the relative file path.
765 *
766 * @param array $relations
767 * @return array
768 */
769 protected function fixFileIDsInRelations(array $relations)
770 {
771 foreach ($relations as $field => $relation) {
772 if (isset($relation['type']) && $relation['type'] === 'file') {
773 foreach ($relation['newValueFiles'] as $key => $fileRelationData) {
774 $absoluteFilePath = $fileRelationData['ID_absFile'];
775 if (GeneralUtility::isFirstPartOfStr($absoluteFilePath, PATH_site)) {
776 $relatedFilePath = PathUtility::stripPathSitePrefix($absoluteFilePath);
777 $relations[$field]['newValueFiles'][$key]['ID'] = md5($relatedFilePath);
778 }
779 }
780 }
781 if ($relation['type'] === 'flex') {
782 if (is_array($relation['flexFormRels']['file'])) {
783 foreach ($relation['flexFormRels']['file'] as $key => $subList) {
784 foreach ($subList as $subKey => $fileRelationData) {
785 $absoluteFilePath = $fileRelationData['ID_absFile'];
786 if (GeneralUtility::isFirstPartOfStr($absoluteFilePath, PATH_site)) {
787 $relatedFilePath = PathUtility::stripPathSitePrefix($absoluteFilePath);
788 $relations[$field]['flexFormRels']['file'][$key][$subKey]['ID'] = md5($relatedFilePath);
789 }
790 }
791 }
792 }
793 }
794 }
795 return $relations;
796 }
797
798 /**
799 * Relations could contain db relations to sys_file records. Some configuration combinations of TCA and
800 * SoftReferenceIndex create also softref relation entries for the identical file. This results
801 * in double included files, one in array "files" and one in array "file_fal".
802 * This function checks the relations for this double inclusions and removes the redundant softref relation.
803 *
804 * @param array $relations
805 * @return array
806 */
807 protected function removeSoftrefsHavingTheSameDatabaseRelation($relations)
808 {
809 $fixedRelations = array();
810 foreach ($relations as $field => $relation) {
811 $newRelation = $relation;
812 if (isset($newRelation['type']) && $newRelation['type'] === 'db') {
813 foreach ($newRelation['itemArray'] as $key => $dbRelationData) {
814 if ($dbRelationData['table'] === 'sys_file') {
815 if (isset($newRelation['softrefs']['keys']['typolink'])) {
816 foreach ($newRelation['softrefs']['keys']['typolink'] as $softrefKey => $softRefData) {
817 if ($softRefData['subst']['type'] === 'file') {
818 $file = ResourceFactory::getInstance()->retrieveFileOrFolderObject($softRefData['subst']['relFileName']);
819 if ($file instanceof File) {
820 if ($file->getUid() == $dbRelationData['id']) {
821 unset($newRelation['softrefs']['keys']['typolink'][$softrefKey]);
822 }
823 }
824 }
825 }
826 if (empty($newRelation['softrefs']['keys']['typolink'])) {
827 unset($newRelation['softrefs']);
828 }
829 }
830 }
831 }
832 }
833 $fixedRelations[$field] = $newRelation;
834 }
835 return $fixedRelations;
836 }
837
838 /**
839 * This analyses the existing added records, finds all database relations to records and adds these records to the export file.
840 * This function can be called repeatedly until it returns an empty array.
841 * In principle it should not allow to infinite recursivity, but you better set a limit...
842 * Call this BEFORE the ext_addFilesFromRelations (so files from added relations are also included of course)
843 *
844 * @param int $relationLevel Recursion level
845 * @return array overview of relations found and added: Keys [table]:[uid], values array with table and id
846 * @see export_addFilesFromRelations()
847 */
848 public function export_addDBRelations($relationLevel = 0)
849 {
850 // Traverse all "rels" registered for "records"
851 if (!is_array($this->dat['records'])) {
852 $this->error('There were no records available.');
853 return array();
854 }
855 $addR = array();
856 foreach ($this->dat['records'] as $k => $value) {
857 if (!is_array($this->dat['records'][$k])) {
858 continue;
859 }
860 foreach ($this->dat['records'][$k]['rels'] as $fieldname => $vR) {
861 // For all DB types of relations:
862 if ($vR['type'] == 'db') {
863 foreach ($vR['itemArray'] as $fI) {
864 $this->export_addDBRelations_registerRelation($fI, $addR);
865 }
866 }
867 // For all flex/db types of relations:
868 if ($vR['type'] == 'flex') {
869 // DB relations in flex form fields:
870 if (is_array($vR['flexFormRels']['db'])) {
871 foreach ($vR['flexFormRels']['db'] as $subList) {
872 foreach ($subList as $fI) {
873 $this->export_addDBRelations_registerRelation($fI, $addR);
874 }
875 }
876 }
877 // DB oriented soft references in flex form fields:
878 if (is_array($vR['flexFormRels']['softrefs'])) {
879 foreach ($vR['flexFormRels']['softrefs'] as $subList) {
880 foreach ($subList['keys'] as $spKey => $elements) {
881 foreach ($elements as $el) {
882 if ($el['subst']['type'] === 'db' && $this->includeSoftref($el['subst']['tokenID'])) {
883 list($tempTable, $tempUid) = explode(':', $el['subst']['recordRef']);
884 $fI = array(
885 'table' => $tempTable,
886 'id' => $tempUid
887 );
888 $this->export_addDBRelations_registerRelation($fI, $addR, $el['subst']['tokenID']);
889 }
890 }
891 }
892 }
893 }
894 }
895 // In any case, if there are soft refs:
896 if (is_array($vR['softrefs']['keys'])) {
897 foreach ($vR['softrefs']['keys'] as $spKey => $elements) {
898 foreach ($elements as $el) {
899 if ($el['subst']['type'] === 'db' && $this->includeSoftref($el['subst']['tokenID'])) {
900 list($tempTable, $tempUid) = explode(':', $el['subst']['recordRef']);
901 $fI = array(
902 'table' => $tempTable,
903 'id' => $tempUid
904 );
905 $this->export_addDBRelations_registerRelation($fI, $addR, $el['subst']['tokenID']);
906 }
907 }
908 }
909 }
910 }
911 }
912
913 // Now, if there were new records to add, do so:
914 if (!empty($addR)) {
915 foreach ($addR as $fI) {
916 // Get and set record:
917 $row = BackendUtility::getRecord($fI['table'], $fI['id']);
918 if (is_array($row)) {
919 $this->export_addRecord($fI['table'], $row, $relationLevel + 1);
920 }
921 // Set status message
922 // Relation pointers always larger than zero except certain "select" types with
923 // negative values pointing to uids - but that is not supported here.
924 if ($fI['id'] > 0) {
925 $rId = $fI['table'] . ':' . $fI['id'];
926 if (!isset($this->dat['records'][$rId])) {
927 $this->dat['records'][$rId] = 'NOT_FOUND';
928 $this->error('Relation record ' . $rId . ' was not found!');
929 }
930 }
931 }
932 }
933 // Return overview of relations found and added
934 return $addR;
935 }
936
937 /**
938 * Helper function for export_addDBRelations()
939 *
940 * @param array $fI Array with table/id keys to add
941 * @param array $addR Add array, passed by reference to be modified
942 * @param string $tokenID Softref Token ID, if applicable.
943 * @return void
944 * @see export_addDBRelations()
945 */
946 public function export_addDBRelations_registerRelation($fI, &$addR, $tokenID = '')
947 {
948 $rId = $fI['table'] . ':' . $fI['id'];
949 if (
950 isset($GLOBALS['TCA'][$fI['table']]) && !$this->isTableStatic($fI['table']) && !$this->isExcluded($fI['table'], $fI['id'])
951 && (!$tokenID || $this->includeSoftref($tokenID)) && $this->inclRelation($fI['table'])
952 ) {
953 if (!isset($this->dat['records'][$rId])) {
954 // Set this record to be included since it is not already.
955 $addR[$rId] = $fI;
956 }
957 }
958 }
959
960 /**
961 * This adds all files in relations.
962 * Call this method AFTER adding all records including relations.
963 *
964 * @return void
965 * @see export_addDBRelations()
966 */
967 public function export_addFilesFromRelations()
968 {
969 // Traverse all "rels" registered for "records"
970 if (!is_array($this->dat['records'])) {
971 $this->error('There were no records available.');
972 return;
973 }
974 foreach ($this->dat['records'] as $k => $value) {
975 if (!isset($this->dat['records'][$k]['rels']) || !is_array($this->dat['records'][$k]['rels'])) {
976 continue;
977 }
978 foreach ($this->dat['records'][$k]['rels'] as $fieldname => $vR) {
979 // For all file type relations:
980 if ($vR['type'] == 'file') {
981 foreach ($vR['newValueFiles'] as $key => $fI) {
982 $this->export_addFile($fI, $k, $fieldname);
983 // Remove the absolute reference to the file so it doesn't expose absolute paths from source server:
984 unset($this->dat['records'][$k]['rels'][$fieldname]['newValueFiles'][$key]['ID_absFile']);
985 }
986 }
987 // For all flex type relations:
988 if ($vR['type'] == 'flex') {
989 if (is_array($vR['flexFormRels']['file'])) {
990 foreach ($vR['flexFormRels']['file'] as $key => $subList) {
991 foreach ($subList as $subKey => $fI) {
992 $this->export_addFile($fI, $k, $fieldname);
993 // Remove the absolute reference to the file so it doesn't expose absolute paths from source server:
994 unset($this->dat['records'][$k]['rels'][$fieldname]['flexFormRels']['file'][$key][$subKey]['ID_absFile']);
995 }
996 }
997 }
998 // DB oriented soft references in flex form fields:
999 if (is_array($vR['flexFormRels']['softrefs'])) {
1000 foreach ($vR['flexFormRels']['softrefs'] as $key => $subList) {
1001 foreach ($subList['keys'] as $spKey => $elements) {
1002 foreach ($elements as $subKey => $el) {
1003 if ($el['subst']['type'] === 'file' && $this->includeSoftref($el['subst']['tokenID'])) {
1004 // Create abs path and ID for file:
1005 $ID_absFile = GeneralUtility::getFileAbsFileName(PATH_site . $el['subst']['relFileName']);
1006 $ID = md5($el['subst']['relFileName']);
1007 if ($ID_absFile) {
1008 if (!$this->dat['files'][$ID]) {
1009 $fI = array(
1010 'filename' => PathUtility::basename($ID_absFile),
1011 'ID_absFile' => $ID_absFile,
1012 'ID' => $ID,
1013 'relFileName' => $el['subst']['relFileName']
1014 );
1015 $this->export_addFile($fI, '_SOFTREF_');
1016 }
1017 $this->dat['records'][$k]['rels'][$fieldname]['flexFormRels']['softrefs'][$key]['keys'][$spKey][$subKey]['file_ID'] = $ID;
1018 }
1019 }
1020 }
1021 }
1022 }
1023 }
1024 }
1025 // In any case, if there are soft refs:
1026 if (is_array($vR['softrefs']['keys'])) {
1027 foreach ($vR['softrefs']['keys'] as $spKey => $elements) {
1028 foreach ($elements as $subKey => $el) {
1029 if ($el['subst']['type'] === 'file' && $this->includeSoftref($el['subst']['tokenID'])) {
1030 // Create abs path and ID for file:
1031 $ID_absFile = GeneralUtility::getFileAbsFileName(PATH_site . $el['subst']['relFileName']);
1032 $ID = md5($el['subst']['relFileName']);
1033 if ($ID_absFile) {
1034 if (!$this->dat['files'][$ID]) {
1035 $fI = array(
1036 'filename' => PathUtility::basename($ID_absFile),
1037 'ID_absFile' => $ID_absFile,
1038 'ID' => $ID,
1039 'relFileName' => $el['subst']['relFileName']
1040 );
1041 $this->export_addFile($fI, '_SOFTREF_');
1042 }
1043 $this->dat['records'][$k]['rels'][$fieldname]['softrefs']['keys'][$spKey][$subKey]['file_ID'] = $ID;
1044 }
1045 }
1046 }
1047 }
1048 }
1049 }
1050 }
1051 }
1052
1053 /**
1054 * This adds all files from sys_file records
1055 *
1056 * @return void
1057 */
1058 public function export_addFilesFromSysFilesRecords()
1059 {
1060 if (!isset($this->dat['header']['records']['sys_file']) || !is_array($this->dat['header']['records']['sys_file'])) {
1061 return;
1062 }
1063 foreach ($this->dat['header']['records']['sys_file'] as $sysFileUid => $_) {
1064 $recordData = $this->dat['records']['sys_file:' . $sysFileUid]['data'];
1065 $file = ResourceFactory::getInstance()->createFileObject($recordData);
1066 $this->export_addSysFile($file);
1067 }
1068 }
1069
1070 /**
1071 * Adds a files content from a sys file record to the export memory
1072 *
1073 * @param File $file
1074 * @return void
1075 */
1076 public function export_addSysFile(File $file)
1077 {
1078 if ($file->getProperty('size') >= $this->maxFileSize) {
1079 $this->error('File ' . $file->getPublicUrl() . ' was larger (' . GeneralUtility::formatSize($file->getProperty('size')) . ') than the maxFileSize (' . GeneralUtility::formatSize($this->maxFileSize) . ')! Skipping.');
1080 return;
1081 }
1082 $fileContent = '';
1083 try {
1084 if (!$this->saveFilesOutsideExportFile) {
1085 $fileContent = $file->getContents();
1086 } else {
1087 $file->checkActionPermission('read');
1088 }
1089 } catch (\Exception $e) {
1090 $this->error('Error when trying to add file ' . $file->getCombinedIdentifier() . ': ' . $e->getMessage());
1091 return;
1092 }
1093 $fileUid = $file->getUid();
1094 $fileInfo = $file->getStorage()->getFileInfo($file);
1095 // we sadly have to cast it to string here, because the size property is also returning a string
1096 $fileSize = (string)$fileInfo['size'];
1097 if ($fileSize !== $file->getProperty('size')) {
1098 $this->error('File size of ' . $file->getCombinedIdentifier() . ' is not up-to-date in index! File added with current size.');
1099 $this->dat['records']['sys_file:' . $fileUid]['data']['size'] = $fileSize;
1100 }
1101 $fileSha1 = $file->getStorage()->hashFile($file, 'sha1');
1102 if ($fileSha1 !== $file->getProperty('sha1')) {
1103 $this->error('File sha1 hash of ' . $file->getCombinedIdentifier() . ' is not up-to-date in index! File added on current sha1.');
1104 $this->dat['records']['sys_file:' . $fileUid]['data']['sha1'] = $fileSha1;
1105 }
1106
1107 $fileRec = array();
1108 $fileRec['filesize'] = $fileSize;
1109 $fileRec['filename'] = $file->getProperty('name');
1110 $fileRec['filemtime'] = $file->getProperty('modification_date');
1111
1112 // build unique id based on the storage and the file identifier
1113 $fileId = md5($file->getStorage()->getUid() . ':' . $file->getProperty('identifier_hash'));
1114
1115 // Setting this data in the header
1116 $this->dat['header']['files_fal'][$fileId] = $fileRec;
1117
1118 if (!$this->saveFilesOutsideExportFile) {
1119 // ... and finally add the heavy stuff:
1120 $fileRec['content'] = $fileContent;
1121 } else {
1122 GeneralUtility::upload_copy_move($file->getForLocalProcessing(false), $this->getTemporaryFilesPathForExport() . $file->getProperty('sha1'));
1123 }
1124 $fileRec['content_sha1'] = $fileSha1;
1125
1126 $this->dat['files_fal'][$fileId] = $fileRec;
1127 }
1128
1129 /**
1130 * Adds a files content to the export memory
1131 *
1132 * @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". "relFileName" is optional for files attached to records, but mandatory for soft referenced files (since the relFileName determines where such a file should be stored!)
1133 * @param string $recordRef If the file is related to a record, this is the id on the form [table]:[id]. Information purposes only.
1134 * @param string $fieldname If the file is related to a record, this is the field name it was related to. Information purposes only.
1135 * @return void
1136 */
1137 public function export_addFile($fI, $recordRef = '', $fieldname = '')
1138 {
1139 if (!@is_file($fI['ID_absFile'])) {
1140 $this->error($fI['ID_absFile'] . ' was not a file! Skipping.');
1141 return;
1142 }
1143 if (filesize($fI['ID_absFile']) >= $this->maxFileSize) {
1144 $this->error($fI['ID_absFile'] . ' was larger (' . GeneralUtility::formatSize(filesize($fI['ID_absFile'])) . ') than the maxFileSize (' . GeneralUtility::formatSize($this->maxFileSize) . ')! Skipping.');
1145 return;
1146 }
1147 $fileInfo = stat($fI['ID_absFile']);
1148 $fileRec = array();
1149 $fileRec['filesize'] = $fileInfo['size'];
1150 $fileRec['filename'] = PathUtility::basename($fI['ID_absFile']);
1151 $fileRec['filemtime'] = $fileInfo['mtime'];
1152 //for internal type file_reference
1153 $fileRec['relFileRef'] = PathUtility::stripPathSitePrefix($fI['ID_absFile']);
1154 if ($recordRef) {
1155 $fileRec['record_ref'] = $recordRef . '/' . $fieldname;
1156 }
1157 if ($fI['relFileName']) {
1158 $fileRec['relFileName'] = $fI['relFileName'];
1159 }
1160 // Setting this data in the header
1161 $this->dat['header']['files'][$fI['ID']] = $fileRec;
1162 // ... and for the recordlisting, why not let us know WHICH relations there was...
1163 if ($recordRef && $recordRef !== '_SOFTREF_') {
1164 $refParts = explode(':', $recordRef, 2);
1165 if (!is_array($this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'])) {
1166 $this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'] = array();
1167 }
1168 $this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'][] = $fI['ID'];
1169 }
1170 $fileMd5 = md5_file($fI['ID_absFile']);
1171 if (!$this->saveFilesOutsideExportFile) {
1172 // ... and finally add the heavy stuff:
1173 $fileRec['content'] = GeneralUtility::getUrl($fI['ID_absFile']);
1174 } else {
1175 GeneralUtility::upload_copy_move($fI['ID_absFile'], $this->getTemporaryFilesPathForExport() . $fileMd5);
1176 }
1177 $fileRec['content_md5'] = $fileMd5;
1178 $this->dat['files'][$fI['ID']] = $fileRec;
1179 // For soft references, do further processing:
1180 if ($recordRef === '_SOFTREF_') {
1181 // RTE files?
1182 if ($RTEoriginal = $this->getRTEoriginalFilename(PathUtility::basename($fI['ID_absFile']))) {
1183 $RTEoriginal_absPath = PathUtility::dirname($fI['ID_absFile']) . '/' . $RTEoriginal;
1184 if (@is_file($RTEoriginal_absPath)) {
1185 $RTEoriginal_ID = md5($RTEoriginal_absPath);
1186 $fileInfo = stat($RTEoriginal_absPath);
1187 $fileRec = array();
1188 $fileRec['filesize'] = $fileInfo['size'];
1189 $fileRec['filename'] = PathUtility::basename($RTEoriginal_absPath);
1190 $fileRec['filemtime'] = $fileInfo['mtime'];
1191 $fileRec['record_ref'] = '_RTE_COPY_ID:' . $fI['ID'];
1192 $this->dat['header']['files'][$fI['ID']]['RTE_ORIG_ID'] = $RTEoriginal_ID;
1193 // Setting this data in the header
1194 $this->dat['header']['files'][$RTEoriginal_ID] = $fileRec;
1195 $fileMd5 = md5_file($RTEoriginal_absPath);
1196 if (!$this->saveFilesOutsideExportFile) {
1197 // ... and finally add the heavy stuff:
1198 $fileRec['content'] = GeneralUtility::getUrl($RTEoriginal_absPath);
1199 } else {
1200 GeneralUtility::upload_copy_move($RTEoriginal_absPath, $this->getTemporaryFilesPathForExport() . $fileMd5);
1201 }
1202 $fileRec['content_md5'] = $fileMd5;
1203 $this->dat['files'][$RTEoriginal_ID] = $fileRec;
1204 } else {
1205 $this->error('RTE original file "' . PathUtility::stripPathSitePrefix($RTEoriginal_absPath) . '" was not found!');
1206 }
1207 }
1208 // Files with external media?
1209 // This is only done with files grabbed by a softreference parser since it is deemed improbable that hard-referenced files should undergo this treatment.
1210 $html_fI = pathinfo(PathUtility::basename($fI['ID_absFile']));
1211 if ($this->includeExtFileResources && GeneralUtility::inList($this->extFileResourceExtensions, strtolower($html_fI['extension']))) {
1212 $uniquePrefix = '###' . md5($GLOBALS['EXEC_TIME']) . '###';
1213 if (strtolower($html_fI['extension']) === 'css') {
1214 $prefixedMedias = explode($uniquePrefix, preg_replace('/(url[[:space:]]*\\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\\))/i', '\\1' . $uniquePrefix . '\\2' . $uniquePrefix . '\\3', $fileRec['content']));
1215 } else {
1216 // html, htm:
1217 $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
1218 $prefixedMedias = explode($uniquePrefix, $htmlParser->prefixResourcePath($uniquePrefix, $fileRec['content'], array(), $uniquePrefix));
1219 }
1220 $htmlResourceCaptured = false;
1221 foreach ($prefixedMedias as $k => $v) {
1222 if ($k % 2) {
1223 $EXTres_absPath = GeneralUtility::resolveBackPath(PathUtility::dirname($fI['ID_absFile']) . '/' . $v);
1224 $EXTres_absPath = GeneralUtility::getFileAbsFileName($EXTres_absPath);
1225 if ($EXTres_absPath && GeneralUtility::isFirstPartOfStr($EXTres_absPath, PATH_site . $this->fileadminFolderName . '/') && @is_file($EXTres_absPath)) {
1226 $htmlResourceCaptured = true;
1227 $EXTres_ID = md5($EXTres_absPath);
1228 $this->dat['header']['files'][$fI['ID']]['EXT_RES_ID'][] = $EXTres_ID;
1229 $prefixedMedias[$k] = '{EXT_RES_ID:' . $EXTres_ID . '}';
1230 // Add file to memory if it is not set already:
1231 if (!isset($this->dat['header']['files'][$EXTres_ID])) {
1232 $fileInfo = stat($EXTres_absPath);
1233 $fileRec = array();
1234 $fileRec['filesize'] = $fileInfo['size'];
1235 $fileRec['filename'] = PathUtility::basename($EXTres_absPath);
1236 $fileRec['filemtime'] = $fileInfo['mtime'];
1237 $fileRec['record_ref'] = '_EXT_PARENT_:' . $fI['ID'];
1238 // Media relative to the HTML file.
1239 $fileRec['parentRelFileName'] = $v;
1240 // Setting this data in the header
1241 $this->dat['header']['files'][$EXTres_ID] = $fileRec;
1242 // ... and finally add the heavy stuff:
1243 $fileRec['content'] = GeneralUtility::getUrl($EXTres_absPath);
1244 $fileRec['content_md5'] = md5($fileRec['content']);
1245 $this->dat['files'][$EXTres_ID] = $fileRec;
1246 }
1247 }
1248 }
1249 }
1250 if ($htmlResourceCaptured) {
1251 $this->dat['files'][$fI['ID']]['tokenizedContent'] = implode('', $prefixedMedias);
1252 }
1253 }
1254 }
1255 }
1256
1257 /**
1258 * If saveFilesOutsideExportFile is enabled, this function returns the path
1259 * where the files referenced in the export are copied to.
1260 *
1261 * @return string
1262 * @throws \RuntimeException
1263 * @see setSaveFilesOutsideExportFile()
1264 */
1265 public function getTemporaryFilesPathForExport()
1266 {
1267 if (!$this->saveFilesOutsideExportFile) {
1268 throw new \RuntimeException('You need to set saveFilesOutsideExportFile to TRUE before you want to get the temporary files path for export.', 1401205213);
1269 }
1270 if ($this->temporaryFilesPathForExport === null) {
1271 $temporaryFolderName = $this->getTemporaryFolderName();
1272 $this->temporaryFilesPathForExport = $temporaryFolderName . '/';
1273 }
1274 return $this->temporaryFilesPathForExport;
1275 }
1276
1277 /**
1278 *
1279 * @return string
1280 */
1281 protected function getTemporaryFolderName()
1282 {
1283 $temporaryPath = PATH_site . 'typo3temp/';
1284 do {
1285 $temporaryFolderName = $temporaryPath . 'export_temp_files_' . mt_rand(1, PHP_INT_MAX);
1286 } while (is_dir($temporaryFolderName));
1287 GeneralUtility::mkdir($temporaryFolderName);
1288 return $temporaryFolderName;
1289 }
1290
1291 /**
1292 * DB relations flattend to 1-dim array.
1293 * The list will be unique, no table/uid combination will appear twice.
1294 *
1295 * @param array $dbrels 2-dim Array of database relations organized by table key
1296 * @return array 1-dim array where entries are table:uid and keys are array with table/id
1297 */
1298 public function flatDBrels($dbrels)
1299 {
1300 $list = array();
1301 foreach ($dbrels as $dat) {
1302 if ($dat['type'] == 'db') {
1303 foreach ($dat['itemArray'] as $i) {
1304 $list[$i['table'] . ':' . $i['id']] = $i;
1305 }
1306 }
1307 if ($dat['type'] == 'flex' && is_array($dat['flexFormRels']['db'])) {
1308 foreach ($dat['flexFormRels']['db'] as $subList) {
1309 foreach ($subList as $i) {
1310 $list[$i['table'] . ':' . $i['id']] = $i;
1311 }
1312 }
1313 }
1314 }
1315 return $list;
1316 }
1317
1318 /**
1319 * Soft References flattend to 1-dim array.
1320 *
1321 * @param array $dbrels 2-dim Array of database relations organized by table key
1322 * @return array 1-dim array where entries are arrays with properties of the soft link found and keys are a unique combination of field, spKey, structure path if applicable and token ID
1323 */
1324 public function flatSoftRefs($dbrels)
1325 {
1326 $list = array();
1327 foreach ($dbrels as $field => $dat) {
1328 if (is_array($dat['softrefs']['keys'])) {
1329 foreach ($dat['softrefs']['keys'] as $spKey => $elements) {
1330 if (is_array($elements)) {
1331 foreach ($elements as $subKey => $el) {
1332 $lKey = $field . ':' . $spKey . ':' . $subKey;
1333 $list[$lKey] = array_merge(array('field' => $field, 'spKey' => $spKey), $el);
1334 // Add file_ID key to header - slightly "risky" way of doing this because if the calculation
1335 // changes for the same value in $this->records[...] this will not work anymore!
1336 if ($el['subst'] && $el['subst']['relFileName']) {
1337 $list[$lKey]['file_ID'] = md5(PATH_site . $el['subst']['relFileName']);
1338 }
1339 }
1340 }
1341 }
1342 }
1343 if ($dat['type'] == 'flex' && is_array($dat['flexFormRels']['softrefs'])) {
1344 foreach ($dat['flexFormRels']['softrefs'] as $structurePath => $subSoftrefs) {
1345 if (is_array($subSoftrefs['keys'])) {
1346 foreach ($subSoftrefs['keys'] as $spKey => $elements) {
1347 foreach ($elements as $subKey => $el) {
1348 $lKey = $field . ':' . $structurePath . ':' . $spKey . ':' . $subKey;
1349 $list[$lKey] = array_merge(array('field' => $field, 'spKey' => $spKey, 'structurePath' => $structurePath), $el);
1350 // Add file_ID key to header - slightly "risky" way of doing this because if the calculation
1351 // changes for the same value in $this->records[...] this will not work anymore!
1352 if ($el['subst'] && $el['subst']['relFileName']) {
1353 $list[$lKey]['file_ID'] = md5(PATH_site . $el['subst']['relFileName']);
1354 }
1355 }
1356 }
1357 }
1358 }
1359 }
1360 }
1361 return $list;
1362 }
1363
1364 /**
1365 * If include fields for a specific record type are set, the data
1366 * are filtered out with fields are not included in the fields.
1367 *
1368 * @param string $table The record type to be filtered
1369 * @param array $row The data to be filtered
1370 * @return array The filtered record row
1371 */
1372 protected function filterRecordFields($table, array $row)
1373 {
1374 if (isset($this->recordTypesIncludeFields[$table])) {
1375 $includeFields = array_unique(array_merge(
1376 $this->recordTypesIncludeFields[$table],
1377 $this->defaultRecordIncludeFields
1378 ));
1379 $newRow = array();
1380 foreach ($row as $key => $value) {
1381 if (in_array($key, $includeFields)) {
1382 $newRow[$key] = $value;
1383 }
1384 }
1385 } else {
1386 $newRow = $row;
1387 }
1388 return $newRow;
1389 }
1390
1391 /**************************
1392 * File Output
1393 *************************/
1394
1395 /**
1396 * This compiles and returns the data content for an exported file
1397 *
1398 * @param string $type Type of output; "xml" gives xml, otherwise serialized array, possibly compressed.
1399 * @return string The output file stream
1400 */
1401 public function compileMemoryToFileContent($type = '')
1402 {
1403 if ($type == 'xml') {
1404 $out = $this->createXML();
1405 } else {
1406 $compress = $this->doOutputCompress();
1407 $out = '';
1408 // adding header:
1409 $out .= $this->addFilePart(serialize($this->dat['header']), $compress);
1410 // adding records:
1411 $out .= $this->addFilePart(serialize($this->dat['records']), $compress);
1412 // adding files:
1413 $out .= $this->addFilePart(serialize($this->dat['files']), $compress);
1414 // adding files_fal:
1415 $out .= $this->addFilePart(serialize($this->dat['files_fal']), $compress);
1416 }
1417 return $out;
1418 }
1419
1420 /**
1421 * Creates XML string from input array
1422 *
1423 * @return string XML content
1424 */
1425 public function createXML()
1426 {
1427 // Options:
1428 $options = array(
1429 'alt_options' => array(
1430 '/header' => array(
1431 'disableTypeAttrib' => true,
1432 'clearStackPath' => true,
1433 'parentTagMap' => array(
1434 'files' => 'file',
1435 'files_fal' => 'file',
1436 'records' => 'table',
1437 'table' => 'rec',
1438 'rec:rels' => 'relations',
1439 'relations' => 'element',
1440 'filerefs' => 'file',
1441 'pid_lookup' => 'page_contents',
1442 'header:relStaticTables' => 'static_tables',
1443 'static_tables' => 'tablename',
1444 'excludeMap' => 'item',
1445 'softrefCfg' => 'softrefExportMode',
1446 'extensionDependencies' => 'extkey',
1447 'softrefs' => 'softref_element'
1448 ),
1449 'alt_options' => array(
1450 '/pagetree' => array(
1451 'disableTypeAttrib' => true,
1452 'useIndexTagForNum' => 'node',
1453 'parentTagMap' => array(
1454 'node:subrow' => 'node'
1455 )
1456 ),
1457 '/pid_lookup/page_contents' => array(
1458 'disableTypeAttrib' => true,
1459 'parentTagMap' => array(
1460 'page_contents' => 'table'
1461 ),
1462 'grandParentTagMap' => array(
1463 'page_contents/table' => 'item'
1464 )
1465 )
1466 )
1467 ),
1468 '/records' => array(
1469 'disableTypeAttrib' => true,
1470 'parentTagMap' => array(
1471 'records' => 'tablerow',
1472 'tablerow:data' => 'fieldlist',
1473 'tablerow:rels' => 'related',
1474 'related' => 'field',
1475 'field:itemArray' => 'relations',
1476 'field:newValueFiles' => 'filerefs',
1477 'field:flexFormRels' => 'flexform',
1478 'relations' => 'element',
1479 'filerefs' => 'file',
1480 'flexform:db' => 'db_relations',
1481 'flexform:file' => 'file_relations',
1482 'flexform:softrefs' => 'softref_relations',
1483 'softref_relations' => 'structurePath',
1484 'db_relations' => 'path',
1485 'file_relations' => 'path',
1486 'path' => 'element',
1487 'keys' => 'softref_key',
1488 'softref_key' => 'softref_element'
1489 ),
1490 'alt_options' => array(
1491 '/records/tablerow/fieldlist' => array(
1492 'useIndexTagForAssoc' => 'field'
1493 )
1494 )
1495 ),
1496 '/files' => array(
1497 'disableTypeAttrib' => true,
1498 'parentTagMap' => array(
1499 'files' => 'file'
1500 )
1501 ),
1502 '/files_fal' => array(
1503 'disableTypeAttrib' => true,
1504 'parentTagMap' => array(
1505 'files_fal' => 'file'
1506 )
1507 )
1508 )
1509 );
1510 // Creating XML file from $outputArray:
1511 $charset = $this->dat['header']['charset'] ?: 'utf-8';
1512 $XML = '<?xml version="1.0" encoding="' . $charset . '" standalone="yes" ?>' . LF;
1513 $XML .= GeneralUtility::array2xml($this->dat, '', 0, 'T3RecordDocument', 0, $options);
1514 return $XML;
1515 }
1516
1517 /**
1518 * Returns TRUE if the output should be compressed.
1519 *
1520 * @return bool TRUE if compression is possible AND requested.
1521 */
1522 public function doOutputCompress()
1523 {
1524 return $this->compress && !$this->dontCompress;
1525 }
1526
1527 /**
1528 * Returns a content part for a filename being build.
1529 *
1530 * @param array $data Data to store in part
1531 * @param bool $compress Compress file?
1532 * @return string Content stream.
1533 */
1534 public function addFilePart($data, $compress = false)
1535 {
1536 if ($compress) {
1537 $data = gzcompress($data);
1538 }
1539 return md5($data) . ':' . ($compress ? '1' : '0') . ':' . str_pad(strlen($data), 10, '0', STR_PAD_LEFT) . ':' . $data . ':';
1540 }
1541
1542 /***********************
1543 * Import
1544 ***********************/
1545
1546 /**
1547 * Initialize all settings for the import
1548 *
1549 * @return void
1550 */
1551 protected function initializeImport()
1552 {
1553 // Set this flag to indicate that an import is being/has been done.
1554 $this->doesImport = 1;
1555 // Initialize:
1556 // 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.
1557 $this->import_mapId = array();
1558 $this->import_newId = array();
1559 $this->import_newId_pids = array();
1560 // Temporary files stack initialized:
1561 $this->unlinkFiles = array();
1562 $this->alternativeFileName = array();
1563 $this->alternativeFilePath = array();
1564
1565 $this->initializeStorageObjects();
1566 }
1567
1568 /**
1569 * Initialize the all present storage objects
1570 *
1571 * @return void
1572 */
1573 protected function initializeStorageObjects()
1574 {
1575 /** @var $storageRepository StorageRepository */
1576 $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
1577 $this->storageObjects = $storageRepository->findAll();
1578 }
1579
1580 /**
1581 * Imports the internal data array to $pid.
1582 *
1583 * @param int $pid Page ID in which to import the content
1584 * @return void
1585 */
1586 public function importData($pid)
1587 {
1588 $this->initializeImport();
1589
1590 // Write sys_file_storages first
1591 $this->writeSysFileStorageRecords();
1592 // Write sys_file records and write the binary file data
1593 $this->writeSysFileRecords();
1594 // Write records, first pages, then the rest
1595 // Fields with "hard" relations to database, files and flexform fields are kept empty during this run
1596 $this->writeRecords_pages($pid);
1597 $this->writeRecords_records($pid);
1598 // Finally all the file and DB record references must be fixed. This is done after all records have supposedly been written to database:
1599 // $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.
1600 $this->setRelations();
1601 // 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):
1602 $this->setFlexFormRelations();
1603 // Unlink temporary files:
1604 $this->unlinkTempFiles();
1605 // Finally, traverse all records and process softreferences with substitution attributes.
1606 $this->processSoftReferences();
1607 // After all migrate records using sys_file_reference now
1608 if ($this->legacyImport) {
1609 $this->migrateLegacyImportRecords();
1610 }
1611 }
1612
1613 /**
1614 * Imports the sys_file_storage records from internal data array.
1615 *
1616 * @return void
1617 */
1618 protected function writeSysFileStorageRecords()
1619 {
1620 if (!isset($this->dat['header']['records']['sys_file_storage'])) {
1621 return;
1622 }
1623 $sysFileStorageUidsToBeResetToDefaultStorage = array();
1624 foreach ($this->dat['header']['records']['sys_file_storage'] as $sysFileStorageUid => $_) {
1625 $storageRecord = $this->dat['records']['sys_file_storage:' . $sysFileStorageUid]['data'];
1626 // continue with Local, writable and online storage only
1627 if ($storageRecord['driver'] === 'Local' && $storageRecord['is_writable'] && $storageRecord['is_online']) {
1628 $useThisStorageUidInsteadOfTheOneInImport = 0;
1629 /** @var $localStorage \TYPO3\CMS\Core\Resource\ResourceStorage */
1630 foreach ($this->storageObjects as $localStorage) {
1631 // check the available storage for Local, writable and online ones
1632 if ($localStorage->getDriverType() === 'Local' && $localStorage->isWritable() && $localStorage->isOnline()) {
1633 // check if there is already an identical storage present (same pathType and basePath)
1634 $storageRecordConfiguration = ResourceFactory::getInstance()->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
1635 $localStorageRecordConfiguration = $localStorage->getConfiguration();
1636 if (
1637 $storageRecordConfiguration['pathType'] === $localStorageRecordConfiguration['pathType']
1638 && $storageRecordConfiguration['basePath'] === $localStorageRecordConfiguration['basePath']
1639 ) {
1640 // same storage is already present
1641 $useThisStorageUidInsteadOfTheOneInImport = $localStorage->getUid();
1642 break;
1643 }
1644 }
1645 }
1646 if ($useThisStorageUidInsteadOfTheOneInImport > 0) {
1647 // same storage is already present; map the to be imported one to the present one
1648 $this->import_mapId['sys_file_storage'][$sysFileStorageUid] = $useThisStorageUidInsteadOfTheOneInImport;
1649 } else {
1650 // Local, writable and online storage. Is allowed to be used to later write files in.
1651 $this->addSingle('sys_file_storage', $sysFileStorageUid, 0);
1652 }
1653 } else {
1654 // Storage with non Local drivers could be imported but must not be used to saves files in, because you
1655 // could not be sure, that this is supported. The default storage will be used in this case.
1656 // It could happen that non writable and non online storage will be created as dupes because you could not
1657 // check the detailed configuration options at this point
1658 $this->addSingle('sys_file_storage', $sysFileStorageUid, 0);
1659 $sysFileStorageUidsToBeResetToDefaultStorage[] = $sysFileStorageUid;
1660 }
1661 }
1662
1663 // Importing the added ones
1664 $tce = $this->getNewTCE();
1665 // Because all records are being submitted in their correct order with positive pid numbers - and so we should reverse submission order internally.
1666 $tce->reverseOrder = 1;
1667 $tce->isImporting = true;
1668 $tce->start($this->import_data, array());
1669 $tce->process_datamap();
1670 $this->addToMapId($tce->substNEWwithIDs);
1671
1672 $defaultStorageUid = null;
1673 // get default storage
1674 $defaultStorage = ResourceFactory::getInstance()->getDefaultStorage();
1675 if ($defaultStorage !== null) {
1676 $defaultStorageUid = $defaultStorage->getUid();
1677 }
1678 foreach ($sysFileStorageUidsToBeResetToDefaultStorage as $sysFileStorageUidToBeResetToDefaultStorage) {
1679 $this->import_mapId['sys_file_storage'][$sysFileStorageUidToBeResetToDefaultStorage] = $defaultStorageUid;
1680 }
1681
1682 // unset the sys_file_storage records to prevent an import in writeRecords_records
1683 unset($this->dat['header']['records']['sys_file_storage']);
1684 }
1685
1686 /**
1687 * Imports the sys_file records and the binary files data from internal data array.
1688 *
1689 * @return void
1690 */
1691 protected function writeSysFileRecords()
1692 {
1693 if (!isset($this->dat['header']['records']['sys_file'])) {
1694 return;
1695 }
1696 $this->addGeneralErrorsByTable('sys_file');
1697
1698 // fetch fresh storage records from database
1699 $storageRecords = $this->fetchStorageRecords();
1700
1701 $defaultStorage = ResourceFactory::getInstance()->getDefaultStorage();
1702
1703 $sanitizedFolderMappings = array();
1704
1705 foreach ($this->dat['header']['records']['sys_file'] as $sysFileUid => $_) {
1706 $fileRecord = $this->dat['records']['sys_file:' . $sysFileUid]['data'];
1707
1708 $temporaryFile = null;
1709 // check if there is the right file already in the local folder
1710 if ($this->filesPathForImport !== null) {
1711 if (is_file($this->filesPathForImport . '/' . $fileRecord['sha1']) && sha1_file($this->filesPathForImport . '/' . $fileRecord['sha1']) === $fileRecord['sha1']) {
1712 $temporaryFile = $this->filesPathForImport . '/' . $fileRecord['sha1'];
1713 }
1714 }
1715
1716 // save file to disk
1717 if ($temporaryFile === null) {
1718 $fileId = md5($fileRecord['storage'] . ':' . $fileRecord['identifier_hash']);
1719 $temporaryFile = $this->writeTemporaryFileFromData($fileId);
1720 if ($temporaryFile === null) {
1721 // error on writing the file. Error message was already added
1722 continue;
1723 }
1724 }
1725
1726 $originalStorageUid = $fileRecord['storage'];
1727 $useStorageFromStorageRecords = false;
1728
1729 // replace storage id, if an alternative one was registered
1730 if (isset($this->import_mapId['sys_file_storage'][$fileRecord['storage']])) {
1731 $fileRecord['storage'] = $this->import_mapId['sys_file_storage'][$fileRecord['storage']];
1732 $useStorageFromStorageRecords = true;
1733 }
1734
1735 if (empty($fileRecord['storage']) && !$this->isFallbackStorage($fileRecord['storage'])) {
1736 // no storage for the file is defined, mostly because of a missing default storage.
1737 $this->error('Error: No storage for the file "' . $fileRecord['identifier'] . '" with storage uid "' . $originalStorageUid . '"');
1738 continue;
1739 }
1740
1741 // using a storage from the local storage is only allowed, if the uid is present in the
1742 // mapping. Only in this case we could be sure, that it's a local, online and writable storage.
1743 if ($useStorageFromStorageRecords && isset($storageRecords[$fileRecord['storage']])) {
1744 /** @var $storage \TYPO3\CMS\Core\Resource\ResourceStorage */
1745 $storage = ResourceFactory::getInstance()->getStorageObject($fileRecord['storage'], $storageRecords[$fileRecord['storage']]);
1746 } elseif ($this->isFallbackStorage($fileRecord['storage'])) {
1747 $storage = ResourceFactory::getInstance()->getStorageObject(0);
1748 } elseif ($defaultStorage !== null) {
1749 $storage = $defaultStorage;
1750 } else {
1751 $this->error('Error: No storage available for the file "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
1752 continue;
1753 }
1754
1755 $newFile = null;
1756
1757 // check, if there is an identical file
1758 try {
1759 if ($storage->hasFile($fileRecord['identifier'])) {
1760 $file = $storage->getFile($fileRecord['identifier']);
1761 if ($file->getSha1() === $fileRecord['sha1']) {
1762 $newFile = $file;
1763 }
1764 }
1765 } catch (Exception $e) {
1766 }
1767
1768 if ($newFile === null) {
1769 $folderName = PathUtility::dirname(ltrim($fileRecord['identifier'], '/'));
1770 if (in_array($folderName, $sanitizedFolderMappings)) {
1771 $folderName = $sanitizedFolderMappings[$folderName];
1772 }
1773 if (!$storage->hasFolder($folderName)) {
1774 try {
1775 $importFolder = $storage->createFolder($folderName);
1776 if ($importFolder->getIdentifier() !== $folderName && !in_array($folderName, $sanitizedFolderMappings)) {
1777 $sanitizedFolderMappings[$folderName] = $importFolder->getIdentifier();
1778 }
1779 } catch (Exception $e) {
1780 $this->error('Error: Folder could not be created for file "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
1781 continue;
1782 }
1783 } else {
1784 $importFolder = $storage->getFolder($folderName);
1785 }
1786
1787 try {
1788 /** @var $newFile File */
1789 $newFile = $storage->addFile($temporaryFile, $importFolder, $fileRecord['name']);
1790 } catch (Exception $e) {
1791 $this->error('Error: File could not be added to the storage: "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
1792 continue;
1793 }
1794
1795 if ($newFile->getSha1() !== $fileRecord['sha1']) {
1796 $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'] . '"');
1797 }
1798 }
1799
1800 // save the new uid in the import id map
1801 $this->import_mapId['sys_file'][$fileRecord['uid']] = $newFile->getUid();
1802 $this->fixUidLocalInSysFileReferenceRecords($fileRecord['uid'], $newFile->getUid());
1803 }
1804
1805 // unset the sys_file records to prevent an import in writeRecords_records
1806 unset($this->dat['header']['records']['sys_file']);
1807 }
1808
1809 /**
1810 * Checks if the $storageId is the id of the fallback storage
1811 *
1812 * @param int|string $storageId
1813 * @return bool
1814 */
1815 protected function isFallbackStorage($storageId)
1816 {
1817 return $storageId === 0 || $storageId === '0';
1818 }
1819
1820 /**
1821 * Normally the importer works like the following:
1822 * Step 1: import the records with cleared field values of relation fields (see addSingle())
1823 * Step 2: update the records with the right relation ids (see setRelations())
1824 *
1825 * In step 2 the saving fields of type "relation to sys_file_reference" checks the related sys_file_reference
1826 * record (created in step 1) with the FileExtensionFilter for matching file extensions of the related file.
1827 * To make this work correct, the uid_local of sys_file_reference records has to be not empty AND has to
1828 * relate to the correct (imported) sys_file record uid!!!
1829 *
1830 * This is fixed here.
1831 *
1832 * @param int $oldFileUid
1833 * @param int $newFileUid
1834 * @return void
1835 */
1836 protected function fixUidLocalInSysFileReferenceRecords($oldFileUid, $newFileUid)
1837 {
1838 if (!isset($this->dat['header']['records']['sys_file_reference'])) {
1839 return;
1840 }
1841
1842 foreach ($this->dat['header']['records']['sys_file_reference'] as $sysFileReferenceUid => $_) {
1843 $fileReferenceRecord = $this->dat['records']['sys_file_reference:' . $sysFileReferenceUid]['data'];
1844 if ($fileReferenceRecord['uid_local'] == $oldFileUid) {
1845 $fileReferenceRecord['uid_local'] = $newFileUid;
1846 $this->dat['records']['sys_file_reference:' . $sysFileReferenceUid]['data'] = $fileReferenceRecord;
1847 }
1848 }
1849 }
1850
1851 /**
1852 * Initializes the folder for legacy imports as subfolder of backend users default upload folder
1853 *
1854 * @return void
1855 */
1856 protected function initializeLegacyImportFolder()
1857 {
1858 /** @var \TYPO3\CMS\Core\Resource\Folder $folder */
1859 $folder = $this->getBackendUser()->getDefaultUploadFolder();
1860 if ($folder === false) {
1861 $this->error('Error: the backend users default upload folder is missing! No files will be imported!');
1862 }
1863 if (!$folder->hasFolder($this->legacyImportTargetPath)) {
1864 try {
1865 $this->legacyImportFolder = $folder->createFolder($this->legacyImportTargetPath);
1866 } catch (Exception $e) {
1867 $this->error('Error: the import folder in the default upload folder could not be created! No files will be imported!');
1868 }
1869 } else {
1870 $this->legacyImportFolder = $folder->getSubFolder($this->legacyImportTargetPath);
1871 }
1872 }
1873
1874 /**
1875 * Fetched fresh storage records from database because the new imported
1876 * ones are not in cached data of the StorageRepository
1877 *
1878 * @return bool|array
1879 */
1880 protected function fetchStorageRecords()
1881 {
1882 $whereClause = BackendUtility::BEenableFields('sys_file_storage');
1883 $whereClause .= BackendUtility::deleteClause('sys_file_storage');
1884
1885 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
1886 '*',
1887 'sys_file_storage',
1888 '1=1' . $whereClause,
1889 '',
1890 '',
1891 '',
1892 'uid'
1893 );
1894
1895 return $rows;
1896 }
1897
1898 /**
1899 * Writes the file from import array to temp dir and returns the filename of it.
1900 *
1901 * @param string $fileId
1902 * @param string $dataKey
1903 * @return string Absolute filename of the temporary filename of the file
1904 */
1905 protected function writeTemporaryFileFromData($fileId, $dataKey = 'files_fal')
1906 {
1907 $temporaryFilePath = null;
1908 if (is_array($this->dat[$dataKey][$fileId])) {
1909 $temporaryFilePathInternal = GeneralUtility::tempnam('import_temp_');
1910 GeneralUtility::writeFile($temporaryFilePathInternal, $this->dat[$dataKey][$fileId]['content']);
1911 clearstatcache();
1912 if (@is_file($temporaryFilePathInternal)) {
1913 $this->unlinkFiles[] = $temporaryFilePathInternal;
1914 if (filesize($temporaryFilePathInternal) == $this->dat[$dataKey][$fileId]['filesize']) {
1915 $temporaryFilePath = $temporaryFilePathInternal;
1916 } else {
1917 $this->error('Error: temporary file ' . $temporaryFilePathInternal . ' had a size (' . filesize($temporaryFilePathInternal) . ') different from the original (' . $this->dat[$dataKey][$fileId]['filesize'] . ')');
1918 }
1919 } else {
1920 $this->error('Error: temporary file ' . $temporaryFilePathInternal . ' was not written as it should have been!');
1921 }
1922 } else {
1923 $this->error('Error: No file found for ID ' . $fileId);
1924 }
1925 return $temporaryFilePath;
1926 }
1927
1928 /**
1929 * Writing pagetree/pages to database:
1930 *
1931 * @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
1932 * @return void
1933 * @see writeRecords_records()
1934 */
1935 public function writeRecords_pages($pid)
1936 {
1937 // First, write page structure if any:
1938 if (is_array($this->dat['header']['records']['pages'])) {
1939 $this->addGeneralErrorsByTable('pages');
1940 // $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.
1941 $pageRecords = $this->dat['header']['records']['pages'];
1942 $this->import_data = array();
1943 // First add page tree if any
1944 if (is_array($this->dat['header']['pagetree'])) {
1945 $pagesFromTree = $this->flatInversePageTree($this->dat['header']['pagetree']);
1946 foreach ($pagesFromTree as $uid) {
1947 $thisRec = $this->dat['header']['records']['pages'][$uid];
1948 // PID: Set the main $pid, unless a NEW-id is found
1949 $setPid = isset($this->import_newId_pids[$thisRec['pid']]) ? $this->import_newId_pids[$thisRec['pid']] : $pid;
1950 $this->addSingle('pages', $uid, $setPid);
1951 unset($pageRecords[$uid]);
1952 }
1953 }
1954 // Then add all remaining pages not in tree on root level:
1955 if (!empty($pageRecords)) {
1956 $remainingPageUids = array_keys($pageRecords);
1957 foreach ($remainingPageUids as $pUid) {
1958 $this->addSingle('pages', $pUid, $pid);
1959 }
1960 }
1961 // Now write to database:
1962 $tce = $this->getNewTCE();
1963 $tce->isImporting = true;
1964 $this->callHook('before_writeRecordsPages', array(
1965 'tce' => &$tce,
1966 'data' => &$this->import_data
1967 ));
1968 $tce->suggestedInsertUids = $this->suggestedInsertUids;
1969 $tce->start($this->import_data, array());
1970 $tce->process_datamap();
1971 $this->callHook('after_writeRecordsPages', array(
1972 'tce' => &$tce
1973 ));
1974 // post-processing: Registering new ids (end all tcemain sessions with this)
1975 $this->addToMapId($tce->substNEWwithIDs);
1976 // In case of an update, order pages from the page tree correctly:
1977 if ($this->update && is_array($this->dat['header']['pagetree'])) {
1978 $this->writeRecords_pages_order();
1979 }
1980 }
1981 }
1982
1983 /**
1984 * Organize all updated pages in page tree so they are related like in the import file
1985 * Only used for updates and when $this->dat['header']['pagetree'] is an array.
1986 *
1987 * @return void
1988 * @access private
1989 * @see writeRecords_pages(), writeRecords_records_order()
1990 */
1991 public function writeRecords_pages_order()
1992 {
1993 $cmd_data = array();
1994 // Get uid-pid relations and traverse them in order to map to possible new IDs
1995 $pidsFromTree = $this->flatInversePageTree_pid($this->dat['header']['pagetree']);
1996 foreach ($pidsFromTree as $origPid => $newPid) {
1997 if ($newPid >= 0 && $this->dontIgnorePid('pages', $origPid)) {
1998 // If the page had a new id (because it was created) use that instead!
1999 if (substr($this->import_newId_pids[$origPid], 0, 3) === 'NEW') {
2000 if ($this->import_mapId['pages'][$origPid]) {
2001 $mappedPid = $this->import_mapId['pages'][$origPid];
2002 $cmd_data['pages'][$mappedPid]['move'] = $newPid;
2003 }
2004 } else {
2005 $cmd_data['pages'][$origPid]['move'] = $newPid;
2006 }
2007 }
2008 }
2009 // Execute the move commands if any:
2010 if (!empty($cmd_data)) {
2011 $tce = $this->getNewTCE();
2012 $this->callHook('before_writeRecordsPagesOrder', array(
2013 'tce' => &$tce,
2014 'data' => &$cmd_data
2015 ));
2016 $tce->start(array(), $cmd_data);
2017 $tce->process_cmdmap();
2018 $this->callHook('after_writeRecordsPagesOrder', array(
2019 'tce' => &$tce
2020 ));
2021 }
2022 }
2023
2024 /**
2025 * Write all database records except pages (writtein in writeRecords_pages())
2026 *
2027 * @param int $pid Page id in which to import
2028 * @return void
2029 * @see writeRecords_pages()
2030 */
2031 public function writeRecords_records($pid)
2032 {
2033 // Write the rest of the records
2034 $this->import_data = array();
2035 if (is_array($this->dat['header']['records'])) {
2036 foreach ($this->dat['header']['records'] as $table => $recs) {
2037 $this->addGeneralErrorsByTable($table);
2038 if ($table != 'pages') {
2039 foreach ($recs as $uid => $thisRec) {
2040 // PID: Set the main $pid, unless a NEW-id is found
2041 $setPid = isset($this->import_mapId['pages'][$thisRec['pid']])
2042 ? (int)$this->import_mapId['pages'][$thisRec['pid']]
2043 : (int)$pid;
2044 if (is_array($GLOBALS['TCA'][$table]) && isset($GLOBALS['TCA'][$table]['ctrl']['rootLevel'])) {
2045 $rootLevelSetting = (int)$GLOBALS['TCA'][$table]['ctrl']['rootLevel'];
2046 if ($rootLevelSetting === 1) {
2047 $setPid = 0;
2048 } elseif ($rootLevelSetting === 0 && $setPid === 0) {
2049 $this->error('Error: Record type ' . $table . ' is not allowed on pid 0');
2050 continue;
2051 }
2052 }
2053 // Add record:
2054 $this->addSingle($table, $uid, $setPid);
2055 }
2056 }
2057 }
2058 } else {
2059 $this->error('Error: No records defined in internal data array.');
2060 }
2061 // Now write to database:
2062 $tce = $this->getNewTCE();
2063 $this->callHook('before_writeRecordsRecords', array(
2064 'tce' => &$tce,
2065 'data' => &$this->import_data
2066 ));
2067 $tce->suggestedInsertUids = $this->suggestedInsertUids;
2068 // Because all records are being submitted in their correct order with positive pid numbers - and so we should reverse submission order internally.
2069 $tce->reverseOrder = 1;
2070 $tce->isImporting = true;
2071 $tce->start($this->import_data, array());
2072 $tce->process_datamap();
2073 $this->callHook('after_writeRecordsRecords', array(
2074 'tce' => &$tce
2075 ));
2076 // post-processing: Removing files and registering new ids (end all tcemain sessions with this)
2077 $this->addToMapId($tce->substNEWwithIDs);
2078 // In case of an update, order pages from the page tree correctly:
2079 if ($this->update) {
2080 $this->writeRecords_records_order($pid);
2081 }
2082 }
2083
2084 /**
2085 * Organize all updated record to their new positions.
2086 * Only used for updates
2087 *
2088 * @param int $mainPid Main PID into which we import.
2089 * @return void
2090 * @access private
2091 * @see writeRecords_records(), writeRecords_pages_order()
2092 */
2093 public function writeRecords_records_order($mainPid)
2094 {
2095 $cmd_data = array();
2096 if (is_array($this->dat['header']['pagetree'])) {
2097 $pagesFromTree = $this->flatInversePageTree($this->dat['header']['pagetree']);
2098 } else {
2099 $pagesFromTree = array();
2100 }
2101 if (is_array($this->dat['header']['pid_lookup'])) {
2102 foreach ($this->dat['header']['pid_lookup'] as $pid => $recList) {
2103 $newPid = isset($this->import_mapId['pages'][$pid]) ? $this->import_mapId['pages'][$pid] : $mainPid;
2104 if (MathUtility::canBeInterpretedAsInteger($newPid)) {
2105 foreach ($recList as $tableName => $uidList) {
2106 // If $mainPid===$newPid then we are on root level and we can consider to move pages as well!
2107 // (they will not be in the page tree!)
2108 if (($tableName != 'pages' || !$pagesFromTree[$pid]) && is_array($uidList)) {
2109 $uidList = array_reverse(array_keys($uidList));
2110 foreach ($uidList as $uid) {
2111 if ($this->dontIgnorePid($tableName, $uid)) {
2112 $cmd_data[$tableName][$uid]['move'] = $newPid;
2113 } else {
2114 }
2115 }
2116 }
2117 }
2118 }
2119 }
2120 }
2121 // Execute the move commands if any:
2122 if (!empty($cmd_data)) {
2123 $tce = $this->getNewTCE();
2124 $this->callHook('before_writeRecordsRecordsOrder', array(
2125 'tce' => &$tce,
2126 'data' => &$cmd_data
2127 ));
2128 $tce->start(array(), $cmd_data);
2129 $tce->process_cmdmap();
2130 $this->callHook('after_writeRecordsRecordsOrder', array(
2131 'tce' => &$tce
2132 ));
2133 }
2134 }
2135
2136 /**
2137 * Adds a single record to the $importData array. Also copies files to tempfolder.
2138 * However all File/DB-references and flexform field contents are set to blank for now!
2139 * That is done with setRelations() later
2140 *
2141 * @param string $table Table name (from import memory)
2142 * @param int $uid Record UID (from import memory)
2143 * @param int $pid Page id
2144 * @return void
2145 * @see writeRecords()
2146 */
2147 public function addSingle($table, $uid, $pid)
2148 {
2149 if ($this->import_mode[$table . ':' . $uid] === 'exclude') {
2150 return;
2151 }
2152 $record = $this->dat['records'][$table . ':' . $uid]['data'];
2153 if (is_array($record)) {
2154 if ($this->update && $this->doesRecordExist($table, $uid) && $this->import_mode[$table . ':' . $uid] !== 'as_new') {
2155 $ID = $uid;
2156 } elseif ($table === 'sys_file_metadata' && $record['sys_language_uid'] == '0' && $this->import_mapId['sys_file'][$record['file']]) {
2157 // on adding sys_file records the belonging sys_file_metadata record was also created
2158 // if there is one the record need to be overwritten instead of creating a new one.
2159 $recordInDatabase = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
2160 'uid',
2161 'sys_file_metadata',
2162 'file = ' . $this->import_mapId['sys_file'][$record['file']] . ' AND sys_language_uid = 0 AND pid = 0'
2163 );
2164 // if no record could be found, $this->import_mapId['sys_file'][$record['file']] is pointing
2165 // to a file, that was already there, thus a new metadata record should be created
2166 if (is_array($recordInDatabase)) {
2167 $this->import_mapId['sys_file_metadata'][$record['uid']] = $recordInDatabase['uid'];
2168 $ID = $recordInDatabase['uid'];
2169 } else {
2170 $ID = StringUtility::getUniqueId('NEW');
2171 }
2172 } else {
2173 $ID = StringUtility::getUniqueId('NEW');
2174 }
2175 $this->import_newId[$table . ':' . $ID] = array('table' => $table, 'uid' => $uid);
2176 if ($table == 'pages') {
2177 $this->import_newId_pids[$uid] = $ID;
2178 }
2179 // Set main record data:
2180 $this->import_data[$table][$ID] = $record;
2181 $this->import_data[$table][$ID]['tx_impexp_origuid'] = $this->import_data[$table][$ID]['uid'];
2182 // Reset permission data:
2183 if ($table === 'pages') {
2184 // Have to reset the user/group IDs so pages are owned by importing user. Otherwise strange things may happen for non-admins!
2185 unset($this->import_data[$table][$ID]['perms_userid']);
2186 unset($this->import_data[$table][$ID]['perms_groupid']);
2187 }
2188 // PID and UID:
2189 unset($this->import_data[$table][$ID]['uid']);
2190 // Updates:
2191 if (MathUtility::canBeInterpretedAsInteger($ID)) {
2192 unset($this->import_data[$table][$ID]['pid']);
2193 } else {
2194 // Inserts:
2195 $this->import_data[$table][$ID]['pid'] = $pid;
2196 if (($this->import_mode[$table . ':' . $uid] === 'force_uid' && $this->update || $this->force_all_UIDS) && $this->getBackendUser()->isAdmin()) {
2197 $this->import_data[$table][$ID]['uid'] = $uid;
2198 $this->suggestedInsertUids[$table . ':' . $uid] = 'DELETE';
2199 }
2200 }
2201 // Setting db/file blank:
2202 foreach ($this->dat['records'][$table . ':' . $uid]['rels'] as $field => $config) {
2203 switch ((string)$config['type']) {
2204 case 'db':
2205
2206 case 'file':
2207 // Fixed later in ->setRelations() [because we need to know ALL newly created IDs before we can map relations!]
2208 // In the meantime we set NO values for relations.
2209 //
2210 // BUT for field uid_local of table sys_file_reference the relation MUST not be cleared here,
2211 // because the value is already the uid of the right imported sys_file record.
2212 // @see fixUidLocalInSysFileReferenceRecords()
2213 // If it's empty or a uid to another record the FileExtensionFilter will throw an exception or
2214 // delete the reference record if the file extension of the related record doesn't match.
2215 if ($table !== 'sys_file_reference' && $field !== 'uid_local') {
2216 $this->import_data[$table][$ID][$field] = '';
2217 }
2218 break;
2219 case 'flex':
2220 // Fixed later in setFlexFormRelations()
2221 // In the meantime we set NO value for flexforms - this is mainly because file references
2222 // inside will not be processed properly; In fact references will point to no file
2223 // or existing files (in which case there will be double-references which is a big problem of course!)
2224 $this->import_data[$table][$ID][$field] = '';
2225 break;
2226 }
2227 }
2228 } elseif ($table . ':' . $uid != 'pages:0') {
2229 // On root level we don't want this error message.
2230 $this->error('Error: no record was found in data array!');
2231 }
2232 }
2233
2234 /**
2235 * Registers the substNEWids in memory.
2236 *
2237 * @param array $substNEWwithIDs From tcemain to be merged into internal mapping variable in this object
2238 * @return void
2239 * @see writeRecords()
2240 */
2241 public function addToMapId($substNEWwithIDs)
2242 {
2243 foreach ($this->import_data as $table => $recs) {
2244 foreach ($recs as $id => $value) {
2245 $old_uid = $this->import_newId[$table . ':' . $id]['uid'];
2246 if (isset($substNEWwithIDs[$id])) {
2247 $this->import_mapId[$table][$old_uid] = $substNEWwithIDs[$id];
2248 } elseif ($this->update) {
2249 // Map same ID to same ID....
2250 $this->import_mapId[$table][$old_uid] = $id;
2251 } else {
2252 // if $this->import_mapId contains already the right mapping, skip the error msg.
2253 // See special handling of sys_file_metadata in addSingle() => nothing to do
2254 if (!($table === 'sys_file_metadata' && isset($this->import_mapId[$table][$old_uid]) && $this->import_mapId[$table][$old_uid] == $id)) {
2255 $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!');
2256 }
2257 }
2258 }
2259 }
2260 }
2261
2262 /**
2263 * Returns a new $TCE object
2264 *
2265 * @return DataHandler $TCE object
2266 */
2267 public function getNewTCE()
2268 {
2269 $tce = GeneralUtility::makeInstance(DataHandler::class);
2270 $tce->stripslashes_values = false;
2271 $tce->dontProcessTransformations = 1;
2272 $tce->enableLogging = $this->enableLogging;
2273 $tce->alternativeFileName = $this->alternativeFileName;
2274 $tce->alternativeFilePath = $this->alternativeFilePath;
2275 return $tce;
2276 }
2277
2278 /**
2279 * Cleaning up all the temporary files stored in typo3temp/ folder
2280 *
2281 * @return void
2282 */
2283 public function unlinkTempFiles()
2284 {
2285 foreach ($this->unlinkFiles as $fileName) {
2286 if (GeneralUtility::isFirstPartOfStr($fileName, PATH_site . 'typo3temp/')) {
2287 GeneralUtility::unlink_tempfile($fileName);
2288 clearstatcache();
2289 if (is_file($fileName)) {
2290 $this->error('Error: ' . $fileName . ' was NOT unlinked as it should have been!');
2291 }
2292 } else {
2293 $this->error('Error: ' . $fileName . ' was not in temp-path. Not removed!');
2294 }
2295 }
2296 $this->unlinkFiles = array();
2297 }
2298
2299 /***************************
2300 * Import / Relations setting
2301 ***************************/
2302
2303 /**
2304 * At the end of the import process all file and DB relations should be set properly (that is relations
2305 * to imported records are all re-created so imported records are correctly related again)
2306 * Relations in flexform fields are processed in setFlexFormRelations() after this function
2307 *
2308 * @return void
2309 * @see setFlexFormRelations()
2310 */
2311 public function setRelations()
2312 {
2313 $updateData = array();
2314 // import_newId contains a register of all records that was in the import memorys "records" key
2315 foreach ($this->import_newId as $nId => $dat) {
2316 $table = $dat['table'];
2317 $uid = $dat['uid'];
2318 // original UID - NOT the new one!
2319 // If the record has been written and received a new id, then proceed:
2320 if (is_array($this->import_mapId[$table]) && isset($this->import_mapId[$table][$uid])) {
2321 $thisNewUid = BackendUtility::wsMapId($table, $this->import_mapId[$table][$uid]);
2322 if (is_array($this->dat['records'][$table . ':' . $uid]['rels'])) {
2323 $thisNewPageUid = 0;
2324 if ($this->legacyImport) {
2325 if ($table != 'pages') {
2326 $oldPid = $this->dat['records'][$table . ':' . $uid]['data']['pid'];
2327 $thisNewPageUid = BackendUtility::wsMapId($table, $this->import_mapId['pages'][$oldPid]);
2328 } else {
2329 $thisNewPageUid = $thisNewUid;
2330 }
2331 }
2332 // Traverse relation fields of each record
2333 foreach ($this->dat['records'][$table . ':' . $uid]['rels'] as $field => $config) {
2334 // uid_local of sys_file_reference needs no update because the correct reference uid was already written
2335 // @see ImportExport::fixUidLocalInSysFileReferenceRecords()
2336 if ($table === 'sys_file_reference' && $field === 'uid_local') {
2337 continue;
2338 }
2339 switch ((string)$config['type']) {
2340 case 'db':
2341 if (is_array($config['itemArray']) && !empty($config['itemArray'])) {
2342 $itemConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
2343 $valArray = $this->setRelations_db($config['itemArray'], $itemConfig);
2344 $updateData[$table][$thisNewUid][$field] = implode(',', $valArray);
2345 }
2346 break;
2347 case 'file':
2348 if (is_array($config['newValueFiles']) && !empty($config['newValueFiles'])) {
2349 $valArr = array();
2350 foreach ($config['newValueFiles'] as $fI) {
2351 $valArr[] = $this->import_addFileNameToBeCopied($fI);
2352 }
2353 if ($this->legacyImport && $this->legacyImportFolder === null && isset($this->legacyImportMigrationTables[$table][$field])) {
2354 // Do nothing - the legacy import folder is missing
2355 } elseif ($this->legacyImport && $this->legacyImportFolder !== null && isset($this->legacyImportMigrationTables[$table][$field])) {
2356 $refIds = array();
2357 foreach ($valArr as $tempFile) {
2358 $fileName = $this->alternativeFileName[$tempFile];
2359 $fileObject = null;
2360
2361 try {
2362 // check, if there is alreay the same file in the folder
2363 if ($this->legacyImportFolder->hasFile($fileName)) {
2364 $fileStorage = $this->legacyImportFolder->getStorage();
2365 $file = $fileStorage->getFile($this->legacyImportFolder->getIdentifier() . $fileName);
2366 if ($file->getSha1() === sha1_file($tempFile)) {
2367 $fileObject = $file;
2368 }
2369 }
2370 } catch (Exception $e) {
2371 }
2372
2373 if ($fileObject === null) {
2374 try {
2375 $fileObject = $this->legacyImportFolder->addFile($tempFile, $fileName, DuplicationBehavior::RENAME);
2376 } catch (Exception $e) {
2377 $this->error('Error: no file could be added to the storage for file name' . $this->alternativeFileName[$tempFile]);
2378 }
2379 }
2380 if ($fileObject !== null) {
2381 $refId = StringUtility::getUniqueId('NEW');
2382 $refIds[] = $refId;
2383 $updateData['sys_file_reference'][$refId] = array(
2384 'uid_local' => $fileObject->getUid(),
2385 'uid_foreign' => $thisNewUid, // uid of your content record
2386 'tablenames' => $table,
2387 'fieldname' => $field,
2388 'pid' => $thisNewPageUid, // parent id of the parent page
2389 'table_local' => 'sys_file',
2390 );
2391 }
2392 }
2393 $updateData[$table][$thisNewUid][$field] = implode(',', $refIds);
2394 if (!empty($this->legacyImportMigrationTables[$table][$field])) {
2395 $this->legacyImportMigrationRecords[$table][$thisNewUid][$field] = $refIds;
2396 }
2397 } else {
2398 $updateData[$table][$thisNewUid][$field] = implode(',', $valArr);
2399 }
2400 }
2401 break;
2402 }
2403 }
2404 } else {
2405 $this->error('Error: no record was found in data array!');
2406 }
2407 } else {
2408 $this->error('Error: this records is NOT created it seems! (' . $table . ':' . $uid . ')');
2409 }
2410 }
2411 if (!empty($updateData)) {
2412 $tce = $this->getNewTCE();
2413 $tce->isImporting = true;
2414 $this->callHook('before_setRelation', array(
2415 'tce' => &$tce,
2416 'data' => &$updateData
2417 ));
2418 $tce->start($updateData, array());
2419 $tce->process_datamap();
2420 // Replace the temporary "NEW" ids with the final ones.
2421 foreach ($this->legacyImportMigrationRecords as $table => $records) {
2422 foreach ($records as $uid => $fields) {
2423 foreach ($fields as $field => $referenceIds) {
2424 foreach ($referenceIds as $key => $referenceId) {
2425 $this->legacyImportMigrationRecords[$table][$uid][$field][$key] = $tce->substNEWwithIDs[$referenceId];
2426 }
2427 }
2428 }
2429 }
2430 $this->callHook('after_setRelations', array(
2431 'tce' => &$tce
2432 ));
2433 }
2434 }
2435
2436 /**
2437 * Maps relations for database
2438 *
2439 * @param array $itemArray Array of item sets (table/uid) from a dbAnalysis object
2440 * @param array $itemConfig Array of TCA config of the field the relation to be set on
2441 * @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.
2442 */
2443 public function setRelations_db($itemArray, $itemConfig)
2444 {
2445 $valArray = array();
2446 foreach ($itemArray as $relDat) {
2447 if (is_array($this->import_mapId[$relDat['table']]) && isset($this->import_mapId[$relDat['table']][$relDat['id']])) {
2448 // Since non FAL file relation type group internal_type file_reference are handled as reference to
2449 // sys_file records Datahandler requires the value as uid of the the related sys_file record only
2450 if ($itemConfig['type'] === 'group' && $itemConfig['internal_type'] === 'file_reference') {
2451 $value = $this->import_mapId[$relDat['table']][$relDat['id']];
2452 } elseif ($itemConfig['type'] === 'input' && isset($itemConfig['wizards']['link'])) {
2453 // If an input field has a relation to a sys_file record this need to be converted back to
2454 // the public path. But use getPublicUrl here, because could normally only be a local file path.
2455 $fileUid = $this->import_mapId[$relDat['table']][$relDat['id']];
2456 // Fallback value
2457 $value = 'file:' . $fileUid;
2458 try {
2459 $file = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileUid);
2460 } catch (\Exception $e) {
2461 $file = null;
2462 }
2463 if ($file instanceof FileInterface) {
2464 $value = $file->getPublicUrl();
2465 }
2466 } else {
2467 $value = $relDat['table'] . '_' . $this->import_mapId[$relDat['table']][$relDat['id']];
2468 }
2469 $valArray[] = $value;
2470 } elseif ($this->isTableStatic($relDat['table']) || $this->isExcluded($relDat['table'], $relDat['id']) || $relDat['id'] < 0) {
2471 // Checking for less than zero because some select types could contain negative values,
2472 // eg. fe_groups (-1, -2) and sys_language (-1 = ALL languages). This must be handled on both export and import.
2473 $valArray[] = $relDat['table'] . '_' . $relDat['id'];
2474 } else {
2475 $this->error('Lost relation: ' . $relDat['table'] . ':' . $relDat['id']);
2476 }
2477 }
2478 return $valArray;
2479 }
2480
2481 /**
2482 * Writes the file from import array to temp dir and returns the filename of it.
2483 *
2484 * @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
2485 * @return string|NULL Absolute filename of the temporary filename of the file. In ->alternativeFileName the original name is set.
2486 */
2487 public function import_addFileNameToBeCopied($fI)
2488 {
2489 if (is_array($this->dat['files'][$fI['ID']])) {
2490 $tmpFile = null;
2491 // check if there is the right file already in the local folder
2492 if ($this->filesPathForImport !== null) {
2493 if (is_file($this->filesPathForImport . '/' . $this->dat['files'][$fI['ID']]['content_md5']) &&
2494 md5_file($this->filesPathForImport . '/' . $this->dat['files'][$fI['ID']]['content_md5']) === $this->dat['files'][$fI['ID']]['content_md5']) {
2495 $tmpFile = $this->filesPathForImport . '/' . $this->dat['files'][$fI['ID']]['content_md5'];
2496 }
2497 }
2498 if ($tmpFile === null) {
2499 $tmpFile = GeneralUtility::tempnam('import_temp_');
2500 GeneralUtility::writeFile($tmpFile, $this->dat['files'][$fI['ID']]['content']);
2501 }
2502 clearstatcache();
2503 if (@is_file($tmpFile)) {
2504 $this->unlinkFiles[] = $tmpFile;
2505 if (filesize($tmpFile) == $this->dat['files'][$fI['ID']]['filesize']) {
2506 $this->alternativeFileName[$tmpFile] = $fI['filename'];
2507 $this->alternativeFilePath[$tmpFile] = $this->dat['files'][$fI['ID']]['relFileRef'];
2508 return $tmpFile;
2509 } else {
2510 $this->error('Error: temporary file ' . $tmpFile . ' had a size (' . filesize($tmpFile) . ') different from the original (' . $this->dat['files'][$fI['ID']]['filesize'] . ')');
2511 }
2512 } else {
2513 $this->error('Error: temporary file ' . $tmpFile . ' was not written as it should have been!');
2514 }
2515 } else {
2516 $this->error('Error: No file found for ID ' . $fI['ID']);
2517 }
2518 return null;
2519 }
2520
2521 /**
2522 * 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.
2523 * 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!
2524 *
2525 * @return void
2526 * @see setRelations()
2527 */
2528 public function setFlexFormRelations()
2529 {
2530 $updateData = array();
2531 // import_newId contains a register of all records that was in the import memorys "records" key
2532 foreach ($this->import_newId as $nId => $dat) {
2533 $table = $dat['table'];
2534 $uid = $dat['uid'];
2535 // original UID - NOT the new one!
2536 // If the record has been written and received a new id, then proceed:
2537 if (!isset($this->import_mapId[$table][$uid])) {
2538 $this->error('Error: this records is NOT created it seems! (' . $table . ':' . $uid . ')');
2539 continue;
2540 }
2541
2542 if (!is_array($this->dat['records'][$table . ':' . $uid]['rels'])) {
2543 $this->error('Error: no record was found in data array!');
2544 continue;
2545 }
2546 $thisNewUid = BackendUtility::wsMapId($table, $this->import_mapId[$table][$uid]);
2547 // Traverse relation fields of each record
2548 foreach ($this->dat['records'][$table . ':' . $uid]['rels'] as $field => $config) {
2549 switch ((string)$config['type']) {
2550 case 'flex':
2551 // Get XML content and set as default value (string, non-processed):
2552 $updateData[$table][$thisNewUid][$field] = $this->dat['records'][$table . ':' . $uid]['data'][$field];
2553 // If there has been registered relations inside the flex form field, run processing on the content:
2554 if (!empty($config['flexFormRels']['db']) || !empty($config['flexFormRels']['file'])) {
2555 $origRecordRow = BackendUtility::getRecord($table, $thisNewUid, '*');
2556 // This will fetch the new row for the element (which should be updated with any references to data structures etc.)
2557 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
2558 if (is_array($origRecordRow) && is_array($conf) && $conf['type'] === 'flex') {
2559 // Get current data structure and value array:
2560 $dataStructArray = BackendUtility::getFlexFormDS($conf, $origRecordRow, $table, $field);
2561 $currentValueArray = GeneralUtility::xml2array($updateData[$table][$thisNewUid][$field]);
2562 // Do recursive processing of the XML data:
2563 $iteratorObj = GeneralUtility::makeInstance(DataHandler::class);
2564 $iteratorObj->callBackObj = $this;
2565 $currentValueArray['data'] = $iteratorObj->checkValue_flex_procInData(
2566 $currentValueArray['data'],
2567 array(),
2568 array(),
2569 $dataStructArray,
2570 array($table, $thisNewUid, $field, $config),
2571 'remapListedDBRecords_flexFormCallBack'
2572 );
2573 // The return value is set as an array which means it will be processed by tcemain for file and DB references!
2574 if (is_array($currentValueArray['data'])) {
2575 $updateData[$table][$thisNewUid][$field] = $currentValueArray;
2576 }
2577 }
2578 }
2579 break;
2580 }
2581 }
2582 }
2583 if (!empty($updateData)) {
2584 $tce = $this->getNewTCE();
2585 $tce->isImporting = true;
2586 $this->callHook('before_setFlexFormRelations', array(
2587 'tce' => &$tce,
2588 'data' => &$updateData
2589 ));
2590 $tce->start($updateData, array());
2591 $tce->process_datamap();
2592 $this->callHook('after_setFlexFormRelations', array(
2593 'tce' => &$tce
2594 ));
2595 }
2596 }
2597
2598 /**
2599 * Callback function for traversing the FlexForm structure in relation to remapping database relations
2600 *
2601 * @param array $pParams Set of parameters in numeric array: table, uid, field
2602 * @param array $dsConf TCA config for field (from Data Structure of course)
2603 * @param string $dataValue Field value (from FlexForm XML)
2604 * @param string $dataValue_ext1 Not used
2605 * @param string $dataValue_ext2 Not used
2606 * @param string $path Path of where the data structure of the element is found
2607 * @return array Array where the "value" key carries the value.
2608 * @see setFlexFormRelations()
2609 */
2610 public function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path)
2611 {
2612 // Extract parameters:
2613 list($table, $uid, $field, $config) = $pParams;
2614 // In case the $path is used as index without a trailing slash we will remove that
2615 if (!is_array($config['flexFormRels']['db'][$path]) && is_array($config['flexFormRels']['db'][rtrim($path, '/')])) {
2616 $path = rtrim($path, '/');
2617 }
2618 if (is_array($config['flexFormRels']['db'][$path])) {
2619 $valArray = $this->setRelations_db($config['flexFormRels']['db'][$path], $dsConf);
2620 $dataValue = implode(',', $valArray);
2621 }
2622 if (is_array($config['flexFormRels']['file'][$path])) {
2623 $valArr = array();
2624 foreach ($config['flexFormRels']['file'][$path] as $fI) {
2625 $valArr[] = $this->import_addFileNameToBeCopied($fI);
2626 }
2627 $dataValue = implode(',', $valArr);
2628 }
2629 return array('value' => $dataValue);
2630 }
2631
2632 /**************************
2633 * Import / Soft References
2634 *************************/
2635
2636 /**
2637 * Processing of soft references
2638 *
2639 * @return void
2640 */
2641 public function processSoftReferences()
2642 {
2643 // Initialize:
2644 $inData = array();
2645 // Traverse records:
2646 if (is_array($this->dat['header']['records'])) {
2647 foreach ($this->dat['header']['records'] as $table => $recs) {
2648 foreach ($recs as $uid => $thisRec) {
2649 // If there are soft references defined, traverse those:
2650 if (isset($GLOBALS['TCA'][$table]) && is_array($thisRec['softrefs'])) {
2651 // First traversal is to collect softref configuration and split them up based on fields.
2652 // This could probably also have been done with the "records" key instead of the header.
2653 $fieldsIndex = array();
2654 foreach ($thisRec['softrefs'] as $softrefDef) {
2655 // If a substitution token is set:
2656 if ($softrefDef['field'] && is_array($softrefDef['subst']) && $softrefDef['subst']['tokenID']) {
2657 $fieldsIndex[$softrefDef['field']][$softrefDef['subst']['tokenID']] = $softrefDef;
2658 }
2659 }
2660 // The new id:
2661 $thisNewUid = BackendUtility::wsMapId($table, $this->import_mapId[$table][$uid]);
2662 // Now, if there are any fields that require substitution to be done, lets go for that:
2663 foreach ($fieldsIndex as $field => $softRefCfgs) {
2664 if (is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2665 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
2666 if ($conf['type'] === 'flex') {
2667 // This will fetch the new row for the element (which should be updated with any references to data structures etc.)
2668 $origRecordRow = BackendUtility::getRecord($table, $thisNewUid, '*');
2669 if (is_array($origRecordRow)) {
2670 // Get current data structure and value array:
2671 $dataStructArray = BackendUtility::getFlexFormDS($conf, $origRecordRow, $table, $field);
2672 $currentValueArray = GeneralUtility::xml2array($origRecordRow[$field]);
2673 // Do recursive processing of the XML data:
2674 /** @var $iteratorObj DataHandler */
2675 $iteratorObj = GeneralUtility::makeInstance(DataHandler::class);
2676 $iteratorObj->callBackObj = $this;
2677 $currentValueArray['data'] = $iteratorObj->checkValue_flex_procInData($currentValueArray['data'], array(), array(), $dataStructArray, array($table, $uid, $field, $softRefCfgs), 'processSoftReferences_flexFormCallBack');
2678 // The return value is set as an array which means it will be processed by tcemain for file and DB references!
2679 if (is_array($currentValueArray['data'])) {
2680 $inData[$table][$thisNewUid][$field] = $currentValueArray;
2681 }
2682 }
2683 } else {
2684 // Get tokenizedContent string and proceed only if that is not blank:
2685 $tokenizedContent = $this->dat['records'][$table . ':' . $uid]['rels'][$field]['softrefs']['tokenizedContent'];
2686 if (strlen($tokenizedContent) && is_array($softRefCfgs)) {
2687 $inData[$table][$thisNewUid][$field] = $this->processSoftReferences_substTokens($tokenizedContent, $softRefCfgs, $table, $uid);
2688 }
2689 }
2690 }
2691 }
2692 }
2693 }
2694 }
2695 }
2696 // Now write to database:
2697 $tce = $this->getNewTCE();
2698 $tce->isImporting = true;
2699 $this->callHook('before_processSoftReferences', array(
2700 'tce' => $tce,
2701 'data' => &$inData
2702 ));
2703 $tce->enableLogging = true;
2704 $tce->start($inData, array());
2705 $tce->process_datamap();
2706 $this->callHook('after_processSoftReferences', array(
2707 'tce' => $tce
2708 ));
2709 }
2710
2711 /**
2712 * Callback function for traversing the FlexForm structure in relation to remapping softreference relations
2713 *
2714 * @param array $pParams Set of parameters in numeric array: table, uid, field
2715 * @param array $dsConf TCA config for field (from Data Structure of course)
2716 * @param string $dataValue Field value (from FlexForm XML)
2717 * @param string $dataValue_ext1 Not used
2718 * @param string $dataValue_ext2 Not used
2719 * @param string $path Path of where the data structure where the element is found
2720 * @return array Array where the "value" key carries the value.
2721 * @see setFlexFormRelations()
2722 */
2723 public function processSoftReferences_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path)
2724 {
2725 // Extract parameters:
2726 list($table, $origUid, $field, $softRefCfgs) = $pParams;
2727 if (is_array($softRefCfgs)) {
2728 // First, find all soft reference configurations for this structure path (they are listed flat in the header):
2729 $thisSoftRefCfgList = array();
2730 foreach ($softRefCfgs as $sK => $sV) {
2731 if ($sV['structurePath'] === $path) {
2732 $thisSoftRefCfgList[$sK] = $sV;
2733 }
2734 }
2735 // If any was found, do processing:
2736 if (!empty($thisSoftRefCfgList)) {
2737 // Get tokenizedContent string and proceed only if that is not blank:
2738 $tokenizedContent = $this->dat['records'][$table . ':' . $origUid]['rels'][$field]['flexFormRels']['softrefs'][$path]['tokenizedContent'];
2739 if (strlen($tokenizedContent)) {
2740 $dataValue = $this->processSoftReferences_substTokens($tokenizedContent, $thisSoftRefCfgList, $table, $origUid);
2741 }
2742 }
2743 }
2744 // Return
2745 return array('value' => $dataValue);
2746 }
2747
2748 /**
2749 * Substition of softreference tokens
2750 *
2751 * @param string $tokenizedContent Content of field with soft reference tokens in.
2752 * @param array $softRefCfgs Soft reference configurations
2753 * @param string $table Table for which the processing occurs
2754 * @param string $uid UID of record from table
2755 * @return string The input content with tokens substituted according to entries in softRefCfgs
2756 */
2757 public function processSoftReferences_substTokens($tokenizedContent, $softRefCfgs, $table, $uid)
2758 {
2759 // traverse each softref type for this field:
2760 foreach ($softRefCfgs as $cfg) {
2761 // Get token ID:
2762 $tokenID = $cfg['subst']['tokenID'];
2763 // Default is current token value:
2764 $insertValue = $cfg['subst']['tokenValue'];
2765 // Based on mode:
2766 switch ((string)$this->softrefCfg[$tokenID]['mode']) {
2767 case 'exclude':
2768 // Exclude is a simple passthrough of the value
2769 break;
2770 case 'editable':
2771 // Editable always picks up the value from this input array:
2772 $insertValue = $this->softrefInputValues[$tokenID];
2773 break;
2774 default:
2775 // Mapping IDs/creating files: Based on type, look up new value:
2776 switch ((string)$cfg['subst']['type']) {
2777 case 'file':
2778 // Create / Overwrite file:
2779 $insertValue = $this->processSoftReferences_saveFile($cfg['subst']['relFileName'], $cfg, $table, $uid);
2780 break;
2781 case 'db':
2782 default:
2783 // Trying to map database element if found in the mapID array:
2784 list($tempTable, $tempUid) = explode(':', $cfg['subst']['recordRef']);
2785 if (isset($this->import_mapId[$tempTable][$tempUid])) {
2786 $insertValue = BackendUtility::wsMapId($tempTable, $this->import_mapId[$tempTable][$tempUid]);
2787 // 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!
2788 if ($tempTable === 'pages' && !MathUtility::canBeInterpretedAsInteger($cfg['subst']['tokenValue'])) {
2789 $recWithUniqueValue = BackendUtility::getRecord($tempTable, $insertValue, 'alias');
2790 if ($recWithUniqueValue['alias']) {
2791 $insertValue = $recWithUniqueValue['alias'];
2792 }
2793 } elseif (strpos($cfg['subst']['tokenValue'], ':') !== false) {
2794 list($tokenKey) = explode(':', $cfg['subst']['tokenValue']);
2795 $insertValue = $tokenKey . ':' . $insertValue;
2796 }
2797 }
2798 }
2799 }
2800 // Finally, swap the soft reference token in tokenized content with the insert value:
2801 $tokenizedContent = str_replace('{softref:' . $tokenID . '}', $insertValue, $tokenizedContent);
2802 }
2803 return $tokenizedContent;
2804 }
2805
2806 /**
2807 * Process a soft reference file
2808 *
2809 * @param string $relFileName Old Relative filename
2810 * @param array $cfg soft reference configuration array
2811 * @param string $table Table for which the processing occurs
2812 * @param string $uid UID of record from table
2813 * @return string New relative filename (value to insert instead of the softref token)
2814 */
2815 public function processSoftReferences_saveFile($relFileName, $cfg, $table, $uid)
2816 {
2817 if ($fileHeaderInfo = $this->dat['header']['files'][$cfg['file_ID']]) {
2818 // Initialize; Get directory prefix for file and find possible RTE filename
2819 $dirPrefix = PathUtility::dirname($relFileName) . '/';
2820 $rteOrigName = $this->getRTEoriginalFilename(PathUtility::basename($relFileName));
2821 // If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file!
2822 if ($rteOrigName && GeneralUtility::isFirstPartOfStr($dirPrefix, 'uploads/')) {
2823 // RTE:
2824 // First, find unique RTE file name:
2825 if (@is_dir((PATH_site . $dirPrefix))) {
2826 // From the "original" RTE filename, produce a new "original" destination filename which is unused.
2827 // Even if updated, the image should be unique. Currently the problem with this is that it leaves a lot of unused RTE images...
2828 $fileProcObj = $this->getFileProcObj();
2829 $origDestName = $fileProcObj->getUniqueName($rteOrigName, PATH_site . $dirPrefix);
2830 // Create copy file name:
2831 $pI = pathinfo($relFileName);
2832 $copyDestName = PathUtility::dirname($origDestName) . '/RTEmagicC_' . substr(PathUtility::basename($origDestName), 10) . '.' . $pI['extension'];
2833 if (
2834 !@is_file($copyDestName) && !@is_file($origDestName)
2835 && $origDestName === GeneralUtility::getFileAbsFileName($origDestName)
2836 && $copyDestName === GeneralUtility::getFileAbsFileName($copyDestName)
2837 ) {
2838 if ($this->dat['header']['files'][$fileHeaderInfo['RTE_ORIG_ID']]) {
2839 if ($this->legacyImport) {
2840 $fileName = PathUtility::basename($copyDestName);
2841 $this->writeSysFileResourceForLegacyImport($fileName, $cfg['file_ID']);
2842 $relFileName = $this->filePathMap[$cfg['file_ID']] . '" data-htmlarea-file-uid="' . $fileName . '" data-htmlarea-file-table="sys_file';
2843 // Also save the original file
2844 $originalFileName = PathUtility::basename($origDestName);
2845 $this->writeSysFileResourceForLegacyImport($originalFileName, $fileHeaderInfo['RTE_ORIG_ID']);
2846 } else {
2847 // Write the copy and original RTE file to the respective filenames:
2848 $this->writeFileVerify($copyDestName, $cfg['file_ID'], true);
2849 $this->writeFileVerify($origDestName, $fileHeaderInfo['RTE_ORIG_ID'], true);
2850 // Return the relative path of the copy file name:
2851 return PathUtility::stripPathSitePrefix($copyDestName);
2852 }
2853 } else {
2854 $this->error('ERROR: Could not find original file ID');
2855 }
2856 } else {
2857 $this->error('ERROR: The destination filenames "' . $copyDestName . '" and "' . $origDestName . '" either existed or have non-valid names');
2858 }
2859 } else {
2860 $this->error('ERROR: "' . PATH_site . $dirPrefix . '" was not a directory, so could not process file "' . $relFileName . '"');
2861 }
2862 } elseif (GeneralUtility::isFirstPartOfStr($dirPrefix, $this->fileadminFolderName . '/')) {
2863 // File in fileadmin/ folder:
2864 // Create file (and possible resources)
2865 $newFileName = $this->processSoftReferences_saveFile_createRelFile($dirPrefix, PathUtility::basename($relFileName), $cfg['file_ID'], $table, $uid);
2866 if (strlen($newFileName)) {
2867 $relFileName = $newFileName;
2868 } else {
2869 $this->error('ERROR: No new file created for "' . $relFileName . '"');
2870 }
2871 } else {
2872 $this->error('ERROR: Sorry, cannot operate on non-RTE files which are outside the fileadmin folder.');
2873 }
2874 } else {
2875 $this->error('ERROR: Could not find file ID in header.');
2876 }
2877 // Return (new) filename relative to PATH_site:
2878 return $relFileName;
2879 }
2880
2881 /**
2882 * Create file in directory and return the new (unique) filename
2883 *
2884 * @param string $origDirPrefix Directory prefix, relative, with trailing slash
2885 * @param string $fileName Filename (without path)
2886 * @param string $fileID File ID from import memory
2887 * @param string $table Table for which the processing occurs
2888 * @param string $uid UID of record from table
2889 * @return string|NULL New relative filename, if any
2890 */
2891 public function processSoftReferences_saveFile_createRelFile($origDirPrefix, $fileName, $fileID, $table, $uid)
2892 {
2893 // If the fileID map contains an entry for this fileID then just return the relative filename of that entry;
2894 // we don't want to write another unique filename for this one!
2895 if (isset($this->fileIDMap[$fileID])) {
2896 return PathUtility::stripPathSitePrefix($this->fileIDMap[$fileID]);
2897 }
2898 if ($this->legacyImport) {
2899 // set dirPrefix to fileadmin because the right target folder is set and checked for permissions later
2900 $dirPrefix = $this->fileadminFolderName . '/';
2901 } else {
2902 // Verify FileMount access to dir-prefix. Returns the best alternative relative path if any
2903 $dirPrefix = $this->verifyFolderAccess($origDirPrefix);
2904 }
2905 if ($dirPrefix && (!$this->update || $origDirPrefix === $dirPrefix) && $this->checkOrCreateDir($dirPrefix)) {
2906 $fileHeaderInfo = $this->dat['header']['files'][$fileID];
2907 $updMode = $this->update && $this->import_mapId[$table][$uid] === $uid && $this->import_mode[$table . ':' . $uid] !== 'as_new';
2908 // Create new name for file:
2909 // Must have same ID in map array (just for security, is not really needed) and NOT be set "as_new".
2910
2911 // Write main file:
2912 if ($this->legacyImport) {
2913 $fileWritten = $this->writeSysFileResourceForLegacyImport($fileName, $fileID);
2914 if ($fileWritten) {
2915 $newName = 'file:' . $fileName;
2916 return $newName;
2917 // no support for HTML/CSS file resources attached ATM - see below
2918 }
2919 } else {
2920 if ($updMode) {
2921 $newName = PATH_site . $dirPrefix . $fileName;
2922 } else {
2923 // Create unique filename:
2924 $fileProcObj = $this->getFileProcObj();
2925 $newName = $fileProcObj->getUniqueName($fileName, PATH_site . $dirPrefix);
2926 }
2927 if ($this->writeFileVerify($newName, $fileID)) {
2928 // If the resource was an HTML/CSS file with resources attached, we will write those as well!
2929 if (is_array($fileHeaderInfo['EXT_RES_ID'])) {
2930 $tokenizedContent = $this->dat['files'][$fileID]['tokenizedContent'];
2931 $tokenSubstituted = false;
2932 $fileProcObj = $this->getFileProcObj();
2933 if ($updMode) {
2934 foreach ($fileHeaderInfo['EXT_RES_ID'] as $res_fileID) {
2935 if ($this->dat['files'][$res_fileID]['filename']) {
2936 // Resolve original filename:
2937 $relResourceFileName = $this->dat['files'][$res_fileID]['parentRelFileName'];
2938 $absResourceFileName = GeneralUtility::resolveBackPath(PATH_site . $origDirPrefix . $relResourceFileName);
2939 $absResourceFileName = GeneralUtility::getFileAbsFileName($absResourceFileName);
2940 if ($absResourceFileName && GeneralUtility::isFirstPartOfStr($absResourceFileName, PATH_site . $this->fileadminFolderName . '/')) {
2941 $destDir = PathUtility::stripPathSitePrefix(PathUtility::dirname($absResourceFileName) . '/');
2942 if ($this->verifyFolderAccess($destDir, true) && $this->checkOrCreateDir($destDir)) {
2943 $this->writeFileVerify($absResourceFileName, $res_fileID);
2944 } else {
2945 $this->error('ERROR: Could not create file in directory "' . $destDir . '"');
2946 }
2947 } else {
2948 $this->error('ERROR: Could not resolve path for "' . $relResourceFileName . '"');
2949 }
2950 $tokenizedContent = str_replace('{EXT_RES_ID:' . $res_fileID . '}', $relResourceFileName, $tokenizedContent);
2951 $tokenSubstituted = true;
2952 }
2953 }
2954 } else {
2955 // Create the resouces directory name (filename without extension, suffixed "_FILES")
2956 $resourceDir = PathUtility::dirname($newName) . '/' . preg_replace('/\\.[^.]*$/', '', PathUtility::basename($newName)) . '_FILES';
2957 if (GeneralUtility::mkdir($resourceDir)) {
2958 foreach ($fileHeaderInfo['EXT_RES_ID'] as $res_fileID) {
2959 if ($this->dat['files'][$res_fileID]['filename']) {
2960 $absResourceFileName = $fileProcObj->getUniqueName($this->dat['files'][$res_fileID]['filename'], $resourceDir);
2961 $relResourceFileName = substr($absResourceFileName, strlen(PathUtility::dirname($resourceDir)) + 1);
2962