[TASK] Use Environment API instead of PATH_site in impexp
[Packages/TYPO3.CMS.git] / typo3 / sysext / impexp / Classes / Export.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\Core\Environment;
19 use TYPO3\CMS\Core\Database\ReferenceIndex;
20 use TYPO3\CMS\Core\Exception;
21 use TYPO3\CMS\Core\Html\HtmlParser;
22 use TYPO3\CMS\Core\Resource\File;
23 use TYPO3\CMS\Core\Resource\ResourceFactory;
24 use TYPO3\CMS\Core\Utility\GeneralUtility;
25 use TYPO3\CMS\Core\Utility\PathUtility;
26
27 /**
28 * EXAMPLE for using the impexp-class for exporting stuff:
29 *
30 * Create and initialize:
31 * $this->export = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Impexp\ImportExport::class);
32 * $this->export->init();
33 * Set which tables relations we will allow:
34 * $this->export->relOnlyTables[]="tt_news"; // exclusively includes. See comment in the class
35 *
36 * Adding records:
37 * $this->export->export_addRecord("pages", $this->pageinfo);
38 * $this->export->export_addRecord("pages", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("pages", 38));
39 * $this->export->export_addRecord("pages", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("pages", 39));
40 * $this->export->export_addRecord("tt_content", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("tt_content", 12));
41 * $this->export->export_addRecord("tt_content", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("tt_content", 74));
42 * $this->export->export_addRecord("sys_template", \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord("sys_template", 20));
43 *
44 * Adding all the relations (recursively in 5 levels so relations has THEIR relations registered as well)
45 * for($a=0;$a<5;$a++) {
46 * $addR = $this->export->export_addDBRelations($a);
47 * if (empty($addR)) break;
48 * }
49 *
50 * Finally load all the files.
51 * $this->export->export_addFilesFromRelations(); // MUST be after the DBrelations are set so that file from ALL added records are included!
52 *
53 * Write export
54 * $out = $this->export->compileMemoryToFileContent();
55 */
56
57 /**
58 * T3D file Export library (TYPO3 Record Document)
59 */
60 class Export extends ImportExport
61 {
62 /**
63 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10. In v10, just remove property, it is not used any longer.
64 * @var int
65 */
66 public $maxFileSize = 1000000;
67
68 /**
69 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10. In v10, just remove property, it is not used any longer.
70 * @var int
71 */
72 public $maxRecordSize = 1000000;
73
74 /**
75 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10. In v10, just remove property, it is not used any longer.
76 * @var int
77 */
78 public $maxExportSize = 10000000;
79
80 /**
81 * Set by user: If set, compression in t3d files is disabled
82 *
83 * @var bool
84 */
85 public $dontCompress = false;
86
87 /**
88 * If set, HTML file resources are included.
89 *
90 * @var bool
91 */
92 public $includeExtFileResources = false;
93
94 /**
95 * Files with external media (HTML/css style references inside)
96 *
97 * @var string
98 */
99 public $extFileResourceExtensions = 'html,htm,css';
100
101 /**
102 * Keys are [recordname], values are an array of fields to be included
103 * in the export
104 *
105 * @var array
106 */
107 protected $recordTypesIncludeFields = [];
108
109 /**
110 * Default array of fields to be included in the export
111 *
112 * @var array
113 */
114 protected $defaultRecordIncludeFields = ['uid', 'pid'];
115
116 /**
117 * @var bool
118 */
119 protected $saveFilesOutsideExportFile = false;
120
121 /**
122 * @var string|null
123 */
124 protected $temporaryFilesPathForExport = null;
125
126 /**************************
127 * Initialize
128 *************************/
129
130 /**
131 * Init the object
132 *
133 * @param bool $dontCompress If set, compression of t3d files is disabled
134 */
135 public function init($dontCompress = false)
136 {
137 parent::init();
138 $this->dontCompress = $dontCompress;
139 $this->mode = 'export';
140 }
141
142 /**************************
143 * Export / Init + Meta Data
144 *************************/
145
146 /**
147 * Set header basics
148 */
149 public function setHeaderBasics()
150 {
151 // Initializing:
152 if (is_array($this->softrefCfg)) {
153 foreach ($this->softrefCfg as $key => $value) {
154 if (!strlen($value['mode'])) {
155 unset($this->softrefCfg[$key]);
156 }
157 }
158 }
159 // Setting in header memory:
160 // Version of file format
161 $this->dat['header']['XMLversion'] = '1.0';
162 // Initialize meta data array (to put it in top of file)
163 $this->dat['header']['meta'] = [];
164 // Add list of tables to consider static
165 $this->dat['header']['relStaticTables'] = $this->relStaticTables;
166 // The list of excluded records
167 $this->dat['header']['excludeMap'] = $this->excludeMap;
168 // Soft Reference mode for elements
169 $this->dat['header']['softrefCfg'] = $this->softrefCfg;
170 // List of extensions the import depends on.
171 $this->dat['header']['extensionDependencies'] = $this->extensionDependencies;
172 $this->dat['header']['charset'] = 'utf-8';
173 }
174
175 /**
176 * Set charset
177 *
178 * @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.
179 */
180 public function setCharset($charset)
181 {
182 $this->dat['header']['charset'] = $charset;
183 }
184
185 /**
186 * Sets meta data
187 *
188 * @param string $title Title of the export
189 * @param string $description Description of the export
190 * @param string $notes Notes about the contents
191 * @param string $packager_username Backend Username of the packager (the guy making the export)
192 * @param string $packager_name Real name of the packager
193 * @param string $packager_email Email of the packager
194 */
195 public function setMetaData($title, $description, $notes, $packager_username, $packager_name, $packager_email)
196 {
197 $this->dat['header']['meta'] = [
198 'title' => $title,
199 'description' => $description,
200 'notes' => $notes,
201 'packager_username' => $packager_username,
202 'packager_name' => $packager_name,
203 'packager_email' => $packager_email,
204 'TYPO3_version' => TYPO3_version,
205 'created' => strftime('%A %e. %B %Y', $GLOBALS['EXEC_TIME'])
206 ];
207 }
208
209 /**
210 * Option to enable having the files not included in the export file.
211 * The files are saved to a temporary folder instead.
212 *
213 * @param bool $saveFilesOutsideExportFile
214 * @see getTemporaryFilesPathForExport()
215 */
216 public function setSaveFilesOutsideExportFile($saveFilesOutsideExportFile)
217 {
218 $this->saveFilesOutsideExportFile = $saveFilesOutsideExportFile;
219 }
220
221 /**************************
222 * Export / Init Page tree
223 *************************/
224
225 /**
226 * Sets the page-tree array in the export header and returns the array in a flattened version
227 *
228 * @param array $idH Hierarchy of ids, the page tree: array([uid] => array("uid" => [uid], "subrow" => array(.....)), [uid] => ....)
229 * @return array The hierarchical page tree converted to a one-dimensional list of pages
230 */
231 public function setPageTree($idH)
232 {
233 $this->dat['header']['pagetree'] = $this->unsetExcludedSections($idH);
234 return $this->flatInversePageTree($this->dat['header']['pagetree']);
235 }
236
237 /**
238 * Removes entries in the page tree which are found in ->excludeMap[]
239 *
240 * @param array $idH Page uid hierarchy
241 * @return array Modified input array
242 * @access private
243 * @see setPageTree()
244 */
245 public function unsetExcludedSections($idH)
246 {
247 if (is_array($idH)) {
248 foreach ($idH as $k => $v) {
249 if ($this->excludeMap['pages:' . $idH[$k]['uid']]) {
250 unset($idH[$k]);
251 } elseif (is_array($idH[$k]['subrow'])) {
252 $idH[$k]['subrow'] = $this->unsetExcludedSections($idH[$k]['subrow']);
253 }
254 }
255 }
256 return $idH;
257 }
258
259 /**************************
260 * Export
261 *************************/
262
263 /**
264 * Sets the fields of record types to be included in the export
265 *
266 * @param array $recordTypesIncludeFields Keys are [recordname], values are an array of fields to be included in the export
267 * @throws Exception if an array value is not type of array
268 */
269 public function setRecordTypesIncludeFields(array $recordTypesIncludeFields)
270 {
271 foreach ($recordTypesIncludeFields as $table => $fields) {
272 if (!is_array($fields)) {
273 throw new Exception('The include fields for record type ' . htmlspecialchars($table) . ' are not defined by an array.', 1391440658);
274 }
275 $this->setRecordTypeIncludeFields($table, $fields);
276 }
277 }
278
279 /**
280 * Sets the fields of a record type to be included in the export
281 *
282 * @param string $table The record type
283 * @param array $fields The fields to be included
284 */
285 public function setRecordTypeIncludeFields($table, array $fields)
286 {
287 $this->recordTypesIncludeFields[$table] = $fields;
288 }
289
290 /**
291 * Adds the record $row from $table.
292 * No checking for relations done here. Pure data.
293 *
294 * @param string $table Table name
295 * @param array $row Record row.
296 * @param int $relationLevel (Internal) if the record is added as a relation, this is set to the "level" it was on.
297 */
298 public function export_addRecord($table, $row, $relationLevel = 0)
299 {
300 BackendUtility::workspaceOL($table, $row);
301 if ($this->excludeDisabledRecords && !$this->isActive($table, $row['uid'])) {
302 return;
303 }
304 if ((string)$table !== '' && is_array($row) && $row['uid'] > 0 && !$this->excludeMap[$table . ':' . $row['uid']]) {
305 if ($this->checkPID($table === 'pages' ? $row['uid'] : $row['pid'])) {
306 if (!isset($this->dat['records'][$table . ':' . $row['uid']])) {
307 // Prepare header info:
308 $row = $this->filterRecordFields($table, $row);
309 $headerInfo = [];
310 $headerInfo['uid'] = $row['uid'];
311 $headerInfo['pid'] = $row['pid'];
312 $headerInfo['title'] = GeneralUtility::fixed_lgd_cs(BackendUtility::getRecordTitle($table, $row), 40);
313 if ($relationLevel) {
314 $headerInfo['relationLevel'] = $relationLevel;
315 }
316 // Set the header summary:
317 $this->dat['header']['records'][$table][$row['uid']] = $headerInfo;
318 // Create entry in the PID lookup:
319 $this->dat['header']['pid_lookup'][$row['pid']][$table][$row['uid']] = 1;
320 // Initialize reference index object:
321 $refIndexObj = GeneralUtility::makeInstance(ReferenceIndex::class);
322 $refIndexObj->enableRuntimeCache();
323 // Yes to workspace overlays for exporting....
324 $refIndexObj->WSOL = true;
325 $relations = $refIndexObj->getRelations($table, $row);
326 $relations = $this->fixFileIDsInRelations($relations);
327 $relations = $this->removeSoftrefsHavingTheSameDatabaseRelation($relations);
328 // Data:
329 $this->dat['records'][$table . ':' . $row['uid']] = [];
330 $this->dat['records'][$table . ':' . $row['uid']]['data'] = $row;
331 $this->dat['records'][$table . ':' . $row['uid']]['rels'] = $relations;
332 // Add information about the relations in the record in the header:
333 $this->dat['header']['records'][$table][$row['uid']]['rels'] = $this->flatDBrels($this->dat['records'][$table . ':' . $row['uid']]['rels']);
334 // Add information about the softrefs to header:
335 $this->dat['header']['records'][$table][$row['uid']]['softrefs'] = $this->flatSoftRefs($this->dat['records'][$table . ':' . $row['uid']]['rels']);
336 } else {
337 $this->error('Record ' . $table . ':' . $row['uid'] . ' already added.');
338 }
339 } else {
340 $this->error('Record ' . $table . ':' . $row['uid'] . ' was outside your DB mounts!');
341 }
342 }
343 }
344
345 /**
346 * This changes the file reference ID from a hash based on the absolute file path
347 * (coming from ReferenceIndex) to a hash based on the relative file path.
348 *
349 * @param array $relations
350 * @return array
351 */
352 protected function fixFileIDsInRelations(array $relations)
353 {
354 foreach ($relations as $field => $relation) {
355 if (isset($relation['type']) && $relation['type'] === 'file') {
356 foreach ($relation['newValueFiles'] as $key => $fileRelationData) {
357 $absoluteFilePath = $fileRelationData['ID_absFile'];
358 if (GeneralUtility::isFirstPartOfStr($absoluteFilePath, Environment::getPublicPath())) {
359 $relatedFilePath = PathUtility::stripPathSitePrefix($absoluteFilePath);
360 $relations[$field]['newValueFiles'][$key]['ID'] = md5($relatedFilePath);
361 }
362 }
363 }
364 if ($relation['type'] === 'flex') {
365 if (is_array($relation['flexFormRels']['file'])) {
366 foreach ($relation['flexFormRels']['file'] as $key => $subList) {
367 foreach ($subList as $subKey => $fileRelationData) {
368 $absoluteFilePath = $fileRelationData['ID_absFile'];
369 if (GeneralUtility::isFirstPartOfStr($absoluteFilePath, Environment::getPublicPath())) {
370 $relatedFilePath = PathUtility::stripPathSitePrefix($absoluteFilePath);
371 $relations[$field]['flexFormRels']['file'][$key][$subKey]['ID'] = md5($relatedFilePath);
372 }
373 }
374 }
375 }
376 }
377 }
378 return $relations;
379 }
380
381 /**
382 * Relations could contain db relations to sys_file records. Some configuration combinations of TCA and
383 * SoftReferenceIndex create also softref relation entries for the identical file. This results
384 * in double included files, one in array "files" and one in array "file_fal".
385 * This function checks the relations for this double inclusions and removes the redundant softref relation.
386 *
387 * @param array $relations
388 * @return array
389 */
390 protected function removeSoftrefsHavingTheSameDatabaseRelation($relations)
391 {
392 $fixedRelations = [];
393 foreach ($relations as $field => $relation) {
394 $newRelation = $relation;
395 if (isset($newRelation['type']) && $newRelation['type'] === 'db') {
396 foreach ($newRelation['itemArray'] as $key => $dbRelationData) {
397 if ($dbRelationData['table'] === 'sys_file') {
398 if (isset($newRelation['softrefs']['keys']['typolink'])) {
399 foreach ($newRelation['softrefs']['keys']['typolink'] as $softrefKey => $softRefData) {
400 if ($softRefData['subst']['type'] === 'file') {
401 $file = ResourceFactory::getInstance()->retrieveFileOrFolderObject($softRefData['subst']['relFileName']);
402 if ($file instanceof File) {
403 if ($file->getUid() == $dbRelationData['id']) {
404 unset($newRelation['softrefs']['keys']['typolink'][$softrefKey]);
405 }
406 }
407 }
408 }
409 if (empty($newRelation['softrefs']['keys']['typolink'])) {
410 unset($newRelation['softrefs']);
411 }
412 }
413 }
414 }
415 }
416 $fixedRelations[$field] = $newRelation;
417 }
418 return $fixedRelations;
419 }
420
421 /**
422 * This analyses the existing added records, finds all database relations to records and adds these records to the export file.
423 * This function can be called repeatedly until it returns an empty array.
424 * In principle it should not allow to infinite recursivity, but you better set a limit...
425 * Call this BEFORE the ext_addFilesFromRelations (so files from added relations are also included of course)
426 *
427 * @param int $relationLevel Recursion level
428 * @return array overview of relations found and added: Keys [table]:[uid], values array with table and id
429 * @see export_addFilesFromRelations()
430 */
431 public function export_addDBRelations($relationLevel = 0)
432 {
433 // Traverse all "rels" registered for "records"
434 if (!is_array($this->dat['records'])) {
435 $this->error('There were no records available.');
436 return [];
437 }
438 $addR = [];
439 foreach ($this->dat['records'] as $k => $value) {
440 if (!is_array($this->dat['records'][$k])) {
441 continue;
442 }
443 foreach ($this->dat['records'][$k]['rels'] as $fieldname => $vR) {
444 // For all DB types of relations:
445 if ($vR['type'] === 'db') {
446 foreach ($vR['itemArray'] as $fI) {
447 $this->export_addDBRelations_registerRelation($fI, $addR);
448 }
449 }
450 // For all flex/db types of relations:
451 if ($vR['type'] === 'flex') {
452 // DB relations in flex form fields:
453 if (is_array($vR['flexFormRels']['db'])) {
454 foreach ($vR['flexFormRels']['db'] as $subList) {
455 foreach ($subList as $fI) {
456 $this->export_addDBRelations_registerRelation($fI, $addR);
457 }
458 }
459 }
460 // DB oriented soft references in flex form fields:
461 if (is_array($vR['flexFormRels']['softrefs'])) {
462 foreach ($vR['flexFormRels']['softrefs'] as $subList) {
463 foreach ($subList['keys'] as $spKey => $elements) {
464 foreach ($elements as $el) {
465 if ($el['subst']['type'] === 'db' && $this->includeSoftref($el['subst']['tokenID'])) {
466 list($tempTable, $tempUid) = explode(':', $el['subst']['recordRef']);
467 $fI = [
468 'table' => $tempTable,
469 'id' => $tempUid
470 ];
471 $this->export_addDBRelations_registerRelation($fI, $addR, $el['subst']['tokenID']);
472 }
473 }
474 }
475 }
476 }
477 }
478 // In any case, if there are soft refs:
479 if (is_array($vR['softrefs']['keys'])) {
480 foreach ($vR['softrefs']['keys'] as $spKey => $elements) {
481 foreach ($elements as $el) {
482 if ($el['subst']['type'] === 'db' && $this->includeSoftref($el['subst']['tokenID'])) {
483 list($tempTable, $tempUid) = explode(':', $el['subst']['recordRef']);
484 $fI = [
485 'table' => $tempTable,
486 'id' => $tempUid
487 ];
488 $this->export_addDBRelations_registerRelation($fI, $addR, $el['subst']['tokenID']);
489 }
490 }
491 }
492 }
493 }
494 }
495
496 // Now, if there were new records to add, do so:
497 if (!empty($addR)) {
498 foreach ($addR as $fI) {
499 // Get and set record:
500 $row = BackendUtility::getRecord($fI['table'], $fI['id']);
501 // Depending on db driver, int fields may or may not be returned as integer or as string. The
502 // loop aligns that detail and forces strings for everything to have exports more db agnostic.
503 foreach ($row as $fieldName => $value) {
504 // Keep null but force everything else to string
505 $row[$fieldName] = $value === null ? $value : (string)$value;
506 }
507
508 if (is_array($row)) {
509 $this->export_addRecord($fI['table'], $row, $relationLevel + 1);
510 }
511 // Set status message
512 // Relation pointers always larger than zero except certain "select" types with
513 // negative values pointing to uids - but that is not supported here.
514 if ($fI['id'] > 0) {
515 $rId = $fI['table'] . ':' . $fI['id'];
516 if (!isset($this->dat['records'][$rId])) {
517 $this->dat['records'][$rId] = 'NOT_FOUND';
518 $this->error('Relation record ' . $rId . ' was not found!');
519 }
520 }
521 }
522 }
523 // Return overview of relations found and added
524 return $addR;
525 }
526
527 /**
528 * Helper function for export_addDBRelations()
529 *
530 * @param array $fI Array with table/id keys to add
531 * @param array $addR Add array, passed by reference to be modified
532 * @param string $tokenID Softref Token ID, if applicable.
533 * @see export_addDBRelations()
534 */
535 public function export_addDBRelations_registerRelation($fI, &$addR, $tokenID = '')
536 {
537 $rId = $fI['table'] . ':' . $fI['id'];
538 if (
539 isset($GLOBALS['TCA'][$fI['table']]) && !$this->isTableStatic($fI['table']) && !$this->isExcluded($fI['table'], $fI['id'])
540 && (!$tokenID || $this->includeSoftref($tokenID)) && $this->inclRelation($fI['table'])
541 ) {
542 if (!isset($this->dat['records'][$rId])) {
543 // Set this record to be included since it is not already.
544 $addR[$rId] = $fI;
545 }
546 }
547 }
548
549 /**
550 * This adds all files in relations.
551 * Call this method AFTER adding all records including relations.
552 *
553 * @see export_addDBRelations()
554 */
555 public function export_addFilesFromRelations()
556 {
557 // Traverse all "rels" registered for "records"
558 if (!is_array($this->dat['records'])) {
559 $this->error('There were no records available.');
560 return;
561 }
562 foreach ($this->dat['records'] as $k => $value) {
563 if (!isset($this->dat['records'][$k]['rels']) || !is_array($this->dat['records'][$k]['rels'])) {
564 continue;
565 }
566 foreach ($this->dat['records'][$k]['rels'] as $fieldname => $vR) {
567 // For all file type relations:
568 if ($vR['type'] === 'file') {
569 foreach ($vR['newValueFiles'] as $key => $fI) {
570 $this->export_addFile($fI, $k, $fieldname);
571 // Remove the absolute reference to the file so it doesn't expose absolute paths from source server:
572 unset($this->dat['records'][$k]['rels'][$fieldname]['newValueFiles'][$key]['ID_absFile']);
573 }
574 }
575 // For all flex type relations:
576 if ($vR['type'] === 'flex') {
577 if (is_array($vR['flexFormRels']['file'])) {
578 foreach ($vR['flexFormRels']['file'] as $key => $subList) {
579 foreach ($subList as $subKey => $fI) {
580 $this->export_addFile($fI, $k, $fieldname);
581 // Remove the absolute reference to the file so it doesn't expose absolute paths from source server:
582 unset($this->dat['records'][$k]['rels'][$fieldname]['flexFormRels']['file'][$key][$subKey]['ID_absFile']);
583 }
584 }
585 }
586 // DB oriented soft references in flex form fields:
587 if (is_array($vR['flexFormRels']['softrefs'])) {
588 foreach ($vR['flexFormRels']['softrefs'] as $key => $subList) {
589 foreach ($subList['keys'] as $spKey => $elements) {
590 foreach ($elements as $subKey => $el) {
591 if ($el['subst']['type'] === 'file' && $this->includeSoftref($el['subst']['tokenID'])) {
592 // Create abs path and ID for file:
593 $ID_absFile = GeneralUtility::getFileAbsFileName(Environment::getPublicPath() . '/' . $el['subst']['relFileName']);
594 $ID = md5($el['subst']['relFileName']);
595 if ($ID_absFile) {
596 if (!$this->dat['files'][$ID]) {
597 $fI = [
598 'filename' => PathUtility::basename($ID_absFile),
599 'ID_absFile' => $ID_absFile,
600 'ID' => $ID,
601 'relFileName' => $el['subst']['relFileName']
602 ];
603 $this->export_addFile($fI, '_SOFTREF_');
604 }
605 $this->dat['records'][$k]['rels'][$fieldname]['flexFormRels']['softrefs'][$key]['keys'][$spKey][$subKey]['file_ID'] = $ID;
606 }
607 }
608 }
609 }
610 }
611 }
612 }
613 // In any case, if there are soft refs:
614 if (is_array($vR['softrefs']['keys'])) {
615 foreach ($vR['softrefs']['keys'] as $spKey => $elements) {
616 foreach ($elements as $subKey => $el) {
617 if ($el['subst']['type'] === 'file' && $this->includeSoftref($el['subst']['tokenID'])) {
618 // Create abs path and ID for file:
619 $ID_absFile = GeneralUtility::getFileAbsFileName(Environment::getPublicPath() . '/' . $el['subst']['relFileName']);
620 $ID = md5($el['subst']['relFileName']);
621 if ($ID_absFile) {
622 if (!$this->dat['files'][$ID]) {
623 $fI = [
624 'filename' => PathUtility::basename($ID_absFile),
625 'ID_absFile' => $ID_absFile,
626 'ID' => $ID,
627 'relFileName' => $el['subst']['relFileName']
628 ];
629 $this->export_addFile($fI, '_SOFTREF_');
630 }
631 $this->dat['records'][$k]['rels'][$fieldname]['softrefs']['keys'][$spKey][$subKey]['file_ID'] = $ID;
632 }
633 }
634 }
635 }
636 }
637 }
638 }
639 }
640
641 /**
642 * This adds all files from sys_file records
643 */
644 public function export_addFilesFromSysFilesRecords()
645 {
646 if (!isset($this->dat['header']['records']['sys_file']) || !is_array($this->dat['header']['records']['sys_file'])) {
647 return;
648 }
649 foreach ($this->dat['header']['records']['sys_file'] as $sysFileUid => $_) {
650 $recordData = $this->dat['records']['sys_file:' . $sysFileUid]['data'];
651 $file = ResourceFactory::getInstance()->createFileObject($recordData);
652 $this->export_addSysFile($file);
653 }
654 }
655
656 /**
657 * Adds a files content from a sys file record to the export memory
658 *
659 * @param File $file
660 */
661 public function export_addSysFile(File $file)
662 {
663 $fileContent = '';
664 try {
665 if (!$this->saveFilesOutsideExportFile) {
666 $fileContent = $file->getContents();
667 } else {
668 $file->checkActionPermission('read');
669 }
670 } catch (\Exception $e) {
671 $this->error('Error when trying to add file ' . $file->getCombinedIdentifier() . ': ' . $e->getMessage());
672 return;
673 }
674 $fileUid = $file->getUid();
675 $fileSha1 = $file->getStorage()->hashFile($file, 'sha1');
676 if ($fileSha1 !== $file->getProperty('sha1')) {
677 $this->error('File sha1 hash of ' . $file->getCombinedIdentifier() . ' is not up-to-date in index! File added on current sha1.');
678 $this->dat['records']['sys_file:' . $fileUid]['data']['sha1'] = $fileSha1;
679 }
680
681 $fileRec = [];
682 $fileRec['filename'] = $file->getProperty('name');
683 $fileRec['filemtime'] = $file->getProperty('modification_date');
684
685 // build unique id based on the storage and the file identifier
686 $fileId = md5($file->getStorage()->getUid() . ':' . $file->getProperty('identifier_hash'));
687
688 // Setting this data in the header
689 $this->dat['header']['files_fal'][$fileId] = $fileRec;
690
691 if (!$this->saveFilesOutsideExportFile) {
692 // ... and finally add the heavy stuff:
693 $fileRec['content'] = $fileContent;
694 } else {
695 GeneralUtility::upload_copy_move($file->getForLocalProcessing(false), $this->getTemporaryFilesPathForExport() . $file->getProperty('sha1'));
696 }
697 $fileRec['content_sha1'] = $fileSha1;
698
699 $this->dat['files_fal'][$fileId] = $fileRec;
700 }
701
702 /**
703 * Adds a files content to the export memory
704 *
705 * @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!)
706 * @param string $recordRef If the file is related to a record, this is the id on the form [table]:[id]. Information purposes only.
707 * @param string $fieldname If the file is related to a record, this is the field name it was related to. Information purposes only.
708 */
709 public function export_addFile($fI, $recordRef = '', $fieldname = '')
710 {
711 if (!@is_file($fI['ID_absFile'])) {
712 $this->error($fI['ID_absFile'] . ' was not a file! Skipping.');
713 return;
714 }
715 $fileInfo = stat($fI['ID_absFile']);
716 $fileRec = [];
717 $fileRec['filename'] = PathUtility::basename($fI['ID_absFile']);
718 $fileRec['filemtime'] = $fileInfo['mtime'];
719 //for internal type file_reference
720 $fileRec['relFileRef'] = PathUtility::stripPathSitePrefix($fI['ID_absFile']);
721 if ($recordRef) {
722 $fileRec['record_ref'] = $recordRef . '/' . $fieldname;
723 }
724 if ($fI['relFileName']) {
725 $fileRec['relFileName'] = $fI['relFileName'];
726 }
727 // Setting this data in the header
728 $this->dat['header']['files'][$fI['ID']] = $fileRec;
729 // ... and for the recordlisting, why not let us know WHICH relations there was...
730 if ($recordRef && $recordRef !== '_SOFTREF_') {
731 $refParts = explode(':', $recordRef, 2);
732 if (!is_array($this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'])) {
733 $this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'] = [];
734 }
735 $this->dat['header']['records'][$refParts[0]][$refParts[1]]['filerefs'][] = $fI['ID'];
736 }
737 $fileMd5 = md5_file($fI['ID_absFile']);
738 if (!$this->saveFilesOutsideExportFile) {
739 // ... and finally add the heavy stuff:
740 $fileRec['content'] = file_get_contents($fI['ID_absFile']);
741 } else {
742 GeneralUtility::upload_copy_move($fI['ID_absFile'], $this->getTemporaryFilesPathForExport() . $fileMd5);
743 }
744 $fileRec['content_md5'] = $fileMd5;
745 $this->dat['files'][$fI['ID']] = $fileRec;
746 // For soft references, do further processing:
747 if ($recordRef === '_SOFTREF_') {
748 // RTE files?
749 if ($RTEoriginal = $this->getRTEoriginalFilename(PathUtility::basename($fI['ID_absFile']))) {
750 $RTEoriginal_absPath = PathUtility::dirname($fI['ID_absFile']) . '/' . $RTEoriginal;
751 if (@is_file($RTEoriginal_absPath)) {
752 $RTEoriginal_ID = md5($RTEoriginal_absPath);
753 $fileInfo = stat($RTEoriginal_absPath);
754 $fileRec = [];
755 $fileRec['filename'] = PathUtility::basename($RTEoriginal_absPath);
756 $fileRec['filemtime'] = $fileInfo['mtime'];
757 $fileRec['record_ref'] = '_RTE_COPY_ID:' . $fI['ID'];
758 $this->dat['header']['files'][$fI['ID']]['RTE_ORIG_ID'] = $RTEoriginal_ID;
759 // Setting this data in the header
760 $this->dat['header']['files'][$RTEoriginal_ID] = $fileRec;
761 $fileMd5 = md5_file($RTEoriginal_absPath);
762 if (!$this->saveFilesOutsideExportFile) {
763 // ... and finally add the heavy stuff:
764 $fileRec['content'] = file_get_contents($RTEoriginal_absPath);
765 } else {
766 GeneralUtility::upload_copy_move($RTEoriginal_absPath, $this->getTemporaryFilesPathForExport() . $fileMd5);
767 }
768 $fileRec['content_md5'] = $fileMd5;
769 $this->dat['files'][$RTEoriginal_ID] = $fileRec;
770 } else {
771 $this->error('RTE original file "' . PathUtility::stripPathSitePrefix($RTEoriginal_absPath) . '" was not found!');
772 }
773 }
774 // Files with external media?
775 // This is only done with files grabbed by a softreference parser since it is deemed improbable that hard-referenced files should undergo this treatment.
776 $html_fI = pathinfo(PathUtility::basename($fI['ID_absFile']));
777 if ($this->includeExtFileResources && GeneralUtility::inList($this->extFileResourceExtensions, strtolower($html_fI['extension']))) {
778 $uniquePrefix = '###' . md5($GLOBALS['EXEC_TIME']) . '###';
779 if (strtolower($html_fI['extension']) === 'css') {
780 $prefixedMedias = explode($uniquePrefix, preg_replace('/(url[[:space:]]*\\([[:space:]]*["\']?)([^"\')]*)(["\']?[[:space:]]*\\))/i', '\\1' . $uniquePrefix . '\\2' . $uniquePrefix . '\\3', $fileRec['content']));
781 } else {
782 // html, htm:
783 $htmlParser = GeneralUtility::makeInstance(HtmlParser::class);
784 $prefixedMedias = explode($uniquePrefix, $htmlParser->prefixResourcePath($uniquePrefix, $fileRec['content'], [], $uniquePrefix));
785 }
786 $htmlResourceCaptured = false;
787 foreach ($prefixedMedias as $k => $v) {
788 if ($k % 2) {
789 $EXTres_absPath = GeneralUtility::resolveBackPath(PathUtility::dirname($fI['ID_absFile']) . '/' . $v);
790 $EXTres_absPath = GeneralUtility::getFileAbsFileName($EXTres_absPath);
791 if ($EXTres_absPath && GeneralUtility::isFirstPartOfStr($EXTres_absPath, Environment::getPublicPath() . '/' . $this->fileadminFolderName . '/') && @is_file($EXTres_absPath)) {
792 $htmlResourceCaptured = true;
793 $EXTres_ID = md5($EXTres_absPath);
794 $this->dat['header']['files'][$fI['ID']]['EXT_RES_ID'][] = $EXTres_ID;
795 $prefixedMedias[$k] = '{EXT_RES_ID:' . $EXTres_ID . '}';
796 // Add file to memory if it is not set already:
797 if (!isset($this->dat['header']['files'][$EXTres_ID])) {
798 $fileInfo = stat($EXTres_absPath);
799 $fileRec = [];
800 $fileRec['filename'] = PathUtility::basename($EXTres_absPath);
801 $fileRec['filemtime'] = $fileInfo['mtime'];
802 $fileRec['record_ref'] = '_EXT_PARENT_:' . $fI['ID'];
803 // Media relative to the HTML file.
804 $fileRec['parentRelFileName'] = $v;
805 // Setting this data in the header
806 $this->dat['header']['files'][$EXTres_ID] = $fileRec;
807 // ... and finally add the heavy stuff:
808 $fileRec['content'] = file_get_contents($EXTres_absPath);
809 $fileRec['content_md5'] = md5($fileRec['content']);
810 $this->dat['files'][$EXTres_ID] = $fileRec;
811 }
812 }
813 }
814 }
815 if ($htmlResourceCaptured) {
816 $this->dat['files'][$fI['ID']]['tokenizedContent'] = implode('', $prefixedMedias);
817 }
818 }
819 }
820 }
821
822 /**
823 * If saveFilesOutsideExportFile is enabled, this function returns the path
824 * where the files referenced in the export are copied to.
825 *
826 * @return string
827 * @throws \RuntimeException
828 * @see setSaveFilesOutsideExportFile()
829 */
830 public function getTemporaryFilesPathForExport()
831 {
832 if (!$this->saveFilesOutsideExportFile) {
833 throw new \RuntimeException('You need to set saveFilesOutsideExportFile to TRUE before you want to get the temporary files path for export.', 1401205213);
834 }
835 if ($this->temporaryFilesPathForExport === null) {
836 $temporaryFolderName = $this->getTemporaryFolderName();
837 $this->temporaryFilesPathForExport = $temporaryFolderName . '/';
838 }
839 return $this->temporaryFilesPathForExport;
840 }
841
842 /**
843 * DB relations flattend to 1-dim array.
844 * The list will be unique, no table/uid combination will appear twice.
845 *
846 * @param array $dbrels 2-dim Array of database relations organized by table key
847 * @return array 1-dim array where entries are table:uid and keys are array with table/id
848 */
849 public function flatDBrels($dbrels)
850 {
851 $list = [];
852 foreach ($dbrels as $dat) {
853 if ($dat['type'] === 'db') {
854 foreach ($dat['itemArray'] as $i) {
855 $list[$i['table'] . ':' . $i['id']] = $i;
856 }
857 }
858 if ($dat['type'] === 'flex' && is_array($dat['flexFormRels']['db'])) {
859 foreach ($dat['flexFormRels']['db'] as $subList) {
860 foreach ($subList as $i) {
861 $list[$i['table'] . ':' . $i['id']] = $i;
862 }
863 }
864 }
865 }
866 return $list;
867 }
868
869 /**
870 * Soft References flattend to 1-dim array.
871 *
872 * @param array $dbrels 2-dim Array of database relations organized by table key
873 * @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
874 */
875 public function flatSoftRefs($dbrels)
876 {
877 $list = [];
878 foreach ($dbrels as $field => $dat) {
879 if (is_array($dat['softrefs']['keys'])) {
880 foreach ($dat['softrefs']['keys'] as $spKey => $elements) {
881 if (is_array($elements)) {
882 foreach ($elements as $subKey => $el) {
883 $lKey = $field . ':' . $spKey . ':' . $subKey;
884 $list[$lKey] = array_merge(['field' => $field, 'spKey' => $spKey], $el);
885 // Add file_ID key to header - slightly "risky" way of doing this because if the calculation
886 // changes for the same value in $this->records[...] this will not work anymore!
887 if ($el['subst'] && $el['subst']['relFileName']) {
888 $list[$lKey]['file_ID'] = md5(Environment::getPublicPath() . '/' . $el['subst']['relFileName']);
889 }
890 }
891 }
892 }
893 }
894 if ($dat['type'] === 'flex' && is_array($dat['flexFormRels']['softrefs'])) {
895 foreach ($dat['flexFormRels']['softrefs'] as $structurePath => $subSoftrefs) {
896 if (is_array($subSoftrefs['keys'])) {
897 foreach ($subSoftrefs['keys'] as $spKey => $elements) {
898 foreach ($elements as $subKey => $el) {
899 $lKey = $field . ':' . $structurePath . ':' . $spKey . ':' . $subKey;
900 $list[$lKey] = array_merge(['field' => $field, 'spKey' => $spKey, 'structurePath' => $structurePath], $el);
901 // Add file_ID key to header - slightly "risky" way of doing this because if the calculation
902 // changes for the same value in $this->records[...] this will not work anymore!
903 if ($el['subst'] && $el['subst']['relFileName']) {
904 $list[$lKey]['file_ID'] = md5(Environment::getPublicPath() . '/' . $el['subst']['relFileName']);
905 }
906 }
907 }
908 }
909 }
910 }
911 }
912 return $list;
913 }
914
915 /**
916 * If include fields for a specific record type are set, the data
917 * are filtered out with fields are not included in the fields.
918 *
919 * @param string $table The record type to be filtered
920 * @param array $row The data to be filtered
921 * @return array The filtered record row
922 */
923 protected function filterRecordFields($table, array $row)
924 {
925 if (isset($this->recordTypesIncludeFields[$table])) {
926 $includeFields = array_unique(array_merge(
927 $this->recordTypesIncludeFields[$table],
928 $this->defaultRecordIncludeFields
929 ));
930 $newRow = [];
931 foreach ($row as $key => $value) {
932 if (in_array($key, $includeFields)) {
933 $newRow[$key] = $value;
934 }
935 }
936 } else {
937 $newRow = $row;
938 }
939 return $newRow;
940 }
941
942 /**************************
943 * File Output
944 *************************/
945
946 /**
947 * This compiles and returns the data content for an exported file
948 *
949 * @param string $type Type of output; "xml" gives xml, otherwise serialized array, possibly compressed.
950 * @return string The output file stream
951 */
952 public function compileMemoryToFileContent($type = '')
953 {
954 if ($type === 'xml') {
955 $out = $this->createXML();
956 } else {
957 $compress = $this->doOutputCompress();
958 $out = '';
959 // adding header:
960 $out .= $this->addFilePart(serialize($this->dat['header']), $compress);
961 // adding records:
962 $out .= $this->addFilePart(serialize($this->dat['records']), $compress);
963 // adding files:
964 $out .= $this->addFilePart(serialize($this->dat['files']), $compress);
965 // adding files_fal:
966 $out .= $this->addFilePart(serialize($this->dat['files_fal']), $compress);
967 }
968 return $out;
969 }
970
971 /**
972 * Creates XML string from input array
973 *
974 * @return string XML content
975 */
976 public function createXML()
977 {
978 // Options:
979 $options = [
980 'alt_options' => [
981 '/header' => [
982 'disableTypeAttrib' => true,
983 'clearStackPath' => true,
984 'parentTagMap' => [
985 'files' => 'file',
986 'files_fal' => 'file',
987 'records' => 'table',
988 'table' => 'rec',
989 'rec:rels' => 'relations',
990 'relations' => 'element',
991 'filerefs' => 'file',
992 'pid_lookup' => 'page_contents',
993 'header:relStaticTables' => 'static_tables',
994 'static_tables' => 'tablename',
995 'excludeMap' => 'item',
996 'softrefCfg' => 'softrefExportMode',
997 'extensionDependencies' => 'extkey',
998 'softrefs' => 'softref_element'
999 ],
1000 'alt_options' => [
1001 '/pagetree' => [
1002 'disableTypeAttrib' => true,
1003 'useIndexTagForNum' => 'node',
1004 'parentTagMap' => [
1005 'node:subrow' => 'node'
1006 ]
1007 ],
1008 '/pid_lookup/page_contents' => [
1009 'disableTypeAttrib' => true,
1010 'parentTagMap' => [
1011 'page_contents' => 'table'
1012 ],
1013 'grandParentTagMap' => [
1014 'page_contents/table' => 'item'
1015 ]
1016 ]
1017 ]
1018 ],
1019 '/records' => [
1020 'disableTypeAttrib' => true,
1021 'parentTagMap' => [
1022 'records' => 'tablerow',
1023 'tablerow:data' => 'fieldlist',
1024 'tablerow:rels' => 'related',
1025 'related' => 'field',
1026 'field:itemArray' => 'relations',
1027 'field:newValueFiles' => 'filerefs',
1028 'field:flexFormRels' => 'flexform',
1029 'relations' => 'element',
1030 'filerefs' => 'file',
1031 'flexform:db' => 'db_relations',
1032 'flexform:file' => 'file_relations',
1033 'flexform:softrefs' => 'softref_relations',
1034 'softref_relations' => 'structurePath',
1035 'db_relations' => 'path',
1036 'file_relations' => 'path',
1037 'path' => 'element',
1038 'keys' => 'softref_key',
1039 'softref_key' => 'softref_element'
1040 ],
1041 'alt_options' => [
1042 '/records/tablerow/fieldlist' => [
1043 'useIndexTagForAssoc' => 'field'
1044 ]
1045 ]
1046 ],
1047 '/files' => [
1048 'disableTypeAttrib' => true,
1049 'parentTagMap' => [
1050 'files' => 'file'
1051 ]
1052 ],
1053 '/files_fal' => [
1054 'disableTypeAttrib' => true,
1055 'parentTagMap' => [
1056 'files_fal' => 'file'
1057 ]
1058 ]
1059 ]
1060 ];
1061 // Creating XML file from $outputArray:
1062 $charset = $this->dat['header']['charset'] ?: 'utf-8';
1063 $XML = '<?xml version="1.0" encoding="' . $charset . '" standalone="yes" ?>' . LF;
1064 $XML .= GeneralUtility::array2xml($this->dat, '', 0, 'T3RecordDocument', 0, $options);
1065 return $XML;
1066 }
1067
1068 /**
1069 * Returns TRUE if the output should be compressed.
1070 *
1071 * @return bool TRUE if compression is possible AND requested.
1072 */
1073 public function doOutputCompress()
1074 {
1075 return $this->compress && !$this->dontCompress;
1076 }
1077
1078 /**
1079 * Returns a content part for a filename being build.
1080 *
1081 * @param array $data Data to store in part
1082 * @param bool $compress Compress file?
1083 * @return string Content stream.
1084 */
1085 public function addFilePart($data, $compress = false)
1086 {
1087 if ($compress) {
1088 $data = gzcompress($data);
1089 }
1090 return md5($data) . ':' . ($compress ? '1' : '0') . ':' . str_pad(strlen($data), 10, '0', STR_PAD_LEFT) . ':' . $data . ':';
1091 }
1092 }