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