xref: /webtrees/app/MediaFile.php (revision 9f9acdbc09170c04c1e150c36ee57d49027e314a)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Fisharebest\Webtrees\Http\RequestHandlers\MediaFileDownload;
23use Fisharebest\Webtrees\Http\RequestHandlers\MediaFileThumbnail;
24use League\Flysystem\Adapter\Local;
25use League\Flysystem\FileNotFoundException;
26use League\Flysystem\Filesystem;
27use League\Flysystem\FilesystemInterface;
28use League\Glide\Signatures\SignatureFactory;
29
30use function getimagesize;
31use function intdiv;
32use function pathinfo;
33use function str_contains;
34use function strtolower;
35
36use const PATHINFO_EXTENSION;
37
38/**
39 * A GEDCOM media file.  A media object can contain many media files,
40 * such as scans of both sides of a document, the transcript of an audio
41 * recording, etc.
42 */
43class MediaFile
44{
45    private const SUPPORTED_IMAGE_MIME_TYPES = [
46        'image/gif',
47        'image/jpeg',
48        'image/png',
49    ];
50
51    /** @var string The filename */
52    private $multimedia_file_refn = '';
53
54    /** @var string The file extension; jpeg, txt, mp4, etc. */
55    private $multimedia_format = '';
56
57    /** @var string The type of document; newspaper, microfiche, etc. */
58    private $source_media_type = '';
59    /** @var string The filename */
60
61    /** @var string The name of the document */
62    private $descriptive_title = '';
63
64    /** @var Media $media The media object to which this file belongs */
65    private $media;
66
67    /** @var string */
68    private $fact_id;
69
70    /**
71     * Create a MediaFile from raw GEDCOM data.
72     *
73     * @param string $gedcom
74     * @param Media  $media
75     */
76    public function __construct($gedcom, Media $media)
77    {
78        $this->media   = $media;
79        $this->fact_id = md5($gedcom);
80
81        if (preg_match('/^\d FILE (.+)/m', $gedcom, $match)) {
82            $this->multimedia_file_refn = $match[1];
83            $this->multimedia_format    = pathinfo($match[1], PATHINFO_EXTENSION);
84        }
85
86        if (preg_match('/^\d FORM (.+)/m', $gedcom, $match)) {
87            $this->multimedia_format = $match[1];
88        }
89
90        if (preg_match('/^\d TYPE (.+)/m', $gedcom, $match)) {
91            $this->source_media_type = $match[1];
92        }
93
94        if (preg_match('/^\d TITL (.+)/m', $gedcom, $match)) {
95            $this->descriptive_title = $match[1];
96        }
97    }
98
99    /**
100     * Get the format.
101     *
102     * @return string
103     */
104    public function format(): string
105    {
106        return $this->multimedia_format;
107    }
108
109    /**
110     * Get the type.
111     *
112     * @return string
113     */
114    public function type(): string
115    {
116        return $this->source_media_type;
117    }
118
119    /**
120     * Get the title.
121     *
122     * @return string
123     */
124    public function title(): string
125    {
126        return $this->descriptive_title;
127    }
128
129    /**
130     * Get the fact ID.
131     *
132     * @return string
133     */
134    public function factId(): string
135    {
136        return $this->fact_id;
137    }
138
139    /**
140     * @return bool
141     */
142    public function isPendingAddition(): bool
143    {
144        foreach ($this->media->facts() as $fact) {
145            if ($fact->id() === $this->fact_id) {
146                return $fact->isPendingAddition();
147            }
148        }
149
150        return false;
151    }
152
153    /**
154     * @return bool
155     */
156    public function isPendingDeletion(): bool
157    {
158        foreach ($this->media->facts() as $fact) {
159            if ($fact->id() === $this->fact_id) {
160                return $fact->isPendingDeletion();
161            }
162        }
163
164        return false;
165    }
166
167    /**
168     * Display an image-thumbnail or a media-icon, and add markup for image viewers such as colorbox.
169     *
170     * @param int      $width            Pixels
171     * @param int      $height           Pixels
172     * @param string   $fit              "crop" or "contain"
173     * @param string[] $image_attributes Additional HTML attributes
174     *
175     * @return string
176     */
177    public function displayImage($width, $height, $fit, $image_attributes = []): string
178    {
179        if ($this->isExternal()) {
180            $src    = $this->multimedia_file_refn;
181            $srcset = [];
182        } else {
183            // Generate multiple images for displays with higher pixel densities.
184            $src    = $this->imageUrl($width, $height, $fit);
185            $srcset = [];
186            foreach ([2, 3, 4] as $x) {
187                $srcset[] = $this->imageUrl($width * $x, $height * $x, $fit) . ' ' . $x . 'x';
188            }
189        }
190
191        if ($this->isImage()) {
192            $image = '<img ' . Html::attributes($image_attributes + [
193                        'dir'    => 'auto',
194                        'src'    => $src,
195                        'srcset' => implode(',', $srcset),
196                        'alt'    => strip_tags($this->media->fullName()),
197                    ]) . '>';
198
199            $link_attributes = Html::attributes([
200                'class'      => 'gallery',
201                'type'       => $this->mimeType(),
202                'href'       => $this->imageUrl(0, 0, 'contain'),
203                'data-title' => strip_tags($this->media->fullName()),
204            ]);
205        } else {
206            $image = view('icons/mime', ['type' => $this->mimeType()]);
207
208            $link_attributes = Html::attributes([
209                'type' => $this->mimeType(),
210                'href' => $this->downloadUrl('inline'),
211            ]);
212        }
213
214        return '<a ' . $link_attributes . '>' . $image . '</a>';
215    }
216
217    /**
218     * Is the media file actually a URL?
219     */
220    public function isExternal(): bool
221    {
222        return str_contains($this->multimedia_file_refn, '://');
223    }
224
225    /**
226     * Generate a URL for an image.
227     *
228     * @param int    $width  Maximum width in pixels
229     * @param int    $height Maximum height in pixels
230     * @param string $fit    "crop" or "contain"
231     *
232     * @return string
233     */
234    public function imageUrl($width, $height, $fit): string
235    {
236        // Sign the URL, to protect against mass-resize attacks.
237        $glide_key = Site::getPreference('glide-key');
238
239        if ($glide_key === '') {
240            $glide_key = bin2hex(random_bytes(128));
241            Site::setPreference('glide-key', $glide_key);
242        }
243
244        $params = [
245            'xref'      => $this->media->xref(),
246            'tree'      => $this->media->tree()->name(),
247            'fact_id'   => $this->fact_id,
248            'w'         => $width,
249            'h'         => $height,
250            'fit'       => $fit,
251            'or'        => 'or',
252            'q'         => 45,
253        ];
254
255        if (Auth::accessLevel($this->media->tree()) > $this->media->tree()->getPreference('SHOW_NO_WATERMARK')) {
256            $params += [
257                'mark'      => 'watermark.png',
258                'markh'     => '100h',
259                'markw'     => '100w',
260                'markpos'   => 'center',
261            ];
262        }
263
264        $params['s'] = SignatureFactory::create($glide_key)->generateSignature('', $params);
265
266        return route(MediaFileThumbnail::class, $params);
267    }
268
269    /**
270     * Is the media file an image?
271     */
272    public function isImage(): bool
273    {
274        return in_array($this->mimeType(), self::SUPPORTED_IMAGE_MIME_TYPES, true);
275    }
276
277    /**
278     * What is the mime-type of this object?
279     * For simplicity and efficiency, use the extension, rather than the contents.
280     *
281     * @return string
282     */
283    public function mimeType(): string
284    {
285        $extension = strtolower(pathinfo($this->multimedia_file_refn, PATHINFO_EXTENSION));
286
287        return Mime::TYPES[$extension] ?? Mime::DEFAULT_TYPE;
288    }
289
290    /**
291     * Generate a URL to download a non-image media file.
292     *
293     * @param string $disposition How should the image be returned - "attachment" or "inline"
294     *
295     * @return string
296     */
297    public function downloadUrl(string $disposition): string
298    {
299        return route(MediaFileDownload::class, [
300            'xref'        => $this->media->xref(),
301            'tree'        => $this->media->tree()->name(),
302            'fact_id'     => $this->fact_id,
303            'disposition' => $disposition,
304        ]);
305    }
306
307    /**
308     * A list of image attributes
309     *
310     * @param FilesystemInterface $data_filesystem
311     *
312     * @return string[]
313     */
314    public function attributes(FilesystemInterface $data_filesystem): array
315    {
316        $attributes = [];
317
318        if (!$this->isExternal() || $this->fileExists($data_filesystem)) {
319            try {
320                $bytes                       = $this->media()->tree()->mediaFilesystem($data_filesystem)->getSize($this->filename());
321                $kb                          = intdiv($bytes + 1023, 1024);
322                $attributes['__FILE_SIZE__'] = I18N::translate('%s KB', I18N::number($kb));
323            } catch (FileNotFoundException $ex) {
324                // External/missing files have no size.
325            }
326
327            // Note: getAdapter() is defined on Filesystem, but not on FilesystemInterface.
328            $filesystem = $this->media()->tree()->mediaFilesystem($data_filesystem);
329            if ($filesystem instanceof Filesystem) {
330                $adapter = $filesystem->getAdapter();
331                // Only works for local filesystems.
332                if ($adapter instanceof Local) {
333                    $file = $adapter->applyPathPrefix($this->filename());
334                    [$width, $height] = getimagesize($file);
335                    $attributes['__IMAGE_SIZE__'] = I18N::translate('%1$s × %2$s pixels', I18N::number($width), I18N::number($height));
336                }
337            }
338        }
339
340        return $attributes;
341    }
342
343    /**
344     * Read the contents of a media file.
345     *
346     * @param FilesystemInterface $data_filesystem
347     *
348     * @return string
349     */
350    public function fileContents(FilesystemInterface $data_filesystem): string
351    {
352        return $this->media->tree()->mediaFilesystem($data_filesystem)->read($this->multimedia_file_refn);
353    }
354
355    /**
356     * Check if the file exists on this server
357     *
358     * @param FilesystemInterface $data_filesystem
359     *
360     * @return bool
361     */
362    public function fileExists(FilesystemInterface $data_filesystem): bool
363    {
364        return $this->media->tree()->mediaFilesystem($data_filesystem)->has($this->multimedia_file_refn);
365    }
366
367    /**
368     * @return Media
369     */
370    public function media(): Media
371    {
372        return $this->media;
373    }
374
375    /**
376     * Get the filename.
377     *
378     * @return string
379     */
380    public function filename(): string
381    {
382        return $this->multimedia_file_refn;
383    }
384
385    /**
386     * What file extension is used by this file?
387     *
388     * @return string
389     *
390     * @deprecated since 2.0.4.  Will be removed in 2.1.0
391     */
392    public function extension(): string
393    {
394        return pathinfo($this->multimedia_file_refn, PATHINFO_EXTENSION);
395    }
396}
397