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