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