[BUGFIX] Import/Export Various Exceptions happening
[Packages/TYPO3.CMS.git] / typo3 / sysext / impexp / Classes / Controller / ImportExportController.php
1 <?php
2 namespace TYPO3\CMS\Impexp\Controller;
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 Psr\Http\Message\ResponseInterface;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Backend\Module\BaseScriptClass;
20 use TYPO3\CMS\Backend\Template\DocumentTemplate;
21 use TYPO3\CMS\Backend\Template\ModuleTemplate;
22 use TYPO3\CMS\Backend\Tree\View\PageTreeView;
23 use TYPO3\CMS\Backend\Utility\BackendUtility;
24 use TYPO3\CMS\Core\Database\DatabaseConnection;
25 use TYPO3\CMS\Core\Imaging\Icon;
26 use TYPO3\CMS\Core\Imaging\IconFactory;
27 use TYPO3\CMS\Core\Messaging\FlashMessage;
28 use TYPO3\CMS\Core\Messaging\FlashMessageService;
29 use TYPO3\CMS\Core\Resource\DuplicationBehavior;
30 use TYPO3\CMS\Core\Resource\Exception;
31 use TYPO3\CMS\Core\Resource\Filter\FileExtensionFilter;
32 use TYPO3\CMS\Core\Resource\ResourceFactory;
33 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
34 use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
35 use TYPO3\CMS\Core\Utility\GeneralUtility;
36 use TYPO3\CMS\Core\Utility\MathUtility;
37 use TYPO3\CMS\Impexp\Domain\Repository\PresetRepository;
38 use TYPO3\CMS\Impexp\Export;
39 use TYPO3\CMS\Impexp\Import;
40 use TYPO3\CMS\Impexp\View\ExportPageTreeView;
41 use TYPO3\CMS\Lang\LanguageService;
42 use TYPO3\CMS\Fluid\View\StandaloneView;
43
44 /**
45 * Main script class for the Import / Export facility
46 */
47 class ImportExportController extends BaseScriptClass
48 {
49 /**
50 * @var array|\TYPO3\CMS\Core\Resource\File[]
51 */
52 protected $uploadedFiles = array();
53
54 /**
55 * Array containing the current page.
56 *
57 * @var array
58 */
59 public $pageinfo;
60
61 /**
62 * @var Export
63 */
64 protected $export;
65
66 /**
67 * @var Import
68 */
69 protected $import;
70
71 /**
72 * @var ExtendedFileUtility
73 */
74 protected $fileProcessor;
75
76 /**
77 * @var string
78 */
79 protected $vC = '';
80
81 /**
82 * @var LanguageService
83 */
84 protected $lang = null;
85
86 /**
87 * @var string
88 */
89 protected $treeHTML = '';
90
91 /**
92 * @var IconFactory
93 */
94 protected $iconFactory;
95
96 /**
97 * The name of the module
98 *
99 * @var string
100 */
101 protected $moduleName = 'xMOD_tximpexp';
102
103 /**
104 * ModuleTemplate Container
105 *
106 * @var ModuleTemplate
107 */
108 protected $moduleTemplate;
109
110 /**
111 * The name of the shortcut for this page
112 *
113 * @var string
114 */
115 protected $shortcutName;
116
117 /**
118 * preset repository
119 *
120 * @var PresetRepository
121 */
122 protected $presetRepository;
123
124 /**
125 * @var StandaloneView
126 */
127 protected $standaloneView = null;
128
129 /**
130 * Constructor
131 */
132 public function __construct()
133 {
134 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
135 $this->moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class);
136 $this->presetRepository = GeneralUtility::makeInstance(PresetRepository::class);
137
138 $templatePath = ExtensionManagementUtility::extPath('impexp') . 'Resources/Private/';
139
140 /* @var $view StandaloneView */
141 $this->standaloneView = GeneralUtility::makeInstance(StandaloneView::class);
142 $this->standaloneView->setTemplateRootPaths([$templatePath . 'Templates/ImportExport/']);
143 $this->standaloneView->setLayoutRootPaths([$templatePath . 'Layouts/']);
144 $this->standaloneView->setPartialRootPaths([$templatePath . 'Partials/']);
145 $this->standaloneView->getRequest()->setControllerExtensionName('impexp');
146 }
147
148 /**
149 * @return void
150 */
151 public function init()
152 {
153 $this->MCONF['name'] = $this->moduleName;
154 parent::init();
155 $this->vC = GeneralUtility::_GP('vC');
156 $this->lang = $this->getLanguageService();
157 }
158
159 /**
160 * Main module function
161 *
162 * @throws \BadFunctionCallException
163 * @throws \InvalidArgumentException
164 * @return void
165 */
166 public function main()
167 {
168 $this->lang->includeLLFile('EXT:impexp/Resources/Private/Language/locallang.xlf');
169
170 // Start document template object:
171 // We keep this here, in case somebody relies on the old doc being here
172 $this->doc = GeneralUtility::makeInstance(DocumentTemplate::class);
173 $this->doc->bodyTagId = 'imp-exp-mod';
174 $this->pageinfo = BackendUtility::readPageAccess($this->id, $this->perms_clause);
175 if(is_array($this->pageinfo)) {
176 $this->moduleTemplate->getDocHeaderComponent()->setMetaInformation($this->pageinfo);
177 }
178 // Setting up the context sensitive menu:
179 $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/ClickMenu');
180 $this->moduleTemplate->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Impexp/ImportExport');
181 $this->moduleTemplate->addJavaScriptCode(
182 'ImpexpInLineJS',
183 'if (top.fsMod) top.fsMod.recentIds["web"] = ' . (int)$this->id . ';'
184 );
185
186 // Input data grabbed:
187 $inData = GeneralUtility::_GP('tx_impexp');
188 $this->standaloneView->assign('moduleUrl', BackendUtility::getModuleUrl('xMOD_tximpexp'));
189 $this->standaloneView->assign('id', $this->id);
190 $this->standaloneView->assign('inData', $inData);
191
192 switch ((string)$inData['action']) {
193 case 'export':
194 $this->shortcutName = $this->lang->getLL('title_export');
195 // Call export interface
196 $this->exportData($inData);
197 $this->standaloneView->setTemplate('Export.html');
198 break;
199 case 'import':
200 $this->shortcutName = $this->lang->getLL('title_import');
201 if (GeneralUtility::_POST('_upload')) {
202 $this->checkUpload();
203 }
204 // Finally: If upload went well, set the new file as the import file:
205 if (!empty($this->uploadedFiles[0])) {
206 // Only allowed extensions....
207 $extension = $this->uploadedFiles[0]->getExtension();
208 if ($extension === 't3d' || $extension === 'xml') {
209 $inData['file'] = $this->uploadedFiles[0]->getCombinedIdentifier();
210 }
211 }
212 // Call import interface:
213 $this->importData($inData);
214 $this->standaloneView->setTemplate('Import.html');
215 break;
216 }
217
218 // Setting up the buttons and markers for docheader
219 $this->getButtons();
220 }
221
222 /**
223 * Injects the request object for the current request and gathers all data
224 *
225 * IMPORTING DATA:
226 *
227 * Incoming array has syntax:
228 * GETvar 'id' = import page id (must be readable)
229 *
230 * file = (pointing to filename relative to PATH_site)
231 *
232 * [all relation fields are clear, but not files]
233 * - page-tree is written first
234 * - then remaining pages (to the root of import)
235 * - then all other records are written either to related included pages or if not found to import-root (should be a sysFolder in most cases)
236 * - then all internal relations are set and non-existing relations removed, relations to static tables preserved.
237 *
238 * EXPORTING DATA:
239 *
240 * Incoming array has syntax:
241 *
242 * file[] = file
243 * dir[] = dir
244 * list[] = table:pid
245 * record[] = table:uid
246 *
247 * pagetree[id] = (single id)
248 * pagetree[levels]=1,2,3, -1 = currently unpacked tree, -2 = only tables on page
249 * pagetree[tables][]=table/_ALL
250 *
251 * external_ref[tables][]=table/_ALL
252 *
253 * @param ServerRequestInterface $request the current request
254 * @param ResponseInterface $response
255 * @return ResponseInterface the response with the content
256 */
257 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
258 {
259 $GLOBALS['SOBE'] = $this;
260 $this->init();
261 $this->main();
262 $this->moduleTemplate->setContent($this->standaloneView->render());
263 $response->getBody()->write($this->moduleTemplate->renderContent());
264
265 return $response;
266 }
267
268 /**
269 * Create the panel of buttons for submitting the form or otherwise perform operations.
270 *
271 * @return array all available buttons as an associated array
272 */
273 protected function getButtons()
274 {
275 $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar();
276 if ($this->getBackendUser()->mayMakeShortcut()) {
277 $shortcutButton = $buttonBar->makeShortcutButton()
278 ->setGetVariables(['tx_impexp'])
279 ->setDisplayName($this->shortcutName)
280 ->setModuleName($this->moduleName);
281 $buttonBar->addButton($shortcutButton);
282 }
283 // Input data grabbed:
284 $inData = GeneralUtility::_GP('tx_impexp');
285 if ((string)$inData['action'] == 'import') {
286 if ($this->id && is_array($this->pageinfo) || $this->getBackendUser()->user['admin'] && !$this->id) {
287 if (is_array($this->pageinfo) && $this->pageinfo['uid']) {
288 // View
289 $onClick = BackendUtility::viewOnClick(
290 $this->pageinfo['uid'],
291 '',
292 BackendUtility::BEgetRootLine($this->pageinfo['uid'])
293 );
294 $viewButton = $buttonBar->makeLinkButton()
295 ->setTitle($this->lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.showPage'))
296 ->setHref('#')
297 ->setIcon($this->iconFactory->getIcon('actions-document-view', Icon::SIZE_SMALL))
298 ->setOnClick($onClick);
299 $buttonBar->addButton($viewButton);
300 }
301 }
302 }
303 }
304
305 /**************************
306 * EXPORT FUNCTIONS
307 **************************/
308
309 /**
310 * Export part of module
311 * Setting content in $this->content
312 *
313 * @param array $inData Content of POST VAR tx_impexp[]..
314 * @throws \InvalidArgumentException
315 * @throws \RuntimeException
316 * @throws \TYPO3\CMS\Core\Resource\Exception\ExistingTargetFileNameException
317 * @return void
318 */
319 public function exportData($inData)
320 {
321 // BUILDING EXPORT DATA:
322 // Processing of InData array values:
323 $inData['pagetree']['maxNumber'] = MathUtility::forceIntegerInRange($inData['pagetree']['maxNumber'], 1, 1000000, 100);
324 $inData['listCfg']['maxNumber'] = MathUtility::forceIntegerInRange($inData['listCfg']['maxNumber'], 1, 1000000, 100);
325 $inData['maxFileSize'] = MathUtility::forceIntegerInRange($inData['maxFileSize'], 1, 1000000, 1000);
326 $inData['filename'] = trim(preg_replace('/[^[:alnum:]._-]*/', '', preg_replace('/\\.(t3d|xml)$/', '', $inData['filename'])));
327 if (strlen($inData['filename'])) {
328 $inData['filename'] .= $inData['filetype'] == 'xml' ? '.xml' : '.t3d';
329 }
330 // Set exclude fields in export object:
331 if (!is_array($inData['exclude'])) {
332 $inData['exclude'] = array();
333 }
334 // Saving/Loading/Deleting presets:
335 $this->presetRepository->processPresets($inData);
336 // Create export object and configure it:
337 $this->export = GeneralUtility::makeInstance(Export::class);
338 $this->export->init(0);
339 $this->export->setCharset($this->lang->charSet);
340 $this->export->maxFileSize = $inData['maxFileSize'] * 1024;
341 $this->export->excludeMap = (array)$inData['exclude'];
342 $this->export->softrefCfg = (array)$inData['softrefCfg'];
343 $this->export->extensionDependencies = (array)$inData['extension_dep'];
344 $this->export->showStaticRelations = $inData['showStaticRelations'];
345 $this->export->includeExtFileResources = !$inData['excludeHTMLfileResources'];
346
347 // Static tables:
348 if (is_array($inData['external_static']['tables'])) {
349 $this->export->relStaticTables = $inData['external_static']['tables'];
350 }
351 // Configure which tables external relations are included for:
352 if (is_array($inData['external_ref']['tables'])) {
353 $this->export->relOnlyTables = $inData['external_ref']['tables'];
354 }
355 $saveFilesOutsideExportFile = false;
356 if (isset($inData['save_export']) && isset($inData['saveFilesOutsideExportFile']) && $inData['saveFilesOutsideExportFile'] === '1') {
357 $this->export->setSaveFilesOutsideExportFile(true);
358 $saveFilesOutsideExportFile = true;
359 }
360 $this->export->setHeaderBasics();
361 // Meta data setting:
362
363 $beUser = $this->getBackendUser();
364 $this->export->setMetaData(
365 $inData['meta']['title'],
366 $inData['meta']['description'],
367 $inData['meta']['notes'],
368 $beUser->user['username'],
369 $beUser->user['realName'],
370 $beUser->user['email']
371 );
372 // Configure which records to export
373 if (is_array($inData['record'])) {
374 foreach ($inData['record'] as $ref) {
375 $rParts = explode(':', $ref);
376 $this->export->export_addRecord($rParts[0], BackendUtility::getRecord($rParts[0], $rParts[1]));
377 }
378 }
379 // Configure which tables to export
380 if (is_array($inData['list'])) {
381 $db = $this->getDatabaseConnection();
382 foreach ($inData['list'] as $ref) {
383 $rParts = explode(':', $ref);
384 if ($beUser->check('tables_select', $rParts[0])) {
385 $res = $this->exec_listQueryPid($rParts[0], $rParts[1], MathUtility::forceIntegerInRange($inData['listCfg']['maxNumber'], 1));
386 while ($subTrow = $db->sql_fetch_assoc($res)) {
387 $this->export->export_addRecord($rParts[0], $subTrow);
388 }
389 $db->sql_free_result($res);
390 }
391 }
392 }
393 // Pagetree
394 if (isset($inData['pagetree']['id'])) {
395 // Based on click-expandable tree
396 $idH = null;
397 if ($inData['pagetree']['levels'] == -1) {
398 $pagetree = GeneralUtility::makeInstance(ExportPageTreeView::class);
399 $tree = $pagetree->ext_tree($inData['pagetree']['id'], $this->filterPageIds($this->export->excludeMap));
400 $this->treeHTML = $pagetree->printTree($tree);
401 $idH = $pagetree->buffer_idH;
402 } elseif ($inData['pagetree']['levels'] == -2) {
403 $this->addRecordsForPid($inData['pagetree']['id'], $inData['pagetree']['tables'], $inData['pagetree']['maxNumber']);
404 } else {
405 // Based on depth
406 // Drawing tree:
407 // If the ID is zero, export root
408 if (!$inData['pagetree']['id'] && $beUser->isAdmin()) {
409 $sPage = array(
410 'uid' => 0,
411 'title' => 'ROOT'
412 );
413 } else {
414 $sPage = BackendUtility::getRecordWSOL('pages', $inData['pagetree']['id'], '*', ' AND ' . $this->perms_clause);
415 }
416 if (is_array($sPage)) {
417 $pid = $inData['pagetree']['id'];
418 $tree = GeneralUtility::makeInstance(PageTreeView::class);
419 $tree->init('AND ' . $this->perms_clause . $this->filterPageIds($this->export->excludeMap));
420 $HTML = $this->iconFactory->getIconForRecord('pages', $sPage, Icon::SIZE_SMALL)->render();
421 $tree->tree[] = array('row' => $sPage, 'HTML' => $HTML);
422 $tree->buffer_idH = array();
423 if ($inData['pagetree']['levels'] > 0) {
424 $tree->getTree($pid, $inData['pagetree']['levels'], '');
425 }
426 $idH = array();
427 $idH[$pid]['uid'] = $pid;
428 if (!empty($tree->buffer_idH)) {
429 $idH[$pid]['subrow'] = $tree->buffer_idH;
430 }
431 $pagetree = GeneralUtility::makeInstance(ExportPageTreeView::class);
432 $this->treeHTML = $pagetree->printTree($tree->tree);
433 $this->shortcutName .= ' (' . $sPage['title'] . ')';
434 }
435 }
436 // In any case we should have a multi-level array, $idH, with the page structure
437 // here (and the HTML-code loaded into memory for nice display...)
438 if (is_array($idH)) {
439 // Sets the pagetree and gets a 1-dim array in return with the pages (in correct submission order BTW...)
440 $flatList = $this->export->setPageTree($idH);
441 foreach ($flatList as $k => $value) {
442 $this->export->export_addRecord('pages', BackendUtility::getRecord('pages', $k));
443 $this->addRecordsForPid($k, $inData['pagetree']['tables'], $inData['pagetree']['maxNumber']);
444 }
445 }
446 }
447 // After adding ALL records we set relations:
448 for ($a = 0; $a < 10; $a++) {
449 $addR = $this->export->export_addDBRelations($a);
450 if (empty($addR)) {
451 break;
452 }
453 }
454 // Finally files are added:
455 // MUST be after the DBrelations are set so that files from ALL added records are included!
456 $this->export->export_addFilesFromRelations();
457
458 $this->export->export_addFilesFromSysFilesRecords();
459
460 // If the download button is clicked, return file
461 if ($inData['download_export'] || $inData['save_export']) {
462 switch ((string)$inData['filetype']) {
463 case 'xml':
464 $out = $this->export->compileMemoryToFileContent('xml');
465 $fExt = '.xml';
466 break;
467 case 't3d':
468 $this->export->dontCompress = 1;
469 // intentional fall-through
470 default:
471 $out = $this->export->compileMemoryToFileContent();
472 $fExt = ($this->export->doOutputCompress() ? '-z' : '') . '.t3d';
473 }
474 // Filename:
475 $dlFile = $inData['filename'];
476 if (!$dlFile) {
477 $exportName = substr(preg_replace('/[^[:alnum:]_]/', '-', $inData['download_export_name']), 0, 20);
478 $dlFile = 'T3D_' . $exportName . '_' . date('Y-m-d_H-i') . $fExt;
479 }
480
481 // Export for download:
482 if ($inData['download_export']) {
483 $mimeType = 'application/octet-stream';
484 Header('Content-Type: ' . $mimeType);
485 Header('Content-Length: ' . strlen($out));
486 Header('Content-Disposition: attachment; filename=' . basename($dlFile));
487 echo $out;
488 die;
489 }
490 // Export by saving:
491 if ($inData['save_export']) {
492 $saveFolder = $this->getDefaultImportExportFolder();
493 $lang = $this->getLanguageService();
494 if ($saveFolder !== false && $saveFolder->checkActionPermission('write')) {
495 $temporaryFileName = GeneralUtility::tempnam('export');
496 file_put_contents($temporaryFileName, $out);
497 $file = $saveFolder->addFile($temporaryFileName, $dlFile, 'replace');
498 if ($saveFilesOutsideExportFile) {
499 $filesFolderName = $dlFile . '.files';
500 $filesFolder = $saveFolder->createFolder($filesFolderName);
501 $temporaryFolderForExport = ResourceFactory::getInstance()->retrieveFileOrFolderObject($this->export->getTemporaryFilesPathForExport());
502 $temporaryFilesForExport = $temporaryFolderForExport->getFiles();
503 foreach ($temporaryFilesForExport as $temporaryFileForExport) {
504 $filesFolder->getStorage()->moveFile($temporaryFileForExport, $filesFolder);
505 }
506 $temporaryFolderForExport->delete();
507 }
508
509 /** @var FlashMessage $flashMessage */
510 $flashMessage = GeneralUtility::makeInstance(
511 FlashMessage::class,
512 sprintf($lang->getLL('exportdata_savedInSBytes'), $file->getPublicUrl(), GeneralUtility::formatSize(strlen($out))),
513 $lang->getLL('exportdata_savedFile'),
514 FlashMessage::OK
515 );
516 } else {
517 /** @var FlashMessage $flashMessage */
518 $flashMessage = GeneralUtility::makeInstance(
519 FlashMessage::class,
520 sprintf($lang->getLL('exportdata_badPathS'), $saveFolder->getPublicUrl()),
521 $lang->getLL('exportdata_problemsSavingFile'),
522 FlashMessage::ERROR
523 );
524 }
525 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
526 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
527 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
528 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
529 $defaultFlashMessageQueue->enqueue($flashMessage);
530 }
531 }
532
533 $this->makeConfigurationForm($inData);
534
535 $this->makeSaveForm($inData);
536
537 $this->makeAdvancedOptionsForm($inData);
538
539 // Print errors that might be:
540 $errors = $this->export->printErrorLog();
541 $this->standaloneView->assign('errors', trim($errors));
542
543 // Generate overview:
544 $this->standaloneView->assign('contentOverview', $this->export->displayContentOverview());
545 }
546
547 /**
548 * Adds records to the export object for a specific page id.
549 *
550 * @param int $k Page id for which to select records to add
551 * @param array $tables Array of table names to select from
552 * @param int $maxNumber Max amount of records to select
553 * @return void
554 */
555 public function addRecordsForPid($k, $tables, $maxNumber)
556 {
557 if (!is_array($tables)) {
558 return;
559 }
560 $db = $this->getDatabaseConnection();
561 foreach ($GLOBALS['TCA'] as $table => $value) {
562 if ($table != 'pages' && (in_array($table, $tables) || in_array('_ALL', $tables))) {
563 if ($this->getBackendUser()->check('tables_select', $table) && !$GLOBALS['TCA'][$table]['ctrl']['is_static']) {
564 $res = $this->exec_listQueryPid($table, $k, MathUtility::forceIntegerInRange($maxNumber, 1));
565 while ($subTrow = $db->sql_fetch_assoc($res)) {
566 $this->export->export_addRecord($table, $subTrow);
567 }
568 $db->sql_free_result($res);
569 }
570 }
571 }
572 }
573
574 /**
575 * Selects records from table / pid
576 *
577 * @param string $table Table to select from
578 * @param int $pid Page ID to select from
579 * @param int $limit Max number of records to select
580 * @return \mysqli_result|object Database resource
581 */
582 public function exec_listQueryPid($table, $pid, $limit)
583 {
584 $db = $this->getDatabaseConnection();
585 $orderBy = $GLOBALS['TCA'][$table]['ctrl']['sortby']
586 ? 'ORDER BY ' . $GLOBALS['TCA'][$table]['ctrl']['sortby']
587 : $GLOBALS['TCA'][$table]['ctrl']['default_sortby'];
588 $res = $db->exec_SELECTquery(
589 '*',
590 $table,
591 'pid=' . (int)$pid . BackendUtility::deleteClause($table) . BackendUtility::versioningPlaceholderClause($table),
592 '',
593 $db->stripOrderBy($orderBy),
594 $limit
595 );
596 // Warning about hitting limit:
597 if ($db->sql_num_rows($res) == $limit) {
598 $limitWarning = sprintf($this->lang->getLL('makeconfig_anSqlQueryReturned'), $limit);
599 /** @var FlashMessage $flashMessage */
600 $flashMessage = GeneralUtility::makeInstance(
601 FlashMessage::class,
602 $this->lang->getLL('execlistqu_maxNumberLimit'),
603 $limitWarning,
604 FlashMessage::WARNING
605 );
606 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
607 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
608 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
609 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
610 $defaultFlashMessageQueue->enqueue($flashMessage);
611 }
612 return $res;
613 }
614
615 /**
616 * Create configuration form
617 *
618 * @param array $inData Form configuration data
619 * @return void
620 */
621 public function makeConfigurationForm($inData)
622 {
623 $nameSuggestion = '';
624 // Page tree export options:
625 if (isset($inData['pagetree']['id'])) {
626 $this->standaloneView->assign('treeHTML', $this->treeHTML);
627
628 $opt = array(
629 '-2' => $this->lang->getLL('makeconfig_tablesOnThisPage'),
630 '-1' => $this->lang->getLL('makeconfig_expandedTree'),
631 '0' => $this->lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_0'),
632 '1' => $this->lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_1'),
633 '2' => $this->lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_2'),
634 '3' => $this->lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_3'),
635 '4' => $this->lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_4'),
636 '999' => $this->lang->sL('LLL:EXT:lang/locallang_core.xlf:labels.depth_infi'),
637 );
638 $this->standaloneView->assign('levelSelectOptions', $opt);
639 $this->standaloneView->assign('tableSelectOptions', $this->getTableSelectOptions('pages'));
640 $nameSuggestion .= 'tree_PID' . $inData['pagetree']['id'] . '_L' . $inData['pagetree']['levels'];
641 }
642 // Single record export:
643 if (is_array($inData['record'])) {
644 $records = array();
645 foreach ($inData['record'] as $ref) {
646 $rParts = explode(':', $ref);
647 $tName = $rParts[0];
648 $rUid = $rParts[1];
649 $nameSuggestion .= $tName . '_' . $rUid;
650 $rec = BackendUtility::getRecordWSOL($tName, $rUid);
651 if (!empty($rec)) {
652 $records[] = '
653 <tr class="bgColor4">
654 <td><strong>' . $this->lang->getLL('makeconfig_record', true) . '</strong></td>
655 <td>' . $this->iconFactory->getIconForRecord($tName, $rec, Icon::SIZE_SMALL)->render() . BackendUtility::getRecordTitle($tName, $rec, true)
656 . '<input type="hidden" name="tx_impexp[record][]" value="' . htmlspecialchars(($tName . ':' . $rUid)) . '" /></td>
657 </tr>';
658 }
659 }
660 $this->standaloneView->assign('records', implode('', $records));
661 }
662 // Single tables/pids:
663 if (is_array($inData['list'])) {
664
665 // Display information about pages from which the export takes place
666 $tblList = '';
667 foreach ($inData['list'] as $reference) {
668 $referenceParts = explode(':', $reference);
669 $tableName = $referenceParts[0];
670 if ($this->getBackendUser()->check('tables_select', $tableName)) {
671 // If the page is actually the root, handle it differently
672 // NOTE: we don't compare integers, because the number actually comes from the split string above
673 if ($referenceParts[1] === '0') {
674 $iconAndTitle = $this->iconFactory->getIcon('apps-pagetree-root', Icon::SIZE_SMALL)->render() . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
675 } else {
676 $record = BackendUtility::getRecordWSOL('pages', $referenceParts[1]);
677 $iconAndTitle = $this->iconFactory->getIconForRecord('pages', $record, Icon::SIZE_SMALL)->render()
678 . BackendUtility::getRecordTitle('pages', $record, true);
679 }
680 $tblList .= 'Table "' . $tableName . '" from ' . $iconAndTitle
681 . '<input type="hidden" name="tx_impexp[list][]" value="' . htmlspecialchars($reference) . '" /><br/>';
682 }
683 }
684 $this->standaloneView->assign('tableList', $tblList);
685 }
686
687 $this->standaloneView->assign('externalReferenceTableSelectOptions', $this->getTableSelectOptions());
688 $this->standaloneView->assign('externalStaticTableSelectOptions', $this->getTableSelectOptions());
689
690 // Exclude:
691 $excludeHiddenFields = '';
692 if (is_array($inData['exclude'])) {
693 foreach ($inData['exclude'] as $key => $value) {
694 $excludeHiddenFields .= '<input type="hidden" name="tx_impexp[exclude][' . $key . ']" value="1" />';
695 }
696 $this->standaloneView->assign('excludedKeys', implode(', ', array_keys($inData['exclude'])));
697 }
698 $this->standaloneView->assign('nameSuggestion', $nameSuggestion);
699 }
700
701 /**
702 * Create advanced options form
703 * Sets content in $this->content
704 *
705 * @param array $inData Form configurat data
706 * @return void
707 */
708 public function makeAdvancedOptionsForm($inData)
709 {
710 $loadedExtensions = ExtensionManagementUtility::getLoadedExtensionListArray();
711 $loadedExtensions = array_combine($loadedExtensions, $loadedExtensions);
712 $this->standaloneView->assign('extensions', $loadedExtensions);
713 $this->standaloneView->assign('inData', $inData);
714 }
715
716 /**
717 * Create configuration form
718 *
719 * @param array $inData Form configuration data
720 * @return void
721 */
722 public function makeSaveForm($inData)
723 {
724
725 // Presets:
726 $opt = array('');
727 $where = '(public>0 OR user_uid=' . (int)$this->getBackendUser()->user['uid'] . ')'
728 . ($inData['pagetree']['id'] ? ' AND (item_uid=' . (int)$inData['pagetree']['id'] . ' OR item_uid=0)' : '');
729 $presets = $this->getDatabaseConnection()->exec_SELECTgetRows('*', 'tx_impexp_presets', $where);
730 if (is_array($presets)) {
731 foreach ($presets as $presetCfg) {
732 $opt[$presetCfg['uid']] = $presetCfg['title'] . ' [' . $presetCfg['uid'] . ']'
733 . ($presetCfg['public'] ? ' [Public]' : '')
734 . ($presetCfg['user_uid'] === $this->getBackendUser()->user['uid'] ? ' [Own]' : '');
735 }
736 }
737
738 $this->standaloneView->assign('presetSelectOptions', $opt);
739
740 $saveFolder = $this->getDefaultImportExportFolder();
741 if ($saveFolder) {
742 $this->standaloneView->assign('saveFolder', $saveFolder->getCombinedIdentifier());
743 }
744
745 // Add file options:
746 $opt = array();
747 if ($this->export->compress) {
748 $opt['t3d_compressed'] = $this->lang->getLL('makesavefo_t3dFileCompressed');
749 }
750 $opt['t3d'] = $this->lang->getLL('makesavefo_t3dFile');
751 $opt['xml'] = $this->lang->getLL('makesavefo_xml');
752
753 $this->standaloneView->assign('filetypeSelectOptions', $opt);
754
755 $fileName = '';
756 if ($saveFolder) {
757 $fileName = sprintf($this->lang->getLL('makesavefo_filenameSavedInS', true), $saveFolder->getPublicUrl())
758 . '<br/>
759 <input type="text" name="tx_impexp[filename]" value="'
760 . htmlspecialchars($inData['filename']) . '" /><br/>';
761
762 $this->standaloneView->assign('hasSaveFolder', true);
763 }
764 $this->standaloneView->assign('fileName', $fileName);
765 }
766
767 /**************************
768 * IMPORT FUNCTIONS
769 **************************/
770
771 /**
772 * Import part of module
773 *
774 * @param array $inData Content of POST VAR tx_impexp[]..
775 * @throws \BadFunctionCallException
776 * @throws \InvalidArgumentException
777 * @throws \RuntimeException
778 * @return void Setting content in $this->content
779 */
780 public function importData($inData)
781 {
782 $access = is_array($this->pageinfo) ? 1 : 0;
783 $beUser = $this->getBackendUser();
784 if ($this->id && $access || $beUser->user['admin'] && !$this->id) {
785 if ($beUser->user['admin'] && !$this->id) {
786 $this->pageinfo = array('title' => '[root-level]', 'uid' => 0, 'pid' => 0);
787 }
788 if ($inData['new_import']) {
789 unset($inData['import_mode']);
790 }
791 /** @var $import Import */
792 $import = GeneralUtility::makeInstance(Import::class);
793 $import->init();
794 $import->update = $inData['do_update'];
795 $import->import_mode = $inData['import_mode'];
796 $import->enableLogging = $inData['enableLogging'];
797 $import->global_ignore_pid = $inData['global_ignore_pid'];
798 $import->force_all_UIDS = $inData['force_all_UIDS'];
799 $import->showDiff = !$inData['notShowDiff'];
800 $import->allowPHPScripts = $inData['allowPHPScripts'];
801 $import->softrefInputValues = $inData['softrefInputValues'];
802
803 // OUTPUT creation:
804
805 // Make input selector:
806 // must have trailing slash.
807 $path = $this->getDefaultImportExportFolder();
808 $exportFiles = $this->getExportFiles();
809
810 $this->shortcutName .= ' (' . $this->pageinfo['title'] . ')';
811
812 // Configuration
813 $selectOptions = array('');
814 foreach ($exportFiles as $file) {
815 $selectOptions[$file->getCombinedIdentifier()] = $file->getPublicUrl();
816 }
817
818 $this->standaloneView->assign('import', $import);
819 $this->standaloneView->assign('inData', $inData);
820 $this->standaloneView->assign('fileSelectOptions', $selectOptions);
821
822 if ($path) {
823 $this->standaloneView->assign('importPath', sprintf($this->lang->getLL('importdata_fromPathS', true), $path->getCombinedIdentifier()));
824 } else {
825 $this->standaloneView->assign('importPath', $this->lang->getLL('importdata_no_default_upload_folder', true));
826 }
827 $this->standaloneView->assign('isAdmin', $beUser->isAdmin());
828
829 // Upload file:
830 $tempFolder = $this->getDefaultImportExportFolder();
831 if ($tempFolder) {
832 $this->standaloneView->assign('tempFolder', $tempFolder->getCombinedIdentifier());
833 $this->standaloneView->assign('hasTempUploadFolder', true);
834 if (GeneralUtility::_POST('_upload')) {
835 $this->standaloneView->assign('submitted', GeneralUtility::_POST('_upload'));
836 $this->standaloneView->assign('noFileUploaded', $this->fileProcessor->internalUploadMap[1]);
837 if($this->uploadedFiles[0]) {
838 $this->standaloneView->assign('uploadedFile', $this->uploadedFiles[0]->getName());
839 }
840 }
841 }
842
843 // Perform import or preview depending:
844 $inFile = $this->getFile($inData['file']);
845 if ($inFile !== null && $inFile->exists()) {
846 $this->standaloneView->assign('metaDataInFileExists', true);
847 $importInhibitedMessages = array();
848 if ($import->loadFile($inFile->getForLocalProcessing(false), 1)) {
849 $importInhibitedMessages = $import->checkImportPrerequisites();
850 if ($inData['import_file']) {
851 if (empty($importInhibitedMessages)) {
852 $import->importData($this->id);
853 BackendUtility::setUpdateSignal('updatePageTree');
854 }
855 }
856 $import->display_import_pid_record = $this->pageinfo;
857 $this->standaloneView->assign('contentOverview', $import->displayContentOverview());
858 }
859 // Compile messages which are inhibiting a proper import and add them to output.
860 if (!empty($importInhibitedMessages)) {
861 $flashMessageQueue = GeneralUtility::makeInstance(FlashMessageService::class)->getMessageQueueByIdentifier('impexp.errors');
862 foreach ($importInhibitedMessages as $message) {
863 $flashMessageQueue->addMessage(GeneralUtility::makeInstance(
864 FlashMessage::class,
865 $message,
866 '',
867 FlashMessage::ERROR
868 ));
869 }
870 }
871 }
872 // Print errors that might be:
873 $errors = $import->printErrorLog();
874 $this->standaloneView->assign('errors', trim($errors));
875 }
876 }
877
878 /****************************
879 * Helper functions
880 ****************************/
881
882 /**
883 * Returns a \TYPO3\CMS\Core\Resource\Folder object for saving export files
884 * to the server and is also used for uploading import files.
885 *
886 * @throws \InvalidArgumentException
887 * @return NULL|\TYPO3\CMS\Core\Resource\Folder
888 */
889 protected function getDefaultImportExportFolder()
890 {
891 $defaultImportExportFolder = null;
892
893 $defaultTemporaryFolder = $this->getBackendUser()->getDefaultUploadTemporaryFolder();
894 if ($defaultTemporaryFolder !== null) {
895 $importExportFolderName = 'importexport';
896 $createFolder = !$defaultTemporaryFolder->hasFolder($importExportFolderName);
897 if ($createFolder === true) {
898 try {
899 $defaultImportExportFolder = $defaultTemporaryFolder->createFolder($importExportFolderName);
900 } catch (Exception $folderAccessException) {
901 }
902 } else {
903 $defaultImportExportFolder = $defaultTemporaryFolder->getSubfolder($importExportFolderName);
904 }
905 }
906
907 return $defaultImportExportFolder;
908 }
909
910 /**
911 * Check if a file has been uploaded
912 *
913 * @throws \InvalidArgumentException
914 * @throws \UnexpectedValueException
915 * @return void
916 */
917 public function checkUpload()
918 {
919 $file = GeneralUtility::_GP('file');
920 // Initializing:
921 $this->fileProcessor = GeneralUtility::makeInstance(ExtendedFileUtility::class);
922 $this->fileProcessor->init(array(), $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']);
923 $this->fileProcessor->setActionPermissions();
924 $this->fileProcessor->setExistingFilesConflictMode((int)GeneralUtility::_GP('overwriteExistingFiles') === 1 ? DuplicationBehavior::REPLACE : DuplicationBehavior::CANCEL);
925 // Checking referer / executing:
926 $refInfo = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
927 $httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
928 if (
929 $httpHost != $refInfo['host']
930 && !$GLOBALS['$TYPO3_CONF_VARS']['SYS']['doNotCheckReferer']
931 && $this->vC != $this->getBackendUser()->veriCode()
932 ) {
933 $this->fileProcessor->writeLog(0, 2, 1, 'Referer host "%s" and server host "%s" did not match!', array($refInfo['host'], $httpHost));
934 } else {
935 $this->fileProcessor->start($file);
936 $result = $this->fileProcessor->processData();
937 if (!empty($result['upload'])) {
938 foreach ($result['upload'] as $uploadedFiles) {
939 $this->uploadedFiles += $uploadedFiles;
940 }
941 }
942 }
943 }
944
945 /**
946 * Returns option array to be used in Fluid
947 *
948 * @param string $excludeList Table names (and the string "_ALL") to exclude. Comma list
949 * @return array
950 */
951 public function getTableSelectOptions($excludeList = '')
952 {
953 $optValues = array();
954 if (!GeneralUtility::inList($excludeList, '_ALL')) {
955 $optValues['_ALL'] = '[' . $this->lang->getLL('ALL_tables') . ']';
956 }
957 foreach ($GLOBALS['TCA'] as $table => $_) {
958 if ($this->getBackendUser()->check('tables_select', $table) && !GeneralUtility::inList($excludeList, $table)) {
959 $optValues[$table] = $table;
960 }
961 }
962 return $optValues;
963 }
964
965 /**
966 * Filter page IDs by traversing exclude array, finding all
967 * excluded pages (if any) and making an AND NOT IN statement for the select clause.
968 *
969 * @param array $exclude Exclude array from import/export object.
970 * @return string AND where clause part to filter out page uids.
971 */
972 public function filterPageIds($exclude)
973 {
974 // Get keys:
975 $exclude = array_keys($exclude);
976 // Traverse
977 $pageIds = array();
978 foreach ($exclude as $element) {
979 list($table, $uid) = explode(':', $element);
980 if ($table === 'pages') {
981 $pageIds[] = (int)$uid;
982 }
983 }
984 // Add to clause:
985 if (!empty($pageIds)) {
986 return ' AND uid NOT IN (' . implode(',', $pageIds) . ')';
987 }
988 return '';
989 }
990
991 /**
992 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
993 */
994 protected function getBackendUser()
995 {
996 return $GLOBALS['BE_USER'];
997 }
998
999 /**
1000 * @return DatabaseConnection
1001 */
1002 protected function getDatabaseConnection()
1003 {
1004 return $GLOBALS['TYPO3_DB'];
1005 }
1006
1007 /**
1008 * @return LanguageService
1009 */
1010 protected function getLanguageService()
1011 {
1012 return $GLOBALS['LANG'];
1013 }
1014
1015 /**
1016 * Gets all export files.
1017 *
1018 * @throws \InvalidArgumentException
1019 * @return array|\TYPO3\CMS\Core\Resource\File[]
1020 */
1021 protected function getExportFiles()
1022 {
1023 $exportFiles = array();
1024
1025 $folder = $this->getDefaultImportExportFolder();
1026 if ($folder !== null) {
1027
1028 /** @var $filter FileExtensionFilter */
1029 $filter = GeneralUtility::makeInstance(FileExtensionFilter::class);
1030 $filter->setAllowedFileExtensions(array('t3d', 'xml'));
1031 $folder->getStorage()->addFileAndFolderNameFilter(array($filter, 'filterFileList'));
1032
1033 $exportFiles = $folder->getFiles();
1034 }
1035
1036 return $exportFiles;
1037 }
1038
1039 /**
1040 * Gets a file by combined identifier.
1041 *
1042 * @param string $combinedIdentifier
1043 * @return NULL|\TYPO3\CMS\Core\Resource\File
1044 */
1045 protected function getFile($combinedIdentifier)
1046 {
1047 try {
1048 $file = ResourceFactory::getInstance()->getFileObjectFromCombinedIdentifier($combinedIdentifier);
1049 } catch (\Exception $exception) {
1050 $file = null;
1051 }
1052
1053 return $file;
1054 }
1055 }