xref: /webtrees/app/Http/RequestHandlers/UploadMediaAction.php (revision f0c88a961929e1d14256ee4286994384bb29fbc1)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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 League\Flysystem\FilesystemException;
30use League\Flysystem\UnableToCheckFileExistence;
31use League\Flysystem\UnableToWriteFile;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34use Psr\Http\Server\RequestHandlerInterface;
35
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_NO_FILE;
45use const UPLOAD_ERR_OK;
46
47/**
48 * Manage media from the control panel.
49 */
50class UploadMediaAction implements RequestHandlerInterface
51{
52    private MediaFileService $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            if ($uploaded_file->getError() == UPLOAD_ERR_NO_FILE) {
79                continue;
80            }
81
82            if ($uploaded_file->getError() !== UPLOAD_ERR_OK) {
83                throw new FileUploadException($uploaded_file);
84            }
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            try {
120                $file_exists = $data_filesystem->fileExists($path);
121            } catch (FilesystemException | UnableToCheckFileExistence $ex) {
122                $file_exists = false;
123            }
124
125            if ($file_exists) {
126                FlashMessages::addMessage(I18N::translate('The file %s already exists. Use another filename.', $path, 'error'));
127                continue;
128            }
129
130            // Now copy the file to the correct location.
131            try {
132                $data_filesystem->writeStream($path, $uploaded_file->getStream()->detach());
133                FlashMessages::addMessage(I18N::translate('The file %s has been uploaded.', Html::filename($path)), 'success');
134                Log::addMediaLog('Media file ' . $path . ' uploaded');
135            } catch (FilesystemException | UnableToWriteFile $ex) {
136                FlashMessages::addMessage(I18N::translate('There was an error uploading your file.') . '<br>' . e($ex->getMessage()), 'danger');
137            }
138        }
139
140        $url = route(UploadMediaPage::class);
141
142        return redirect($url);
143    }
144}
145