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