xref: /webtrees/app/MediaFile.php (revision 10e0649788c8d7d4974d81c048ca2b225df8f22e)
18f5f5da8SGreg Roach<?php
23976b470SGreg Roach
38f5f5da8SGreg Roach/**
48f5f5da8SGreg Roach * webtrees: online genealogy
55bfc6897SGreg Roach * Copyright (C) 2022 webtrees development team
68f5f5da8SGreg Roach * This program is free software: you can redistribute it and/or modify
78f5f5da8SGreg Roach * it under the terms of the GNU General Public License as published by
88f5f5da8SGreg Roach * the Free Software Foundation, either version 3 of the License, or
98f5f5da8SGreg Roach * (at your option) any later version.
108f5f5da8SGreg Roach * This program is distributed in the hope that it will be useful,
118f5f5da8SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
128f5f5da8SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
138f5f5da8SGreg Roach * GNU General Public License for more details.
148f5f5da8SGreg Roach * You should have received a copy of the GNU General Public License
1589f7189bSGreg Roach * along with this program. If not, see <https://www.gnu.org/licenses/>.
168f5f5da8SGreg Roach */
17fcfa147eSGreg Roach
18e7f56f2aSGreg Roachdeclare(strict_types=1);
19e7f56f2aSGreg Roach
208f5f5da8SGreg Roachnamespace Fisharebest\Webtrees;
218f5f5da8SGreg Roach
2246b03695SGreg Roachuse Fisharebest\Webtrees\Http\RequestHandlers\MediaFileDownload;
2346b03695SGreg Roachuse Fisharebest\Webtrees\Http\RequestHandlers\MediaFileThumbnail;
24f7cf8a15SGreg Roachuse League\Flysystem\FilesystemException;
25f7cf8a15SGreg Roachuse League\Flysystem\FilesystemOperator;
26f0448b68SGreg Roachuse League\Flysystem\UnableToCheckFileExistence;
27f0448b68SGreg Roachuse League\Flysystem\UnableToReadFile;
28f0448b68SGreg Roachuse League\Flysystem\UnableToRetrieveMetadata;
293976b470SGreg Roach
306577bfc3SGreg Roachuse function bin2hex;
31f7cf8a15SGreg Roachuse function getimagesizefromstring;
326577bfc3SGreg Roachuse function http_build_query;
33*10e06497SGreg Roachuse function in_array;
3485a166d8SGreg Roachuse function intdiv;
35*10e06497SGreg Roachuse function is_array;
366577bfc3SGreg Roachuse function ksort;
376577bfc3SGreg Roachuse function md5;
3885a166d8SGreg Roachuse function pathinfo;
396577bfc3SGreg Roachuse function random_bytes;
40dec352c1SGreg Roachuse function str_contains;
410ea5fc1cSGreg Roachuse function strtoupper;
423976b470SGreg Roach
4385a166d8SGreg Roachuse const PATHINFO_EXTENSION;
448f5f5da8SGreg Roach
458f5f5da8SGreg Roach/**
468f5f5da8SGreg Roach * A GEDCOM media file.  A media object can contain many media files,
478f5f5da8SGreg Roach * such as scans of both sides of a document, the transcript of an audio
488f5f5da8SGreg Roach * recording, etc.
498f5f5da8SGreg Roach */
50c1010edaSGreg Roachclass MediaFile
51c1010edaSGreg Roach{
5285a166d8SGreg Roach    private const SUPPORTED_IMAGE_MIME_TYPES = [
5385a166d8SGreg Roach        'image/gif',
5485a166d8SGreg Roach        'image/jpeg',
5585a166d8SGreg Roach        'image/png',
56c68bc8e2SGreg Roach        'image/webp',
5785a166d8SGreg Roach    ];
5885a166d8SGreg Roach
59693fd32aSGreg Roach    private string $multimedia_file_refn = '';
608f5f5da8SGreg Roach
61693fd32aSGreg Roach    private string $multimedia_format = '';
628f5f5da8SGreg Roach
63693fd32aSGreg Roach    private string $source_media_type = '';
648f5f5da8SGreg Roach
65693fd32aSGreg Roach    private string $descriptive_title = '';
668f5f5da8SGreg Roach
67693fd32aSGreg Roach    private Media $media;
688f5f5da8SGreg Roach
69693fd32aSGreg Roach    private string $fact_id;
7064b90bf1SGreg Roach
718f5f5da8SGreg Roach    /**
728f5f5da8SGreg Roach     * Create a MediaFile from raw GEDCOM data.
738f5f5da8SGreg Roach     *
748f5f5da8SGreg Roach     * @param string $gedcom
758f5f5da8SGreg Roach     * @param Media  $media
768f5f5da8SGreg Roach     */
7724f2a3afSGreg Roach    public function __construct(string $gedcom, Media $media)
78c1010edaSGreg Roach    {
798f5f5da8SGreg Roach        $this->media   = $media;
8064b90bf1SGreg Roach        $this->fact_id = md5($gedcom);
818f5f5da8SGreg Roach
828f5f5da8SGreg Roach        if (preg_match('/^\d FILE (.+)/m', $gedcom, $match)) {
838f5f5da8SGreg Roach            $this->multimedia_file_refn = $match[1];
848f5f5da8SGreg Roach        }
858f5f5da8SGreg Roach
868f5f5da8SGreg Roach        if (preg_match('/^\d FORM (.+)/m', $gedcom, $match)) {
878f5f5da8SGreg Roach            $this->multimedia_format = $match[1];
888f5f5da8SGreg Roach        }
898f5f5da8SGreg Roach
908f5f5da8SGreg Roach        if (preg_match('/^\d TYPE (.+)/m', $gedcom, $match)) {
918f5f5da8SGreg Roach            $this->source_media_type = $match[1];
928f5f5da8SGreg Roach        }
938f5f5da8SGreg Roach
948f5f5da8SGreg Roach        if (preg_match('/^\d TITL (.+)/m', $gedcom, $match)) {
958f5f5da8SGreg Roach            $this->descriptive_title = $match[1];
968f5f5da8SGreg Roach        }
978f5f5da8SGreg Roach    }
988f5f5da8SGreg Roach
998f5f5da8SGreg Roach    /**
10064b90bf1SGreg Roach     * Get the format.
1018f5f5da8SGreg Roach     *
1028f5f5da8SGreg Roach     * @return string
1038f5f5da8SGreg Roach     */
104c1010edaSGreg Roach    public function format(): string
105c1010edaSGreg Roach    {
1068f5f5da8SGreg Roach        return $this->multimedia_format;
1078f5f5da8SGreg Roach    }
1088f5f5da8SGreg Roach
1098f5f5da8SGreg Roach    /**
11064b90bf1SGreg Roach     * Get the type.
1118f5f5da8SGreg Roach     *
1128f5f5da8SGreg Roach     * @return string
1138f5f5da8SGreg Roach     */
114c1010edaSGreg Roach    public function type(): string
115c1010edaSGreg Roach    {
1168f5f5da8SGreg Roach        return $this->source_media_type;
1178f5f5da8SGreg Roach    }
1188f5f5da8SGreg Roach
1198f5f5da8SGreg Roach    /**
12064b90bf1SGreg Roach     * Get the title.
1218f5f5da8SGreg Roach     *
1228f5f5da8SGreg Roach     * @return string
1238f5f5da8SGreg Roach     */
124c1010edaSGreg Roach    public function title(): string
125c1010edaSGreg Roach    {
1268f5f5da8SGreg Roach        return $this->descriptive_title;
1278f5f5da8SGreg Roach    }
1288f5f5da8SGreg Roach
1298f5f5da8SGreg Roach    /**
13064b90bf1SGreg Roach     * Get the fact ID.
13164b90bf1SGreg Roach     *
13264b90bf1SGreg Roach     * @return string
13364b90bf1SGreg Roach     */
134c1010edaSGreg Roach    public function factId(): string
135c1010edaSGreg Roach    {
13664b90bf1SGreg Roach        return $this->fact_id;
13764b90bf1SGreg Roach    }
13864b90bf1SGreg Roach
13964b90bf1SGreg Roach    /**
140d6641c58SGreg Roach     * @return bool
141d6641c58SGreg Roach     */
1428f53f488SRico Sonntag    public function isPendingAddition(): bool
143c1010edaSGreg Roach    {
14430158ae7SGreg Roach        foreach ($this->media->facts() as $fact) {
145905ab80aSGreg Roach            if ($fact->id() === $this->fact_id) {
146d6641c58SGreg Roach                return $fact->isPendingAddition();
147d6641c58SGreg Roach            }
148d6641c58SGreg Roach        }
149d6641c58SGreg Roach
150d6641c58SGreg Roach        return false;
151d6641c58SGreg Roach    }
152d6641c58SGreg Roach
153d6641c58SGreg Roach    /**
154d6641c58SGreg Roach     * @return bool
155d6641c58SGreg Roach     */
1568f53f488SRico Sonntag    public function isPendingDeletion(): bool
157c1010edaSGreg Roach    {
15830158ae7SGreg Roach        foreach ($this->media->facts() as $fact) {
159905ab80aSGreg Roach            if ($fact->id() === $this->fact_id) {
160d6641c58SGreg Roach                return $fact->isPendingDeletion();
161d6641c58SGreg Roach            }
162d6641c58SGreg Roach        }
163d6641c58SGreg Roach
164d6641c58SGreg Roach        return false;
165d6641c58SGreg Roach    }
166d6641c58SGreg Roach
167d6641c58SGreg Roach    /**
16864b90bf1SGreg Roach     * Display an image-thumbnail or a media-icon, and add markup for image viewers such as colorbox.
16964b90bf1SGreg Roach     *
17064b90bf1SGreg Roach     * @param int                  $width            Pixels
17164b90bf1SGreg Roach     * @param int                  $height           Pixels
17264b90bf1SGreg Roach     * @param string               $fit              "crop" or "contain"
17324f2a3afSGreg Roach     * @param array<string,string> $image_attributes Additional HTML attributes
17464b90bf1SGreg Roach     *
17564b90bf1SGreg Roach     * @return string
17664b90bf1SGreg Roach     */
17724f2a3afSGreg Roach    public function displayImage(int $width, int $height, string $fit, array $image_attributes = []): string
178c1010edaSGreg Roach    {
17964b90bf1SGreg Roach        if ($this->isExternal()) {
18064b90bf1SGreg Roach            $src    = $this->multimedia_file_refn;
18164b90bf1SGreg Roach            $srcset = [];
18264b90bf1SGreg Roach        } else {
18364b90bf1SGreg Roach            // Generate multiple images for displays with higher pixel densities.
18464b90bf1SGreg Roach            $src    = $this->imageUrl($width, $height, $fit);
18564b90bf1SGreg Roach            $srcset = [];
186bb308685SGreg Roach            foreach ([2, 3, 4] as $x) {
18764b90bf1SGreg Roach                $srcset[] = $this->imageUrl($width * $x, $height * $x, $fit) . ' ' . $x . 'x';
18864b90bf1SGreg Roach            }
18964b90bf1SGreg Roach        }
19064b90bf1SGreg Roach
19148b53306SGreg Roach        if ($this->isImage()) {
192e364afe4SGreg Roach            $image = '<img ' . Html::attributes($image_attributes + [
19364b90bf1SGreg Roach                        'dir'    => 'auto',
19464b90bf1SGreg Roach                        'src'    => $src,
19564b90bf1SGreg Roach                        'srcset' => implode(',', $srcset),
196d33f6d5eSGreg Roach                        'alt'    => strip_tags($this->media->fullName()),
19764b90bf1SGreg Roach                    ]) . '>';
19864b90bf1SGreg Roach
199e364afe4SGreg Roach            $link_attributes = Html::attributes([
20064b90bf1SGreg Roach                'class'      => 'gallery',
20164b90bf1SGreg Roach                'type'       => $this->mimeType(),
2026577bfc3SGreg Roach                'href'       => $this->downloadUrl('inline'),
203d33f6d5eSGreg Roach                'data-title' => strip_tags($this->media->fullName()),
20464b90bf1SGreg Roach            ]);
205e1d1700bSGreg Roach        } else {
20648b53306SGreg Roach            $image = view('icons/mime', ['type' => $this->mimeType()]);
207e364afe4SGreg Roach
208e364afe4SGreg Roach            $link_attributes = Html::attributes([
209e1d1700bSGreg Roach                'type' => $this->mimeType(),
21071625badSGreg Roach                'href' => $this->downloadUrl('inline'),
211e1d1700bSGreg Roach            ]);
212e1d1700bSGreg Roach        }
21364b90bf1SGreg Roach
214e364afe4SGreg Roach        return '<a ' . $link_attributes . '>' . $image . '</a>';
21564b90bf1SGreg Roach    }
21664b90bf1SGreg Roach
2174a9f750fSGreg Roach    /**
2184a9f750fSGreg Roach     * Is the media file actually a URL?
2194a9f750fSGreg Roach     */
220c1010edaSGreg Roach    public function isExternal(): bool
221c1010edaSGreg Roach    {
222dec352c1SGreg Roach        return str_contains($this->multimedia_file_refn, '://');
2234a9f750fSGreg Roach    }
2244a9f750fSGreg Roach
2254a9f750fSGreg Roach    /**
2268f5f5da8SGreg Roach     * Generate a URL for an image.
2278f5f5da8SGreg Roach     *
2288f5f5da8SGreg Roach     * @param int    $width  Maximum width in pixels
2298f5f5da8SGreg Roach     * @param int    $height Maximum height in pixels
2308f5f5da8SGreg Roach     * @param string $fit    "crop" or "contain"
2318f5f5da8SGreg Roach     *
2328f5f5da8SGreg Roach     * @return string
2338f5f5da8SGreg Roach     */
23424f2a3afSGreg Roach    public function imageUrl(int $width, int $height, string $fit): string
235c1010edaSGreg Roach    {
2368f5f5da8SGreg Roach        // Sign the URL, to protect against mass-resize attacks.
2378f5f5da8SGreg Roach        $glide_key = Site::getPreference('glide-key');
23846b03695SGreg Roach
23954c1ab5eSGreg Roach        if ($glide_key === '') {
2408f5f5da8SGreg Roach            $glide_key = bin2hex(random_bytes(128));
2418f5f5da8SGreg Roach            Site::setPreference('glide-key', $glide_key);
2428f5f5da8SGreg Roach        }
2438f5f5da8SGreg Roach
2446577bfc3SGreg Roach        // The "mark" parameter is ignored, but needed for cache-busting.
245ee4364daSGreg Roach        $params = [
246c0935879SGreg Roach            'xref'      => $this->media->xref(),
247d72b284aSGreg Roach            'tree'      => $this->media->tree()->name(),
2484a9f750fSGreg Roach            'fact_id'   => $this->fact_id,
2498f5f5da8SGreg Roach            'w'         => $width,
2508f5f5da8SGreg Roach            'h'         => $height,
2518f5f5da8SGreg Roach            'fit'       => $fit,
2526b9cb339SGreg Roach            'mark'      => Registry::imageFactory()->thumbnailNeedsWatermark($this, Auth::user())
25346b03695SGreg Roach        ];
25446b03695SGreg Roach
2556577bfc3SGreg Roach        $params['s'] = $this->signature($params);
256ee4364daSGreg Roach
25746b03695SGreg Roach        return route(MediaFileThumbnail::class, $params);
2588f5f5da8SGreg Roach    }
2598f5f5da8SGreg Roach
2608f5f5da8SGreg Roach    /**
26185a166d8SGreg Roach     * Is the media file an image?
2628f5f5da8SGreg Roach     */
26385a166d8SGreg Roach    public function isImage(): bool
264c1010edaSGreg Roach    {
26585a166d8SGreg Roach        return in_array($this->mimeType(), self::SUPPORTED_IMAGE_MIME_TYPES, true);
2668f5f5da8SGreg Roach    }
2678f5f5da8SGreg Roach
2688f5f5da8SGreg Roach    /**
2698f5f5da8SGreg Roach     * What is the mime-type of this object?
2708f5f5da8SGreg Roach     * For simplicity and efficiency, use the extension, rather than the contents.
2718f5f5da8SGreg Roach     *
2728f5f5da8SGreg Roach     * @return string
2738f5f5da8SGreg Roach     */
2748f53f488SRico Sonntag    public function mimeType(): string
275c1010edaSGreg Roach    {
2760ea5fc1cSGreg Roach        $extension = strtoupper(pathinfo($this->multimedia_file_refn, PATHINFO_EXTENSION));
27785a166d8SGreg Roach
278e7f16b43SGreg Roach        return Mime::TYPES[$extension] ?? Mime::DEFAULT_TYPE;
27985a166d8SGreg Roach    }
28085a166d8SGreg Roach
28185a166d8SGreg Roach    /**
2826577bfc3SGreg Roach     * Generate a URL to download a media file.
28385a166d8SGreg Roach     *
28471625badSGreg Roach     * @param string $disposition How should the image be returned - "attachment" or "inline"
28571625badSGreg Roach     *
28685a166d8SGreg Roach     * @return string
28785a166d8SGreg Roach     */
28871625badSGreg Roach    public function downloadUrl(string $disposition): string
28985a166d8SGreg Roach    {
2906577bfc3SGreg Roach        // The "mark" parameter is ignored, but needed for cache-busting.
29146b03695SGreg Roach        return route(MediaFileDownload::class, [
29285a166d8SGreg Roach            'xref'        => $this->media->xref(),
293d72b284aSGreg Roach            'tree'        => $this->media->tree()->name(),
29485a166d8SGreg Roach            'fact_id'     => $this->fact_id,
29571625badSGreg Roach            'disposition' => $disposition,
2966b9cb339SGreg Roach            'mark'        => Registry::imageFactory()->fileNeedsWatermark($this, Auth::user())
29785a166d8SGreg Roach        ]);
29885a166d8SGreg Roach    }
29985a166d8SGreg Roach
30085a166d8SGreg Roach    /**
30185a166d8SGreg Roach     * A list of image attributes
30285a166d8SGreg Roach     *
303f7cf8a15SGreg Roach     * @param FilesystemOperator $data_filesystem
3048a3784e1SGreg Roach     *
30569cdf014SGreg Roach     * @return array<string,string>
30685a166d8SGreg Roach     */
307f7cf8a15SGreg Roach    public function attributes(FilesystemOperator $data_filesystem): array
30885a166d8SGreg Roach    {
30985a166d8SGreg Roach        $attributes = [];
31085a166d8SGreg Roach
311a04bb9a2SGreg Roach        if (!$this->isExternal() || $this->fileExists($data_filesystem)) {
31285a166d8SGreg Roach            try {
313f7cf8a15SGreg Roach                $bytes = $this->media()->tree()->mediaFilesystem($data_filesystem)->fileSize($this->filename());
31485a166d8SGreg Roach                $kb    = intdiv($bytes + 1023, 1024);
315693fd32aSGreg Roach                $text  = I18N::translate('%s KB', I18N::number($kb));
316693fd32aSGreg Roach
317693fd32aSGreg Roach                $attributes[I18N::translate('File size')] = $text;
318f0448b68SGreg Roach            } catch (FilesystemException | UnableToRetrieveMetadata $ex) {
31985a166d8SGreg Roach                // External/missing files have no size.
32085a166d8SGreg Roach            }
32185a166d8SGreg Roach
322a04bb9a2SGreg Roach            $filesystem = $this->media()->tree()->mediaFilesystem($data_filesystem);
323f0448b68SGreg Roach            try {
324f0448b68SGreg Roach                $data       = $filesystem->read($this->filename());
325693fd32aSGreg Roach                $image_size = getimagesizefromstring($data);
326693fd32aSGreg Roach
327693fd32aSGreg Roach                if (is_array($image_size)) {
328693fd32aSGreg Roach                    [$width, $height] = $image_size;
329693fd32aSGreg Roach
330693fd32aSGreg Roach                    $text = I18N::translate('%1$s × %2$s pixels', I18N::number($width), I18N::number($height));
331693fd32aSGreg Roach
332693fd32aSGreg Roach                    $attributes[I18N::translate('Image dimensions')] = $text;
333693fd32aSGreg Roach                }
334f0448b68SGreg Roach            } catch (FilesystemException | UnableToReadFile $ex) {
335f0448b68SGreg Roach                // Cannot read the file.
336f0448b68SGreg Roach            }
3375c98992aSGreg Roach        }
33885a166d8SGreg Roach
33985a166d8SGreg Roach        return $attributes;
34085a166d8SGreg Roach    }
34185a166d8SGreg Roach
34285a166d8SGreg Roach    /**
34329518ad2SGreg Roach     * Read the contents of a media file.
34429518ad2SGreg Roach     *
345f7cf8a15SGreg Roach     * @param FilesystemOperator $data_filesystem
346a04bb9a2SGreg Roach     *
34729518ad2SGreg Roach     * @return string
34829518ad2SGreg Roach     */
349f7cf8a15SGreg Roach    public function fileContents(FilesystemOperator $data_filesystem): string
35029518ad2SGreg Roach    {
351f0448b68SGreg Roach        try {
352a04bb9a2SGreg Roach            return $this->media->tree()->mediaFilesystem($data_filesystem)->read($this->multimedia_file_refn);
353f0448b68SGreg Roach        } catch (FilesystemException | UnableToReadFile $ex) {
354f0448b68SGreg Roach            return '';
355f0448b68SGreg Roach        }
35629518ad2SGreg Roach    }
35729518ad2SGreg Roach
35829518ad2SGreg Roach    /**
35929518ad2SGreg Roach     * Check if the file exists on this server
36085a166d8SGreg Roach     *
361f7cf8a15SGreg Roach     * @param FilesystemOperator $data_filesystem
362a04bb9a2SGreg Roach     *
36385a166d8SGreg Roach     * @return bool
36485a166d8SGreg Roach     */
365f7cf8a15SGreg Roach    public function fileExists(FilesystemOperator $data_filesystem): bool
36685a166d8SGreg Roach    {
367f0448b68SGreg Roach        try {
368f7cf8a15SGreg Roach            return $this->media->tree()->mediaFilesystem($data_filesystem)->fileExists($this->multimedia_file_refn);
369f0448b68SGreg Roach        } catch (FilesystemException | UnableToCheckFileExistence $ex) {
370f0448b68SGreg Roach            return false;
371f0448b68SGreg Roach        }
37285a166d8SGreg Roach    }
37385a166d8SGreg Roach
37485a166d8SGreg Roach    /**
37585a166d8SGreg Roach     * @return Media
37685a166d8SGreg Roach     */
37785a166d8SGreg Roach    public function media(): Media
37885a166d8SGreg Roach    {
37985a166d8SGreg Roach        return $this->media;
38085a166d8SGreg Roach    }
38185a166d8SGreg Roach
38285a166d8SGreg Roach    /**
38385a166d8SGreg Roach     * Get the filename.
38485a166d8SGreg Roach     *
38585a166d8SGreg Roach     * @return string
38685a166d8SGreg Roach     */
38785a166d8SGreg Roach    public function filename(): string
38885a166d8SGreg Roach    {
38985a166d8SGreg Roach        return $this->multimedia_file_refn;
39085a166d8SGreg Roach    }
39185a166d8SGreg Roach
39285a166d8SGreg Roach    /**
393fceda430SGreg Roach     * Create a URL signature parameter, using the same algorithm as league/glide,
3946577bfc3SGreg Roach     * for compatibility with URLs generated by older versions of webtrees.
3956577bfc3SGreg Roach     *
3966577bfc3SGreg Roach     * @param array<mixed> $params
3976577bfc3SGreg Roach     *
3986577bfc3SGreg Roach     * @return string
3996577bfc3SGreg Roach     */
4006577bfc3SGreg Roach    public function signature(array $params): string
4016577bfc3SGreg Roach    {
4026577bfc3SGreg Roach        unset($params['s']);
4036577bfc3SGreg Roach
4046577bfc3SGreg Roach        ksort($params);
4056577bfc3SGreg Roach
4066577bfc3SGreg Roach        // Sign the URL, to protect against mass-resize attacks.
4076577bfc3SGreg Roach        $glide_key = Site::getPreference('glide-key');
4086577bfc3SGreg Roach
4096577bfc3SGreg Roach        if ($glide_key === '') {
4106577bfc3SGreg Roach            $glide_key = bin2hex(random_bytes(128));
4116577bfc3SGreg Roach            Site::setPreference('glide-key', $glide_key);
4126577bfc3SGreg Roach        }
4136577bfc3SGreg Roach
4146577bfc3SGreg Roach        return md5($glide_key . ':?' . http_build_query($params));
4156577bfc3SGreg Roach    }
4168f5f5da8SGreg Roach}
417