xref: /webtrees/app/MediaFile.php (revision 64c83a78b4caa4bdc810446739df37776e706d8d)
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                'markalpha' => 25,
262            ];
263        }
264
265        $params['s'] = SignatureFactory::create($glide_key)->generateSignature('', $params);
266
267        return route(MediaFileThumbnail::class, $params);
268    }
269
270    /**
271     * Is the media file an image?
272     */
273    public function isImage(): bool
274    {
275        return in_array($this->mimeType(), self::SUPPORTED_IMAGE_MIME_TYPES, true);
276    }
277
278    /**
279     * What is the mime-type of this object?
280     * For simplicity and efficiency, use the extension, rather than the contents.
281     *
282     * @return string
283     */
284    public function mimeType(): string
285    {
286        $extension = strtolower(pathinfo($this->multimedia_file_refn, PATHINFO_EXTENSION));
287
288        return Mime::TYPES[$extension] ?? Mime::DEFAULT_TYPE;
289    }
290
291    /**
292     * Generate a URL to download a non-image media file.
293     *
294     * @param string $disposition How should the image be returned - "attachment" or "inline"
295     *
296     * @return string
297     */
298    public function downloadUrl(string $disposition): string
299    {
300        return route(MediaFileDownload::class, [
301            'xref'        => $this->media->xref(),
302            'tree'        => $this->media->tree()->name(),
303            'fact_id'     => $this->fact_id,
304            'disposition' => $disposition,
305        ]);
306    }
307
308    /**
309     * A list of image attributes
310     *
311     * @param FilesystemInterface $data_filesystem
312     *
313     * @return string[]
314     */
315    public function attributes(FilesystemInterface $data_filesystem): array
316    {
317        $attributes = [];
318
319        if (!$this->isExternal() || $this->fileExists($data_filesystem)) {
320            try {
321                $bytes                       = $this->media()->tree()->mediaFilesystem($data_filesystem)->getSize($this->filename());
322                $kb                          = intdiv($bytes + 1023, 1024);
323                $attributes['__FILE_SIZE__'] = I18N::translate('%s KB', I18N::number($kb));
324            } catch (FileNotFoundException $ex) {
325                // External/missing files have no size.
326            }
327
328            // Note: getAdapter() is defined on Filesystem, but not on FilesystemInterface.
329            $filesystem = $this->media()->tree()->mediaFilesystem($data_filesystem);
330            if ($filesystem instanceof Filesystem) {
331                $adapter = $filesystem->getAdapter();
332                // Only works for local filesystems.
333                if ($adapter instanceof Local) {
334                    $file = $adapter->applyPathPrefix($this->filename());
335                    [$width, $height] = getimagesize($file);
336                    $attributes['__IMAGE_SIZE__'] = I18N::translate('%1$s × %2$s pixels', I18N::number($width), I18N::number($height));
337                }
338            }
339        }
340
341        return $attributes;
342    }
343
344    /**
345     * Read the contents of a media file.
346     *
347     * @param FilesystemInterface $data_filesystem
348     *
349     * @return string
350     */
351    public function fileContents(FilesystemInterface $data_filesystem): string
352    {
353        return $this->media->tree()->mediaFilesystem($data_filesystem)->read($this->multimedia_file_refn);
354    }
355
356    /**
357     * Check if the file exists on this server
358     *
359     * @param FilesystemInterface $data_filesystem
360     *
361     * @return bool
362     */
363    public function fileExists(FilesystemInterface $data_filesystem): bool
364    {
365        return $this->media->tree()->mediaFilesystem($data_filesystem)->has($this->multimedia_file_refn);
366    }
367
368    /**
369     * @return Media
370     */
371    public function media(): Media
372    {
373        return $this->media;
374    }
375
376    /**
377     * Get the filename.
378     *
379     * @return string
380     */
381    public function filename(): string
382    {
383        return $this->multimedia_file_refn;
384    }
385
386    /**
387     * What file extension is used by this file?
388     *
389     * @return string
390     *
391     * @deprecated since 2.0.4.  Will be removed in 2.1.0
392     */
393    public function extension(): string
394    {
395        return pathinfo($this->multimedia_file_refn, PATHINFO_EXTENSION);
396    }
397}
398