xref: /webtrees/app/Http/RequestHandlers/UploadMediaAction.php (revision 99125a335d0be11b975e213c69fc4ede0c5303f1)
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;
36
37use function assert;
38use function e;
39use function preg_match;
40use function redirect;
41use function route;
42use function str_replace;
43use function substr;
44use function trim;
45
46use const UPLOAD_ERR_OK;
47
48/**
49 * Manage media from the control panel.
50 */
51class UploadMediaAction implements RequestHandlerInterface
52{
53    private MediaFileService $media_file_service;
54
55    /**
56     * MediaController constructor.
57     *
58     * @param MediaFileService $media_file_service
59     */
60    public function __construct(MediaFileService $media_file_service)
61    {
62        $this->media_file_service = $media_file_service;
63    }
64
65    /**
66     * @param ServerRequestInterface $request
67     *
68     * @return ResponseInterface
69     */
70    public function handle(ServerRequestInterface $request): ResponseInterface
71    {
72        $data_filesystem = Registry::filesystem()->data();
73
74        $params = (array) $request->getParsedBody();
75
76        $all_folders = $this->media_file_service->allMediaFolders($data_filesystem);
77
78        foreach ($request->getUploadedFiles() as $key => $uploaded_file) {
79            assert($uploaded_file instanceof UploadedFileInterface);
80            if ($uploaded_file->getClientFilename() === '') {
81                continue;
82            }
83            if ($uploaded_file->getError() !== UPLOAD_ERR_OK) {
84                FlashMessages::addMessage(Functions::fileUploadErrorText($uploaded_file->getError()), 'danger');
85                continue;
86            }
87            $key = substr($key, 9);
88
89            $folder   = $params['folder' . $key];
90            $filename = $params['filename' . $key];
91
92            // If no filename specified, use the original filename.
93            if ($filename === '') {
94                $filename = $uploaded_file->getClientFilename();
95            }
96
97            // Validate the folder
98            if (!$all_folders->contains($folder)) {
99                break;
100            }
101
102            // Validate the filename.
103            $filename = str_replace('\\', '/', $filename);
104            $filename = trim($filename, '/');
105
106            if (preg_match('/([:])/', $filename, $match)) {
107                // Local media files cannot contain certain special characters, especially on MS Windows
108                FlashMessages::addMessage(I18N::translate('Filenames are not allowed to contain the character “%s”.', $match[1]));
109                continue;
110            }
111
112            if (preg_match('/(\.(php|pl|cgi|bash|sh|bat|exe|com|htm|html|shtml))$/i', $filename, $match)) {
113                // Do not allow obvious script files.
114                FlashMessages::addMessage(I18N::translate('Filenames are not allowed to have the extension “%s”.', $match[1]));
115                continue;
116            }
117
118            $path = $folder . $filename;
119
120            try {
121                $file_exists = $data_filesystem->fileExists($path);
122            } catch (FilesystemException | UnableToCheckFileExistence $ex) {
123                $file_exists = false;
124            }
125
126            if ($file_exists) {
127                FlashMessages::addMessage(I18N::translate('The file %s already exists. Use another filename.', $path, 'error'));
128                continue;
129            }
130
131            // Now copy the file to the correct location.
132            try {
133                $data_filesystem->writeStream($path, $uploaded_file->getStream()->detach());
134                FlashMessages::addMessage(I18N::translate('The file %s has been uploaded.', Html::filename($path)), 'success');
135                Log::addMediaLog('Media file ' . $path . ' uploaded');
136            } catch (FilesystemException | UnableToWriteFile $ex) {
137                FlashMessages::addMessage(I18N::translate('There was an error uploading your file.') . '<br>' . e($ex->getMessage()), 'danger');
138            }
139        }
140
141        $url = route(UploadMediaPage::class);
142
143        return redirect($url);
144    }
145}
146