xref: /webtrees/app/Http/RequestHandlers/EditMediaFileAction.php (revision 2ebcf907ed34213f816592af04e6c160335d6311)
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\Auth;
23use Fisharebest\Webtrees\FlashMessages;
24use Fisharebest\Webtrees\Html;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\MediaFile;
27use Fisharebest\Webtrees\Registry;
28use Fisharebest\Webtrees\Services\MediaFileService;
29use Fisharebest\Webtrees\Services\PendingChangesService;
30use Fisharebest\Webtrees\Tree;
31use League\Flysystem\FilesystemException;
32use League\Flysystem\UnableToMoveFile;
33use League\Flysystem\UnableToRetrieveMetadata;
34use Psr\Http\Message\ResponseInterface;
35use Psr\Http\Message\ServerRequestInterface;
36use Psr\Http\Server\RequestHandlerInterface;
37
38use function assert;
39use function is_string;
40use function preg_replace;
41use function redirect;
42use function route;
43use function str_replace;
44use function trim;
45
46/**
47 * Edit a media file.
48 */
49class EditMediaFileAction implements RequestHandlerInterface
50{
51    private MediaFileService $media_file_service;
52
53    private PendingChangesService $pending_changes_service;
54
55    /**
56     * EditMediaFileAction constructor.
57     *
58     * @param MediaFileService      $media_file_service
59     * @param PendingChangesService $pending_changes_service
60     */
61    public function __construct(MediaFileService $media_file_service, PendingChangesService $pending_changes_service)
62    {
63        $this->media_file_service      = $media_file_service;
64        $this->pending_changes_service = $pending_changes_service;
65    }
66
67    /**
68     * Save an edited media file.
69     *
70     * @param ServerRequestInterface $request
71     *
72     * @return ResponseInterface
73     */
74    public function handle(ServerRequestInterface $request): ResponseInterface
75    {
76        $tree = $request->getAttribute('tree');
77        assert($tree instanceof Tree);
78
79        $xref = $request->getAttribute('xref');
80        assert(is_string($xref));
81
82        $fact_id = $request->getAttribute('fact_id');
83        assert(is_string($fact_id));
84
85        $data_filesystem = Registry::filesystem()->data();
86
87        $params   = (array) $request->getParsedBody();
88        $folder   = $params['folder'] ?? '';
89        $new_file = $params['new_file'] ?? '';
90        $remote   = $params['remote'] ?? '';
91        $title    = $params['title'] ?? '';
92        $type     = $params['type'] ?? '';
93        $media    = Registry::mediaFactory()->make($xref, $tree);
94        $media    = Auth::checkMediaAccess($media, true);
95
96        // Tidy non-printing characters
97        $type  = trim(preg_replace('/\s+/', ' ', $type));
98        $title = trim(preg_replace('/\s+/', ' ', $title));
99
100        // Find the fact to edit
101        $media_file = $media->mediaFiles()
102            ->first(static function (MediaFile $media_file) use ($fact_id): bool {
103                return $media_file->factId() === $fact_id;
104            });
105
106        // Media file does not exist?
107        if ($media_file === null) {
108            return redirect(route(TreePage::class, ['tree' => $tree->name()]));
109        }
110
111        // We can edit the file as either a URL or a folder/file
112        if ($remote !== '') {
113            $file = $remote;
114        } else {
115            $new_file = str_replace('\\', '/', $new_file);
116            $folder   = str_replace('\\', '/', $folder);
117            $folder   = trim($folder, '/');
118
119            if ($folder === '') {
120                $file = $new_file;
121            } else {
122                $file = $folder . '/' . $new_file;
123            }
124        }
125
126        // Invalid filename?  Do not change it.
127        if ($new_file === '') {
128            $file = $media_file->filename();
129        }
130
131        $filesystem = $media->tree()->mediaFilesystem($data_filesystem);
132        $old        = $media_file->filename();
133        $new        = $file;
134
135        // Update the filesystem, if we can.
136        if ($old !== $new && !$media_file->isExternal() && $filesystem->fileExists($old)) {
137            try {
138                $file_exists = $filesystem->fileExists($old);
139
140                if ($file_exists) {
141                    try {
142                        $filesystem->move($old, $new);
143                        FlashMessages::addMessage(I18N::translate('The media file %1$s has been renamed to %2$s.', Html::filename($media_file->filename()), Html::filename($file)), 'info');
144                    } catch (FilesystemException | UnableToMoveFile $ex) {
145                        // Don't overwrite existing file
146                        FlashMessages::addMessage(I18N::translate('The media file %1$s could not be renamed to %2$s.', Html::filename($media_file->filename()), Html::filename($file)), 'info');
147                        $file = $old;
148                    }
149                }
150            } catch (FilesystemException | UnableToRetrieveMetadata $ex) {
151                // File does not exist?
152            }
153        }
154
155        $gedcom = $this->media_file_service->createMediaFileGedcom($file, $type, $title, '');
156
157        $media->updateFact($fact_id, $gedcom, true);
158
159        // Accept the changes, to keep the filesystem in sync with the GEDCOM data.
160        if ($old !== $new && !$media_file->isExternal()) {
161            $this->pending_changes_service->acceptRecord($media);
162        }
163
164        return redirect($media->url());
165    }
166}
167