xref: /webtrees/app/Http/RequestHandlers/UploadMediaAction.php (revision 7a5056377a17a523a3cb7b5d744019bb97ce0343)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\FlashMessages;
23use Fisharebest\Webtrees\Functions\Functions;
24use Fisharebest\Webtrees\Html;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Log;
27use Fisharebest\Webtrees\Registry;
28use Fisharebest\Webtrees\Services\MediaFileService;
29use League\Flysystem\FilesystemException;
30use League\Flysystem\UnableToCheckFileExistence;
31use League\Flysystem\UnableToWriteFile;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34use Psr\Http\Message\UploadedFileInterface;
35use Psr\Http\Server\RequestHandlerInterface;
36use Throwable;
37
38use function assert;
39use function e;
40use function preg_match;
41use function redirect;
42use function route;
43use function str_replace;
44use function substr;
45use function trim;
46
47use const UPLOAD_ERR_OK;
48
49/**
50 * Manage media from the control panel.
51 */
52class UploadMediaAction implements RequestHandlerInterface
53{
54    /** @var MediaFileService */
55    private $media_file_service;
56
57    /**
58     * MediaController constructor.
59     *
60     * @param MediaFileService $media_file_service
61     */
62    public function __construct(MediaFileService $media_file_service)
63    {
64        $this->media_file_service = $media_file_service;
65    }
66
67    /**
68     * @param ServerRequestInterface $request
69     *
70     * @return ResponseInterface
71     */
72    public function handle(ServerRequestInterface $request): ResponseInterface
73    {
74        $data_filesystem = Registry::filesystem()->data();
75
76        $params = (array) $request->getParsedBody();
77
78        $all_folders = $this->media_file_service->allMediaFolders($data_filesystem);
79
80        foreach ($request->getUploadedFiles() as $key => $uploaded_file) {
81            assert($uploaded_file instanceof UploadedFileInterface);
82            if ($uploaded_file->getClientFilename() === '') {
83                continue;
84            }
85            if ($uploaded_file->getError() !== UPLOAD_ERR_OK) {
86                FlashMessages::addMessage(Functions::fileUploadErrorText($uploaded_file->getError()), 'danger');
87                continue;
88            }
89            $key = substr($key, 9);
90
91            $folder   = $params['folder' . $key];
92            $filename = $params['filename' . $key];
93
94            // If no filename specified, use the original filename.
95            if ($filename === '') {
96                $filename = $uploaded_file->getClientFilename();
97            }
98
99            // Validate the folder
100            if (!$all_folders->contains($folder)) {
101                break;
102            }
103
104            // Validate the filename.
105            $filename = str_replace('\\', '/', $filename);
106            $filename = trim($filename, '/');
107
108            if (preg_match('/([:])/', $filename, $match)) {
109                // Local media files cannot contain certain special characters, especially on MS Windows
110                FlashMessages::addMessage(I18N::translate('Filenames are not allowed to contain the character “%s”.', $match[1]));
111                continue;
112            }
113
114            if (preg_match('/(\.(php|pl|cgi|bash|sh|bat|exe|com|htm|html|shtml))$/i', $filename, $match)) {
115                // Do not allow obvious script files.
116                FlashMessages::addMessage(I18N::translate('Filenames are not allowed to have the extension “%s”.', $match[1]));
117                continue;
118            }
119
120            $path = $folder . $filename;
121
122            try {
123                $file_exists = $data_filesystem->fileExists($path);
124            } catch (FilesystemException | UnableToCheckFileExistence $ex) {
125                $file_exists = false;
126            }
127
128            if ($file_exists) {
129                FlashMessages::addMessage(I18N::translate('The file %s already exists. Use another filename.', $path, 'error'));
130                continue;
131            }
132
133            // Now copy the file to the correct location.
134            try {
135                $data_filesystem->writeStream($path, $uploaded_file->getStream()->detach());
136                FlashMessages::addMessage(I18N::translate('The file %s has been uploaded.', Html::filename($path)), 'success');
137                Log::addMediaLog('Media file ' . $path . ' uploaded');
138            } catch (FilesystemException | UnableToWriteFile $ex) {
139                FlashMessages::addMessage(I18N::translate('There was an error uploading your file.') . '<br>' . e($ex->getMessage()), 'danger');
140            }
141        }
142
143        $url = route(UploadMediaPage::class);
144
145        return redirect($url);
146    }
147}
148