xref: /webtrees/app/Http/RequestHandlers/UploadMediaAction.php (revision 4c8fd9a21a2f83b2d6f6ff708f3d81a9938d02f3)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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\Exceptions\FileUploadException;
23use Fisharebest\Webtrees\FlashMessages;
24use Fisharebest\Webtrees\Html;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Log;
27use Fisharebest\Webtrees\Registry;
28use Fisharebest\Webtrees\Services\MediaFileService;
29use Fisharebest\Webtrees\Validator;
30use League\Flysystem\FilesystemException;
31use League\Flysystem\UnableToCheckFileExistence;
32use League\Flysystem\UnableToWriteFile;
33use Psr\Http\Message\ResponseInterface;
34use Psr\Http\Message\ServerRequestInterface;
35use Psr\Http\Server\RequestHandlerInterface;
36
37use function e;
38use function preg_match;
39use function redirect;
40use function route;
41use function str_replace;
42use function substr;
43use function trim;
44
45use const UPLOAD_ERR_NO_FILE;
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     * @param MediaFileService $media_file_service
57     */
58    public function __construct(MediaFileService $media_file_service)
59    {
60        $this->media_file_service = $media_file_service;
61    }
62
63    /**
64     * @param ServerRequestInterface $request
65     *
66     * @return ResponseInterface
67     */
68    public function handle(ServerRequestInterface $request): ResponseInterface
69    {
70        $data_filesystem = Registry::filesystem()->data();
71        $all_folders     = $this->media_file_service->allMediaFolders($data_filesystem);
72
73        foreach ($request->getUploadedFiles() as $key => $uploaded_file) {
74            if ($uploaded_file->getError() === UPLOAD_ERR_NO_FILE) {
75                continue;
76            }
77
78            if ($uploaded_file->getError() !== UPLOAD_ERR_OK) {
79                throw new FileUploadException($uploaded_file);
80            }
81
82            $key      = substr($key, 9);
83            $folder   = Validator::parsedBody($request)->string('folder' . $key);
84            $filename = Validator::parsedBody($request)->string('filename' . $key);
85
86            // If no filename specified, use the original filename.
87            if ($filename === '') {
88                $filename = $uploaded_file->getClientFilename();
89            }
90
91            // Validate the folder
92            if (!$all_folders->contains($folder)) {
93                break;
94            }
95
96            // Validate the filename.
97            $filename = str_replace('\\', '/', $filename);
98            $filename = trim($filename, '/');
99
100            if (preg_match('/([:])/', $filename, $match)) {
101                // Local media files cannot contain certain special characters, especially on MS Windows
102                FlashMessages::addMessage(I18N::translate('Filenames are not allowed to contain the character “%s”.', $match[1]));
103                continue;
104            }
105
106            if (preg_match('/(\.(php|pl|cgi|bash|sh|bat|exe|com|htm|html|shtml))$/i', $filename, $match)) {
107                // Do not allow obvious script files.
108                FlashMessages::addMessage(I18N::translate('Filenames are not allowed to have the extension “%s”.', $match[1]));
109                continue;
110            }
111
112            $path = $folder . $filename;
113
114            try {
115                $file_exists = $data_filesystem->fileExists($path);
116            } catch (FilesystemException | UnableToCheckFileExistence) {
117                $file_exists = false;
118            }
119
120            if ($file_exists) {
121                FlashMessages::addMessage(I18N::translate('The file %s already exists. Use another filename.', $path, 'error'));
122                continue;
123            }
124
125            // Now copy the file to the correct location.
126            try {
127                $data_filesystem->writeStream($path, $uploaded_file->getStream()->detach());
128                FlashMessages::addMessage(I18N::translate('The file %s has been uploaded.', Html::filename($path)), 'success');
129                Log::addMediaLog('Media file ' . $path . ' uploaded');
130            } catch (FilesystemException | UnableToWriteFile $ex) {
131                FlashMessages::addMessage(I18N::translate('There was an error uploading your file.') . '<br>' . e($ex->getMessage()), 'danger');
132            }
133        }
134
135        $url = route(UploadMediaPage::class);
136
137        return redirect($url);
138    }
139}
140