xref: /webtrees/app/Media.php (revision 1061e22b1b45229338a3a3f8a1ab6b200c36b100)
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 Closure;
23use Exception;
24use Fisharebest\Webtrees\Functions\FunctionsPrintFacts;
25use Fisharebest\Webtrees\Http\RequestHandlers\MediaPage;
26use Illuminate\Database\Capsule\Manager as DB;
27use Illuminate\Support\Collection;
28use stdClass;
29
30/**
31 * A GEDCOM media (OBJE) object.
32 */
33class Media extends GedcomRecord
34{
35    public const RECORD_TYPE = 'OBJE';
36
37    protected const ROUTE_NAME = MediaPage::class;
38
39    /**
40     * A closure which will create a record from a database row.
41     *
42     * @param Tree $tree
43     *
44     * @return Closure
45     */
46    public static function rowMapper(Tree $tree): Closure
47    {
48        return static function (stdClass $row) use ($tree): Media {
49            $media = Media::getInstance($row->m_id, $tree, $row->m_gedcom);
50            assert($media instanceof Media);
51
52            return $media;
53        };
54    }
55
56    /**
57     * Get an instance of a media object. For single records,
58     * we just receive the XREF. For bulk records (such as lists
59     * and search results) we can receive the GEDCOM data as well.
60     *
61     * @param string      $xref
62     * @param Tree        $tree
63     * @param string|null $gedcom
64     *
65     * @throws Exception
66     *
67     * @return Media|null
68     */
69    public static function getInstance(string $xref, Tree $tree, string $gedcom = null): ?Media
70    {
71        $record = parent::getInstance($xref, $tree, $gedcom);
72
73        if ($record instanceof self) {
74            return $record;
75        }
76
77        return null;
78    }
79
80    /**
81     * Each object type may have its own special rules, and re-implement this function.
82     *
83     * @param int $access_level
84     *
85     * @return bool
86     */
87    protected function canShowByType(int $access_level): bool
88    {
89        // Hide media objects if they are attached to private records
90        $linked_ids = DB::table('link')
91            ->where('l_file', '=', $this->tree->id())
92            ->where('l_to', '=', $this->xref)
93            ->pluck('l_from');
94
95        foreach ($linked_ids as $linked_id) {
96            $linked_record = GedcomRecord::getInstance($linked_id, $this->tree);
97            if ($linked_record && !$linked_record->canShow($access_level)) {
98                return false;
99            }
100        }
101
102        // ... otherwise apply default behavior
103        return parent::canShowByType($access_level);
104    }
105
106    /**
107     * Fetch data from the database
108     *
109     * @param string $xref
110     * @param int    $tree_id
111     *
112     * @return string|null
113     */
114    protected static function fetchGedcomRecord(string $xref, int $tree_id): ?string
115    {
116        return DB::table('media')
117            ->where('m_id', '=', $xref)
118            ->where('m_file', '=', $tree_id)
119            ->value('m_gedcom');
120    }
121
122    /**
123     * Get the media files for this media object
124     *
125     * @return Collection<MediaFile>
126     */
127    public function mediaFiles(): Collection
128    {
129        return $this->facts(['FILE'])
130            ->map(function (Fact $fact): MediaFile {
131                return new MediaFile($fact->gedcom(), $this);
132            });
133    }
134
135    /**
136     * Get the first media file that contains an image.
137     *
138     * @return MediaFile|null
139     */
140    public function firstImageFile(): ?MediaFile
141    {
142        return $this->mediaFiles()
143            ->first(static function (MediaFile $media_file): bool {
144                return $media_file->isImage() && !$media_file->isExternal();
145            });
146    }
147
148    /**
149     * Get the first note attached to this media object
150     *
151     * @return string
152     */
153    public function getNote(): string
154    {
155        $fact = $this->facts(['NOTE'])->first();
156
157        if ($fact instanceof Fact) {
158            // Link to note object
159            $note = $fact->target();
160            if ($note instanceof Note) {
161                return $note->getNote();
162            }
163
164            // Inline note
165            return $fact->value();
166        }
167
168        return '';
169    }
170
171    /**
172     * Extract names from the GEDCOM record.
173     *
174     * @return void
175     */
176    public function extractNames(): void
177    {
178        $names = [];
179        foreach ($this->mediaFiles() as $media_file) {
180            $names[] = $media_file->title();
181        }
182        foreach ($this->mediaFiles() as $media_file) {
183            $names[] = $media_file->filename();
184        }
185        $names = array_filter(array_unique($names));
186
187        if ($names === []) {
188            $names[] = $this->getFallBackName();
189        }
190
191        foreach ($names as $name) {
192            $this->addName(static::RECORD_TYPE, $name, '');
193        }
194    }
195
196    /**
197     * This function should be redefined in derived classes to show any major
198     * identifying characteristics of this record.
199     *
200     * @return string
201     */
202    public function formatListDetails(): string
203    {
204        ob_start();
205        FunctionsPrintFacts::printMediaLinks($this->tree(), '1 OBJE @' . $this->xref() . '@', 1);
206
207        return ob_get_clean();
208    }
209
210    /**
211     * Display an image-thumbnail or a media-icon, and add markup for image viewers such as colorbox.
212     *
213     * @param int      $width      Pixels
214     * @param int      $height     Pixels
215     * @param string   $fit        "crop" or "contain"
216     * @param string[] $attributes Additional HTML attributes
217     *
218     * @return string
219     */
220    public function displayImage($width, $height, $fit, $attributes = []): string
221    {
222        // Display the first image
223        foreach ($this->mediaFiles() as $media_file) {
224            if ($media_file->isImage()) {
225                return $media_file->displayImage($width, $height, $fit, $attributes);
226            }
227        }
228
229        // Display the first file of any type
230        $media_file = $this->mediaFiles()->first();
231
232        if ($media_file instanceof MediaFile) {
233            return $media_file->displayImage($width, $height, $fit, $attributes);
234        }
235
236        // No image?
237        return '';
238    }
239}
240