xref: /webtrees/app/MediaFile.php (revision 9b802b22a7b94d1d30e0433dd46fe641f3757505)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees;
19
20use League\Glide\Urls\UrlBuilderFactory;
21use Throwable;
22
23/**
24 * A GEDCOM media file.  A media object can contain many media files,
25 * such as scans of both sides of a document, the transcript of an audio
26 * recording, etc.
27 */
28class MediaFile
29{
30    private const MIME_TYPES = [
31        'bmp'  => 'image/bmp',
32        'doc'  => 'application/msword',
33        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
34        'ged'  => 'text/x-gedcom',
35        'gif'  => 'image/gif',
36        'html' => 'text/html',
37        'htm'  => 'text/html',
38        'jpeg' => 'image/jpeg',
39        'jpg'  => 'image/jpeg',
40        'mov'  => 'video/quicktime',
41        'mp3'  => 'audio/mpeg',
42        'mp4'  => 'video/mp4',
43        'ogv'  => 'video/ogg',
44        'pdf'  => 'application/pdf',
45        'png'  => 'image/png',
46        'rar'  => 'application/x-rar-compressed',
47        'swf'  => 'application/x-shockwave-flash',
48        'svg'  => 'image/svg',
49        'tiff' => 'image/tiff',
50        'tif'  => 'image/tiff',
51        'xls'  => 'application/vnd-ms-excel',
52        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
53        'wmv'  => 'video/x-ms-wmv',
54        'zip'  => 'application/zip',
55    ];
56
57    /** @var string The filename */
58    private $multimedia_file_refn = '';
59
60    /** @var string The file extension; jpeg, txt, mp4, etc. */
61    private $multimedia_format = '';
62
63    /** @var string The type of document; newspaper, microfiche, etc. */
64    private $source_media_type = '';
65    /** @var string The filename */
66
67    /** @var string The name of the document */
68    private $descriptive_title = '';
69
70    /** @var Media $media The media object to which this file belongs */
71    private $media;
72
73    /** @var string */
74    private $fact_id;
75
76    /**
77     * Create a MediaFile from raw GEDCOM data.
78     *
79     * @param string $gedcom
80     * @param Media  $media
81     */
82    public function __construct($gedcom, Media $media)
83    {
84        $this->media   = $media;
85        $this->fact_id = md5($gedcom);
86
87        if (preg_match('/^\d FILE (.+)/m', $gedcom, $match)) {
88            $this->multimedia_file_refn = $match[1];
89            $this->multimedia_format    = pathinfo($match[1], PATHINFO_EXTENSION);
90        }
91
92        if (preg_match('/^\d FORM (.+)/m', $gedcom, $match)) {
93            $this->multimedia_format = $match[1];
94        }
95
96        if (preg_match('/^\d TYPE (.+)/m', $gedcom, $match)) {
97            $this->source_media_type = $match[1];
98        }
99
100        if (preg_match('/^\d TITL (.+)/m', $gedcom, $match)) {
101            $this->descriptive_title = $match[1];
102        }
103    }
104
105    /**
106     * Get the filename.
107     *
108     * @return string
109     */
110    public function filename(): string
111    {
112        return $this->multimedia_file_refn;
113    }
114
115    /**
116     * Get the base part of the filename.
117     *
118     * @return string
119     */
120    public function basename(): string
121    {
122        return basename($this->multimedia_file_refn);
123    }
124
125    /**
126     * Get the folder part of the filename.
127     *
128     * @return string
129     */
130    public function dirname(): string
131    {
132        $dirname = dirname($this->multimedia_file_refn);
133
134        if ($dirname === '.') {
135            return '';
136        }
137
138        return $dirname;
139    }
140
141    /**
142     * Get the format.
143     *
144     * @return string
145     */
146    public function format(): string
147    {
148        return $this->multimedia_format;
149    }
150
151    /**
152     * Get the type.
153     *
154     * @return string
155     */
156    public function type(): string
157    {
158        return $this->source_media_type;
159    }
160
161    /**
162     * Get the title.
163     *
164     * @return string
165     */
166    public function title(): string
167    {
168        return $this->descriptive_title;
169    }
170
171    /**
172     * Get the fact ID.
173     *
174     * @return string
175     */
176    public function factId(): string
177    {
178        return $this->fact_id;
179    }
180
181    /**
182     * @return bool
183     */
184    public function isPendingAddition(): bool
185    {
186        foreach ($this->media->facts() as $fact) {
187            if ($fact->id() === $this->fact_id) {
188                return $fact->isPendingAddition();
189            }
190        }
191
192        return false;
193    }
194
195    /**
196     * @return bool
197     */
198    public function isPendingDeletion(): bool
199    {
200        foreach ($this->media->facts() as $fact) {
201            if ($fact->id() === $this->fact_id) {
202                return $fact->isPendingDeletion();
203            }
204        }
205
206        return false;
207    }
208
209    /**
210     * Display an image-thumbnail or a media-icon, and add markup for image viewers such as colorbox.
211     *
212     * @param int      $width      Pixels
213     * @param int      $height     Pixels
214     * @param string   $fit        "crop" or "contain"
215     * @param string[] $attributes Additional HTML attributes
216     *
217     * @return string
218     */
219    public function displayImage($width, $height, $fit, $attributes = []): string
220    {
221        if ($this->isExternal()) {
222            $src    = $this->multimedia_file_refn;
223            $srcset = [];
224        } else {
225            // Generate multiple images for displays with higher pixel densities.
226            $src    = $this->imageUrl($width, $height, $fit);
227            $srcset = [];
228            foreach ([
229                         2,
230                         3,
231                         4,
232                     ] as $x) {
233                $srcset[] = $this->imageUrl($width * $x, $height * $x, $fit) . ' ' . $x . 'x';
234            }
235        }
236
237        $image = '<img ' . Html::attributes($attributes + [
238                    'dir'    => 'auto',
239                    'src'    => $src,
240                    'srcset' => implode(',', $srcset),
241                    'alt'    => htmlspecialchars_decode(strip_tags($this->media->getFullName())),
242                ]) . '>';
243
244        if ($this->isImage()) {
245            $attributes = Html::attributes([
246                'class'      => 'gallery',
247                'type'       => $this->mimeType(),
248                'href'       => $this->imageUrl(0, 0, 'contain'),
249                'data-title' => htmlspecialchars_decode(strip_tags($this->media->getFullName())),
250            ]);
251        } else {
252            $attributes = Html::attributes([
253                'type' => $this->mimeType(),
254                'href' => $this->downloadUrl(),
255            ]);
256        }
257
258        return '<a ' . $attributes . '>' . $image . '</a>';
259    }
260
261    /**
262     * A list of image attributes
263     *
264     * @return string[]
265     */
266    public function attributes(): array
267    {
268        $attributes = [];
269
270        if (!$this->isExternal() || $this->fileExists()) {
271            $file = $this->folder() . $this->multimedia_file_refn;
272
273            $attributes['__FILE_SIZE__'] = $this->fileSizeKB();
274
275            $imgsize = getimagesize($file);
276            if (is_array($imgsize) && !empty($imgsize['0'])) {
277                $attributes['__IMAGE_SIZE__'] = I18N::translate('%1$s × %2$s pixels', I18N::number($imgsize['0']), I18N::number($imgsize['1']));
278            }
279        }
280
281        return $attributes;
282    }
283
284    /**
285     * check if the file exists on this server
286     *
287     * @return bool
288     */
289    public function fileExists(): bool
290    {
291        return !$this->isExternal() && file_exists($this->folder() . $this->multimedia_file_refn);
292    }
293
294    /**
295     * Is the media file actually a URL?
296     */
297    public function isExternal(): bool
298    {
299        return strpos($this->multimedia_file_refn, '://') !== false;
300    }
301
302    /**
303     * Is the media file an image?
304     */
305    public function isImage(): bool
306    {
307        return in_array($this->extension(), [
308            'jpeg',
309            'jpg',
310            'gif',
311            'png',
312        ]);
313    }
314
315    /**
316     * Where is the file stored on disk?
317     */
318    public function folder(): string
319    {
320        return WT_DATA_DIR . $this->media->tree()->getPreference('MEDIA_DIRECTORY');
321    }
322
323    /**
324     * A user-friendly view of the file size
325     *
326     * @return int
327     */
328    private function fileSizeBytes(): int
329    {
330        try {
331            return filesize($this->folder() . $this->multimedia_file_refn);
332        } catch (Throwable $ex) {
333            return 0;
334        }
335    }
336
337    /**
338     * get the media file size in KB
339     *
340     * @return string
341     */
342    public function fileSizeKB(): string
343    {
344        $size = $this->fileSizeBytes();
345        $size = intdiv($size + 1023, 1024);
346
347        /* I18N: size of file in KB */
348        return I18N::translate('%s KB', I18N::number($size));
349    }
350
351    /**
352     * Get the filename on the server - for those (very few!) functions which actually
353     * need the filename, such as the PDF reports.
354     *
355     * @return string
356     */
357    public function getServerFilename()
358    {
359        $MEDIA_DIRECTORY = $this->media->tree()->getPreference('MEDIA_DIRECTORY');
360
361        if ($this->isExternal() || !$this->multimedia_file_refn) {
362            // External image, or (in the case of corrupt GEDCOM data) no image at all
363            return $this->multimedia_file_refn;
364        }
365
366        // Main image
367        return WT_DATA_DIR . $MEDIA_DIRECTORY . $this->multimedia_file_refn;
368    }
369
370    /**
371     * Generate a URL to download a non-image media file.
372     *
373     * @return string
374     */
375    public function downloadUrl(): string
376    {
377        return route('media-download', [
378            'xref'    => $this->media->xref(),
379            'ged'     => $this->media->tree()->name(),
380            'fact_id' => $this->fact_id,
381        ]);
382    }
383
384    /**
385     * Generate a URL for an image.
386     *
387     * @param int    $width  Maximum width in pixels
388     * @param int    $height Maximum height in pixels
389     * @param string $fit    "crop" or "contain"
390     *
391     * @return string
392     */
393    public function imageUrl($width, $height, $fit): string
394    {
395        // Sign the URL, to protect against mass-resize attacks.
396        $glide_key = Site::getPreference('glide-key');
397        if (empty($glide_key)) {
398            $glide_key = bin2hex(random_bytes(128));
399            Site::setPreference('glide-key', $glide_key);
400        }
401
402        if (Auth::accessLevel($this->media->tree()) > $this->media->tree()->getPreference('SHOW_NO_WATERMARK')) {
403            $mark = 'watermark.png';
404        } else {
405            $mark = '';
406        }
407
408        $url_builder = UrlBuilderFactory::create(WT_BASE_URL, $glide_key);
409
410        $url = $url_builder->getUrl('index.php', [
411            'route'     => 'media-thumbnail',
412            'xref'      => $this->media->xref(),
413            'ged'       => $this->media->tree()->name(),
414            'fact_id'   => $this->fact_id,
415            'w'         => $width,
416            'h'         => $height,
417            'fit'       => $fit,
418            'mark'      => $mark,
419            'markh'     => '100h',
420            'markw'     => '100w',
421            'markalpha' => 25,
422            'or'        => 0,
423            // Intervention uses exif_read_data() which is very buggy.
424        ]);
425
426        return $url;
427    }
428
429    /**
430     * What file extension is used by this file?
431     *
432     * @return string
433     */
434    public function extension()
435    {
436        if (preg_match('/\.([a-zA-Z0-9]+)$/', $this->multimedia_file_refn, $match)) {
437            return strtolower($match[1]);
438        }
439
440        return '';
441    }
442
443    /**
444     * What is the mime-type of this object?
445     * For simplicity and efficiency, use the extension, rather than the contents.
446     *
447     * @return string
448     */
449    public function mimeType(): string
450    {
451        return self::MIME_TYPES[$this->extension()] ?? 'application/octet-stream';
452    }
453}
454