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