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