xref: /webtrees/app/Http/RequestHandlers/UploadMediaAction.php (revision 52672e95f9626642591e18327ff0eaa0bf5c2806)
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     * 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        $all_folders     = $this->media_file_service->allMediaFolders($data_filesystem);
74
75        foreach ($request->getUploadedFiles() as $key => $uploaded_file) {
76            if ($uploaded_file->getError() === UPLOAD_ERR_NO_FILE) {
77                continue;
78            }
79
80            if ($uploaded_file->getError() !== UPLOAD_ERR_OK) {
81                throw new FileUploadException($uploaded_file);
82            }
83
84            $key      = substr($key, 9);
85            $folder   = Validator::parsedBody($request)->string('folder' . $key);
86            $filename = Validator::parsedBody($request)->string('filename' . $key);
87
88            // If no filename specified, use the original filename.
89            if ($filename === '') {
90                $filename = $uploaded_file->getClientFilename();
91            }
92
93            // Validate the folder
94            if (!$all_folders->contains($folder)) {
95                break;
96            }
97
98            // Validate the filename.
99            $filename = str_replace('\\', '/', $filename);
100            $filename = trim($filename, '/');
101
102            if (preg_match('/([:])/', $filename, $match)) {
103                // Local media files cannot contain certain special characters, especially on MS Windows
104                FlashMessages::addMessage(I18N::translate('Filenames are not allowed to contain the character “%s”.', $match[1]));
105                continue;
106            }
107
108            if (preg_match('/(\.(php|pl|cgi|bash|sh|bat|exe|com|htm|html|shtml))$/i', $filename, $match)) {
109                // Do not allow obvious script files.
110                FlashMessages::addMessage(I18N::translate('Filenames are not allowed to have the extension “%s”.', $match[1]));
111                continue;
112            }
113
114            $path = $folder . $filename;
115
116            try {
117                $file_exists = $data_filesystem->fileExists($path);
118            } catch (FilesystemException | UnableToCheckFileExistence) {
119                $file_exists = false;
120            }
121
122            if ($file_exists) {
123                FlashMessages::addMessage(I18N::translate('The file %s already exists. Use another filename.', $path, 'error'));
124                continue;
125            }
126
127            // Now copy the file to the correct location.
128            try {
129                $data_filesystem->writeStream($path, $uploaded_file->getStream()->detach());
130                FlashMessages::addMessage(I18N::translate('The file %s has been uploaded.', Html::filename($path)), 'success');
131                Log::addMediaLog('Media file ' . $path . ' uploaded');
132            } catch (FilesystemException | UnableToWriteFile $ex) {
133                FlashMessages::addMessage(I18N::translate('There was an error uploading your file.') . '<br>' . e($ex->getMessage()), 'danger');
134            }
135        }
136
137        $url = route(UploadMediaPage::class);
138
139        return redirect($url);
140    }
141}
142