ImportController.php 9.4 KB
Newer Older
1
<?php
2

3
declare(strict_types=1);
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/*
 * 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!
 */

18
19
namespace TYPO3\CMS\Impexp\Controller;

20
21
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
22
use TYPO3\CMS\Backend\Routing\PreviewUriBuilder;
23
24
use TYPO3\CMS\Backend\Template\ModuleTemplate;
use TYPO3\CMS\Backend\Template\ModuleTemplateFactory;
25
use TYPO3\CMS\Backend\Utility\BackendUtility;
26
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
27
use TYPO3\CMS\Core\Imaging\Icon;
28
29
30
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Messaging\AbstractMessage;
31
32
33
use TYPO3\CMS\Core\Resource\DuplicationBehavior;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\Filter\FileExtensionFilter;
34
use TYPO3\CMS\Core\Resource\Folder;
35
use TYPO3\CMS\Core\Resource\ResourceFactory;
36
use TYPO3\CMS\Core\Type\Bitmask\Permission;
37
38
39
40
41
use TYPO3\CMS\Core\Utility\File\ExtendedFileUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Impexp\Import;

/**
42
 * Import module controller
43
 *
Alexander Nitsche's avatar
Alexander Nitsche committed
44
 * @internal This class is not considered part of the public TYPO3 API.
45
 */
46
class ImportController
47
{
Alexander Nitsche's avatar
Alexander Nitsche committed
48
49
50
51
    protected const NO_UPLOAD = 0;
    protected const UPLOAD_DONE = 1;
    protected const UPLOAD_FAILED = 2;

52
    public function __construct(
53
54
55
56
        protected readonly IconFactory $iconFactory,
        protected readonly ModuleTemplateFactory $moduleTemplateFactory,
        protected readonly ExtendedFileUtility $fileProcessor,
        protected readonly ResourceFactory $resourceFactory
57
58
    ) {
    }
59

60
    public function handleRequest(ServerRequestInterface $request): ResponseInterface
Alexander Nitsche's avatar
Alexander Nitsche committed
61
    {
62
        if (!$this->getBackendUser()->isImportEnabled()) {
Alexander Nitsche's avatar
Alexander Nitsche committed
63
            throw new \RuntimeException(
64
                'Import module is disabled for non admin users and userTsConfig options.impexp.enableImportForNonAdminUser is not enabled.',
Alexander Nitsche's avatar
Alexander Nitsche committed
65
66
67
68
                1464435459
            );
        }

69
70
71
72
        $backendUser = $this->getBackendUser();
        $languageService = $this->getLanguageService();
        $queryParams = $request->getQueryParams();
        $parsedBody = $request->getParsedBody();
Alexander Nitsche's avatar
Alexander Nitsche committed
73

74
75
76
77
78
79
        $id = (int)($parsedBody['id'] ?? $queryParams['id'] ?? 0);
        $permsClause = $backendUser->getPagePermsClause(Permission::PAGE_SHOW);
        $pageInfo = BackendUtility::readPageAccess($id, $permsClause) ?: [];
        if ($pageInfo === []) {
            throw new \RuntimeException("You don't have access to this page.", 1604308205);
        }
Alexander Nitsche's avatar
Alexander Nitsche committed
80

81
82
83
84
        $inputData = $request->getParsedBody()['tx_impexp'] ?? $request->getQueryParams()['tx_impexp'] ?? [];
        if ($inputData['new_import'] ?? false) {
            unset($inputData['import_mode']);
        }
Alexander Nitsche's avatar
Alexander Nitsche committed
85

86
        $view = $this->moduleTemplateFactory->create($request);
Alexander Nitsche's avatar
Alexander Nitsche committed
87

88
89
90
91
        $uploadStatus = self::NO_UPLOAD;
        $uploadedFileName = '';
        if ($request->getMethod() === 'POST' && empty($parsedBody)) {
            // This happens if the post request was larger than allowed on the server.
92
            $view->addFlashMessage(
93
94
95
96
97
98
99
100
101
102
103
104
105
106
                $languageService->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:importdata_upload_nodata'),
                $languageService->sL('LLL:EXT:impexp/Resources/Private/Language/locallang.xlf:importdata_upload_error'),
                AbstractMessage::ERROR
            );
        }
        if ($request->getMethod() === 'POST' && isset($parsedBody['_upload'])) {
            $uploadStatus = self::UPLOAD_FAILED;
            $file = $this->handleFileUpload($request);
            if (($file instanceof File) && in_array($file->getExtension(), ['t3d', 'xml'], true)) {
                $inputData['file'] = $file->getCombinedIdentifier();
                $uploadStatus = self::UPLOAD_DONE;
                $uploadedFileName = $file->getName();
            }
        }
107

108
        $import = $this->configureImportFromFormDataAndImportIfRequested($view, $id, $inputData);
109
110
111
112
113
114
115
116
117
118
119
120
121
122
        $importFolder = $import->getOrCreateDefaultImportExportFolder();

        $view->assignMultiple([
            'importFolder' => ($importFolder instanceof Folder) ? $importFolder->getCombinedIdentifier(): '',
            'import' => $import,
            'errors' => $import->getErrorLog(),
            'preview' => $import->renderPreview(),
            'id' => $id,
            'fileSelectOptions' => $this->getSelectableFileList($import),
            'inData' => $inputData,
            'isAdmin' => $this->getBackendUser()->isAdmin(),
            'uploadedFile' => $uploadedFileName,
            'uploadStatus' => $uploadStatus,
        ]);
123
124
        $view->setModuleName('');
        $view->getDocHeaderComponent()->setMetaInformation($pageInfo);
125
        if ((int)($pageInfo['uid'] ?? 0) > 0) {
126
            $this->addDocHeaderPreviewButton($view, (int)$pageInfo['uid']);
127
        }
128
        return $view->renderResponse('Import');
Alexander Nitsche's avatar
Alexander Nitsche committed
129
130
    }

131
    protected function addDocHeaderPreviewButton(ModuleTemplate $view, int $pageUid): void
Alexander Nitsche's avatar
Alexander Nitsche committed
132
    {
133
        $buttonBar = $view->getDocHeaderComponent()->getButtonBar();
134
135
136
137
138
139
140
141
142
        $previewDataAttributes = PreviewUriBuilder::create($pageUid)
            ->withRootLine(BackendUtility::BEgetRootLine($pageUid))
            ->buildDispatcherDataAttributes();
        $viewButton = $buttonBar->makeLinkButton()
            ->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.showPage'))
            ->setHref('#')
            ->setIcon($this->iconFactory->getIcon('actions-view-page', Icon::SIZE_SMALL))
            ->setDataAttributes($previewDataAttributes ?? []);
        $buttonBar->addButton($viewButton);
Alexander Nitsche's avatar
Alexander Nitsche committed
143
    }
144

145
146
    protected function handleFileUpload(ServerRequestInterface $request): ?File
    {
Alexander Nitsche's avatar
Alexander Nitsche committed
147
        $parsedBody = $request->getParsedBody() ?? [];
148
149
150
151
152
153
154
155
156
        $file = $parsedBody['file'] ?? [];
        $conflictMode = empty($parsedBody['overwriteExistingFiles']) ? DuplicationBehavior::CANCEL : DuplicationBehavior::REPLACE;
        $this->fileProcessor->setActionPermissions();
        $this->fileProcessor->setExistingFilesConflictMode(DuplicationBehavior::cast($conflictMode));
        $this->fileProcessor->start($file);
        $result = $this->fileProcessor->processData();
        if (isset($result['upload'][0][0])) {
            // If upload went well, set the new file as the import file.
            return $result['upload'][0][0];
157
        }
158
        return null;
159
160
161
162
163
164
165
    }

    /**
     * @throws \BadFunctionCallException
     * @throws \InvalidArgumentException
     * @throws \RuntimeException
     */
166
    protected function configureImportFromFormDataAndImportIfRequested(ModuleTemplate $view, int $id, array $inputData): Import
167
    {
168
169
170
171
172
173
174
175
176
177
178
        $import = GeneralUtility::makeInstance(Import::class);
        $import->setPid($id);
        $import->setUpdate((bool)($inputData['do_update'] ?? false));
        $import->setImportMode((array)($inputData['import_mode'] ?? null));
        $import->setEnableLogging((bool)($inputData['enableLogging'] ?? false));
        $import->setGlobalIgnorePid((bool)($inputData['global_ignore_pid'] ?? false));
        $import->setForceAllUids((bool)($inputData['force_all_UIDS'] ?? false));
        $import->setShowDiff(!(bool)($inputData['notShowDiff'] ?? false));
        $import->setSoftrefInputValues((array)($inputData['softrefInputValues'] ?? null));
        if (!empty($inputData['file'])) {
            $filePath = $this->getFilePathWithinFileMountBoundaries((string)$inputData['file']);
Alexander Nitsche's avatar
Alexander Nitsche committed
179
            try {
180
181
182
183
                $import->loadFile($filePath, true);
                $import->checkImportPrerequisites();
                if ($inputData['import_file'] ?? false) {
                    $import->importData();
Alexander Nitsche's avatar
Alexander Nitsche committed
184
                    BackendUtility::setUpdateSignal('updatePageTree');
185
                }
Alexander Nitsche's avatar
Alexander Nitsche committed
186
            } catch (\Exception $e) {
187
                $view->addFlashMessage($e->getMessage(), '', AbstractMessage::ERROR);
188
            }
Alexander Nitsche's avatar
Alexander Nitsche committed
189
        }
190
        return $import;
Alexander Nitsche's avatar
Alexander Nitsche committed
191
    }
192

Alexander Nitsche's avatar
Alexander Nitsche committed
193
194
195
    protected function getFilePathWithinFileMountBoundaries(string $filePath): string
    {
        try {
196
            $file = $this->resourceFactory->getFileObjectFromCombinedIdentifier($filePath);
Alexander Nitsche's avatar
Alexander Nitsche committed
197
198
199
            return $file->getForLocalProcessing(false);
        } catch (\Exception $exception) {
            return '';
200
201
202
        }
    }

203
    protected function getSelectableFileList(Import $import): array
204
205
    {
        $exportFiles = [];
206
        $folder = $import->getOrCreateDefaultImportExportFolder();
207
208
209
210
211
212
        if ($folder !== null) {
            $filter = GeneralUtility::makeInstance(FileExtensionFilter::class);
            $filter->setAllowedFileExtensions(['t3d', 'xml']);
            $folder->getStorage()->addFileAndFolderNameFilter([$filter, 'filterFileList']);
            $exportFiles = $folder->getFiles();
        }
213
214
215
216
217
        $selectableFiles = [''];
        foreach ($exportFiles as $file) {
            $selectableFiles[$file->getCombinedIdentifier()] = $file->getPublicUrl();
        }
        return $selectableFiles;
218
219
    }

220
    protected function getBackendUser(): BackendUserAuthentication
221
    {
222
223
        return $GLOBALS['BE_USER'];
    }
224

225
226
227
    protected function getLanguageService(): LanguageService
    {
        return $GLOBALS['LANG'];
228
229
    }
}