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