-
Notifications
You must be signed in to change notification settings - Fork 649
/
ImportExport.php
1518 lines (1384 loc) · 58.7 KB
/
ImportExport.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Impexp;
use TYPO3\CMS\Backend\Routing\PreviewUriBuilder;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\DataHandling\PageDoktypeRegistry;
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Imaging\IconSize;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Resource\DefaultUploadFolderResolver;
use TYPO3\CMS\Core\Resource\Exception;
use TYPO3\CMS\Core\Resource\Exception\InsufficientFolderAccessPermissionsException;
use TYPO3\CMS\Core\Resource\Folder;
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\Resource\Security\FileNameValidator;
use TYPO3\CMS\Core\Type\Bitmask\Permission;
use TYPO3\CMS\Core\Utility\DiffUtility;
use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
/**
* T3D file Import / Export library (TYPO3 Record Document)
*
* @internal This class is not considered part of the public TYPO3 API.
*/
abstract class ImportExport
{
/**
* Whether "import" or "export" mode of object.
*
* @var string
*/
protected string $mode = '';
/**
* A WHERE clause for selection records from the pages table based on read-permissions of the current backend user.
*/
protected string $permsClause;
/**
* Root page of import or export page tree
*/
protected int $pid = -1;
/**
* Root page record of import or of export page tree
*/
protected ?array $pidRecord = null;
/**
* If set, static relations (not exported) will be shown in preview as well
*/
protected bool $showStaticRelations = false;
/**
* Updates all records that has same UID instead of creating new!
*/
protected bool $update = false;
/**
* Set by importData() when an import is started.
*/
protected bool $doesImport = false;
/**
* Setting the import mode for specific import records.
* Available options are: force_uid, as_new, exclude, ignore_pid, respect_pid
*/
protected array $importMode = [];
/**
* If set, PID correct is ignored globally
*/
protected bool $globalIgnorePid = false;
/**
* If set, all UID values are forced! (update or import)
*/
protected bool $forceAllUids = false;
/**
* If set, a diff-view column is added to the preview.
*/
protected bool $showDiff = false;
/**
* Array of values to substitute in editable soft references.
*/
protected array $softrefInputValues = [];
/**
* Mapping between the fileID from import memory and the final filenames they are written to.
*/
protected array $fileIdMap = [];
/**
* Add tables names here which should not be exported with the file.
* (Where relations should be mapped to same UIDs in target system).
*/
protected array $relStaticTables = [];
/**
* Exclude map. Keys are table:uid pairs and if set, records are not added to the export.
*/
protected array $excludeMap = [];
/**
* Soft reference token ID modes.
*/
protected array $softrefCfg = [];
/**
* Listing extension dependencies.
*/
protected array $extensionDependencies = [];
/**
* After records are written this array is filled with [table][original_uid] = [new_uid]
*/
protected array $importMapId = [];
/**
* Error log.
*/
protected array $errorLog = [];
/**
* Cache for record paths
*/
protected array $cacheGetRecordPath = [];
/**
* Internal import/export memory
*/
protected array $dat = [];
/**
* File processing object
*/
protected ?ExtendedFileUtility $fileProcObj = null;
protected array $remainHeader = [];
protected LanguageService $lang;
protected IconFactory $iconFactory;
protected ?string $temporaryFolderName = null;
protected ?Folder $defaultImportExportFolder = null;
/**
* Flag to control whether all disabled records and their children are excluded (true) or included (false). Defaults
* to the old behaviour of including everything.
*/
protected bool $excludeDisabledRecords = false;
public function __construct()
{
$this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
$this->lang = $this->getLanguageService();
$this->permsClause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW);
}
/********************************************************
* Visual rendering of import/export memory, $this->dat
********************************************************/
/**
* Displays a preview of the import or export.
*
* @return array The preview data
*/
public function renderPreview(): array
{
// @todo: Why is this done?
unset($this->dat['files']);
$previewData = [
'update' => $this->update,
'showDiff' => $this->showDiff,
'insidePageTree' => [],
'outsidePageTree' => [],
];
if (!isset($this->dat['header']['pagetree']) && !isset($this->dat['header']['records'])) {
return $previewData;
}
// Traverse header:
$this->remainHeader = $this->dat['header'];
// Preview of the page tree to be exported
if (is_array($this->dat['header']['pagetree'] ?? null)) {
$this->traversePageTree($this->dat['header']['pagetree'], $previewData['insidePageTree']);
foreach ($previewData['insidePageTree'] as &$line) {
$line['controls'] = $this->renderControls($line);
$line['message'] = (!empty($line['msg']) && !$this->doesImport ? '<span class="text-danger">' . htmlspecialchars($line['msg']) . '</span>' : '');
}
}
// Preview the remaining records that were not included in the page tree
if (is_array($this->remainHeader['records'] ?? null)) {
if (is_array($this->remainHeader['records']['pages'] ?? null)) {
$this->traversePageRecords($this->remainHeader['records']['pages'], $previewData['outsidePageTree']);
}
$this->traverseAllRecords($this->remainHeader['records'], $previewData['outsidePageTree']);
foreach ($previewData['outsidePageTree'] as &$line) {
$line['controls'] = $this->renderControls($line);
$line['message'] = (!empty($line['msg']) && !$this->doesImport ? '<span class="text-danger">' . htmlspecialchars($line['msg']) . '</span>' : '');
}
}
return $previewData;
}
/**
* Go through page tree for display
*
* @param array<int, array> $pageTree Page tree array with uid/subrow (from ->dat[header][pagetree])
* @param array $lines Output lines array
* @param int $indent Indentation level
*/
protected function traversePageTree(array $pageTree, array &$lines, int $indent = 0): void
{
foreach ($pageTree as $pageUid => $page) {
if ($this->excludeDisabledRecords === true && $this->isRecordDisabled('pages', $pageUid)) {
$this->excludePageAndRecords($pageUid, $page);
continue;
}
// Add page
$this->addRecord('pages', $pageUid, $lines, $indent);
// Add records
foreach ($this->dat['header']['pid_lookup'][$pageUid] ?? [] as $table => $records) {
$table = (string)$table;
if ($table !== 'pages') {
foreach (array_keys($records) as $uid) {
$this->addRecord($table, (int)$uid, $lines, $indent + 1);
}
}
}
unset($this->remainHeader['pid_lookup'][$pageUid]);
// Add subtree
if (is_array($page['subrow'] ?? null)) {
$this->traversePageTree($page['subrow'], $lines, $indent + 1);
}
}
}
/**
* Test whether a record is disabled (e.g. hidden)
*
* @param string $table Name of the records' database table
* @param int $uid Database uid of the record
* @return bool true if the record is disabled, false otherwise
*/
protected function isRecordDisabled(string $table, int $uid): bool
{
return (bool)($this->dat['records'][$table . ':' . $uid]['data'][
$GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'] ?? ''
] ?? false);
}
/**
* Exclude a page, its sub pages (recursively) and records placed in them from this import/export
*
* @param int $pageUid Uid of the page to exclude
* @param array $page Page array with uid/subrow (from ->dat[header][pagetree])
*/
protected function excludePageAndRecords(int $pageUid, array $page): void
{
// Exclude page
unset($this->remainHeader['records']['pages'][$pageUid]);
// Exclude records
foreach ($this->dat['header']['pid_lookup'][$pageUid] ?? [] as $table => $records) {
if ($table !== 'pages') {
foreach (array_keys($records) as $uid) {
unset($this->remainHeader['records'][$table][$uid]);
}
}
}
unset($this->remainHeader['pid_lookup'][$pageUid]);
// Exclude subtree
foreach ($page['subrow'] ?? [] as $subPageUid => $subPage) {
$this->excludePageAndRecords($subPageUid, $subPage);
}
}
/**
* Go through remaining pages (not in tree)
*
* @param array<int, array> $pageTree Page tree array with uid/subrow (from ->dat[header][pagetree])
* @param array $lines Output lines array
*/
protected function traversePageRecords(array $pageTree, array &$lines): void
{
foreach ($pageTree as $pageUid => $_) {
// Add page
$this->addRecord('pages', (int)$pageUid, $lines, 0, true);
// Add records
foreach ($this->dat['header']['pid_lookup'][$pageUid] ?? [] as $table => $records) {
if ($table !== 'pages') {
foreach (array_keys($records) as $uid) {
$this->addRecord((string)$table, (int)$uid, $lines, 2);
}
}
}
unset($this->remainHeader['pid_lookup'][$pageUid]);
}
}
/**
* Go through ALL records (if the pages are displayed first, those will not be among these!)
*
* @param array $pageTree Page tree array with uid/subrow (from ->dat[header][pagetree])
* @param array $lines Output lines array
*/
protected function traverseAllRecords(array $pageTree, array &$lines): void
{
foreach ($pageTree as $table => $records) {
$this->addGeneralErrorsByTable($table);
if ($table !== 'pages') {
foreach (array_keys($records) as $uid) {
$this->addRecord((string)$table, (int)$uid, $lines, 0, true);
}
}
}
}
/**
* Log general error message for a given table
*
* @param string $table database table name
*/
protected function addGeneralErrorsByTable(string $table): void
{
if ($this->update && $table === 'sys_file') {
$this->addError('Updating sys_file records is not supported! They will be imported as new records!');
}
if ($this->forceAllUids && $table === 'sys_file') {
$this->addError('Forcing uids of sys_file records is not supported! They will be imported as new records!');
}
}
/**
* Add a record, its relations and soft references, to the preview
*
* @param string $table Table name
* @param int $uid Record uid
* @param array $lines Output lines array
* @param int $indent Indentation level
* @param bool $checkImportInPidRecord If you want import validation, you can set this so it checks if the import can take place on the specified page.
*/
protected function addRecord(string $table, int $uid, array &$lines, int $indent, bool $checkImportInPidRecord = false): void
{
$record = $this->dat['header']['records'][$table][$uid] ?? null;
unset($this->remainHeader['records'][$table][$uid]);
if (!is_array($record) && !($table === 'pages' && $uid === 0)) {
$this->addError('MISSING RECORD: ' . $table . ':' . $uid);
}
// Create record information for preview
$line = [];
$line['ref'] = $table . ':' . $uid;
$line['type'] = 'record';
$line['msg'] = '';
if ($table === '_SOFTREF_') {
// Record is a soft reference
$line['preCode'] = $this->renderIndent($indent);
$line['title'] = '<em>' . htmlspecialchars($this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_softReferencesFiles')) . '</em>';
} elseif (!isset($GLOBALS['TCA'][$table])) {
// Record is of unknown table
$line['preCode'] = $this->renderIndent($indent);
$line['title'] = '<em>' . htmlspecialchars((string)$record['title']) . '</em>';
$line['msg'] = 'UNKNOWN TABLE "' . $line['ref'] . '"';
} else {
$pidRecord = $this->getPidRecord();
$line['preCode'] = ''
. $this->renderIndent($indent)
. $this->iconFactory
->getIconForRecord(
$table,
(array)($this->dat['records'][$table . ':' . $uid]['data'] ?? []),
IconSize::SMALL
)
->setTitle($line['ref'])
->render();
$line['title'] = htmlspecialchars($record['title'] ?? '');
// Link to page view
if ($table === 'pages') {
$viewID = $this->mode === 'export' ? $uid : ($this->doesImport ? ($this->importMapId['pages'][$uid] ?? 0) : 0);
if ($viewID) {
$attributes = PreviewUriBuilder::create($viewID)->serializeDispatcherAttributes();
if ($attributes) {
$line['title'] = sprintf('<a href="#" %s>%s</a>', $attributes, $line['title']);
}
}
}
$line['active'] = !$this->isRecordDisabled($table, $uid) ? 'active' : 'hidden';
if ($this->mode === 'import' && $pidRecord !== null) {
if ($checkImportInPidRecord) {
if (!$this->getBackendUser()->doesUserHaveAccess($pidRecord, ($table === 'pages' ? 8 : 16))) {
$line['msg'] .= '"' . $line['ref'] . '" cannot be INSERTED on this page! ';
}
if ($this->pid > 0 && !$this->checkDokType($table, $pidRecord['doktype']) && !($GLOBALS['TCA'][$table]['ctrl']['rootLevel'] ?? 0)) {
$line['msg'] .= '"' . $table . '" cannot be INSERTED on this page type (change page type to "Folder".) ';
}
}
if (!$this->getBackendUser()->check('tables_modify', $table)) {
$line['msg'] .= 'You are not allowed to CREATE "' . $table . '" tables! ';
}
if ($GLOBALS['TCA'][$table]['ctrl']['readOnly'] ?? false) {
$line['msg'] .= 'TABLE "' . $table . '" is READ ONLY! ';
}
if (($GLOBALS['TCA'][$table]['ctrl']['adminOnly'] ?? false) && !$this->getBackendUser()->isAdmin()) {
$line['msg'] .= 'TABLE "' . $table . '" is ADMIN ONLY! ';
}
if ($GLOBALS['TCA'][$table]['ctrl']['is_static'] ?? false) {
$line['msg'] .= 'TABLE "' . $table . '" is a STATIC TABLE! ';
}
if ((int)($GLOBALS['TCA'][$table]['ctrl']['rootLevel'] ?? 0) === 1) {
$line['msg'] .= 'TABLE "' . $table . '" will be inserted on ROOT LEVEL! ';
}
$databaseRecord = null;
if ($this->update) {
$databaseRecord = $this->getRecordFromDatabase($table, $uid, $this->showDiff ? '*' : 'uid,pid');
if ($databaseRecord === null) {
$line['updatePath'] = '<strong>NEW!</strong>';
} else {
$line['updatePath'] = htmlspecialchars($this->getRecordPath((int)($databaseRecord['pid'] ?? 0)));
}
if ($table === 'sys_file') {
$line['updateMode'] = '';
} else {
$line['updateMode'] = $this->renderImportModeSelector(
$table,
$uid,
$databaseRecord !== null
);
}
}
// Diff view
if ($this->showDiff) {
$diffInverse = $this->update;
// For imports, get new id:
if (isset($this->importMapId[$table][$uid]) && $newUid = $this->importMapId[$table][$uid]) {
$diffInverse = false;
$databaseRecord = $this->getRecordFromDatabase($table, $newUid, '*');
BackendUtility::workspaceOL($table, $databaseRecord);
}
/** @var array|null $importRecord */
$importRecord = $this->dat['records'][$table . ':' . $uid]['data'] ?? null;
if ($databaseRecord === null) {
$line['showDiffContent'] = '';
} elseif (is_array($databaseRecord) && is_array($importRecord)) {
$line['showDiffContent'] = $this->compareRecords($databaseRecord, $importRecord, $table, $diffInverse);
} else {
$line['showDiffContent'] = 'ERROR: One of the inputs were not an array!';
}
}
}
}
$lines[] = $line;
// File relations
if (is_array($record['filerefs'] ?? null)) {
$this->addFiles($record['filerefs'], $lines, $indent);
}
// Database relations
if (is_array($record['rels'] ?? null)) {
$this->addRelations($record['rels'], $lines, $indent);
}
// Soft references
if (is_array($record['softrefs'] ?? null)) {
$this->addSoftRefs($record['softrefs'], $lines, $indent);
}
}
/**
* Add database relations of a record to the preview
*
* @param array $relations Array of relations
* @param array $lines Output lines array
* @param int $indent Indentation level
* @param array $recursionCheck Recursion check stack
*
* @see addRecord()
*/
protected function addRelations(array $relations, array &$lines, int $indent, array $recursionCheck = []): void
{
foreach ($relations as $relation) {
$table = $relation['table'];
$uid = $relation['id'];
$line = [];
$line['ref'] = $table . ':' . $uid;
$line['type'] = 'rel';
$line['msg'] = '';
if (in_array($line['ref'], $recursionCheck, true)) {
continue;
}
$iconName = 'status-status-checked';
$staticFixed = false;
$record = null;
if ($uid > 0) {
$record = $this->dat['header']['records'][$table][$uid] ?? null;
if (!is_array($record)) {
if ($this->isTableStatic($table) || $this->isRecordExcluded($table, (int)$uid)
|| ($relation['tokenID'] ?? '') && !$this->isSoftRefIncluded($relation['tokenID'] ?? '')) {
$line['title'] = htmlspecialchars('STATIC: ' . $line['ref']);
$staticFixed = true;
} else {
$databaseRecord = $this->getRecordFromDatabase($table, (int)$uid);
$recordPath = $this->getRecordPath($databaseRecord === null ? 0 : ($table === 'pages' ? (int)$databaseRecord['uid'] : (int)$databaseRecord['pid']));
$line['title'] = sprintf(
'<span title="%s">%s</span>',
htmlspecialchars($recordPath),
htmlspecialchars($line['ref'])
);
$line['msg'] = 'LOST RELATION' . ($databaseRecord === null ? ' (Record not found!)' : ' (Path: ' . $recordPath . ')');
$iconName = 'status-dialog-warning';
}
} else {
$recordPath = $this->getRecordPath($table === 'pages' ? (int)$record['uid'] : (int)$record['pid']);
$line['title'] = sprintf(
'<span title="%s">%s</span>',
htmlspecialchars($recordPath),
htmlspecialchars((string)$record['title'])
);
}
} else {
// Negative values in relation fields. These are typically fields of e.g. fe_users.
// They are static values. They CAN theoretically be negative pointers to uids in other tables,
// but this is so rarely used that it is not supported.
$line['title'] = htmlspecialchars('FIXED: ' . $line['ref']);
$staticFixed = true;
}
$line['preCode'] = ''
. $this->renderIndent($indent + 1)
. $this->iconFactory
->getIcon($iconName, IconSize::SMALL)
->setTitle($line['ref'])
->render();
if (!$staticFixed || $this->showStaticRelations) {
$lines[] = $line;
if (is_array($record) && is_array($record['rels'] ?? null)) {
$this->addRelations($record['rels'], $lines, $indent + 1, array_merge($recursionCheck, [$line['ref']]));
}
}
}
}
/**
* Add file relations of a record to the preview.
*
* Public access for testing purpose only.
*
* @param array $relations Array of file IDs
* @param array $lines Output lines array
* @param int $indent Indentation level
* @param string $tokenID Token ID if this is a soft reference (in which case it only makes sense with a single element in the $relations array!)
*
* @see addRecord()
*/
public function addFiles(array $relations, array &$lines, int $indent, string $tokenID = ''): void
{
foreach ($relations as $ID) {
$line = [];
$line['msg'] = '';
$fileInfo = $this->dat['header']['files'][$ID] ?? null;
if (!is_array($fileInfo)) {
if ($tokenID !== '' || $this->isSoftRefIncluded($tokenID)) {
$line['msg'] = 'MISSING FILE: ' . $ID;
$this->addError('MISSING FILE: ' . $ID);
// In case of an error, this relation shall be unset,
// so that no follow-up errors on the missing file
// softref can occur.
unset($this->remainHeader['files'][$ID]);
$line['type'] = '';
$lines[] = $line;
continue;
}
return;
}
$line['ref'] = 'FILE';
$line['type'] = 'file';
$line['preCode'] = ''
. $this->renderIndent($indent + 1)
. $this->iconFactory
->getIcon('status-reference-hard', IconSize::SMALL)
->setTitle($line['ref'])
->render();
$line['title'] = htmlspecialchars($fileInfo['filename'] ?? 'Missing filename');
$line['showDiffContent'] = PathUtility::stripPathSitePrefix((string)($this->fileIdMap[$ID] ?? ''));
// If import mode and there is a soft reference, check the destination directory.
if ($this->mode === 'import' && $tokenID !== '') {
// Check folder existence
if (isset($fileInfo['parentRelFileName'])) {
$line['msg'] = 'Seems like this file is already referenced from within an HTML/CSS file. That takes precedence. ';
} elseif (isset($fileInfo['relFileName'])) {
$origDirPrefix = PathUtility::dirname($fileInfo['relFileName']) . '/';
$dirPrefix = $this->resolveStoragePath($origDirPrefix);
if ($dirPrefix === null) {
$line['msg'] = 'ERROR: There are no available file mounts to write file in!';
} elseif ($origDirPrefix !== $dirPrefix) {
$line['msg'] = 'File will be attempted written to "' . $dirPrefix . '". ';
}
}
// Check file existence
if (file_exists(Environment::getPublicPath() . '/' . $fileInfo['relFileName'])) {
if ($this->update) {
$line['updatePath'] = 'File exists.';
} else {
$line['msg'] .= 'File already exists! ';
}
}
// Check file extension
$fileProcObj = $this->getFileProcObj();
if ($fileProcObj->actionPerms['addFile']) {
$pathInfo = GeneralUtility::split_fileref(Environment::getPublicPath() . '/' . $fileInfo['relFileName']);
if (!GeneralUtility::makeInstance(FileNameValidator::class)->isValid($pathInfo['file'])) {
$line['msg'] .= 'File extension was not allowed!';
}
} else {
$line['msg'] = 'Your user profile does not allow you to create files on the server!';
}
}
$lines[] = $line;
unset($this->remainHeader['files'][$ID]);
// External resources
foreach ($fileInfo['EXT_RES_ID'] ?? [] as $extID) {
$line = [];
$fileInfo = $this->dat['header']['files'][$extID];
if (!is_array($fileInfo)) {
$line['msg'] = 'MISSING External Resource FILE: ' . $extID;
$this->addError('MISSING External Resource FILE: ' . $extID);
} else {
$line['updatePath'] = $fileInfo['parentRelFileName'];
}
$line['ref'] = 'FILE';
$line['type'] = 'file';
$line['preCode'] = ''
. $this->renderIndent($indent + 1)
. $this->iconFactory
->getIcon('actions-insert-reference', IconSize::SMALL)
->setTitle($line['ref'])
->render();
$line['title'] = htmlspecialchars($fileInfo['filename']) . ' <em>(Resource)</em>';
$line['showDiffContent'] = PathUtility::stripPathSitePrefix($this->fileIdMap[$extID]);
$lines[] = $line;
unset($this->remainHeader['files'][$extID]);
}
}
}
/**
* Add soft references of a record to the preview
*
* @param array $softrefs Soft references
* @param array $lines Output lines array
* @param int $indent Indentation level
*
* @see addRecord()
*/
protected function addSoftRefs(array $softrefs, array &$lines, int $indent): void
{
foreach ($softrefs as $softref) {
$line = [];
$line['ref'] = 'SOFTREF';
$line['type'] = 'softref';
$line['msg'] = '';
$line['preCode'] = ''
. $this->renderIndent($indent)
. $this->iconFactory
->getIcon('status-reference-soft', IconSize::SMALL)
->setTitle($line['ref'])
->render();
$line['title'] = sprintf(
'<em>%s, "%s"</em>: <span title="%s">%s</span>',
$softref['field'],
$softref['spKey'],
htmlspecialchars($softref['matchString'] ?? ''),
htmlspecialchars(GeneralUtility::fixed_lgd_cs($softref['matchString'] ?? '', 60))
);
if ($softref['subst']['type'] ?? false) {
if ($softref['subst']['title'] ?? false) {
$line['title'] .= sprintf(
'<br>%s <strong>%s</strong> %s',
$this->renderIndent($indent + 1),
htmlspecialchars($this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_title')),
htmlspecialchars(GeneralUtility::fixed_lgd_cs($softref['subst']['title'], 60))
);
}
if ($softref['subst']['description'] ?? false) {
$line['title'] .= sprintf(
'<br>%s <strong>%s</strong> %s',
$this->renderIndent($indent + 1),
htmlspecialchars($this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_descr')),
htmlspecialchars(GeneralUtility::fixed_lgd_cs($softref['subst']['description'], 60))
);
}
if ($softref['subst']['type'] === 'db') {
$line['title'] .= sprintf(
'<br>%s <strong>%s</strong> %s',
$this->renderIndent($indent + 1),
htmlspecialchars($this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_softrefsel_record')),
$softref['subst']['recordRef']
);
} elseif ($softref['subst']['type'] === 'file') {
$line['title'] .= sprintf(
'<br>%s <strong>%s</strong> %s',
$this->renderIndent($indent + 1),
htmlspecialchars($this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_filename')),
$softref['subst']['relFileName']
);
} elseif ($softref['subst']['type'] === 'string') {
$line['title'] .= sprintf(
'<br>%s <strong>%s</strong> %s',
$this->renderIndent($indent + 1),
htmlspecialchars($this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_value')),
$softref['subst']['tokenValue']
);
}
}
$line['_softRefInfo'] = $softref;
$mode = $this->softrefCfg[$softref['subst']['tokenID'] ?? null]['mode'] ?? '';
if (isset($softref['error']) && $mode !== Import::SOFTREF_IMPORT_MODE_EDITABLE && $mode !== Import::SOFTREF_IMPORT_MODE_EXCLUDE) {
$line['msg'] .= $softref['error'];
}
$lines[] = $line;
// Add database relations
if (($softref['subst']['type'] ?? '') === 'db') {
[$referencedTable, $referencedUid] = explode(':', $softref['subst']['recordRef']);
$relations = [['table' => $referencedTable, 'id' => $referencedUid, 'tokenID' => $softref['subst']['tokenID']]];
$this->addRelations($relations, $lines, $indent + 1);
}
// Add files relations
if (($softref['subst']['type'] ?? '') === 'file') {
$relations = [$softref['file_ID']];
$this->addFiles($relations, $lines, $indent + 1, $softref['subst']['tokenID']);
}
}
}
protected function renderIndent(int $indent): string
{
return $indent > 0 ? '<span class="indent indent-inline-block" style="--indent-level: ' . $indent . '"></span>' : '';
}
/**
* Verifies that a table is allowed on a certain doktype of a page.
*
* @param string $table Table name to check
* @param int $dokType Page doktype
* @return bool TRUE if OK
*/
protected function checkDokType(string $table, int $dokType): bool
{
return GeneralUtility::makeInstance(PageDoktypeRegistry::class)->isRecordTypeAllowedForDoktype($table, $dokType);
}
/**
* Render input controls for import or export
*
* @param array $line Output line array
* @return string HTML
*/
protected function renderControls(array $line): string
{
if ($this->mode === 'export') {
if ($line['type'] === 'record') {
return $this->renderRecordExcludeCheckbox($line['ref']);
}
if ($line['type'] === 'softref') {
return $this->renderSoftRefExportSelector($line['_softRefInfo']);
}
} elseif ($this->mode === 'import') {
if ($line['type'] === 'softref') {
return $this->renderSoftRefImportTextField($line['_softRefInfo']);
}
}
return '';
}
/**
* Render check box for exclusion of a record from export.
*
* @param string $recordRef The record ID of the form [table]:[id].
* @return string HTML
*/
protected function renderRecordExcludeCheckbox(string $recordRef): string
{
return ''
. '<div class="form-check mb-0">'
. '<input class="form-check-input t3js-exclude-checkbox" type="checkbox" name="tx_impexp[exclude][' . $recordRef . ']" id="checkExclude' . $recordRef . '" value="1" />'
. '<label class="form-check-label" for="checkExclude' . $recordRef . '">' . htmlspecialchars($this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_exclude')) . '</label>'
. '</div>';
}
/**
* Render text field when importing a soft reference.
*
* @param array $softref Soft reference
* @return string HTML
*/
protected function renderSoftRefImportTextField(array $softref): string
{
if (isset($softref['subst']['tokenID'])) {
$tokenID = $softref['subst']['tokenID'];
$cfg = $this->softrefCfg[$tokenID] ?? [];
if (($cfg['mode'] ?? '') === Import::SOFTREF_IMPORT_MODE_EDITABLE) {
$html = '';
if ($cfg['title'] ?? false) {
$html .= '<strong>' . htmlspecialchars((string)$cfg['title']) . '</strong><br>';
}
$html .= htmlspecialchars((string)$cfg['description']) . '<br>';
$html .= sprintf(
'<input type="text" name="tx_impexp[softrefInputValues][%s]" value="%s" />',
$tokenID,
htmlspecialchars($this->softrefInputValues[$tokenID] ?? $cfg['defValue'])
);
return $html;
}
}
return '';
}
/**
* Render select box with export options for soft references.
* An export box is shown only if a substitution scheme is found for the soft reference.
*
* @param array $softref Soft reference
* @return string HTML
*/
protected function renderSoftRefExportSelector(array $softref): string
{
// Substitution scheme has to be around.
if (isset($softref['subst']['tokenID'])) {
$options = [];
$options[''] = '';
$options[Import::SOFTREF_IMPORT_MODE_EDITABLE] = $this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_softrefsel_editable');
$options[Import::SOFTREF_IMPORT_MODE_EXCLUDE] = $this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_softrefsel_exclude');
$value = $this->softrefCfg[$softref['subst']['tokenID']]['mode'] ?? '';
$selectHtml = $this->renderSelectBox(
'tx_impexp[softrefCfg][' . $softref['subst']['tokenID'] . '][mode]',
$value,
$options
);
$textFieldHtml = '';
if ($value === Import::SOFTREF_IMPORT_MODE_EDITABLE) {
if ($softref['subst']['title'] ?? false) {
$textFieldHtml .= sprintf(
'
<input type="hidden" name="tx_impexp[softrefCfg][%1$s][title]" value="%2$s" />
<strong>%2$s</strong><br>',
$softref['subst']['tokenID'],
htmlspecialchars($softref['subst']['title'])
);
}
if (!($softref['subst']['description'] ?? false)) {
$textFieldHtml .= sprintf(
'
%s<br>
<input type="text" name="tx_impexp[softrefCfg][%s][description]" value="%s" />',
htmlspecialchars($this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_printerror_description')),
$softref['subst']['tokenID'],
htmlspecialchars($this->softrefCfg[$softref['subst']['tokenID']]['description'] ?? '')
);
} else {
$textFieldHtml .= sprintf(
'
<input type="hidden" name="tx_impexp[softrefCfg][%1$s][description]" value="%2$s" />%2$s',
$softref['subst']['tokenID'],
htmlspecialchars($softref['subst']['description'])
);
}
$textFieldHtml .= sprintf(
'
<input type="hidden" name="tx_impexp[softrefCfg][%s][defValue]" value="%s" />',
$softref['subst']['tokenID'],
htmlspecialchars($softref['subst']['tokenValue'])
);
}
return $selectHtml . $textFieldHtml;
}
return '';
}
/**
* Render select box with import options for the record.
*
* @param string $table Table name
* @param int $uid Record UID
* @param bool $doesRecordExist Is there already a record with this UID in the database?
* @return string HTML
*/
protected function renderImportModeSelector(string $table, int $uid, bool $doesRecordExist): string
{
$options = [];
if (!$doesRecordExist) {
$options[] = $this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_insert');
if ($this->getBackendUser()->isAdmin()) {
$options[Import::IMPORT_MODE_FORCE_UID] = sprintf($this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_forceUidSAdmin'), $uid);
}
} else {
$options[] = $this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_update');
$options[Import::IMPORT_MODE_AS_NEW] = $this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_importAsNew');
if (!$this->globalIgnorePid) {
$options[Import::IMPORT_MODE_IGNORE_PID] = $this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_ignorePid');
} else {
$options[Import::IMPORT_MODE_RESPECT_PID] = $this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_respectPid');
}
}
$options[Import::IMPORT_MODE_EXCLUDE] = $this->lang->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:impexpcore_singlereco_exclude');
return $this->renderSelectBox(
'tx_impexp[import_mode][' . $table . ':' . $uid . ']',
(string)($this->importMode[$table . ':' . $uid] ?? ''),
$options
);
}
/**
* Renders a select box from option values.
*
* @param string $name Form element name
* @param string $value Current value
* @param array $options Options to display (key/value pairs)
* @return string HTML
*/
protected function renderSelectBox(string $name, string $value, array $options): string
{
$optionsHtml = '';
$isValueInOptions = false;
foreach ($options as $k => $v) {
if ((string)$k === $value) {
$isValueInOptions = true;
$selectedHtml = ' selected="selected"';
} else {
$selectedHtml = '';
}
$optionsHtml .= sprintf(
'<option value="%s"%s>%s</option>',
htmlspecialchars((string)$k),
$selectedHtml,
htmlspecialchars((string)$v)
);
}
// Append and select the current value as an option of the form "[value]"
// if it is not available in the options.
if (!$isValueInOptions && $value !== '') {
$optionsHtml .= sprintf(
'<option value="%s" selected="selected">%s</option>',
htmlspecialchars($value),
htmlspecialchars('[\'' . $value . '\']')
);
}
return '<select class="form-select form-select-sm" name="' . $name . '" style="width: 100px">' . $optionsHtml . '</select>';
}
public function getOrCreateTemporaryFolderName(): string
{
if (empty($this->temporaryFolderName)) {
$this->temporaryFolderName = $this->createTemporaryFolderName();
}
return $this->temporaryFolderName;
}
protected function createTemporaryFolderName(): string
{
$temporaryPath = Environment::getVarPath() . '/transient';
do {
$temporaryFolderName = sprintf(