xref: /webtrees/app/Http/RequestHandlers/ManageMediaData.php (revision 8634febf6487fcb3ee7b59e88f828071a22cba22)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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\Http\Exceptions\HttpNotFoundException;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Media;
25use Fisharebest\Webtrees\Mime;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Services\DatatablesService;
28use Fisharebest\Webtrees\Services\LinkedRecordService;
29use Fisharebest\Webtrees\Services\MediaFileService;
30use Fisharebest\Webtrees\Services\TreeService;
31use Fisharebest\Webtrees\Validator;
32use Illuminate\Database\Capsule\Manager as DB;
33use Illuminate\Database\Query\Builder;
34use Illuminate\Database\Query\Expression;
35use Illuminate\Database\Query\JoinClause;
36use League\Flysystem\FilesystemException;
37use League\Flysystem\FilesystemOperator;
38use League\Flysystem\UnableToCheckFileExistence;
39use League\Flysystem\UnableToReadFile;
40use League\Flysystem\UnableToRetrieveMetadata;
41use Psr\Http\Message\ResponseInterface;
42use Psr\Http\Message\ServerRequestInterface;
43use Psr\Http\Server\RequestHandlerInterface;
44use Throwable;
45
46use function assert;
47use function e;
48use function getimagesizefromstring;
49use function intdiv;
50use function route;
51use function str_starts_with;
52use function strlen;
53use function substr;
54use function view;
55
56/**
57 * Manage media from the control panel.
58 */
59class ManageMediaData implements RequestHandlerInterface
60{
61    private DatatablesService $datatables_service;
62
63    private LinkedRecordService $linked_record_service;
64
65    private MediaFileService $media_file_service;
66
67    private TreeService $tree_service;
68
69    /**
70     * MediaController constructor.
71     *
72     * @param DatatablesService   $datatables_service
73     * @param LinkedRecordService $linked_record_service
74     * @param MediaFileService    $media_file_service
75     * @param TreeService         $tree_service
76     */
77    public function __construct(
78        DatatablesService $datatables_service,
79        LinkedRecordService $linked_record_service,
80        MediaFileService $media_file_service,
81        TreeService $tree_service
82    ) {
83        $this->datatables_service    = $datatables_service;
84        $this->linked_record_service = $linked_record_service;
85        $this->media_file_service    = $media_file_service;
86        $this->tree_service          = $tree_service;
87    }
88
89    /**
90     * @param ServerRequestInterface $request
91     *
92     * @return ResponseInterface
93     */
94    public function handle(ServerRequestInterface $request): ResponseInterface
95    {
96        $data_filesystem = Registry::filesystem()->data();
97
98        $files = Validator::queryParams($request)->isInArray(['local', 'external', 'unused'])->string('files');
99
100        // Files within this folder
101        $media_folder = Validator::queryParams($request)->string('media_folder');
102
103        // Show sub-folders within $media_folder
104        $subfolders = Validator::queryParams($request)->isInArray(['include', 'exclude'])->string('subfolders');
105
106        $search_columns = ['multimedia_file_refn', 'descriptive_title'];
107
108        $sort_columns = [
109            0 => 'multimedia_file_refn',
110            2 => new Expression('descriptive_title || multimedia_file_refn'),
111        ];
112
113        // Convert a row from the database into a row for datatables
114        $callback = function (object $row): array {
115            $tree  = $this->tree_service->find((int) $row->m_file);
116            $media = Registry::mediaFactory()->make($row->m_id, $tree, $row->m_gedcom);
117            assert($media instanceof Media);
118
119            $is_http  = str_starts_with($row->multimedia_file_refn, 'http://');
120            $is_https = str_starts_with($row->multimedia_file_refn, 'https://');
121
122            if ($is_http || $is_https) {
123                return [
124                    '<a href="' . e($row->multimedia_file_refn) . '">' . e($row->multimedia_file_refn) . '</a>',
125                    view('icons/mime', ['type' => Mime::DEFAULT_TYPE]),
126                    $this->mediaObjectInfo($media),
127                ];
128            }
129
130            try {
131                $path = $row->media_folder . $row->multimedia_file_refn;
132
133                try {
134                    $mime_type = Registry::filesystem()->data()->mimeType($path);
135                } catch (UnableToRetrieveMetadata) {
136                    $mime_type = Mime::DEFAULT_TYPE;
137                }
138
139                if (str_starts_with($mime_type, 'image/')) {
140                    $url = route(AdminMediaFileThumbnail::class, ['path' => $path]);
141                    $img = '<img src="' . e($url) . '">';
142                } else {
143                    $img = view('icons/mime', ['type' => $mime_type]);
144                }
145
146                $url = route(AdminMediaFileDownload::class, ['path' => $path]);
147                $img = '<a href="' . e($url) . '" type="' . $mime_type . '" class="gallery">' . $img . '</a>';
148            } catch (UnableToReadFile) {
149                $url = route(AdminMediaFileThumbnail::class, ['path' => $path]);
150                $img = '<img src="' . e($url) . '">';
151            }
152
153            return [
154                e($row->multimedia_file_refn),
155                $img,
156                $this->mediaObjectInfo($media),
157            ];
158        };
159
160        switch ($files) {
161            case 'local':
162                $query = DB::table('media_file')
163                    ->join('media', static function (JoinClause $join): void {
164                        $join
165                            ->on('media.m_file', '=', 'media_file.m_file')
166                            ->on('media.m_id', '=', 'media_file.m_id');
167                    })
168                    ->leftJoin('gedcom_setting', static function (JoinClause $join): void {
169                        $join
170                            ->on('gedcom_setting.gedcom_id', '=', 'media.m_file')
171                            ->where('setting_name', '=', 'MEDIA_DIRECTORY');
172                    })
173                    ->where('multimedia_file_refn', 'NOT LIKE', 'http://%')
174                    ->where('multimedia_file_refn', 'NOT LIKE', 'https://%')
175                    ->select([
176                        'media.*',
177                        'multimedia_file_refn',
178                        'descriptive_title',
179                        new Expression("COALESCE(setting_value, 'media/') AS media_folder"),
180                    ]);
181
182                $query->where(new Expression('setting_value || multimedia_file_refn'), 'LIKE', $media_folder . '%');
183
184                if ($subfolders === 'exclude') {
185                    $query->where(new Expression('setting_value || multimedia_file_refn'), 'NOT LIKE', $media_folder . '%/%');
186                }
187
188                return $this->datatables_service->handleQuery($request, $query, $search_columns, $sort_columns, $callback);
189
190            case 'external':
191                $query = DB::table('media_file')
192                    ->join('media', static function (JoinClause $join): void {
193                        $join
194                            ->on('media.m_file', '=', 'media_file.m_file')
195                            ->on('media.m_id', '=', 'media_file.m_id');
196                    })
197                    ->where(static function (Builder $query): void {
198                        $query
199                            ->where('multimedia_file_refn', 'LIKE', 'http://%')
200                            ->orWhere('multimedia_file_refn', 'LIKE', 'https://%');
201                    })
202                    ->select([
203                        'media.*',
204                        'multimedia_file_refn',
205                        'descriptive_title',
206                        new Expression("'' AS media_folder"),
207                    ]);
208
209                return $this->datatables_service->handleQuery($request, $query, $search_columns, $sort_columns, $callback);
210
211            case 'unused':
212                // Which trees use which media folder?
213                $media_trees = DB::table('gedcom')
214                    ->join('gedcom_setting', 'gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
215                    ->where('setting_name', '=', 'MEDIA_DIRECTORY')
216                    ->where('gedcom.gedcom_id', '>', 0)
217                    ->pluck('setting_value', 'gedcom_name');
218
219                $disk_files = $this->media_file_service->allFilesOnDisk($data_filesystem, $media_folder, $subfolders === 'include');
220                $db_files   = $this->media_file_service->allFilesInDatabase($media_folder, $subfolders === 'include');
221
222                // All unused files
223                $unused_files = $disk_files->diff($db_files)
224                    ->map(static function (string $file): array {
225                        return (array) $file;
226                    });
227
228                $search_columns = [0];
229                $sort_columns   = [0 => 0];
230
231                $callback = function (array $row) use ($data_filesystem, $media_trees): array {
232                    try {
233                        $mime_type = $data_filesystem->mimeType($row[0]) ?: Mime::DEFAULT_TYPE;
234                    } catch (FilesystemException | UnableToRetrieveMetadata) {
235                        $mime_type = Mime::DEFAULT_TYPE;
236                    }
237
238
239                    if (str_starts_with($mime_type, 'image/')) {
240                        $url = route(AdminMediaFileThumbnail::class, ['path' => $row[0]]);
241                        $img = '<img src="' . e($url) . '">';
242                    } else {
243                        $img = view('icons/mime', ['type' => $mime_type]);
244                    }
245
246                    $url = route(AdminMediaFileDownload::class, ['path' => $row[0]]);
247                    $img = '<a href="' . e($url) . '">' . $img . '</a>';
248
249                    // Form to create new media object in each tree
250                    $create_form = '';
251                    foreach ($media_trees as $media_tree => $media_directory) {
252                        if (str_starts_with($row[0], $media_directory)) {
253                            $tmp = substr($row[0], strlen($media_directory));
254                            $create_form .=
255                                '<p><a href="#" data-bs-toggle="modal" data-bs-backdrop="static" data-bs-target="#modal-create-media-from-file" data-file="' . e($tmp) . '" data-url="' . e(route(CreateMediaObjectFromFile::class, ['tree' => $media_tree])) . '" onclick="document.getElementById(\'modal-create-media-from-file-form\').action=this.dataset.url; document.getElementById(\'file\').value=this.dataset.file;">' . I18N::translate('Create') . '</a> — ' . e($media_tree) . '<p>';
256                        }
257                    }
258
259                    $delete_link = '<p><a data-wt-confirm="' . I18N::translate('Are you sure you want to delete “%s”?', e($row[0])) . '" data-wt-post-url="' . e(route(DeletePath::class, [
260                            'path' => $row[0],
261                        ])) . '" href="#">' . I18N::translate('Delete') . '</a></p>';
262
263                    return [
264                        $this->mediaFileInfo($data_filesystem, $row[0]) . $delete_link,
265                        $img,
266                        $create_form,
267                    ];
268                };
269
270                return $this->datatables_service->handleCollection($request, $unused_files, $search_columns, $sort_columns, $callback);
271
272            default:
273                throw new HttpNotFoundException();
274        }
275    }
276
277    /**
278     * Generate some useful information and links about a media object.
279     *
280     * @param Media $media
281     *
282     * @return string HTML
283     */
284    private function mediaObjectInfo(Media $media): string
285    {
286        $element = Registry::elementFactory()->make('NOTE:CONC');
287        $html    = '<a href="' . e($media->url()) . '" title="' . e($media->tree()->title()) . '">' . $media->fullName() . '</a>';
288
289        if ($this->tree_service->all()->count() > 1) {
290            $html .= ' — ' . e($media->tree()->title());
291        }
292
293        $html .= $element->value($media->getNote(), $media->tree());
294
295        $linked = [];
296
297        foreach ($this->linked_record_service->linkedIndividuals($media) as $link) {
298            $linked[] = view('icons/individual') . '<a href="' . e($link->url()) . '">' . $link->fullName() . '</a>';
299        }
300
301        foreach ($this->linked_record_service->linkedFamilies($media) as $link) {
302            $linked[] = view('icons/family') . '<a href="' . e($link->url()) . '">' . $link->fullName() . '</a>';
303        }
304
305        foreach ($this->linked_record_service->linkedSources($media) as $link) {
306            $linked[] = view('icons/source') . '<a href="' . e($link->url()) . '">' . $link->fullName() . '</a>';
307        }
308
309        foreach ($this->linked_record_service->linkedNotes($media) as $link) {
310            $linked[] = view('icons/note') . '<a href="' . e($link->url()) . '">' . $link->fullName() . '</a>';
311        }
312
313        foreach ($this->linked_record_service->linkedRepositories($media) as $link) {
314            $linked[] = view('icons/media') . '<a href="' . e($link->url()) . '">' . $link->fullName() . '</a>';
315        }
316
317        foreach ($this->linked_record_service->linkedMedia($media) as $link) {
318            $linked[] = view('icons/location') . '<a href="' . e($link->url()) . '">' . $link->fullName() . '</a>';
319        }
320
321        if ($linked !== []) {
322            $html .= '<ul class="list-unstyled">';
323            foreach ($linked as $link) {
324                $html .= '<li>' . $link . '</li>';
325            }
326            $html .= '</ul>';
327        } else {
328            $html .= '<div class="alert alert-danger">' . I18N::translate('There are no links to this media object.') . '</div>';
329        }
330
331        return $html;
332    }
333
334    /**
335     * Generate some useful information and links about a media file.
336     *
337     * @param FilesystemOperator $data_filesystem
338     * @param string             $file
339     *
340     * @return string
341     */
342    private function mediaFileInfo(FilesystemOperator $data_filesystem, string $file): string
343    {
344        $html = '<dl>';
345        $html .= '<dt>' . I18N::translate('Filename') . '</dt>';
346        $html .= '<dd>' . e($file) . '</dd>';
347
348        try {
349            $file_exists = $data_filesystem->fileExists($file);
350        } catch (FilesystemException | UnableToCheckFileExistence) {
351            $file_exists = false;
352        }
353
354        if ($file_exists) {
355            try {
356                $size = $data_filesystem->fileSize($file);
357            } catch (FilesystemException | UnableToRetrieveMetadata) {
358                $size = 0;
359            }
360            $size = intdiv($size + 1023, 1024); // Round up to next KB
361            /* I18N: size of file in KB */
362            $size = I18N::translate('%s KB', I18N::number($size));
363            $html .= '<dt>' . I18N::translate('File size') . '</dt>';
364            $html .= '<dd>' . $size . '</dd>';
365
366            try {
367                // This will work for local filesystems.  For remote filesystems, we will
368                // need to copy the file locally to work out the image size.
369                $imgsize = getimagesizefromstring($data_filesystem->read($file));
370                $html .= '<dt>' . I18N::translate('Image dimensions') . '</dt>';
371                /* I18N: image dimensions, width × height */
372                $html .= '<dd>' . I18N::translate('%1$s × %2$s pixels', I18N::number($imgsize['0']), I18N::number($imgsize['1'])) . '</dd>';
373            } catch (FilesystemException | UnableToReadFile | Throwable) {
374                // Not an image, or not a valid image?
375            }
376        }
377
378        $html .= '</dl>';
379
380        return $html;
381    }
382}
383