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