[TASK] Replace GeneralUtility::inList() with comparison
[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 $this->errorLog = array_merge($this->errorLog, $refIndexObj->errorLog);
747 // Merge error logs.
748 // Add information about the relations in the record in the header:
749 $this->dat['header']['records'][$table][$row['uid']]['rels'] = $this->flatDBrels($this->dat['records'][$table . ':' . $row['uid']]['rels']);
750 // Add information about the softrefs to header:
751 $this->dat['header']['records'][$table][$row['uid']]['softrefs'] = $this->flatSoftRefs($this->dat['records'][$table . ':' . $row['uid']]['rels']);
752 } else {
753 $this->error('Record ' . $table . ':' . $row['uid'] . ' was larger than maxRecordSize (' . GeneralUtility::formatSize($this->maxRecordSize) . ')');
754 }
755 } else {
756 $this->error('Record ' . $table . ':' . $row['uid'] . ' already added.');
757 }
758 } else {
759 $this->error('Record ' . $table . ':' . $row['uid'] . ' was outside your DB mounts!');
760 }
761 }
762 }
763
764 /**
765 * This changes the file reference ID from a hash based on the absolute file path
766 * (coming from ReferenceIndex) to a hash based on the relative file path.
767 *
768 * @param array $relations
769 * @return array
770 */
771 protected function fixFileIDsInRelations(array $relations)
772 {
773 foreach ($relations as $field => $relation) {
774 if (isset($relation['type']) && $relation['type'] === 'file') {
775 foreach ($relation['newValueFiles'] as $key => $fileRelationData) {
776 $absoluteFilePath = $fileRelationData['ID_absFile'];
777 if (GeneralUtility::isFirstPartOfStr($absoluteFilePath, PATH_site)) {
778 $relatedFilePath = PathUtility::stripPathSitePrefix($absoluteFilePath);
779 $relations[$field]['newValueFiles'][$key]['ID'] = md5($relatedFilePath);
780 }
781 }
782 }
783 if ($relation['type'] === 'flex') {
784 if (is_array($relation['flexFormRels']['file'])) {
785 foreach ($relation['flexFormRels']['file'] as $key => $subList) {
786 foreach ($subList as $subKey => $fileRelationData) {
787 $absoluteFilePath = $fileRelationData['ID_absFile'];
788 if (GeneralUtility::isFirstPartOfStr($absoluteFilePath, PATH_site)) {
789 $relatedFilePath = PathUtility::stripPathSitePrefix($absoluteFilePath);
790 $relations[$field]['flexFormRels']['file'][$key][$subKey]['ID'] = md5($relatedFilePath);
791 }
792 }
793 }
794 }
795 }
796 }
797 return $relations;
798 }
799
800 /**
801 * Relations could contain db relations to sys_file records. Some configuration combinations of TCA and
802 * SoftReferenceIndex create also softref relation entries for the identical file. This results
803 * in double included files, one in array "files" and one in array "file_fal".
804 * This function checks the relations for this double inclusions and removes the redundant softref relation.
805 *
806 * @param array $relations
807 * @return array
808 */
809 protected function removeSoftrefsHavingTheSameDatabaseRelation($relations)
810 {
811 $fixedRelations = array();
812 foreach ($relations as $field => $relation) {
813 $newRelation = $relation;
814 if (isset($newRelation['type']) && $newRelation['type'] === 'db') {
815 foreach ($newRelation['itemArray'] as $key => $dbRelationData) {
816 if ($dbRelationData['table'] === 'sys_file') {
817 if (isset($newRelation['softrefs']['keys']['typolink'])) {
818 foreach ($newRelation['softrefs']['keys']['typolink'] as $softrefKey => $softRefData) {
819 if ($softRefData['subst']['type'] === 'file') {
820 $file = ResourceFactory::getInstance()->retrieveFileOrFolderObject($softRefData['subst']['relFileName']);
821 if ($file instanceof File) {
822 if ($file->getUid() == $dbRelationData['id']) {
823 unset($newRelation['softrefs']['keys']['typolink'][$softrefKey]);
824 }
825 }
826 }
827 }
828 if (empty($newRelation['softrefs']['keys']['typolink'])) {
829 unset($newRelation['softrefs']);
830 }
831 }
832 }
833 }
834 }
835 $fixedRelations[$field] = $newRelation;
836 }
837 return $fixedRelations;
838 }
839
840 /**
841 * This analyses the existing added records, finds all database relations to records and adds these records to the export file.
842 * This function can be called repeatedly until it returns an empty array.
843 * In principle it should not allow to infinite recursivity, but you better set a limit...
844 * Call this BEFORE the ext_addFilesFromRelations (so files from added relations are also included of course)
845 *
846 * @param int $relationLevel Recursion level
847 * @return array overview of relations found and added: Keys [table]:[uid], values array with table and id
848 * @see export_addFilesFromRelations()
849 */
850 public function export_addDBRelations($relationLevel = 0)
851 {
852 // Traverse all "rels" registered for "records"
853 if (!is_array($this->dat['records'])) {
854 $this->error('There were no records available.');
855 return array();
856 }
857 $addR = array();
858 foreach ($this->dat['records'] as $k => $value) {
859 if (!is_array($this->dat['records'][$k])) {
860 continue;
861 }
862 foreach ($this->dat['records'][$k]['rels'] as $fieldname => $vR) {
863 // For all DB types of relations:
864 if ($vR['type'] == 'db') {
865 foreach ($vR['itemArray'] as $fI) {
866 $this->export_addDBRelations_registerRelation($fI, $addR);
867 }
868 }
869 // For all flex/db types of relations:
870 if ($vR['type'] == 'flex') {
871 // DB relations in flex form fields:
872 if (is_array($vR['flexFormRels']['db'])) {
873 foreach ($vR['flexFormRels']['db'] as $subList) {
874 foreach ($subList as $fI) {
875 $this->export_addDBRelations_registerRelation($fI, $addR);
876 }
877 }
878 }
879 // DB oriented soft references in flex form fields:
880 if (is_array($vR['flexFormRels']['softrefs'])) {
881 foreach ($vR['flexFormRels']['softrefs'] as $subList) {
882 foreach ($subList['keys'] as $spKey => $elements) {
883 foreach ($elements as $el) {
884 if ($el['subst']['type'] === 'db' && $this->includeSoftref($el['subst']['tokenID'])) {
885 list($tempTable, $tempUid) = explode(':', $el['subst']['recordRef']);
886 $fI = array(
887 'table' => $tempTable,
888 'id' => $tempUid
889 );
890 $this->export_addDBRelations_registerRelation($fI, $addR, $el['subst']['tokenID']);
891 }
892 }
893 }
894 }
895 }
896 }
897 // In any case, if there are soft refs:
898 if (is_array($vR['softrefs']['keys'])) {
899 foreach ($vR['softrefs']['keys'] as $spKey => $elements) {
900 foreach ($elements as $el) {
901 if ($el['subst']['type'] === 'db' && $this->includeSoftref($el['subst']['tokenID'])) {
902 list($tempTable, $tempUid) = explode(':', $el['subst']['recordRef']);
903 $fI = array(
904 'table' => $tempTable,
905 'id' => $tempUid
906 );
907 $this->export_addDBRelations_registerRelation($fI, $addR, $el['subst']['tokenID']);
908 }
909 }
910 }
911 }
912 }
913 }
914
915 // Now, if there were new records to add, do so:
916 if (!empty($addR)) {
917 foreach ($addR as $fI) {
918 // Get and set record:
919 $row = BackendUtility::getRecord($fI['table'], $fI['id']);
920 if (is_array($row)) {
921 $this->export_addRecord($fI['table'], $row, $relationLevel + 1);
922 }
923 // Set status message
924 // Relation pointers always larger than zero except certain "select" types with
925 // negative values pointing to uids - but that is not supported here.
926 if ($fI['id'] > 0) {
927 $rId = $fI['table'] . ':' . $fI['id'];
928 if (!isset($this->dat['records'][$rId])) {
929 $this->dat['records'][$rId] = 'NOT_FOUND';
930 $this->error('Relation record ' . $rId . ' was not found!');
931 }
932 }
933 }
934 }
935 // Return overview of relations found and added
936 return $addR;
937 }
938
939 /**
940 * Helper function for export_addDBRelations()
941 *
942 * @param array $fI Array with table/id keys to add
943 * @param array $addR Add array, passed by reference to be modified
944 * @param string $tokenID Softref Token ID, if applicable.
945 * @return void
946 * @see export_addDBRelations()
947 */
948 public function export_addDBRelations_registerRelation($fI, &$addR, $tokenID = '')
949 {
950 $rId = $fI['table'] . ':' . $fI['id'];
951 if (
952 isset($GLOBALS['TCA'][$fI['table']]) && !$this->isTableStatic($fI['table']) && !$this->isExcluded($fI['table'], $fI['id'])
953 && (!$tokenID || $this->includeSoftref($tokenID)) && $this->inclRelation($fI['table'])
954 ) {
955 if (!isset($this->dat['records'][$rId])) {
956 // Set this record to be included since it is not already.
957 $addR[$rId] = $fI;
958 }
959 }
960 }
961
962 /**
963 * This adds all files in relations.
964 * Call this method AFTER adding all records including relations.
965 *
966 * @return void
967 * @see export_addDBRelations()
968 */
969 public function export_addFilesFromRelations()
970 {
971 // Traverse all "rels" registered for "records"
972 if (!is_array($this->dat['records'])) {
973 $this->error('There were no records available.');
974 return;
975 }
976 foreach ($this->dat['records'] as $k => $value) {
977 if (!isset($this->dat['records'][$k]['rels']) || !is_array($this->dat['records'][$k]['rels'])) {
978 continue;
979 }
980 foreach ($this->dat['records'][$k]['rels'] as $fieldname => $vR) {
981 // For all file type relations:
982 if ($vR['type'] == 'file') {
983 foreach ($vR['newValueFiles'] as $key => $fI) {
984 $this->export_addFile($fI, $k, $fieldname);
985 // Remove the absolute reference to the file so it doesn't expose absolute paths from source server:
986 unset($this->dat['records'][$k]['rels'][$fieldname]['newValueFiles'][$key]['ID_absFile']);
987 }
988 }
989 // For all flex type relations:
990 if ($vR['type'] == 'flex') {
991 if (is_array($vR['flexFormRels']['file'])) {
992 foreach ($vR['flexFormRels']['file'] as $key => $subList) {
993 foreach ($subList as $subKey => $fI) {
994 $this->export_addFile($fI, $k, $fieldname);
995 // Remove the absolute reference to the file so it doesn't expose absolute paths from source server:
996 unset($this->dat['records'][$k]['rels'][$fieldname]['flexFormRels']['file'][$key][$subKey]['ID_absFile']);
997 }
998 }
999 }
1000 // DB oriented soft references in flex form fields:
1001 if (is_array($vR['flexFormRels']['softrefs'])) {
1002 foreach ($vR['flexFormRels']['softrefs'] as $key => $subList) {
1003 foreach ($subList['keys'] as $spKey => $elements) {
1004 foreach ($elements as $subKey => $el) {
1005 if ($el['subst']['type'] === 'file' && $this->includeSoftref($el['subst']['tokenID'])) {
1006 // Create abs path and ID for file:
1007 $ID_absFile = GeneralUtility::getFileAbsFileName(PATH_site . $el['subst']['relFileName']);
1008 $ID = md5($el['subst']['relFileName']);
1009 if ($ID_absFile) {
1010 if (!$this->dat['files'][$ID]) {
1011 $fI = array(
1012 'filename' => PathUtility::basename($ID_absFile),
1013 'ID_absFile' => $ID_absFile,
1014 'ID' => $ID,
1015 'relFileName' => $el['subst']['relFileName']
1016 );
1017 $this->export_addFile($fI, '_SOFTREF_');
1018 }
1019 $this->dat['records'][$k]['rels'][$fieldname]['flexFormRels']['softrefs'][$key]['keys'][$spKey][$subKey]['file_ID'] = $ID;
1020 }
1021 }
1022 }
1023 }
1024 }
1025 }
1026 }
1027 // In any case, if there are soft refs:
1028 if (is_array($vR['softrefs']['keys'])) {
1029 foreach ($vR['softrefs']['keys'] as $spKey => $elements) {
1030 foreach ($elements as $subKey => $el) {
1031 if ($el['subst']['type'] === 'file' && $this->includeSoftref($el['subst']['tokenID'])) {
1032 // Create abs path and ID for file:
1033 $ID_absFile = GeneralUtility::getFileAbsFileName(PATH_site . $el['subst']['relFileName']);
1034 $ID = md5($el['subst']['relFileName']);
1035 if ($ID_absFile) {
1036 if (!$this->dat['files'][$ID]) {
1037 $fI = array(
1038 'filename' => PathUtility::basename($ID_absFile),
1039 'ID_absFile' => $ID_absFile,
1040 'ID' => $ID,
1041 'relFileName' => $el['subst']['relFileName']
1042 );
1043 $this->export_addFile($fI, '_SOFTREF_');
1044 }
1045 $this->dat['records'][$k]['rels'][$fieldname]['softrefs']['keys'][$spKey][$subKey]['file_ID'] = $ID;
1046 }
1047 }
1048 }
1049 }
1050 }
1051 }
1052 }
1053 }
1054
1055 /**
1056 * This adds all files from sys_file records
1057 *
1058 * @return void
1059 */
1060 public function export_addFilesFromSysFilesRecords()
1061 {
1062 if (!isset($this->dat['header']['records']['sys_file']) || !is_array($this->dat['header']['records']['sys_file'])) {
1063 return;
1064 }
1065 foreach ($this->dat['header']['records']['sys_file'] as $sysFileUid => $_) {
1066 $recordData = $this->dat['records']['sys_file:' . $sysFileUid]['data'];
1067 $file = ResourceFactory::getInstance()->createFileObject($recordData);
1068 $this->export_addSysFile($file);
1069 }
1070 }
1071
1072 /**
1073 * Adds a files content from a sys file record to the export memory
1074 *
1075 * @param File $file
1076 * @return void
1077 */
1078 public function export_addSysFile(File $file)
1079 {
1080 if ($file->getProperty('size') >= $this->maxFileSize) {
1081 $this->error('File ' . $file->getPublicUrl() . ' was larger (' . GeneralUtility::formatSize($file->getProperty('size')) . ') than the maxFileSize (' . GeneralUtility::formatSize($this->maxFileSize) . ')! Skipping.');
1082 return;
1083 }
1084 $fileContent = '';
1085 try {
1086 if (!$this->saveFilesOutsideExportFile) {
1087 $fileContent = $file->getContents();
1088 } else {
1089 $file->checkActionPermission('read');
1090 }
1091 } catch (\Exception $e) {
1092 $this->error('Error when trying to add file ' . $file->getCombinedIdentifier() . ': ' . $e->getMessage());
1093 return;
1094 }
1095 $fileUid = $file->getUid();
1096 $fileInfo = $file->getStorage()->getFileInfo($file);
1097 // we sadly have to cast it to string here, because the size property is also returning a string
1098 $fileSize = (string)$fileInfo['size'];
1099 if ($fileSize !== $file->getProperty('size')) {
1100 $this->error('File size of ' . $file->getCombinedIdentifier() . ' is not up-to-date in index! File added with current size.');
1101 $this->dat['records']['sys_file:' . $fileUid]['data']['size'] = $fileSize;
1102 }
1103 $fileSha1 = $file->getStorage()->hashFile($file, 'sha1');
1104 if ($fileSha1 !== $file->getProperty('sha1')) {
1105 $this->error('File sha1 hash of ' . $file->getCombinedIdentifier() . ' is not up-to-date in index! File added on current sha1.');
1106 $this->dat['records']['sys_file:' . $fileUid]['data']['sha1'] = $fileSha1;
1107 }
1108
1109 $fileRec = array();
1110 $fileRec['filesize'] = $fileSize;
1111 $fileRec['filename'] = $file->getProperty('name');
1112 $fileRec['filemtime'] = $file->getProperty('modification_date');
1113
1114 // build unique id based on the storage and the file identifier
1115 $fileId = md5($file->getStorage()->getUid() . ':' . $file->getProperty('identifier_hash'));
1116
1117 // Setting this data in the header
1118 $this->dat['header']['files_fal'][$fileId] = $fileRec;
1119
1120 if (!$this->saveFilesOutsideExportFile) {
1121 // ... and finally add the heavy stuff:
1122 $fileRec['content'] = $fileContent;
1123 } else {
1124 GeneralUtility::upload_copy_move($file->getForLocalProcessing(false), $this->getTemporaryFilesPathForExport() . $file->getProperty('sha1'));
1125 }
1126 $fileRec['content_sha1'] = $fileSha1;
1127
1128 $this->dat['files_fal'][$fileId] = $fileRec;
1129 }
1130
1131 /**
1132 * Adds a files content to the export memory
1133 *
1134 * @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!)
1135 * @param string $recordRef If the file is related to a record, this is the id on the form [table]:[id]. Information purposes only.
1136 * @param string $fieldname If the file is related to a record, this is the field name it was related to. Information purposes only.
1137 * @return void
1138 */
1139 public function export_addFile($fI, $recordRef = '', $fieldname = '')
1140 {
1141 if (!@is_file($fI['ID_absFile'])) {
1142 $this->error($fI['ID_absFile'] . ' was not a file! Skipping.');
1143 return;
1144 }
1145 if (filesize($fI['ID_absFile']) >= $this->maxFileSize) {
1146 $this->error($fI['ID_absFile'] . ' was larger (' . GeneralUtility::formatSize(filesize($fI['ID_absFile'])) . ') than the maxFileSize (' . GeneralUtility::formatSize($this->maxFileSize) . ')! Skipping.');
1147 return;
1148 }
1149 $fileInfo = stat($fI['ID_absFile']);
1150 $fileRec = array();
1151 $fileRec['filesize'] = $fileInfo['size'];
1152 $fileRec['filename'] = PathUtility::basename($fI['ID_absFile']);
1153 $fileRec['filemtime'] = $fileInfo['mtime'];
1154 //for internal type file_reference
1155 $fileRec['relFileRef'] = PathUtility::stripPathSitePrefix($fI['ID_absFile']);
1156 if ($recordRef) {
1157 $fileRec['record_ref'] = $recordRef . '/' . $fieldname;
1158 }
1159 if ($fI['relFileName']) {
1160 $fileRec['relFileName'] = $fI['relFileName'];
1161 }
1162 // Setting this data in the header
1163 $this->dat['header']['files'][$fI['ID']] = $fileRec;
1164 // ... and for the recordlisting, why not let us know WHICH relations there was...
1165 if ($recordRef && $recordRef !== '_SOFTREF_') {
1166 $refParts = explode(':', $recordRef, 2);
1167 if (!is_array($this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'])) {
1168 $this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'] = array();
1169 }
1170 $this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'][] = $fI['ID'];
1171 }
1172 $fileMd5 = md5_file($fI['ID_absFile']);
1173 if (!$this->saveFilesOutsideExportFile) {
1174 // ... and finally add the heavy stuff:
1175 $fileRec['content'] = GeneralUtility::getUrl($fI['ID_absFile']);
1176 } else {
1177 GeneralUtility::upload_copy_move($fI['ID_absFile'], $this->getTemporaryFilesPathForExport() . $fileMd5);
1178 }
1179 $fileRec['content_md5'] = $fileMd5;
1180 $this->dat['files'][$fI['ID']] = $fileRec;
1181 // For soft references, do further processing:
1182 if ($recordRef === '_SOFTREF_') {
1183 // RTE files?
1184 if ($RTEoriginal = $this->getRTEoriginalFilename(PathUtility::basename($fI['ID_absFile']))) {
1185 $RTEoriginal_absPath = PathUtility::dirname($fI['ID_absFile']) . '/' . $RTEoriginal;
1186 if (@is_file($RTEoriginal_absPath)) {
1187 $RTEoriginal_ID = md5($RTEoriginal_absPath);
1188 $fileInfo = stat($RTEoriginal_absPath);
1189 $fileRec = array();
1190 $fileRec['filesize'] = $fileInfo['size'];
1191 $fileRec['filename'] = PathUtility::basename($RTEoriginal_absPath);
1192 $fileRec['filemtime'] = $fileInfo['mtime'];
1193 $fileRec['record_ref'] = '_RTE_COPY_ID:' . $fI['ID'];
1194 $this->dat['header']['files'][$fI['ID']]['RTE_ORIG_ID'] = $RTEoriginal_ID;
1195 // Setting this data in the header
1196 $this->dat['header']['files'][$RTEoriginal_ID] = $fileRec;
1197 $fileMd5 = md5_file($RTEoriginal_absPath);
1198 if (!$this->saveFilesOutsideExportFile) {
1199 // ... and finally add the heavy stuff:
1200 $fileRec['content'] = GeneralUtility::getUrl($RTEoriginal_absPath);
1201 } else {
1202 GeneralUtility::upload_copy_move($RTEoriginal_absPath, $this->getTemporaryFilesPathForExport() . $fileMd5);
1203 }
1204 $fileRec['content_md5'] = $fileMd5;
1205 $this->dat['files'][$RTEoriginal_ID] = $fileRec;
1206 } else {
1207 $this->error('RTE original file "' . PathUtility::stripPathSitePrefix($RTEoriginal_absPath) . '" was not found!');
1208 }
1209 }
1210 // Files with external media?
1211 // This is only done with files grabbed by a softreference parser since it is deemed improbable that hard-referenced files should undergo this treatment.
1212 $html_fI = pathinfo(PathUtility::basename($fI['ID_absFile']));
1213 if ($this->includeExtFileResources && GeneralUtility::inList($this->extFileResourceExtensions, strtolower($html_fI['extension']))) {
1214 $uniquePrefix = '###' . md5($GLOBALS['EXEC_TIME']) . '###';
1215 if (strtolower($html_fI['extension']) === 'css') {
1216 $prefixedMedias = explode($uniquePrefix, preg_replace('/(url[[:space:]]*\\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\\))/i', '\\1' . $uniquePrefix . '\\2' . $uniquePrefix . '\\3', $fileRec['content']));
1217 } else {
1218 // html, htm:
1219 $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
1220 $prefixedMedias = explode($uniquePrefix, $htmlParser->prefixResourcePath($uniquePrefix, $fileRec['content'], array(), $uniquePrefix));
1221 }
1222 $htmlResourceCaptured = false;
1223 foreach ($prefixedMedias as $k => $v) {
1224 if ($k % 2) {
1225 $EXTres_absPath = GeneralUtility::resolveBackPath(PathUtility::dirname($fI['ID_absFile']) . '/' . $v);
1226 $EXTres_absPath = GeneralUtility::getFileAbsFileName($EXTres_absPath);
1227 if ($EXTres_absPath && GeneralUtility::isFirstPartOfStr($EXTres_absPath, PATH_site . $this->fileadminFolderName . '/') && @is_file($EXTres_absPath)) {
1228 $htmlResourceCaptured = true;
1229 $EXTres_ID = md5($EXTres_absPath);
1230 $this->dat['header']['files'][$fI['ID']]['EXT_RES_ID'][] = $EXTres_ID;
1231 $prefixedMedias[$k] = '{EXT_RES_ID:' . $EXTres_ID . '}';
1232 // Add file to memory if it is not set already:
1233 if (!isset($this->dat['header']['files'][$EXTres_ID])) {
1234 $fileInfo = stat($EXTres_absPath);
1235 $fileRec = array();
1236 $fileRec['filesize'] = $fileInfo['size'];
1237 $fileRec['filename'] = PathUtility::basename($EXTres_absPath);
1238 $fileRec['filemtime'] = $fileInfo['mtime'];
1239 $fileRec['record_ref'] = '_EXT_PARENT_:' . $fI['ID'];
1240 // Media relative to the HTML file.
1241 $fileRec['parentRelFileName'] = $v;
1242 // Setting this data in the header
1243 $this->dat['header']['files'][$EXTres_ID] = $fileRec;
1244 // ... and finally add the heavy stuff:
1245 $fileRec['content'] = GeneralUtility::getUrl($EXTres_absPath);
1246 $fileRec['content_md5'] = md5($fileRec['content']);
1247 $this->dat['files'][$EXTres_ID] = $fileRec;
1248 }
1249 }
1250 }
1251 }
1252 if ($htmlResourceCaptured) {
1253 $this->dat['files'][$fI['ID']]['tokenizedContent'] = implode('', $prefixedMedias);
1254 }
1255 }
1256 }
1257 }
1258
1259 /**
1260 * If saveFilesOutsideExportFile is enabled, this function returns the path
1261 * where the files referenced in the export are copied to.
1262 *
1263 * @return string
1264 * @throws \RuntimeException
1265 * @see setSaveFilesOutsideExportFile()
1266 */
1267 public function getTemporaryFilesPathForExport()
1268 {
1269 if (!$this->saveFilesOutsideExportFile) {
1270 throw new \RuntimeException('You need to set saveFilesOutsideExportFile to TRUE before you want to get the temporary files path for export.', 1401205213);
1271 }
1272 if ($this->temporaryFilesPathForExport === null) {
1273 $temporaryFolderName = $this->getTemporaryFolderName();
1274 $this->temporaryFilesPathForExport = $temporaryFolderName . '/';
1275 }
1276 return $this->temporaryFilesPathForExport;
1277 }
1278
1279 /**
1280 *
1281 * @return string
1282 */
1283 protected function getTemporaryFolderName()
1284 {
1285 $temporaryPath = PATH_site . 'typo3temp/';
1286 do {
1287 $temporaryFolderName = $temporaryPath . 'export_temp_files_' . mt_rand(1, PHP_INT_MAX);
1288 } while (is_dir($temporaryFolderName));
1289 GeneralUtility::mkdir($temporaryFolderName);
1290 return $temporaryFolderName;
1291 }
1292
1293 /**
1294 * DB relations flattend to 1-dim array.
1295 * The list will be unique, no table/uid combination will appear twice.
1296 *
1297 * @param array $dbrels 2-dim Array of database relations organized by table key
1298 * @return array 1-dim array where entries are table:uid and keys are array with table/id
1299 */
1300 public function flatDBrels($dbrels)
1301 {
1302 $list = array();
1303 foreach ($dbrels as $dat) {
1304 if ($dat['type'] == 'db') {
1305 foreach ($dat['itemArray'] as $i) {
1306 $list[$i['table'] . ':' . $i['id']] = $i;
1307 }
1308 }
1309 if ($dat['type'] == 'flex' && is_array($dat['flexFormRels']['db'])) {
1310 foreach ($dat['flexFormRels']['db'] as $subList) {
1311 foreach ($subList as $i) {
1312 $list[$i['table'] . ':' . $i['id']] = $i;
1313 }
1314 }
1315 }
1316 }
1317 return $list;
1318 }
1319
1320 /**
1321 * Soft References flattend to 1-dim array.
1322 *
1323 * @param array $dbrels 2-dim Array of database relations organized by table key
1324 * @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
1325 */
1326 public function flatSoftRefs($dbrels)
1327 {
1328 $list = array();
1329 foreach ($dbrels as $field => $dat) {
1330 if (is_array($dat['softrefs']['keys'])) {
1331 foreach ($dat['softrefs']['keys'] as $spKey => $elements) {
1332 if (is_array($elements)) {
1333 foreach ($elements as $subKey => $el) {
1334 $lKey = $field . ':' . $spKey . ':' . $subKey;
1335 $list[$lKey] = array_merge(array('field' => $field, 'spKey' => $spKey), $el);
1336 // Add file_ID key to header - slightly "risky" way of doing this because if the calculation
1337 // changes for the same value in $this->records[...] this will not work anymore!
1338 if ($el['subst'] && $el['subst']['relFileName']) {
1339 $list[$lKey]['file_ID'] = md5(PATH_site . $el['subst']['relFileName']);
1340 }
1341 }
1342 }
1343 }
1344 }
1345 if ($dat['type'] == 'flex' && is_array($dat['flexFormRels']['softrefs'])) {
1346 foreach ($dat['flexFormRels']['softrefs'] as $structurePath => $subSoftrefs) {
1347 if (is_array($subSoftrefs['keys'])) {
1348 foreach ($subSoftrefs['keys'] as $spKey => $elements) {
1349 foreach ($elements as $subKey => $el) {
1350 $lKey = $field . ':' . $structurePath . ':' . $spKey . ':' . $subKey;
1351 $list[$lKey] = array_merge(array('field' => $field, 'spKey' => $spKey, 'structurePath' => $structurePath), $el);
1352 // Add file_ID key to header - slightly "risky" way of doing this because if the calculation
1353 // changes for the same value in $this->records[...] this will not work anymore!
1354 if ($el['subst'] && $el['subst']['relFileName']) {
1355 $list[$lKey]['file_ID'] = md5(PATH_site . $el['subst']['relFileName']);
1356 }
1357 }
1358 }
1359 }
1360 }
1361 }
1362 }
1363 return $list;
1364 }
1365
1366 /**
1367 * If include fields for a specific record type are set, the data
1368 * are filtered out with fields are not included in the fields.
1369 *
1370 * @param string $table The record type to be filtered
1371 * @param array $row The data to be filtered
1372 * @return array The filtered record row
1373 */
1374 protected function filterRecordFields($table, array $row)
1375 {
1376 if (isset($this->recordTypesIncludeFields[$table])) {
1377 $includeFields = array_unique(array_merge(
1378 $this->recordTypesIncludeFields[$table],
1379 $this->defaultRecordIncludeFields
1380 ));
1381 $newRow = array();
1382 foreach ($row as $key => $value) {
1383 if (in_array($key, $includeFields)) {
1384 $newRow[$key] = $value;
1385 }
1386 }
1387 } else {
1388 $newRow = $row;
1389 }
1390 return $newRow;
1391 }
1392
1393 /**************************
1394 * File Output
1395 *************************/
1396
1397 /**
1398 * This compiles and returns the data content for an exported file
1399 *
1400 * @param string $type Type of output; "xml" gives xml, otherwise serialized array, possibly compressed.
1401 * @return string The output file stream
1402 */
1403 public function compileMemoryToFileContent($type = '')
1404 {
1405 if ($type == 'xml') {
1406 $out = $this->createXML();
1407 } else {
1408 $compress = $this->doOutputCompress();
1409 $out = '';
1410 // adding header:
1411 $out .= $this->addFilePart(serialize($this->dat['header']), $compress);
1412 // adding records:
1413 $out .= $this->addFilePart(serialize($this->dat['records']), $compress);
1414 // adding files:
1415 $out .= $this->addFilePart(serialize($this->dat['files']), $compress);
1416 // adding files_fal:
1417 $out .= $this->addFilePart(serialize($this->dat['files_fal']), $compress);
1418 }
1419 return $out;
1420 }
1421
1422 /**
1423 * Creates XML string from input array
1424 *
1425 * @return string XML content
1426 */
1427 public function createXML()
1428 {
1429 // Options:
1430 $options = array(
1431 'alt_options' => array(
1432 '/header' => array(
1433 'disableTypeAttrib' => true,
1434 'clearStackPath' => true,
1435 'parentTagMap' => array(
1436 'files' => 'file',
1437 'files_fal' => 'file',
1438 'records' => 'table',
1439 'table' => 'rec',
1440 'rec:rels' => 'relations',
1441 'relations' => 'element',
1442 'filerefs' => 'file',
1443 'pid_lookup' => 'page_contents',
1444 'header:relStaticTables' => 'static_tables',
1445 'static_tables' => 'tablename',
1446 'excludeMap' => 'item',
1447 'softrefCfg' => 'softrefExportMode',
1448 'extensionDependencies' => 'extkey',
1449 'softrefs' => 'softref_element'
1450 ),
1451 'alt_options' => array(
1452 '/pagetree' => array(
1453 'disableTypeAttrib' => true,
1454 'useIndexTagForNum' => 'node',
1455 'parentTagMap' => array(
1456 'node:subrow' => 'node'
1457 )
1458 ),
1459 '/pid_lookup/page_contents' => array(
1460 'disableTypeAttrib' => true,
1461 'parentTagMap' => array(
1462 'page_contents' => 'table'
1463 ),
1464 'grandParentTagMap' => array(
1465 'page_contents/table' => 'item'
1466 )
1467 )
1468 )
1469 ),
1470 '/records' => array(
1471 'disableTypeAttrib' => true,
1472 'parentTagMap' => array(
1473 'records' => 'tablerow',
1474 'tablerow:data' => 'fieldlist',
1475 'tablerow:rels' => 'related',
1476 'related' => 'field',
1477 'field:itemArray' => 'relations',
1478 'field:newValueFiles' => 'filerefs',
1479 'field:flexFormRels' => 'flexform',
1480 'relations' => 'element',
1481 'filerefs' => 'file',
1482 'flexform:db' => 'db_relations',
1483 'flexform:file' => 'file_relations',
1484 'flexform:softrefs' => 'softref_relations',
1485 'softref_relations' => 'structurePath',
1486 'db_relations' => 'path',
1487 'file_relations' => 'path',
1488 'path' => 'element',
1489 'keys' => 'softref_key',
1490 'softref_key' => 'softref_element'
1491 ),
1492 'alt_options' => array(
1493 '/records/tablerow/fieldlist' => array(
1494 'useIndexTagForAssoc' => 'field'
1495 )
1496 )
1497 ),
1498 '/files' => array(
1499 'disableTypeAttrib' => true,
1500 'parentTagMap' => array(
1501 'files' => 'file'
1502 )
1503 ),
1504 '/files_fal' => array(
1505 'disableTypeAttrib' => true,
1506 'parentTagMap' => array(
1507 'files_fal' => 'file'
1508 )
1509 )
1510 )
1511 );
1512 // Creating XML file from $outputArray:
1513 $charset = $this->dat['header']['charset'] ?: 'utf-8';
1514 $XML = '<?xml version="1.0" encoding="' . $charset . '" standalone="yes" ?>' . LF;
1515 $XML .= GeneralUtility::array2xml($this->dat, '', 0, 'T3RecordDocument', 0, $options);
1516 return $XML;
1517 }
1518
1519 /**
1520 * Returns TRUE if the output should be compressed.
1521 *
1522 * @return bool TRUE if compression is possible AND requested.
1523 */
1524 public function doOutputCompress()
1525 {
1526 return $this->compress && !$this->dontCompress;
1527 }
1528
1529 /**
1530 * Returns a content part for a filename being build.
1531 *
1532 * @param array $data Data to store in part
1533 * @param bool $compress Compress file?
1534 * @return string Content stream.
1535 */
1536 public function addFilePart($data, $compress = false)
1537 {
1538 if ($compress) {
1539 $data = gzcompress($data);
1540 }
1541 return md5($data) . ':' . ($compress ? '1' : '0') . ':' . str_pad(strlen($data), 10, '0', STR_PAD_LEFT) . ':' . $data . ':';
1542 }
1543
1544 /***********************
1545 * Import
1546 ***********************/
1547
1548 /**
1549 * Initialize all settings for the import
1550 *
1551 * @return void
1552 */
1553 protected function initializeImport()
1554 {
1555 // Set this flag to indicate that an import is being/has been done.
1556 $this->doesImport = 1;
1557 // Initialize:
1558 // 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.
1559 $this->import_mapId = array();
1560 $this->import_newId = array();
1561 $this->import_newId_pids = array();
1562 // Temporary files stack initialized:
1563 $this->unlinkFiles = array();
1564 $this->alternativeFileName = array();
1565 $this->alternativeFilePath = array();
1566
1567 $this->initializeStorageObjects();
1568 }
1569
1570 /**
1571 * Initialize the all present storage objects
1572 *
1573 * @return void
1574 */
1575 protected function initializeStorageObjects()
1576 {
1577 /** @var $storageRepository StorageRepository */
1578 $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
1579 $this->storageObjects = $storageRepository->findAll();
1580 }
1581
1582 /**
1583 * Imports the internal data array to $pid.
1584 *
1585 * @param int $pid Page ID in which to import the content
1586 * @return void
1587 */
1588 public function importData($pid)
1589 {
1590 $this->initializeImport();
1591
1592 // Write sys_file_storages first
1593 $this->writeSysFileStorageRecords();
1594 // Write sys_file records and write the binary file data
1595 $this->writeSysFileRecords();
1596 // Write records, first pages, then the rest
1597 // Fields with "hard" relations to database, files and flexform fields are kept empty during this run
1598 $this->writeRecords_pages($pid);
1599 $this->writeRecords_records($pid);
1600 // Finally all the file and DB record references must be fixed. This is done after all records have supposedly been written to database:
1601 // $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.
1602 $this->setRelations();
1603 // 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):
1604 $this->setFlexFormRelations();
1605 // Unlink temporary files:
1606 $this->unlinkTempFiles();
1607 // Finally, traverse all records and process softreferences with substitution attributes.
1608 $this->processSoftReferences();
1609 // After all migrate records using sys_file_reference now
1610 if ($this->legacyImport) {
1611 $this->migrateLegacyImportRecords();
1612 }
1613 }
1614
1615 /**
1616 * Imports the sys_file_storage records from internal data array.
1617 *
1618 * @return void
1619 */
1620 protected function writeSysFileStorageRecords()
1621 {
1622 if (!isset($this->dat['header']['records']['sys_file_storage'])) {
1623 return;
1624 }
1625 $sysFileStorageUidsToBeResetToDefaultStorage = array();
1626 foreach ($this->dat['header']['records']['sys_file_storage'] as $sysFileStorageUid => $_) {
1627 $storageRecord = $this->dat['records']['sys_file_storage:' . $sysFileStorageUid]['data'];
1628 // continue with Local, writable and online storage only
1629 if ($storageRecord['driver'] === 'Local' && $storageRecord['is_writable'] && $storageRecord['is_online']) {
1630 $useThisStorageUidInsteadOfTheOneInImport = 0;
1631 /** @var $localStorage \TYPO3\CMS\Core\Resource\ResourceStorage */
1632 foreach ($this->storageObjects as $localStorage) {
1633 // check the available storage for Local, writable and online ones
1634 if ($localStorage->getDriverType() === 'Local' && $localStorage->isWritable() && $localStorage->isOnline()) {
1635 // check if there is already an identical storage present (same pathType and basePath)
1636 $storageRecordConfiguration = ResourceFactory::getInstance()->convertFlexFormDataToConfigurationArray($storageRecord['configuration']);
1637 $localStorageRecordConfiguration = $localStorage->getConfiguration();
1638 if (
1639 $storageRecordConfiguration['pathType'] === $localStorageRecordConfiguration['pathType']
1640 && $storageRecordConfiguration['basePath'] === $localStorageRecordConfiguration['basePath']
1641 ) {
1642 // same storage is already present
1643 $useThisStorageUidInsteadOfTheOneInImport = $localStorage->getUid();
1644 break;
1645 }
1646 }
1647 }
1648 if ($useThisStorageUidInsteadOfTheOneInImport > 0) {
1649 // same storage is already present; map the to be imported one to the present one
1650 $this->import_mapId['sys_file_storage'][$sysFileStorageUid] = $useThisStorageUidInsteadOfTheOneInImport;
1651 } else {
1652 // Local, writable and online storage. Is allowed to be used to later write files in.
1653 $this->addSingle('sys_file_storage', $sysFileStorageUid, 0);
1654 }
1655 } else {
1656 // Storage with non Local drivers could be imported but must not be used to saves files in, because you
1657 // could not be sure, that this is supported. The default storage will be used in this case.
1658 // It could happen that non writable and non online storage will be created as dupes because you could not
1659 // check the detailed configuration options at this point
1660 $this->addSingle('sys_file_storage', $sysFileStorageUid, 0);
1661 $sysFileStorageUidsToBeResetToDefaultStorage[] = $sysFileStorageUid;
1662 }
1663 }
1664
1665 // Importing the added ones
1666 $tce = $this->getNewTCE();
1667 // Because all records are being submitted in their correct order with positive pid numbers - and so we should reverse submission order internally.
1668 $tce->reverseOrder = 1;
1669 $tce->isImporting = true;
1670 $tce->start($this->import_data, array());
1671 $tce->process_datamap();
1672 $this->addToMapId($tce->substNEWwithIDs);
1673
1674 $defaultStorageUid = null;
1675 // get default storage
1676 $defaultStorage = ResourceFactory::getInstance()->getDefaultStorage();
1677 if ($defaultStorage !== null) {
1678 $defaultStorageUid = $defaultStorage->getUid();
1679 }
1680 foreach ($sysFileStorageUidsToBeResetToDefaultStorage as $sysFileStorageUidToBeResetToDefaultStorage) {
1681 $this->import_mapId['sys_file_storage'][$sysFileStorageUidToBeResetToDefaultStorage] = $defaultStorageUid;
1682 }
1683
1684 // unset the sys_file_storage records to prevent an import in writeRecords_records
1685 unset($this->dat['header']['records']['sys_file_storage']);
1686 }
1687
1688 /**
1689 * Imports the sys_file records and the binary files data from internal data array.
1690 *
1691 * @return void
1692 */
1693 protected function writeSysFileRecords()
1694 {
1695 if (!isset($this->dat['header']['records']['sys_file'])) {
1696 return;
1697 }
1698 $this->addGeneralErrorsByTable('sys_file');
1699
1700 // fetch fresh storage records from database
1701 $storageRecords = $this->fetchStorageRecords();
1702
1703 $defaultStorage = ResourceFactory::getInstance()->getDefaultStorage();
1704
1705 $sanitizedFolderMappings = array();
1706
1707 foreach ($this->dat['header']['records']['sys_file'] as $sysFileUid => $_) {
1708 $fileRecord = $this->dat['records']['sys_file:' . $sysFileUid]['data'];
1709
1710 $temporaryFile = null;
1711 // check if there is the right file already in the local folder
1712 if ($this->filesPathForImport !== null) {
1713 if (is_file($this->filesPathForImport . '/' . $fileRecord['sha1']) && sha1_file($this->filesPathForImport . '/' . $fileRecord['sha1']) === $fileRecord['sha1']) {
1714 $temporaryFile = $this->filesPathForImport . '/' . $fileRecord['sha1'];
1715 }
1716 }
1717
1718 // save file to disk
1719 if ($temporaryFile === null) {
1720 $fileId = md5($fileRecord['storage'] . ':' . $fileRecord['identifier_hash']);
1721 $temporaryFile = $this->writeTemporaryFileFromData($fileId);
1722 if ($temporaryFile === null) {
1723 // error on writing the file. Error message was already added
1724 continue;
1725 }
1726 }
1727
1728 $originalStorageUid = $fileRecord['storage'];
1729 $useStorageFromStorageRecords = false;
1730
1731 // replace storage id, if an alternative one was registered
1732 if (isset($this->import_mapId['sys_file_storage'][$fileRecord['storage']])) {
1733 $fileRecord['storage'] = $this->import_mapId['sys_file_storage'][$fileRecord['storage']];
1734 $useStorageFromStorageRecords = true;
1735 }
1736
1737 if (empty($fileRecord['storage']) && !$this->isFallbackStorage($fileRecord['storage'])) {
1738 // no storage for the file is defined, mostly because of a missing default storage.
1739 $this->error('Error: No storage for the file "' . $fileRecord['identifier'] . '" with storage uid "' . $originalStorageUid . '"');
1740 continue;
1741 }
1742
1743 // using a storage from the local storage is only allowed, if the uid is present in the
1744 // mapping. Only in this case we could be sure, that it's a local, online and writable storage.
1745 if ($useStorageFromStorageRecords && isset($storageRecords[$fileRecord['storage']])) {
1746 /** @var $storage \TYPO3\CMS\Core\Resource\ResourceStorage */
1747 $storage = ResourceFactory::getInstance()->getStorageObject($fileRecord['storage'], $storageRecords[$fileRecord['storage']]);
1748 } elseif ($this->isFallbackStorage($fileRecord['storage'])) {
1749 $storage = ResourceFactory::getInstance()->getStorageObject(0);
1750 } elseif ($defaultStorage !== null) {
1751 $storage = $defaultStorage;
1752 } else {
1753 $this->error('Error: No storage available for the file "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
1754 continue;
1755 }
1756
1757 $newFile = null;
1758
1759 // check, if there is an identical file
1760 try {
1761 if ($storage->hasFile($fileRecord['identifier'])) {
1762 $file = $storage->getFile($fileRecord['identifier']);
1763 if ($file->getSha1() === $fileRecord['sha1']) {
1764 $newFile = $file;
1765 }
1766 }
1767 } catch (Exception $e) {
1768 }
1769
1770 if ($newFile === null) {
1771 $folderName = PathUtility::dirname(ltrim($fileRecord['identifier'], '/'));
1772 if (in_array($folderName, $sanitizedFolderMappings)) {
1773 $folderName = $sanitizedFolderMappings[$folderName];
1774 }
1775 if (!$storage->hasFolder($folderName)) {
1776 try {
1777 $importFolder = $storage->createFolder($folderName);
1778 if ($importFolder->getIdentifier() !== $folderName && !in_array($folderName, $sanitizedFolderMappings)) {
1779 $sanitizedFolderMappings[$folderName] = $importFolder->getIdentifier();
1780 }
1781 } catch (Exception $e) {
1782 $this->error('Error: Folder could not be created for file "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
1783 continue;
1784 }
1785 } else {
1786 $importFolder = $storage->getFolder($folderName);
1787 }
1788
1789 try {
1790 /** @var $newFile File */
1791 $newFile = $storage->addFile($temporaryFile, $importFolder, $fileRecord['name']);
1792 } catch (Exception $e) {
1793 $this->error('Error: File could not be added to the storage: "' . $fileRecord['identifier'] . '" with storage uid "' . $fileRecord['storage'] . '"');
1794 continue;
1795 }
1796
1797 if ($newFile->getSha1() !== $fileRecord['sha1']) {
1798 $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'] . '"');
1799 }
1800 }
1801
1802 // save the new uid in the import id map
1803 $this->import_mapId['sys_file'][$fileRecord['uid']] = $newFile->getUid();
1804 $this->fixUidLocalInSysFileReferenceRecords($fileRecord['uid'], $newFile->getUid());
1805 }
1806
1807 // unset the sys_file records to prevent an import in writeRecords_records
1808 unset($this->dat['header']['records']['sys_file']);
1809 }
1810
1811 /**
1812 * Checks if the $storageId is the id of the fallback storage
1813 *
1814 * @param int|string $storageId
1815 * @return bool
1816 */
1817 protected function isFallbackStorage($storageId)
1818 {
1819 return $storageId === 0 || $storageId === '0';
1820 }
1821
1822 /**
1823 * Normally the importer works like the following:
1824 * Step 1: import the records with cleared field values of relation fields (see addSingle())
1825 * Step 2: update the records with the right relation ids (see setRelations())
1826 *
1827 * In step 2 the saving fields of type "relation to sys_file_reference" checks the related sys_file_reference
1828 * record (created in step 1) with the FileExtensionFilter for matching file extensions of the related file.
1829 * To make this work correct, the uid_local of sys_file_reference records has to be not empty AND has to
1830 * relate to the correct (imported) sys_file record uid!!!
1831 *
1832 * This is fixed here.
1833 *
1834 * @param int $oldFileUid
1835 * @param int $newFileUid
1836 * @return void
1837 */
1838 protected function fixUidLocalInSysFileReferenceRecords($oldFileUid, $newFileUid)
1839 {
1840 if (!isset($this->dat['header']['records']['sys_file_reference'])) {
1841 return;
1842 }
1843
1844 foreach ($this->dat['header']['records']['sys_file_reference'] as $sysFileReferenceUid => $_) {
1845 $fileReferenceRecord = $this->dat['records']['sys_file_reference:' . $sysFileReferenceUid]['data'];
1846 if ($fileReferenceRecord['uid_local'] == $oldFileUid) {
1847 $fileReferenceRecord['uid_local'] = $newFileUid;
1848 $this->dat['records']['sys_file_reference:' . $sysFileReferenceUid]['data'] = $fileReferenceRecord;
1849 }
1850 }
1851 }
1852
1853 /**
1854 * Initializes the folder for legacy imports as subfolder of backend users default upload folder
1855 *
1856 * @return void
1857 */
1858 protected function initializeLegacyImportFolder()
1859 {
1860 /** @var \TYPO3\CMS\Core\Resource\Folder $folder */
1861 $folder = $this->getBackendUser()->getDefaultUploadFolder();
1862 if ($folder === false) {
1863 $this->error('Error: the backend users default upload folder is missing! No files will be imported!');
1864 }
1865 if (!$folder->hasFolder($this->legacyImportTargetPath)) {
1866 try {
1867 $this->legacyImportFolder = $folder->createFolder($this->legacyImportTargetPath);
1868 } catch (Exception $e) {
1869 $this->error('Error: the import folder in the default upload folder could not be created! No files will be imported!');
1870 }
1871 } else {
1872 $this->legacyImportFolder = $folder->getSubFolder($this->legacyImportTargetPath);
1873 }
1874 }
1875
1876 /**
1877 * Fetched fresh storage records from database because the new imported
1878 * ones are not in cached data of the StorageRepository
1879 *
1880 * @return bool|array
1881 */
1882 protected function fetchStorageRecords()
1883 {
1884 $whereClause = BackendUtility::BEenableFields('sys_file_storage');
1885 $whereClause .= BackendUtility::deleteClause('sys_file_storage');
1886
1887 $rows = $this->getDatabaseConnection()->exec_SELECTgetRows(
1888 '*',
1889 'sys_file_storage',
1890 '1=1' . $whereClause,
1891 '',
1892 '',
1893 '',
1894 'uid'
1895 );
1896
1897 return $rows;
1898 }
1899
1900 /**
1901 * Writes the file from import array to temp dir and returns the filename of it.
1902 *
1903 * @param string $fileId
1904 * @param string $dataKey
1905 * @return string Absolute filename of the temporary filename of the file
1906 */
1907 protected function writeTemporaryFileFromData($fileId, $dataKey = 'files_fal')
1908 {
1909 $temporaryFilePath = null;
1910 if (is_array($this->dat[$dataKey][$fileId])) {
1911 $temporaryFilePathInternal = GeneralUtility::tempnam('import_temp_');
1912 GeneralUtility::writeFile($temporaryFilePathInternal, $this->dat[$dataKey][$fileId]['content']);
1913 clearstatcache();
1914 if (@is_file($temporaryFilePathInternal)) {
1915 $this->unlinkFiles[] = $temporaryFilePathInternal;
1916 if (filesize($temporaryFilePathInternal) == $this->dat[$dataKey][$fileId]['filesize']) {
1917 $temporaryFilePath = $temporaryFilePathInternal;
1918 } else {
1919 $this->error('Error: temporary file ' . $temporaryFilePathInternal . ' had a size (' . filesize($temporaryFilePathInternal) . ') different from the original (' . $this->dat[$dataKey][$fileId]['filesize'] . ')');
1920 }
1921 } else {
1922 $this->error('Error: temporary file ' . $temporaryFilePathInternal . ' was not written as it should have been!');
1923 }
1924 } else {
1925 $this->error('Error: No file found for ID ' . $fileId);
1926 }
1927 return $temporaryFilePath;
1928 }
1929
1930 /**
1931 * Writing pagetree/pages to database:
1932 *
1933 * @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
1934 * @return void
1935 * @see writeRecords_records()
1936 */
1937 public function writeRecords_pages($pid)
1938 {
1939 // First, write page structure if any:
1940 if (is_array($this->dat['header']['records']['pages'])) {
1941 $this->addGeneralErrorsByTable('pages');
1942 // $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.
1943 $pageRecords = $this->dat['header']['records']['pages'];
1944 $this->import_data = array();
1945 // First add page tree if any
1946 if (is_array($this->dat['header']['pagetree'])) {
1947 $pagesFromTree = $this->flatInversePageTree($this->dat['header']['pagetree']);
1948 foreach ($pagesFromTree as $uid) {
1949 $thisRec = $this->dat['header']['records']['pages'][$uid];
1950 // PID: Set the main $pid, unless a NEW-id is found
1951 $setPid = isset($this->import_newId_pids[$thisRec['pid']]) ? $this->import_newId_pids[$thisRec['pid']] : $pid;
1952 $this->addSingle('pages', $uid, $setPid);
1953 unset($pageRecords[$uid]);
1954 }
1955 }
1956 // Then add all remaining pages not in tree on root level:
1957 if (!empty($pageRecords)) {
1958 $remainingPageUids = array_keys($pageRecords);
1959 foreach ($remainingPageUids as $pUid) {
1960 $this->addSingle('pages', $pUid, $pid);
1961 }
1962 }
1963 // Now write to database:
1964 $tce = $this->getNewTCE();
1965 $tce->isImporting = true;
1966 $this->callHook('before_writeRecordsPages', array(
1967 'tce' => &$tce,
1968 'data' => &$this->import_data
1969 ));
1970 $tce->suggestedInsertUids = $this->suggestedInsertUids;
1971 $tce->start($this->import_data, array());
1972 $tce->process_datamap();
1973 $this->callHook('after_writeRecordsPages', array(
1974 'tce' => &$tce
1975 ));
1976 // post-processing: Registering new ids (end all tcemain sessions with this)
1977 $this->addToMapId($tce->substNEWwithIDs);
1978 // In case of an update, order pages from the page tree correctly:
1979 if ($this->update && is_array($this->dat['header']['pagetree'])) {
1980 $this->writeRecords_pages_order();
1981 }
1982 }
1983 }
1984
1985 /**
1986 * Organize all updated pages in page tree so they are related like in the import file
1987 * Only used for updates and when $this->dat['header']['pagetree'] is an array.
1988 *
1989 * @return void
1990 * @access private
1991 * @see writeRecords_pages(), writeRecords_records_order()
1992 */
1993 public function writeRecords_pages_order()
1994 {
1995 $cmd_data = array();
1996 // Get uid-pid relations and traverse them in order to map to possible new IDs
1997 $pidsFromTree = $this->flatInversePageTree_pid($this->dat['header']['pagetree']);
1998 foreach ($pidsFromTree as $origPid => $newPid) {
1999 if ($newPid >= 0 && $this->dontIgnorePid('pages', $origPid)) {
2000 // If the page had a new id (because it was created) use that instead!
2001 if (substr($this->import_newId_pids[$origPid], 0, 3) === 'NEW') {
2002 if ($this->import_mapId['pages'][$origPid]) {
2003 $mappedPid = $this->import_mapId['pages'][$origPid];
2004 $cmd_data['pages'][$mappedPid]['move'] = $newPid;
2005 }
2006 } else {
2007 $cmd_data['pages'][$origPid]['move'] = $newPid;
2008 }
2009 }
2010 }
2011 // Execute the move commands if any:
2012 if (!empty($cmd_data)) {
2013 $tce = $this->getNewTCE();
2014 $this->callHook('before_writeRecordsPagesOrder', array(
2015 'tce' => &$tce,
2016 'data' => &$cmd_data
2017 ));
2018 $tce->start(array(), $cmd_data);
2019 $tce->process_cmdmap();
2020 $this->callHook('after_writeRecordsPagesOrder', array(
2021 'tce' => &$tce
2022 ));
2023 }
2024 }
2025
2026 /**
2027 * Write all database records except pages (writtein in writeRecords_pages())
2028 *
2029 * @param int $pid Page id in which to import
2030 * @return void
2031 * @see writeRecords_pages()
2032 */
2033 public function writeRecords_records($pid)
2034 {
2035 // Write the rest of the records
2036 $this->import_data = array();
2037 if (is_array($this->dat['header']['records'])) {
2038 foreach ($this->dat['header']['records'] as $table => $recs) {
2039 $this->addGeneralErrorsByTable($table);
2040 if ($table != 'pages') {
2041 foreach ($recs as $uid => $thisRec) {
2042 // PID: Set the main $pid, unless a NEW-id is found
2043 $setPid = isset($this->import_mapId['pages'][$thisRec['pid']])
2044 ? (int)$this->import_mapId['pages'][$thisRec['pid']]
2045 : (int)$pid;
2046 if (is_array($GLOBALS['TCA'][$table]) && isset($GLOBALS['TCA'][$table]['ctrl']['rootLevel'])) {
2047 $rootLevelSetting = (int)$GLOBALS['TCA'][$table]['ctrl']['rootLevel'];
2048 if ($rootLevelSetting === 1) {
2049 $setPid = 0;
2050 } elseif ($rootLevelSetting === 0 && $setPid === 0) {
2051 $this->error('Error: Record type ' . $table . ' is not allowed on pid 0');
2052 continue;
2053 }
2054 }
2055 // Add record:
2056 $this->addSingle($table, $uid, $setPid);
2057 }
2058 }
2059 }
2060 } else {
2061 $this->error('Error: No records defined in internal data array.');
2062 }
2063 // Now write to database:
2064 $tce = $this->getNewTCE();
2065 $this->callHook('before_writeRecordsRecords', array(
2066 'tce' => &$tce,
2067 'data' => &$this->import_data
2068 ));
2069 $tce->suggestedInsertUids = $this->suggestedInsertUids;
2070 // Because all records are being submitted in their correct order with positive pid numbers - and so we should reverse submission order internally.
2071 $tce->reverseOrder = 1;
2072 $tce->isImporting = true;
2073 $tce->start($this->import_data, array());
2074 $tce->process_datamap();
2075 $this->callHook('after_writeRecordsRecords', array(
2076 'tce' => &$tce
2077 ));
2078 // post-processing: Removing files and registering new ids (end all tcemain sessions with this)
2079 $this->addToMapId($tce->substNEWwithIDs);
2080 // In case of an update, order pages from the page tree correctly:
2081 if ($this->update) {
2082 $this->writeRecords_records_order($pid);
2083 }
2084 }
2085
2086 /**
2087 * Organize all updated record to their new positions.
2088 * Only used for updates
2089 *
2090 * @param int $mainPid Main PID into which we import.
2091 * @return void
2092 * @access private
2093 * @see writeRecords_records(), writeRecords_pages_order()
2094 */
2095 public function writeRecords_records_order($mainPid)
2096 {
2097 $cmd_data = array();
2098 if (is_array($this->dat['header']['pagetree'])) {
2099 $pagesFromTree = $this->flatInversePageTree($this->dat['header']['pagetree']);
2100 } else {
2101 $pagesFromTree = array();
2102 }
2103 if (is_array($this->dat['header']['pid_lookup'])) {
2104 foreach ($this->dat['header']['pid_lookup'] as $pid => $recList) {
2105 $newPid = isset($this->import_mapId['pages'][$pid]) ? $this->import_mapId['pages'][$pid] : $mainPid;
2106 if (MathUtility::canBeInterpretedAsInteger($newPid)) {
2107 foreach ($recList as $tableName => $uidList) {
2108 // If $mainPid===$newPid then we are on root level and we can consider to move pages as well!
2109 // (they will not be in the page tree!)
2110 if (($tableName != 'pages' || !$pagesFromTree[$pid]) && is_array($uidList)) {
2111 $uidList = array_reverse(array_keys($uidList));
2112 foreach ($uidList as $uid) {
2113 if ($this->dontIgnorePid($tableName, $uid)) {
2114 $cmd_data[$tableName][$uid]['move'] = $newPid;
2115 } else {
2116 }
2117 }
2118 }
2119 }
2120 }
2121 }
2122 }
2123 // Execute the move commands if any:
2124 if (!empty($cmd_data)) {
2125 $tce = $this->getNewTCE();
2126 $this->callHook('before_writeRecordsRecordsOrder', array(
2127 'tce' => &$tce,
2128 'data' => &$cmd_data
2129 ));
2130 $tce->start(array(), $cmd_data);
2131 $tce->process_cmdmap();
2132 $this->callHook('after_writeRecordsRecordsOrder', array(
2133 'tce' => &$tce
2134 ));
2135 }
2136 }
2137
2138 /**
2139 * Adds a single record to the $importData array. Also copies files to tempfolder.
2140 * However all File/DB-references and flexform field contents are set to blank for now!
2141 * That is done with setRelations() later
2142 *
2143 * @param string $table Table name (from import memory)
2144 * @param int $uid Record UID (from import memory)
2145 * @param int $pid Page id
2146 * @return void
2147 * @see writeRecords()
2148 */
2149 public function addSingle($table, $uid, $pid)
2150 {
2151 if ($this->import_mode[$table . ':' . $uid] === 'exclude') {
2152 return;
2153 }
2154 $record = $this->dat['records'][$table . ':' . $uid]['data'];
2155 if (is_array($record)) {
2156 if ($this->update && $this->doesRecordExist($table, $uid) && $this->import_mode[$table . ':' . $uid] !== 'as_new') {
2157 $ID = $uid;
2158 } elseif ($table === 'sys_file_metadata' && $record['sys_language_uid'] == '0' && $this->import_mapId['sys_file'][$record['file']]) {
2159 // on adding sys_file records the belonging sys_file_metadata record was also created
2160 // if there is one the record need to be overwritten instead of creating a new one.
2161 $recordInDatabase = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
2162 'uid',
2163 'sys_file_metadata',
2164 'file = ' . $this->import_mapId['sys_file'][$record['file']] . ' AND sys_language_uid = 0 AND pid = 0'
2165 );
2166 // if no record could be found, $this->import_mapId['sys_file'][$record['file']] is pointing
2167 // to a file, that was already there, thus a new metadata record should be created
2168 if (is_array($recordInDatabase)) {
2169 $this->import_mapId['sys_file_metadata'][$record['uid']] = $recordInDatabase['uid'];
2170 $ID = $recordInDatabase['uid'];
2171 } else {
2172 $ID = StringUtility::getUniqueId('NEW');
2173 }
2174 } else {
2175 $ID = StringUtility::getUniqueId('NEW');
2176 }
2177 $this->import_newId[$table . ':' . $ID] = array('table' => $table, 'uid' => $uid);
2178 if ($table == 'pages') {
2179 $this->import_newId_pids[$uid] = $ID;
2180 }
2181 // Set main record data:
2182 $this->import_data[$table][$ID] = $record;
2183 $this->import_data[$table][$ID]['tx_impexp_origuid'] = $this->import_data[$table][$ID]['uid'];
2184 // Reset permission data:
2185 if ($table === 'pages') {
2186 // Have to reset the user/group IDs so pages are owned by importing user. Otherwise strange things may happen for non-admins!
2187 unset($this->import_data[$table][$ID]['perms_userid']);
2188 unset($this->import_data[$table][$ID]['perms_groupid']);
2189 }
2190 // PID and UID:
2191 unset($this->import_data[$table][$ID]['uid']);
2192 // Updates:
2193 if (MathUtility::canBeInterpretedAsInteger($ID)) {
2194 unset($this->import_data[$table][$ID]['pid']);
2195 } else {
2196 // Inserts:
2197 $this->import_data[$table][$ID]['pid'] = $pid;
2198 if (($this->import_mode[$table . ':' . $uid] === 'force_uid' && $this->update || $this->force_all_UIDS) && $this->getBackendUser()->isAdmin()) {
2199 $this->import_data[$table][$ID]['uid'] = $uid;
2200 $this->suggestedInsertUids[$table . ':' . $uid] = 'DELETE';
2201 }
2202 }
2203 // Setting db/file blank:
2204 foreach ($this->dat['records'][$table . ':' . $uid]['rels'] as $field => $config) {
2205 switch ((string)$config['type']) {
2206 case 'db':
2207
2208 case 'file':
2209 // Fixed later in ->setRelations() [because we need to know ALL newly created IDs before we can map relations!]
2210 // In the meantime we set NO values for relations.
2211 //
2212 // BUT for field uid_local of table sys_file_reference the relation MUST not be cleared here,
2213 // because the value is already the uid of the right imported sys_file record.
2214 // @see fixUidLocalInSysFileReferenceRecords()
2215 // If it's empty or a uid to another record the FileExtensionFilter will throw an exception or
2216 // delete the reference record if the file extension of the related record doesn't match.
2217 if ($table !== 'sys_file_reference' && $field !== 'uid_local') {
2218 $this->import_data[$table][$ID][$field] = '';
2219 }
2220 break;
2221 case 'flex':
2222 // Fixed later in setFlexFormRelations()
2223 // In the meantime we set NO value for flexforms - this is mainly because file references
2224 // inside will not be processed properly; In fact references will point to no file
2225 // or existing files (in which case there will be double-references which is a big problem of course!)
2226 $this->import_data[$table][$ID][$field] = '';
2227 break;
2228 }
2229 }
2230 } elseif ($table . ':' . $uid != 'pages:0') {
2231 // On root level we don't want this error message.
2232 $this->error('Error: no record was found in data array!');
2233 }
2234 }
2235
2236 /**
2237 * Registers the substNEWids in memory.
2238 *
2239 * @param array $substNEWwithIDs From tcemain to be merged into internal mapping variable in this object
2240 * @return void
2241 * @see writeRecords()
2242 */
2243 public function addToMapId($substNEWwithIDs)
2244 {
2245 foreach ($this->import_data as $table => $recs) {
2246 foreach ($recs as $id => $value) {
2247 $old_uid = $this->import_newId[$table . ':' . $id]['uid'];
2248 if (isset($substNEWwithIDs[$id])) {
2249 $this->import_mapId[$table][$old_uid] = $substNEWwithIDs[$id];
2250 } elseif ($this->update) {
2251 // Map same ID to same ID....
2252 $this->import_mapId[$table][$old_uid] = $id;
2253 } else {
2254 // if $this->import_mapId contains already the right mapping, skip the error msg.
2255 // See special handling of sys_file_metadata in addSingle() => nothing to do
2256 if (!($table === 'sys_file_metadata' && isset($this->import_mapId[$table][$old_uid]) && $this->import_mapId[$table][$old_uid] == $id)) {
2257 $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!');
2258 }
2259 }
2260 }
2261 }
2262 }
2263
2264 /**
2265 * Returns a new $TCE object
2266 *
2267 * @return DataHandler $TCE object
2268 */
2269 public function getNewTCE()
2270 {
2271 $tce = GeneralUtility::makeInstance(DataHandler::class);
2272 $tce->stripslashes_values = false;
2273 $tce->dontProcessTransformations = 1;
2274 $tce->enableLogging = $this->enableLogging;
2275 $tce->alternativeFileName = $this->alternativeFileName;
2276 $tce->alternativeFilePath = $this->alternativeFilePath;
2277 return $tce;
2278 }
2279
2280 /**
2281 * Cleaning up all the temporary files stored in typo3temp/ folder
2282 *
2283 * @return void
2284 */
2285 public function unlinkTempFiles()
2286 {
2287 foreach ($this->unlinkFiles as $fileName) {
2288 if (GeneralUtility::isFirstPartOfStr($fileName, PATH_site . 'typo3temp/')) {
2289 GeneralUtility::unlink_tempfile($fileName);
2290 clearstatcache();
2291 if (is_file($fileName)) {
2292 $this->error('Error: ' . $fileName . ' was NOT unlinked as it should have been!');
2293 }
2294 } else {
2295 $this->error('Error: ' . $fileName . ' was not in temp-path. Not removed!');
2296 }
2297 }
2298 $this->unlinkFiles = array();
2299 }
2300
2301 /***************************
2302 * Import / Relations setting
2303 ***************************/
2304
2305 /**
2306 * At the end of the import process all file and DB relations should be set properly (that is relations
2307 * to imported records are all re-created so imported records are correctly related again)
2308 * Relations in flexform fields are processed in setFlexFormRelations() after this function
2309 *
2310 * @return void
2311 * @see setFlexFormRelations()
2312 */
2313 public function setRelations()
2314 {
2315 $updateData = array();
2316 // import_newId contains a register of all records that was in the import memorys "records" key
2317 foreach ($this->import_newId as $nId => $dat) {
2318 $table = $dat['table'];
2319 $uid = $dat['uid'];
2320 // original UID - NOT the new one!
2321 // If the record has been written and received a new id, then proceed:
2322 if (is_array($this->import_mapId[$table]) && isset($this->import_mapId[$table][$uid])) {
2323 $thisNewUid = BackendUtility::wsMapId($table, $this->import_mapId[$table][$uid]);
2324 if (is_array($this->dat['records'][$table . ':' . $uid]['rels'])) {
2325 $thisNewPageUid = 0;
2326 if ($this->legacyImport) {
2327 if ($table != 'pages') {
2328 $oldPid = $this->dat['records'][$table . ':' . $uid]['data']['pid'];
2329 $thisNewPageUid = BackendUtility::wsMapId($table, $this->import_mapId['pages'][$oldPid]);
2330 } else {
2331 $thisNewPageUid = $thisNewUid;
2332 }
2333 }
2334 // Traverse relation fields of each record
2335 foreach ($this->dat['records'][$table . ':' . $uid]['rels'] as $field => $config) {
2336 // uid_local of sys_file_reference needs no update because the correct reference uid was already written
2337 // @see ImportExport::fixUidLocalInSysFileReferenceRecords()
2338 if ($table === 'sys_file_reference' && $field === 'uid_local') {
2339 continue;
2340 }
2341 switch ((string)$config['type']) {
2342 case 'db':
2343 if (is_array($config['itemArray']) && !empty($config['itemArray'])) {
2344 $itemConfig = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
2345 $valArray = $this->setRelations_db($config['itemArray'], $itemConfig);
2346 $updateData[$table][$thisNewUid][$field] = implode(',', $valArray);
2347 }
2348 break;
2349 case 'file':
2350 if (is_array($config['newValueFiles']) && !empty($config['newValueFiles'])) {
2351 $valArr = array();
2352 foreach ($config['newValueFiles'] as $fI) {
2353 $valArr[] = $this->import_addFileNameToBeCopied($fI);
2354 }
2355 if ($this->legacyImport && $this->legacyImportFolder === null && isset($this->legacyImportMigrationTables[$table][$field])) {
2356 // Do nothing - the legacy import folder is missing
2357 } elseif ($this->legacyImport && $this->legacyImportFolder !== null && isset($this->legacyImportMigrationTables[$table][$field])) {
2358 $refIds = array();
2359 foreach ($valArr as $tempFile) {
2360 $fileName = $this->alternativeFileName[$tempFile];
2361 $fileObject = null;
2362
2363 try {
2364 // check, if there is alreay the same file in the folder
2365 if ($this->legacyImportFolder->hasFile($fileName)) {
2366 $fileStorage = $this->legacyImportFolder->getStorage();
2367 $file = $fileStorage->getFile($this->legacyImportFolder->getIdentifier() . $fileName);
2368 if ($file->getSha1() === sha1_file($tempFile)) {
2369 $fileObject = $file;
2370 }
2371 }
2372 } catch (Exception $e) {
2373 }
2374
2375 if ($fileObject === null) {
2376 try {
2377 $fileObject = $this->legacyImportFolder->addFile($tempFile, $fileName, DuplicationBehavior::RENAME);
2378 } catch (Exception $e) {
2379 $this->error('Error: no file could be added to the storage for file name' . $this->alternativeFileName[$tempFile]);
2380 }
2381 }
2382 if ($fileObject !== null) {
2383 $refId = StringUtility::getUniqueId('NEW');
2384 $refIds[] = $refId;
2385 $updateData['sys_file_reference'][$refId] = array(
2386 'uid_local' => $fileObject->getUid(),
2387 'uid_foreign' => $thisNewUid, // uid of your content record
2388 'tablenames' => $table,
2389 'fieldname' => $field,
2390 'pid' => $thisNewPageUid, // parent id of the parent page
2391 'table_local' => 'sys_file',
2392 );
2393 }
2394 }
2395 $updateData[$table][$thisNewUid][$field] = implode(',', $refIds);
2396 if (!empty($this->legacyImportMigrationTables[$table][$field])) {
2397 $this->legacyImportMigrationRecords[$table][$thisNewUid][$field] = $refIds;
2398 }
2399 } else {
2400 $updateData[$table][$thisNewUid][$field] = implode(',', $valArr);
2401 }
2402 }
2403 break;
2404 }
2405 }
2406 } else {
2407 $this->error('Error: no record was found in data array!');
2408 }
2409 } else {
2410 $this->error('Error: this records is NOT created it seems! (' . $table . ':' . $uid . ')');
2411 }
2412 }
2413 if (!empty($updateData)) {
2414 $tce = $this->getNewTCE();
2415 $tce->isImporting = true;
2416 $this->callHook('before_setRelation', array(
2417 'tce' => &$tce,
2418 'data' => &$updateData
2419 ));
2420 $tce->start($updateData, array());
2421 $tce->process_datamap();
2422 // Replace the temporary "NEW" ids with the final ones.
2423 foreach ($this->legacyImportMigrationRecords as $table => $records) {
2424 foreach ($records as $uid => $fields) {
2425 foreach ($fields as $field => $referenceIds) {
2426 foreach ($referenceIds as $key => $referenceId) {
2427 $this->legacyImportMigrationRecords[$table][$uid][$field][$key] = $tce->substNEWwithIDs[$referenceId];
2428 }
2429 }
2430 }
2431 }
2432 $this->callHook('after_setRelations', array(
2433 'tce' => &$tce
2434 ));
2435 }
2436 }
2437
2438 /**
2439 * Maps relations for database
2440 *
2441 * @param array $itemArray Array of item sets (table/uid) from a dbAnalysis object
2442 * @param array $itemConfig Array of TCA config of the field the relation to be set on
2443 * @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.
2444 */
2445 public function setRelations_db($itemArray, $itemConfig)
2446 {
2447 $valArray = array();
2448 foreach ($itemArray as $relDat) {
2449 if (is_array($this->import_mapId[$relDat['table']]) && isset($this->import_mapId[$relDat['table']][$relDat['id']])) {
2450 // Since non FAL file relation type group internal_type file_reference are handled as reference to
2451 // sys_file records Datahandler requires the value as uid of the the related sys_file record only
2452 if ($itemConfig['type'] === 'group' && $itemConfig['internal_type'] === 'file_reference') {
2453 $value = $this->import_mapId[$relDat['table']][$relDat['id']];
2454 } elseif ($itemConfig['type'] === 'input' && isset($itemConfig['wizards']['link'])) {
2455 // If an input field has a relation to a sys_file record this need to be converted back to
2456 // the public path. But use getPublicUrl here, because could normally only be a local file path.
2457 $fileUid = $this->import_mapId[$relDat['table']][$relDat['id']];
2458 // Fallback value
2459 $value = 'file:' . $fileUid;
2460 try {
2461 $file = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileUid);
2462 } catch (\Exception $e) {
2463 $file = null;
2464 }
2465 if ($file instanceof FileInterface) {
2466 $value = $file->getPublicUrl();
2467 }
2468 } else {
2469 $value = $relDat['table'] . '_' . $this->import_mapId[$relDat['table']][$relDat['id']];
2470 }
2471 $valArray[] = $value;
2472 } elseif ($this->isTableStatic($relDat['table']) || $this->isExcluded($relDat['table'], $relDat['id']) || $relDat['id'] < 0) {
2473 // Checking for less than zero because some select types could contain negative values,
2474 // eg. fe_groups (-1, -2) and sys_language (-1 = ALL languages). This must be handled on both export and import.
2475 $valArray[] = $relDat['table'] . '_' . $relDat['id'];
2476 } else {
2477 $this->error('Lost relation: ' . $relDat['table'] . ':' . $relDat['id']);
2478 }
2479 }
2480 return $valArray;
2481 }
2482
2483 /**
2484 * Writes the file from import array to temp dir and returns the filename of it.
2485 *
2486 * @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
2487 * @return string|NULL Absolute filename of the temporary filename of the file. In ->alternativeFileName the original name is set.
2488 */
2489 public function import_addFileNameToBeCopied($fI)
2490 {
2491 if (is_array($this->dat['files'][$fI['ID']])) {
2492 $tmpFile = null;
2493 // check if there is the right file already in the local folder
2494 if ($this->filesPathForImport !== null) {
2495 if (is_file($this->filesPathForImport . '/' . $this->dat['files'][$fI['ID']]['content_md5']) &&
2496 md5_file($this->filesPathForImport . '/' . $this->dat['files'][$fI['ID']]['content_md5']) === $this->dat['files'][$fI['ID']]['content_md5']) {
2497 $tmpFile = $this->filesPathForImport . '/' . $this->dat['files'][$fI['ID']]['content_md5'];
2498 }
2499 }
2500 if ($tmpFile === null) {
2501 $tmpFile = GeneralUtility::tempnam('import_temp_');
2502 GeneralUtility::writeFile($tmpFile, $this->dat['files'][$fI['ID']]['content']);
2503 }
2504 clearstatcache();
2505 if (@is_file($tmpFile)) {
2506 $this->unlinkFiles[] = $tmpFile;
2507 if (filesize($tmpFile) == $this->dat['files'][$fI['ID']]['filesize']) {
2508 $this->alternativeFileName[$tmpFile] = $fI['filename'];
2509 $this->alternativeFilePath[$tmpFile] = $this->dat['files'][$fI['ID']]['relFileRef'];
2510 return $tmpFile;
2511 } else {
2512 $this->error('Error: temporary file ' . $tmpFile . ' had a size (' . filesize($tmpFile) . ') different from the original (' . $this->dat['files'][$fI['ID']]['filesize'] . ')');
2513 }
2514 } else {
2515 $this->error('Error: temporary file ' . $tmpFile . ' was not written as it should have been!');
2516 }
2517 } else {
2518 $this->error('Error: No file found for ID ' . $fI['ID']);
2519 }
2520 return null;
2521 }
2522
2523 /**
2524 * 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.
2525 * 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!
2526 *
2527 * @return void
2528 * @see setRelations()
2529 */
2530 public function setFlexFormRelations()
2531 {
2532 $updateData = array();
2533 // import_newId contains a register of all records that was in the import memorys "records" key
2534 foreach ($this->import_newId as $nId => $dat) {
2535 $table = $dat['table'];
2536 $uid = $dat['uid'];
2537 // original UID - NOT the new one!
2538 // If the record has been written and received a new id, then proceed:
2539 if (!isset($this->import_mapId[$table][$uid])) {
2540 $this->error('Error: this records is NOT created it seems! (' . $table . ':' . $uid . ')');
2541 continue;
2542 }
2543
2544 if (!is_array($this->dat['records'][$table . ':' . $uid]['rels'])) {
2545 $this->error('Error: no record was found in data array!');
2546 continue;
2547 }
2548 $thisNewUid = BackendUtility::wsMapId($table, $this->import_mapId[$table][$uid]);
2549 // Traverse relation fields of each record
2550 foreach ($this->dat['records'][$table . ':' . $uid]['rels'] as $field => $config) {
2551 switch ((string)$config['type']) {
2552 case 'flex':
2553 // Get XML content and set as default value (string, non-processed):
2554 $updateData[$table][$thisNewUid][$field] = $this->dat['records'][$table . ':' . $uid]['data'][$field];
2555 // If there has been registered relations inside the flex form field, run processing on the content:
2556 if (!empty($config['flexFormRels']['db']) || !empty($config['flexFormRels']['file'])) {
2557 $origRecordRow = BackendUtility::getRecord($table, $thisNewUid, '*');
2558 // This will fetch the new row for the element (which should be updated with any references to data structures etc.)
2559 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
2560 if (is_array($origRecordRow) && is_array($conf) && $conf['type'] === 'flex') {
2561 // Get current data structure and value array:
2562 $dataStructArray = BackendUtility::getFlexFormDS($conf, $origRecordRow, $table, $field);
2563 $currentValueArray = GeneralUtility::xml2array($updateData[$table][$thisNewUid][$field]);
2564 // Do recursive processing of the XML data:
2565 $iteratorObj = GeneralUtility::makeInstance(DataHandler::class);
2566 $iteratorObj->callBackObj = $this;
2567 $currentValueArray['data'] = $iteratorObj->checkValue_flex_procInData(
2568 $currentValueArray['data'],
2569 array(),
2570 array(),
2571 $dataStructArray,
2572 array($table, $thisNewUid, $field, $config),
2573 'remapListedDBRecords_flexFormCallBack'
2574 );
2575 // The return value is set as an array which means it will be processed by tcemain for file and DB references!
2576 if (is_array($currentValueArray['data'])) {
2577 $updateData[$table][$thisNewUid][$field] = $currentValueArray;
2578 }
2579 }
2580 }
2581 break;
2582 }
2583 }
2584 }
2585 if (!empty($updateData)) {
2586 $tce = $this->getNewTCE();
2587 $tce->isImporting = true;
2588 $this->callHook('before_setFlexFormRelations', array(
2589 'tce' => &$tce,
2590 'data' => &$updateData
2591 ));
2592 $tce->start($updateData, array());
2593 $tce->process_datamap();
2594 $this->callHook('after_setFlexFormRelations', array(
2595 'tce' => &$tce
2596 ));
2597 }
2598 }
2599
2600 /**
2601 * Callback function for traversing the FlexForm structure in relation to remapping database relations
2602 *
2603 * @param array $pParams Set of parameters in numeric array: table, uid, field
2604 * @param array $dsConf TCA config for field (from Data Structure of course)
2605 * @param string $dataValue Field value (from FlexForm XML)
2606 * @param string $dataValue_ext1 Not used
2607 * @param string $dataValue_ext2 Not used
2608 * @param string $path Path of where the data structure of the element is found
2609 * @return array Array where the "value" key carries the value.
2610 * @see setFlexFormRelations()
2611 */
2612 public function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path)
2613 {
2614 // Extract parameters:
2615 list($table, $uid, $field, $config) = $pParams;
2616 // In case the $path is used as index without a trailing slash we will remove that
2617 if (!is_array($config['flexFormRels']['db'][$path]) && is_array($config['flexFormRels']['db'][rtrim($path, '/')])) {
2618 $path = rtrim($path, '/');
2619 }
2620 if (is_array($config['flexFormRels']['db'][$path])) {
2621 $valArray = $this->setRelations_db($config['flexFormRels']['db'][$path], $dsConf);
2622 $dataValue = implode(',', $valArray);
2623 }
2624 if (is_array($config['flexFormRels']['file'][$path])) {
2625 $valArr = array();
2626 foreach ($config['flexFormRels']['file'][$path] as $fI) {
2627 $valArr[] = $this->import_addFileNameToBeCopied($fI);
2628 }
2629 $dataValue = implode(',', $valArr);
2630 }
2631 return array('value' => $dataValue);
2632 }
2633
2634 /**************************
2635 * Import / Soft References
2636 *************************/
2637
2638 /**
2639 * Processing of soft references
2640 *
2641 * @return void
2642 */
2643 public function processSoftReferences()
2644 {
2645 // Initialize:
2646 $inData = array();
2647 // Traverse records:
2648 if (is_array($this->dat['header']['records'])) {
2649 foreach ($this->dat['header']['records'] as $table => $recs) {
2650 foreach ($recs as $uid => $thisRec) {
2651 // If there are soft references defined, traverse those:
2652 if (isset($GLOBALS['TCA'][$table]) && is_array($thisRec['softrefs'])) {
2653 // First traversal is to collect softref configuration and split them up based on fields.
2654 // This could probably also have been done with the "records" key instead of the header.
2655 $fieldsIndex = array();
2656 foreach ($thisRec['softrefs'] as $softrefDef) {
2657 // If a substitution token is set:
2658 if ($softrefDef['field'] && is_array($softrefDef['subst']) && $softrefDef['subst']['tokenID']) {
2659 $fieldsIndex[$softrefDef['field']][$softrefDef['subst']['tokenID']] = $softrefDef;
2660 }
2661 }
2662 // The new id:
2663 $thisNewUid = BackendUtility::wsMapId($table, $this->import_mapId[$table][$uid]);
2664 // Now, if there are any fields that require substitution to be done, lets go for that:
2665 foreach ($fieldsIndex as $field => $softRefCfgs) {
2666 if (is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2667 $conf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
2668 if ($conf['type'] === 'flex') {
2669 // This will fetch the new row for the element (which should be updated with any references to data structures etc.)
2670 $origRecordRow = BackendUtility::getRecord($table, $thisNewUid, '*');
2671 if (is_array($origRecordRow)) {
2672 // Get current data structure and value array:
2673 $dataStructArray = BackendUtility::getFlexFormDS($conf, $origRecordRow, $table, $field);
2674 $currentValueArray = GeneralUtility::xml2array($origRecordRow[$field]);
2675 // Do recursive processing of the XML data:
2676 /** @var $iteratorObj DataHandler */
2677 $iteratorObj = GeneralUtility::makeInstance(DataHandler::class);
2678 $iteratorObj->callBackObj = $this;
2679 $currentValueArray['data'] = $iteratorObj->checkValue_flex_procInData($currentValueArray['data'], array(), array(), $dataStructArray, array($table, $uid, $field, $softRefCfgs), 'processSoftReferences_flexFormCallBack');
2680 // The return value is set as an array which means it will be processed by tcemain for file and DB references!
2681 if (is_array($currentValueArray['data'])) {
2682 $inData[$table][$thisNewUid][$field] = $currentValueArray;
2683 }
2684 }
2685 } else {
2686 // Get tokenizedContent string and proceed only if that is not blank:
2687 $tokenizedContent = $this->dat['records'][$table . ':' . $uid]['rels'][$field]['softrefs']['tokenizedContent'];
2688 if (strlen($tokenizedContent) && is_array($softRefCfgs)) {
2689 $inData[$table][$thisNewUid][$field] = $this->processSoftReferences_substTokens($tokenizedContent, $softRefCfgs, $table, $uid);
2690 }
2691 }
2692 }
2693 }
2694 }
2695 }
2696 }
2697 }
2698 // Now write to database:
2699 $tce = $this->getNewTCE();
2700 $tce->isImporting = true;
2701 $this->callHook('before_processSoftReferences', array(
2702 'tce' => $tce,
2703 'data' => &$inData
2704 ));
2705 $tce->enableLogging = true;
2706 $tce->start($inData, array());
2707 $tce->process_datamap();
2708 $this->callHook('after_processSoftReferences', array(
2709 'tce' => $tce
2710 ));
2711 }
2712
2713 /**
2714 * Callback function for traversing the FlexForm structure in relation to remapping softreference relations
2715 *
2716 * @param array $pParams Set of parameters in numeric array: table, uid, field
2717 * @param array $dsConf TCA config for field (from Data Structure of course)
2718 * @param string $dataValue Field value (from FlexForm XML)
2719 * @param string $dataValue_ext1 Not used
2720 * @param string $dataValue_ext2 Not used
2721 * @param string $path Path of where the data structure where the element is found
2722 * @return array Array where the "value" key carries the value.
2723 * @see setFlexFormRelations()
2724 */
2725 public function processSoftReferences_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path)
2726 {
2727 // Extract parameters:
2728 list($table, $origUid, $field, $softRefCfgs) = $pParams;
2729 if (is_array($softRefCfgs)) {
2730 // First, find all soft reference configurations for this structure path (they are listed flat in the header):
2731 $thisSoftRefCfgList = array();
2732 foreach ($softRefCfgs as $sK => $sV) {
2733 if ($sV['structurePath'] === $path) {
2734 $thisSoftRefCfgList[$sK] = $sV;
2735 }
2736 }
2737 // If any was found, do processing:
2738 if (!empty($thisSoftRefCfgList)) {
2739 // Get tokenizedContent string and proceed only if that is not blank:
2740 $tokenizedContent = $this->dat['records'][$table . ':' . $origUid]['rels'][$field]['flexFormRels']['softrefs'][$path]['tokenizedContent'];
2741 if (strlen($tokenizedContent)) {
2742 $dataValue = $this->processSoftReferences_substTokens($tokenizedContent, $thisSoftRefCfgList, $table, $origUid);
2743 }
2744 }
2745 }
2746 // Return
2747 return array('value' => $dataValue);
2748 }
2749
2750 /**
2751 * Substition of softreference tokens
2752 *
2753 * @param string $tokenizedContent Content of field with soft reference tokens in.
2754 * @param array $softRefCfgs Soft reference configurations
2755 * @param string $table Table for which the processing occurs
2756 * @param string $uid UID of record from table
2757 * @return string The input content with tokens substituted according to entries in softRefCfgs
2758 */
2759 public function processSoftReferences_substTokens($tokenizedContent, $softRefCfgs, $table, $uid)
2760 {
2761 // traverse each softref type for this field:
2762 foreach ($softRefCfgs as $cfg) {
2763 // Get token ID:
2764 $tokenID = $cfg['subst']['tokenID'];
2765 // Default is current token value:
2766 $insertValue = $cfg['subst']['tokenValue'];
2767 // Based on mode:
2768 switch ((string)$this->softrefCfg[$tokenID]['mode']) {
2769 case 'exclude':
2770 // Exclude is a simple passthrough of the value
2771 break;
2772 case 'editable':
2773 // Editable always picks up the value from this input array:
2774 $insertValue = $this->softrefInputValues[$tokenID];
2775 break;
2776 default:
2777 // Mapping IDs/creating files: Based on type, look up new value:
2778 switch ((string)$cfg['subst']['type']) {
2779 case 'file':
2780 // Create / Overwrite file:
2781 $insertValue = $this->processSoftReferences_saveFile($cfg['subst']['relFileName'], $cfg, $table, $uid);
2782 break;
2783 case 'db':
2784 default:
2785 // Trying to map database element if found in the mapID array:
2786 list($tempTable, $tempUid) = explode(':', $cfg['subst']['recordRef']);
2787 if (isset($this->import_mapId[$tempTable][$tempUid])) {
2788 $insertValue = BackendUtility::wsMapId($tempTable, $this->import_mapId[$tempTable][$tempUid]);
2789 // 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!
2790 if ($tempTable === 'pages' && !MathUtility::canBeInterpretedAsInteger($cfg['subst']['tokenValue'])) {
2791 $recWithUniqueValue = BackendUtility::getRecord($tempTable, $insertValue, 'alias');
2792 if ($recWithUniqueValue['alias']) {
2793 $insertValue = $recWithUniqueValue['alias'];
2794 }
2795 } elseif (strpos($cfg['subst']['tokenValue'], ':') !== false) {
2796 list($tokenKey) = explode(':', $cfg['subst']['tokenValue']);
2797 $insertValue = $tokenKey . ':' . $insertValue;
2798 }
2799 }
2800 }
2801 }
2802 // Finally, swap the soft reference token in tokenized content with the insert value:
2803 $tokenizedContent = str_replace('{softref:' . $tokenID . '}', $insertValue, $tokenizedContent);
2804 }
2805 return $tokenizedContent;
2806 }
2807
2808 /**
2809 * Process a soft reference file
2810 *
2811 * @param string $relFileName Old Relative filename
2812 * @param array $cfg soft reference configuration array
2813 * @param string $table Table for which the processing occurs
2814 * @param string $uid UID of record from table
2815 * @return string New relative filename (value to insert instead of the softref token)
2816 */
2817 public function processSoftReferences_saveFile($relFileName, $cfg, $table, $uid)
2818 {
2819 if ($fileHeaderInfo = $this->dat['header']['files'][$cfg['file_ID']]) {
2820 // Initialize; Get directory prefix for file and find possible RTE filename
2821 $dirPrefix = PathUtility::dirname($relFileName) . '/';
2822 $rteOrigName = $this->getRTEoriginalFilename(PathUtility::basename($relFileName));
2823 // If filename looks like an RTE file, and the directory is in "uploads/", then process as a RTE file!
2824 if ($rteOrigName && GeneralUtility::isFirstPartOfStr($dirPrefix, 'uploads/')) {
2825 // RTE:
2826 // First, find unique RTE file name:
2827 if (@is_dir((PATH_site . $dirPrefix))) {
2828 // From the "original" RTE filename, produce a new "original" destination filename which is unused.
2829 // Even if updated, the image should be unique. Currently the problem with this is that it leaves a lot of unused RTE images...
2830 $fileProcObj = $this->getFileProcObj();
2831 $origDestName = $fileProcObj->getUniqueName($rteOrigName, PATH_site . $dirPrefix);
2832 // Create copy file name:
2833 $pI = pathinfo($relFileName);
2834 $copyDestName = PathUtility::dirname($origDestName) . '/RTEmagicC_' . substr(PathUtility::basename($origDestName), 10) . '.' . $pI['extension'];
2835 if (
2836 !@is_file($copyDestName) && !@is_file($origDestName)
2837 && $origDestName === GeneralUtility::getFileAbsFileName($origDestName)
2838 && $copyDestName === GeneralUtility::getFileAbsFileName($copyDestName)
2839 ) {
2840 if ($this->dat['header']['files'][$fileHeaderInfo['RTE_ORIG_ID']]) {
2841 if ($this->legacyImport) {
2842 $fileName = PathUtility::basename($copyDestName);
2843 $this->writeSysFileResourceForLegacyImport($fileName, $cfg['file_ID']);
2844 $relFileName = $this->filePathMap[$cfg['file_ID']] . '" data-htmlarea-file-uid="' . $fileName . '" data-htmlarea-file-table="sys_file';
2845 // Also save the original file
2846 $originalFileName = PathUtility::basename($origDestName);
2847 $this->writeSysFileResourceForLegacyImport($originalFileName, $fileHeaderInfo['RTE_ORIG_ID']);
2848 } else {
2849 // Write the copy and original RTE file to the respective filenames:
2850 $this->writeFileVerify($copyDestName, $cfg['file_ID'], true);
2851 $this->writeFileVerify($origDestName, $fileHeaderInfo['RTE_ORIG_ID'], true);
2852 // Return the relative path of the copy file name:
2853 return PathUtility::stripPathSitePrefix($copyDestName);
2854 }
2855 } else {
2856 $this->error('ERROR: Could not find original file ID');
2857 }
2858 } else {
2859 $this->error('ERROR: The destination filenames "' . $copyDestName . '" and "' . $origDestName . '" either existed or have non-valid names');
2860 }
2861 } else {
2862 $this->error('ERROR: "' . PATH_site . $dirPrefix . '" was not a directory, so could not process file "' . $relFileName . '"');
2863 }
2864 } elseif (GeneralUtility::isFirstPartOfStr($dirPrefix, $this->fileadminFolderName . '/')) {
2865 // File in fileadmin/ folder:
2866 // Create file (and possible resources)
2867 $newFileName = $this->processSoftReferences_saveFile_createRelFile($dirPrefix, PathUtility::basename($relFileName), $cfg['file_ID'], $table, $uid);
2868 if (strlen($newFileName)) {
2869 $relFileName = $newFileName;
2870 } else {
2871 $this->error('ERROR: No new file created for "' . $relFileName . '"');
2872 }
2873 } else {
2874 $this->error('ERROR: Sorry, cannot operate on non-RTE files which are outside the fileadmin folder.');
2875 }
2876 } else {
2877 $this->error('ERROR: Could not find file ID in header.');
2878 }
2879 // Return (new) filename relative to PATH_site:
2880 return $relFileName;
2881 }
2882
2883 /**
2884 * Create file in directory and return the new (unique) filename
2885 *
2886 * @param string $origDirPrefix Directory prefix, relative, with trailing slash
2887 * @param string $fileName Filename (without path)
2888 * @param string $fileID File ID from import memory
2889 * @param string $table Table for which the processing occurs
2890 * @param string $uid UID of record from table
2891 * @return string|NULL New relative filename, if any
2892 */
2893 public function processSoftReferences_saveFile_createRelFile($origDirPrefix, $fileName, $fileID, $table, $uid)
2894 {
2895 // If the fileID map contains an entry for this fileID then just return the relative filename of that entry;
2896 // we don't want to write another unique filename for this one!
2897 if (isset($this->fileIDMap[$fileID])) {
2898 return PathUtility::stripPathSitePrefix($this->fileIDMap[$fileID]);
2899 }
2900 if ($this->legacyImport) {
2901 // set dirPrefix to fileadmin because the right target folder is set and checked for permissions later
2902 $dirPrefix = $this->fileadminFolderName . '/';
2903 } else {
2904 // Verify FileMount access to dir-prefix. Returns the best alternative relative path if any
2905 $dirPrefix = $this->verifyFolderAccess($origDirPrefix);
2906 }
2907 if ($dirPrefix && (!$this->update || $origDirPrefix === $dirPrefix) && $this->checkOrCreateDir($dirPrefix)) {
2908 $fileHeaderInfo = $this->dat['header']['files'][$fileID];
2909 $updMode = $this->update && $this->import_mapId[$table][$uid] === $uid && $this->import_mode[$table . ':' . $uid] !== 'as_new';
2910 // Create new name for file:
2911 // Must have same ID in map array (just for security, is not really needed) and NOT be set "as_new".
2912
2913 // Write main file:
2914 if ($this->legacyImport) {
2915 $fileWritten = $this->writeSysFileResourceForLegacyImport($fileName, $fileID);
2916 if ($fileWritten) {
2917 $newName = 'file:' . $fileName;
2918 return $newName;
2919 // no support for HTML/CSS file resources attached ATM - see below
2920 }
2921 } else {
2922 if ($updMode) {
2923 $newName = PATH_site . $dirPrefix . $fileName;
2924 } else {
2925 // Create unique filename:
2926 $fileProcObj = $this->getFileProcObj();
2927 $newName = $fileProcObj->getUniqueName($fileName, PATH_site . $dirPrefix);
2928 }
2929 if ($this->writeFileVerify($newName, $fileID)) {
2930 // If the resource was an HTML/CSS file with resources attached, we will write those as well!
2931 if (is_array($fileHeaderInfo['EXT_RES_ID'])) {
2932 $tokenizedContent = $this->dat['files'][$fileID]['tokenizedContent'];
2933 $tokenSubstituted = false;
2934 $fileProcObj = $this->getFileProcObj();
2935 if ($updMode) {
2936 foreach ($fileHeaderInfo['EXT_RES_ID'] as $res_fileID) {
2937 if ($this->dat['files'][$res_fileID]['filename']) {
2938 // Resolve original filename:
2939 $relResourceFileName = $this->dat['files'][$res_fileID]['parentRelFileName'];
2940 $absResourceFileName = GeneralUtility::resolveBackPath(PATH_site . $origDirPrefix . $relResourceFileName);
2941 $absResourceFileName = GeneralUtility::getFileAbsFileName($absResourceFileName);
2942 if ($absResourceFileName && GeneralUtility::isFirstPartOfStr($absResourceFileName, PATH_site . $this->fileadminFolderName . '/')) {
2943 $destDir = PathUtility::stripPathSitePrefix(PathUtility::dirname($absResourceFileName) . '/');
2944 if ($this->verifyFolderAccess($destDir, true) && $this->checkOrCreateDir($destDir)) {
2945 $this->writeFileVerify($absResourceFileName, $res_fileID);
2946 } else {
2947 $this->error('ERROR: Could not create file in directory "' . $destDir . '"');
2948 }
2949 } else {
2950 $this->error('ERROR: Could not resolve path for "' . $relResourceFileName . '"');
2951 }
2952 $tokenizedContent = str_replace('{EXT_RES_ID:' . $res_fileID . '}', $relResourceFileName, $tokenizedContent);
2953 $tokenSubstituted = true;
2954 }
2955 }
2956 } else {
2957 // Create the resouces directory name (filename without extension, suffixed "_FILES")
2958 $resourceDir = PathUtility::dirname($newName) . '/' . preg_replace('/\\.[^.]*$/', '', PathUtility::basename($newName)) . '_FILES';
2959 if (GeneralUtility::mkdir($resourceDir)) {
2960 foreach ($fileHeaderInfo['EXT_RES_ID'] as $res_fileID) {
2961 if ($this->dat['files'][$res_fileID]['filename']) {
2962 $absResourceFileName = $fileProcObj->getUniqueName($this->dat['files'][$res_fileID]['filename'], $resourceDir);