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