xref: /webtrees/app/GedcomRecord.php (revision 74670d655f32fd507269018676acd5c651c2025b)
1a25f0a04SGreg Roach<?php
23976b470SGreg Roach
3a25f0a04SGreg Roach/**
4a25f0a04SGreg Roach * webtrees: online genealogy
58fcd0d32SGreg Roach * Copyright (C) 2019 webtrees development team
6a25f0a04SGreg Roach * This program is free software: you can redistribute it and/or modify
7a25f0a04SGreg Roach * it under the terms of the GNU General Public License as published by
8a25f0a04SGreg Roach * the Free Software Foundation, either version 3 of the License, or
9a25f0a04SGreg Roach * (at your option) any later version.
10a25f0a04SGreg Roach * This program is distributed in the hope that it will be useful,
11a25f0a04SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
12a25f0a04SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13a25f0a04SGreg Roach * GNU General Public License for more details.
14a25f0a04SGreg Roach * You should have received a copy of the GNU General Public License
15a25f0a04SGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
16a25f0a04SGreg Roach */
17fcfa147eSGreg Roach
18e7f56f2aSGreg Roachdeclare(strict_types=1);
19e7f56f2aSGreg Roach
2076692c8bSGreg Roachnamespace Fisharebest\Webtrees;
2176692c8bSGreg Roach
22886b77daSGreg Roachuse Closure;
237e96c925SGreg Roachuse Exception;
243d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsPrint;
255818a371SGreg Roachuse Fisharebest\Webtrees\Http\RequestHandlers\GedcomRecordPage;
2622e73debSGreg Roachuse Fisharebest\Webtrees\Services\PendingChangesService;
27bf4eb542SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
2883242252SGreg Roachuse Illuminate\Database\Query\Builder;
2983242252SGreg Roachuse Illuminate\Database\Query\Expression;
30ba1c12e8SGreg Roachuse Illuminate\Database\Query\JoinClause;
3139ca88baSGreg Roachuse Illuminate\Support\Collection;
3279529c87SGreg Roachuse stdClass;
33*74670d65SGreg Roachuse Throwable;
345ab92b3fSGreg Roachuse Transliterator;
35a25f0a04SGreg Roach
3622e73debSGreg Roachuse function app;
37f7440925SGreg Roachuse function array_shift;
38f7440925SGreg Roachuse function assert;
39f7440925SGreg Roachuse function class_exists;
40f7440925SGreg Roachuse function count;
41f7440925SGreg Roachuse function date;
42f7440925SGreg Roachuse function e;
43f7440925SGreg Roachuse function explode;
44f7440925SGreg Roachuse function in_array;
45f7440925SGreg Roachuse function md5;
46f7440925SGreg Roachuse function preg_match;
47f7440925SGreg Roachuse function preg_match_all;
48f7440925SGreg Roachuse function preg_replace;
49f7440925SGreg Roachuse function preg_replace_callback;
50f7440925SGreg Roachuse function preg_split;
51f7440925SGreg Roachuse function route;
52f7440925SGreg Roachuse function str_pad;
53f7440925SGreg Roachuse function strip_tags;
54f7440925SGreg Roachuse function strpos;
55f7440925SGreg Roachuse function strtoupper;
56f7440925SGreg Roachuse function trim;
57f7440925SGreg Roach
58f7440925SGreg Roachuse const PREG_SET_ORDER;
59f7440925SGreg Roachuse const STR_PAD_LEFT;
6022e73debSGreg Roach
61a25f0a04SGreg Roach/**
6276692c8bSGreg Roach * A GEDCOM object.
63a25f0a04SGreg Roach */
64c1010edaSGreg Roachclass GedcomRecord
65c1010edaSGreg Roach{
6616d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
6716d6367aSGreg Roach
685818a371SGreg Roach    protected const ROUTE_NAME = GedcomRecordPage::class;
695818a371SGreg Roach
7076692c8bSGreg Roach    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
71bec87e94SGreg Roach    public static $gedcom_record_cache;
7279529c87SGreg Roach    /** @var stdClass[][] Fetch all pending edits in one database query */
73bec87e94SGreg Roach    public static $pending_record_cache;
7422e73debSGreg Roach    /** @var string The record identifier */
7522e73debSGreg Roach    protected $xref;
7622e73debSGreg Roach    /** @var Tree  The family tree to which this record belongs */
7722e73debSGreg Roach    protected $tree;
7822e73debSGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
7922e73debSGreg Roach    protected $gedcom;
8022e73debSGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
8122e73debSGreg Roach    protected $pending;
8222e73debSGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
8322e73debSGreg Roach    protected $facts;
8422e73debSGreg Roach    /** @var string[][] All the names of this individual */
8522e73debSGreg Roach    protected $getAllNames;
8622e73debSGreg Roach    /** @var int|null Cached result */
8722e73debSGreg Roach    protected $getPrimaryName;
8822e73debSGreg Roach    /** @var int|null Cached result */
8922e73debSGreg Roach    protected $getSecondaryName;
90a25f0a04SGreg Roach
91a25f0a04SGreg Roach    /**
92a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
93a25f0a04SGreg Roach     *
94a25f0a04SGreg Roach     * @param string      $xref
95a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
96a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
97a25f0a04SGreg Roach     *                             empty string for records with pending deletions
9824ec66ceSGreg Roach     * @param Tree        $tree
99a25f0a04SGreg Roach     */
100e364afe4SGreg Roach    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
101c1010edaSGreg Roach    {
102a25f0a04SGreg Roach        $this->xref    = $xref;
103a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
104a25f0a04SGreg Roach        $this->pending = $pending;
10524ec66ceSGreg Roach        $this->tree    = $tree;
106a25f0a04SGreg Roach
107a25f0a04SGreg Roach        $this->parseFacts();
108a25f0a04SGreg Roach    }
109a25f0a04SGreg Roach
110a25f0a04SGreg Roach    /**
111886b77daSGreg Roach     * A closure which will create a record from a database row.
112886b77daSGreg Roach     *
113d5ad3db0SGreg Roach     * @param Tree $tree
114d5ad3db0SGreg Roach     *
115886b77daSGreg Roach     * @return Closure
116886b77daSGreg Roach     */
117d5ad3db0SGreg Roach    public static function rowMapper(Tree $tree): Closure
118886b77daSGreg Roach    {
119d5ad3db0SGreg Roach        return static function (stdClass $row) use ($tree): GedcomRecord {
120ffc0a61fSGreg Roach            $record = GedcomRecord::getInstance($row->o_id, $tree, $row->o_gedcom);
121ffc0a61fSGreg Roach            assert($record instanceof GedcomRecord);
122ffc0a61fSGreg Roach
123ffc0a61fSGreg Roach            return $record;
124886b77daSGreg Roach        };
125886b77daSGreg Roach    }
126886b77daSGreg Roach
127886b77daSGreg Roach    /**
128886b77daSGreg Roach     * A closure which will filter out private records.
129886b77daSGreg Roach     *
130886b77daSGreg Roach     * @return Closure
131886b77daSGreg Roach     */
1324146fabcSGreg Roach    public static function accessFilter(): Closure
133886b77daSGreg Roach    {
1346c2179e2SGreg Roach        return static function (GedcomRecord $record): bool {
135886b77daSGreg Roach            return $record->canShow();
136886b77daSGreg Roach        };
137886b77daSGreg Roach    }
138886b77daSGreg Roach
139886b77daSGreg Roach    /**
140c156e8f5SGreg Roach     * A closure which will compare records by name.
141c156e8f5SGreg Roach     *
142c156e8f5SGreg Roach     * @return Closure
143c156e8f5SGreg Roach     */
144c156e8f5SGreg Roach    public static function nameComparator(): Closure
145c156e8f5SGreg Roach    {
1466c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y): int {
147c156e8f5SGreg Roach            if ($x->canShowName()) {
148c156e8f5SGreg Roach                if ($y->canShowName()) {
14939ca88baSGreg Roach                    return I18N::strcasecmp($x->sortName(), $y->sortName());
150c156e8f5SGreg Roach                }
151c156e8f5SGreg Roach
152c156e8f5SGreg Roach                return -1; // only $y is private
153c156e8f5SGreg Roach            }
154c156e8f5SGreg Roach
155c156e8f5SGreg Roach            if ($y->canShowName()) {
156c156e8f5SGreg Roach                return 1; // only $x is private
157c156e8f5SGreg Roach            }
158c156e8f5SGreg Roach
159c156e8f5SGreg Roach            return 0; // both $x and $y private
160c156e8f5SGreg Roach        };
161c156e8f5SGreg Roach    }
162c156e8f5SGreg Roach
163c156e8f5SGreg Roach    /**
164c156e8f5SGreg Roach     * A closure which will compare records by change time.
165c156e8f5SGreg Roach     *
166c156e8f5SGreg Roach     * @param int $direction +1 to sort ascending, -1 to sort descending
167c156e8f5SGreg Roach     *
168c156e8f5SGreg Roach     * @return Closure
169c156e8f5SGreg Roach     */
170c156e8f5SGreg Roach    public static function lastChangeComparator(int $direction = 1): Closure
171c156e8f5SGreg Roach    {
1726c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
1734459dc9aSGreg Roach            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
174c156e8f5SGreg Roach        };
175c156e8f5SGreg Roach    }
176c156e8f5SGreg Roach
177c156e8f5SGreg Roach    /**
178a25f0a04SGreg Roach     * Get an instance of a GedcomRecord object. For single records,
179a25f0a04SGreg Roach     * we just receive the XREF. For bulk records (such as lists
180a25f0a04SGreg Roach     * and search results) we can receive the GEDCOM data as well.
181a25f0a04SGreg Roach     *
182a25f0a04SGreg Roach     * @param string      $xref
18324ec66ceSGreg Roach     * @param Tree        $tree
184a25f0a04SGreg Roach     * @param string|null $gedcom
185a25f0a04SGreg Roach     *
186ffc0a61fSGreg Roach     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|Submitter|null
18722e73debSGreg Roach     * @throws Exception
188a25f0a04SGreg Roach     */
18976f666f4SGreg Roach    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
190c1010edaSGreg Roach    {
19172cf66d4SGreg Roach        $tree_id = $tree->id();
19224ec66ceSGreg Roach
193e71ef9d2SGreg Roach        // Is this record already in the cache?
19424ec66ceSGreg Roach        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
195e71ef9d2SGreg Roach            return self::$gedcom_record_cache[$xref][$tree_id];
196a25f0a04SGreg Roach        }
197a25f0a04SGreg Roach
198a25f0a04SGreg Roach        // Do we need to fetch the record from the database?
199a25f0a04SGreg Roach        if ($gedcom === null) {
20024ec66ceSGreg Roach            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
201a25f0a04SGreg Roach        }
202a25f0a04SGreg Roach
203a25f0a04SGreg Roach        // If we can edit, then we also need to be able to see pending records.
20494075df0SGreg Roach        if (Auth::isEditor($tree)) {
20524ec66ceSGreg Roach            if (!isset(self::$pending_record_cache[$tree_id])) {
206a25f0a04SGreg Roach                // Fetch all pending records in one database query
20713abd6f3SGreg Roach                self::$pending_record_cache[$tree_id] = [];
20885fc8064SGreg Roach                $rows                                 = DB::table('change')
20985fc8064SGreg Roach                    ->where('gedcom_id', '=', $tree_id)
21085fc8064SGreg Roach                    ->where('status', '=', 'pending')
21185fc8064SGreg Roach                    ->orderBy('change_id')
21285fc8064SGreg Roach                    ->select(['xref', 'new_gedcom'])
21385fc8064SGreg Roach                    ->get();
214d17d7b9eSGreg Roach
215a25f0a04SGreg Roach                foreach ($rows as $row) {
21624ec66ceSGreg Roach                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
217a25f0a04SGreg Roach                }
218a25f0a04SGreg Roach            }
219a25f0a04SGreg Roach
220d17d7b9eSGreg Roach            $pending = self::$pending_record_cache[$tree_id][$xref] ?? null;
221a25f0a04SGreg Roach        } else {
222a25f0a04SGreg Roach            // There are no pending changes for this record
223a25f0a04SGreg Roach            $pending = null;
224a25f0a04SGreg Roach        }
225a25f0a04SGreg Roach
226a25f0a04SGreg Roach        // No such record exists
227a25f0a04SGreg Roach        if ($gedcom === null && $pending === null) {
228a25f0a04SGreg Roach            return null;
229a25f0a04SGreg Roach        }
230a25f0a04SGreg Roach
231fc3ccce4SGreg Roach        // No such record, but a pending creation exists
232fc3ccce4SGreg Roach        if ($gedcom === null) {
233fc3ccce4SGreg Roach            $gedcom = '';
234fc3ccce4SGreg Roach        }
235fc3ccce4SGreg Roach
236a25f0a04SGreg Roach        // Create the object
2378d0ebef0SGreg Roach        if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedcom . $pending, $match)) {
238a25f0a04SGreg Roach            $xref = $match[1]; // Collation - we may have requested I123 and found i123
239a25f0a04SGreg Roach            $type = $match[2];
240a25f0a04SGreg Roach        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
241a25f0a04SGreg Roach            $xref = $match[1];
242a25f0a04SGreg Roach            $type = $match[1];
243a25f0a04SGreg Roach        } elseif ($gedcom . $pending) {
2447e96c925SGreg Roach            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
245a25f0a04SGreg Roach        } else {
246a25f0a04SGreg Roach            // A record with both pending creation and pending deletion
247a25f0a04SGreg Roach            $type = static::RECORD_TYPE;
248a25f0a04SGreg Roach        }
249a25f0a04SGreg Roach
250a25f0a04SGreg Roach        switch ($type) {
251ac107fcfSGreg Roach            case Individual::RECORD_TYPE:
25224ec66ceSGreg Roach                $record = new Individual($xref, $gedcom, $pending, $tree);
253a25f0a04SGreg Roach                break;
254ac107fcfSGreg Roach
255ac107fcfSGreg Roach            case Family::RECORD_TYPE:
25624ec66ceSGreg Roach                $record = new Family($xref, $gedcom, $pending, $tree);
257a25f0a04SGreg Roach                break;
258ac107fcfSGreg Roach
259ac107fcfSGreg Roach            case Source::RECORD_TYPE:
26024ec66ceSGreg Roach                $record = new Source($xref, $gedcom, $pending, $tree);
261a25f0a04SGreg Roach                break;
262ac107fcfSGreg Roach
263ac107fcfSGreg Roach            case Media::RECORD_TYPE:
26424ec66ceSGreg Roach                $record = new Media($xref, $gedcom, $pending, $tree);
265a25f0a04SGreg Roach                break;
266ac107fcfSGreg Roach
267ac107fcfSGreg Roach            case Repository::RECORD_TYPE:
26824ec66ceSGreg Roach                $record = new Repository($xref, $gedcom, $pending, $tree);
269a25f0a04SGreg Roach                break;
270ac107fcfSGreg Roach
271ac107fcfSGreg Roach            case Note::RECORD_TYPE:
27224ec66ceSGreg Roach                $record = new Note($xref, $gedcom, $pending, $tree);
273a25f0a04SGreg Roach                break;
274ac107fcfSGreg Roach
275ac107fcfSGreg Roach            case Submitter::RECORD_TYPE:
276ffc0a61fSGreg Roach                $record = new Submitter($xref, $gedcom, $pending, $tree);
277ffc0a61fSGreg Roach                break;
278ac107fcfSGreg Roach
279a25f0a04SGreg Roach            default:
28006ef8e02SGreg Roach                $record = new self($xref, $gedcom, $pending, $tree);
281a25f0a04SGreg Roach                break;
282a25f0a04SGreg Roach        }
283a25f0a04SGreg Roach
284a25f0a04SGreg Roach        // Store it in the cache
28524ec66ceSGreg Roach        self::$gedcom_record_cache[$xref][$tree_id] = $record;
286a25f0a04SGreg Roach
287a25f0a04SGreg Roach        return $record;
288a25f0a04SGreg Roach    }
289a25f0a04SGreg Roach
290a25f0a04SGreg Roach    /**
291a25f0a04SGreg Roach     * Fetch data from the database
292a25f0a04SGreg Roach     *
293a25f0a04SGreg Roach     * @param string $xref
294cbc1590aSGreg Roach     * @param int    $tree_id
295a25f0a04SGreg Roach     *
296e364afe4SGreg Roach     * @return string|null
297a25f0a04SGreg Roach     */
298e364afe4SGreg Roach    protected static function fetchGedcomRecord(string $xref, int $tree_id): ?string
299c1010edaSGreg Roach    {
300a25f0a04SGreg Roach        // We don't know what type of object this is. Try each one in turn.
30164d9078aSGreg Roach        $data = Individual::fetchGedcomRecord($xref, $tree_id);
30285fc8064SGreg Roach        if ($data !== null) {
303a25f0a04SGreg Roach            return $data;
304a25f0a04SGreg Roach        }
30564d9078aSGreg Roach        $data = Family::fetchGedcomRecord($xref, $tree_id);
30685fc8064SGreg Roach        if ($data !== null) {
307a25f0a04SGreg Roach            return $data;
308a25f0a04SGreg Roach        }
30964d9078aSGreg Roach        $data = Source::fetchGedcomRecord($xref, $tree_id);
31085fc8064SGreg Roach        if ($data !== null) {
311a25f0a04SGreg Roach            return $data;
312a25f0a04SGreg Roach        }
31364d9078aSGreg Roach        $data = Repository::fetchGedcomRecord($xref, $tree_id);
31485fc8064SGreg Roach        if ($data !== null) {
315a25f0a04SGreg Roach            return $data;
316a25f0a04SGreg Roach        }
31764d9078aSGreg Roach        $data = Media::fetchGedcomRecord($xref, $tree_id);
31885fc8064SGreg Roach        if ($data !== null) {
319a25f0a04SGreg Roach            return $data;
320a25f0a04SGreg Roach        }
32164d9078aSGreg Roach        $data = Note::fetchGedcomRecord($xref, $tree_id);
32285fc8064SGreg Roach        if ($data !== null) {
323a25f0a04SGreg Roach            return $data;
324a25f0a04SGreg Roach        }
325ffc0a61fSGreg Roach        $data = Submitter::fetchGedcomRecord($xref, $tree_id);
326ffc0a61fSGreg Roach        if ($data !== null) {
327ffc0a61fSGreg Roach            return $data;
328ffc0a61fSGreg Roach        }
329c1010edaSGreg Roach
330a25f0a04SGreg Roach        // Some other type of record...
331d09b6323SGreg Roach        return DB::table('other')
33285fc8064SGreg Roach            ->where('o_file', '=', $tree_id)
33385fc8064SGreg Roach            ->where('o_id', '=', $xref)
33485fc8064SGreg Roach            ->value('o_gedcom');
335a25f0a04SGreg Roach    }
336a25f0a04SGreg Roach
337a25f0a04SGreg Roach    /**
338a25f0a04SGreg Roach     * Get the XREF for this record
339a25f0a04SGreg Roach     *
340a25f0a04SGreg Roach     * @return string
341a25f0a04SGreg Roach     */
342c0935879SGreg Roach    public function xref(): string
343c1010edaSGreg Roach    {
344a25f0a04SGreg Roach        return $this->xref;
345a25f0a04SGreg Roach    }
346a25f0a04SGreg Roach
347a25f0a04SGreg Roach    /**
348000959d9SGreg Roach     * Get the tree to which this record belongs
349000959d9SGreg Roach     *
350000959d9SGreg Roach     * @return Tree
351000959d9SGreg Roach     */
352f4afa648SGreg Roach    public function tree(): Tree
353c1010edaSGreg Roach    {
354518bbdc1SGreg Roach        return $this->tree;
355000959d9SGreg Roach    }
356000959d9SGreg Roach
357000959d9SGreg Roach    /**
358a25f0a04SGreg Roach     * Application code should access data via Fact objects.
359a25f0a04SGreg Roach     * This function exists to support old code.
360a25f0a04SGreg Roach     *
361a25f0a04SGreg Roach     * @return string
362a25f0a04SGreg Roach     */
363e364afe4SGreg Roach    public function gedcom(): string
364c1010edaSGreg Roach    {
365b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
366a25f0a04SGreg Roach    }
367a25f0a04SGreg Roach
368a25f0a04SGreg Roach    /**
369a25f0a04SGreg Roach     * Does this record have a pending change?
370a25f0a04SGreg Roach     *
371cbc1590aSGreg Roach     * @return bool
372a25f0a04SGreg Roach     */
3738f53f488SRico Sonntag    public function isPendingAddition(): bool
374c1010edaSGreg Roach    {
375a25f0a04SGreg Roach        return $this->pending !== null;
376a25f0a04SGreg Roach    }
377a25f0a04SGreg Roach
378a25f0a04SGreg Roach    /**
379a25f0a04SGreg Roach     * Does this record have a pending deletion?
380a25f0a04SGreg Roach     *
381cbc1590aSGreg Roach     * @return bool
382a25f0a04SGreg Roach     */
3838f53f488SRico Sonntag    public function isPendingDeletion(): bool
384c1010edaSGreg Roach    {
385a25f0a04SGreg Roach        return $this->pending === '';
386a25f0a04SGreg Roach    }
387a25f0a04SGreg Roach
388a25f0a04SGreg Roach    /**
389ee4364daSGreg Roach     * Generate a "slug" to use in pretty URLs.
390ee4364daSGreg Roach     *
391ee4364daSGreg Roach     * @return string
392ee4364daSGreg Roach     */
393ee4364daSGreg Roach    public function slug(): string
394ee4364daSGreg Roach    {
3955ab92b3fSGreg Roach        $slug = strip_tags($this->fullName());
396f7440925SGreg Roach
397*74670d65SGreg Roach        try {
398f7440925SGreg Roach            $transliterator = Transliterator::create('Any-Latin;Latin-ASCII');
3995ab92b3fSGreg Roach            $slug           = $transliterator->transliterate($slug);
400*74670d65SGreg Roach        } catch (Throwable $ex) {
401*74670d65SGreg Roach            // ext-intl not installed?
402*74670d65SGreg Roach            // Transliteration algorithms not present in lib-icu?
403f7440925SGreg Roach        }
404f7440925SGreg Roach
4055ab92b3fSGreg Roach        $slug = preg_replace('/[^A-Za-z0-9]+/', '-', $slug);
4065ab92b3fSGreg Roach
4075ab92b3fSGreg Roach        return trim($slug, '-') ?: '-';
408ee4364daSGreg Roach    }
409ee4364daSGreg Roach
410ee4364daSGreg Roach    /**
411225e381fSGreg Roach     * Generate a URL to this record.
412a25f0a04SGreg Roach     *
413a25f0a04SGreg Roach     * @return string
414a25f0a04SGreg Roach     */
4158f53f488SRico Sonntag    public function url(): string
416c1010edaSGreg Roach    {
417225e381fSGreg Roach        return route(static::ROUTE_NAME, [
418c0935879SGreg Roach            'xref' => $this->xref(),
419ee4364daSGreg Roach            'tree' => $this->tree->name(),
420ee4364daSGreg Roach            'slug' => $this->slug(),
421225e381fSGreg Roach        ]);
422a25f0a04SGreg Roach    }
423a25f0a04SGreg Roach
424a25f0a04SGreg Roach    /**
425a25f0a04SGreg Roach     * Can the details of this record be shown?
426a25f0a04SGreg Roach     *
427cbc1590aSGreg Roach     * @param int|null $access_level
428a25f0a04SGreg Roach     *
429cbc1590aSGreg Roach     * @return bool
430a25f0a04SGreg Roach     */
43135584196SGreg Roach    public function canShow(int $access_level = null): bool
432c1010edaSGreg Roach    {
433f0b9c048SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
4344b9ff166SGreg Roach
435a25f0a04SGreg Roach        // We use this value to bypass privacy checks. For example,
436a25f0a04SGreg Roach        // when downloading data or when calculating privacy itself.
437f0b9c048SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
438a25f0a04SGreg Roach            return true;
439a25f0a04SGreg Roach        }
440f0b9c048SGreg Roach
4417476e8a5SGreg Roach        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
442f0b9c048SGreg Roach
443c692965aSGreg Roach        return app('cache.array')->remember($cache_key, function () use ($access_level) {
444f0b9c048SGreg Roach            return $this->canShowRecord($access_level);
445f0b9c048SGreg Roach        });
446a25f0a04SGreg Roach    }
447a25f0a04SGreg Roach
448a25f0a04SGreg Roach    /**
449a25f0a04SGreg Roach     * Can the name of this record be shown?
450a25f0a04SGreg Roach     *
451cbc1590aSGreg Roach     * @param int|null $access_level
452a25f0a04SGreg Roach     *
453cbc1590aSGreg Roach     * @return bool
454a25f0a04SGreg Roach     */
45576f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
456c1010edaSGreg Roach    {
457a25f0a04SGreg Roach        return $this->canShow($access_level);
458a25f0a04SGreg Roach    }
459a25f0a04SGreg Roach
460a25f0a04SGreg Roach    /**
461a25f0a04SGreg Roach     * Can we edit this record?
462a25f0a04SGreg Roach     *
463cbc1590aSGreg Roach     * @return bool
464a25f0a04SGreg Roach     */
4658f53f488SRico Sonntag    public function canEdit(): bool
466c1010edaSGreg Roach    {
4671450f098SGreg Roach        if ($this->isPendingDeletion()) {
4681450f098SGreg Roach            return false;
4691450f098SGreg Roach        }
4701450f098SGreg Roach
4711450f098SGreg Roach        if (Auth::isManager($this->tree)) {
4721450f098SGreg Roach            return true;
4731450f098SGreg Roach        }
4741450f098SGreg Roach
4751450f098SGreg Roach        return Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
476a25f0a04SGreg Roach    }
477a25f0a04SGreg Roach
478a25f0a04SGreg Roach    /**
479a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
480a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
481a25f0a04SGreg Roach     *
482cbc1590aSGreg Roach     * @param int $access_level
483a25f0a04SGreg Roach     *
484a25f0a04SGreg Roach     * @return string
485a25f0a04SGreg Roach     */
486e364afe4SGreg Roach    public function privatizeGedcom(int $access_level): string
487c1010edaSGreg Roach    {
488e364afe4SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
489a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
490a25f0a04SGreg Roach            return $this->gedcom;
491b2ce94c6SRico Sonntag        }
492b2ce94c6SRico Sonntag
493b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
494a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
495a25f0a04SGreg Roach
496a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
49765e02381SGreg Roach            [$gedrec] = explode("\n", $this->gedcom, 2);
498a25f0a04SGreg Roach
499a25f0a04SGreg Roach            // Check each of the facts for access
5008d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
501138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
502a25f0a04SGreg Roach            }
503cbc1590aSGreg Roach
504a25f0a04SGreg Roach            return $gedrec;
505b2ce94c6SRico Sonntag        }
506b2ce94c6SRico Sonntag
507a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
508a25f0a04SGreg Roach        // limited data, such as links to other records.
509a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
510a25f0a04SGreg Roach    }
511a25f0a04SGreg Roach
512a25f0a04SGreg Roach    /**
513a25f0a04SGreg Roach     * Default for "other" object types
514c7ff4153SGreg Roach     *
515c7ff4153SGreg Roach     * @return void
516a25f0a04SGreg Roach     */
517e364afe4SGreg Roach    public function extractNames(): void
518c1010edaSGreg Roach    {
51976f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
520a25f0a04SGreg Roach    }
521a25f0a04SGreg Roach
522a25f0a04SGreg Roach    /**
523a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
524a25f0a04SGreg Roach     *
525a25f0a04SGreg Roach     * @return string[][]
526a25f0a04SGreg Roach     */
5278f53f488SRico Sonntag    public function getAllNames(): array
528c1010edaSGreg Roach    {
529bdb3725aSGreg Roach        if ($this->getAllNames === null) {
530bdb3725aSGreg Roach            $this->getAllNames = [];
531a25f0a04SGreg Roach            if ($this->canShowName()) {
532a25f0a04SGreg Roach                // Ask the record to extract its names
533a25f0a04SGreg Roach                $this->extractNames();
534a25f0a04SGreg Roach                // No name found? Use a fallback.
535bdb3725aSGreg Roach                if (!$this->getAllNames) {
536db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
537a25f0a04SGreg Roach                }
538a25f0a04SGreg Roach            } else {
539db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
540a25f0a04SGreg Roach            }
541a25f0a04SGreg Roach        }
542cbc1590aSGreg Roach
543bdb3725aSGreg Roach        return $this->getAllNames;
544a25f0a04SGreg Roach    }
545a25f0a04SGreg Roach
546a25f0a04SGreg Roach    /**
547a25f0a04SGreg Roach     * If this object has no name, what do we call it?
548a25f0a04SGreg Roach     *
549a25f0a04SGreg Roach     * @return string
550a25f0a04SGreg Roach     */
5518f53f488SRico Sonntag    public function getFallBackName(): string
552c1010edaSGreg Roach    {
553c0935879SGreg Roach        return e($this->xref());
554a25f0a04SGreg Roach    }
555a25f0a04SGreg Roach
556a25f0a04SGreg Roach    /**
557a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
558a25f0a04SGreg Roach     *
559cbc1590aSGreg Roach     * @return int
560a25f0a04SGreg Roach     */
5618f53f488SRico Sonntag    public function getPrimaryName(): int
562c1010edaSGreg Roach    {
563a25f0a04SGreg Roach        static $language_script;
564a25f0a04SGreg Roach
565a25f0a04SGreg Roach        if ($language_script === null) {
56665cf5706SGreg Roach            $language_script = $language_script ?? I18N::locale()->script()->code();
567a25f0a04SGreg Roach        }
568a25f0a04SGreg Roach
569bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
570a25f0a04SGreg Roach            // Generally, the first name is the primary one....
571bdb3725aSGreg Roach            $this->getPrimaryName = 0;
572a25f0a04SGreg Roach            // ...except when the language/name use different character sets
573a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
57469546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
575bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
576a25f0a04SGreg Roach                    break;
577a25f0a04SGreg Roach                }
578a25f0a04SGreg Roach            }
579a25f0a04SGreg Roach        }
580a25f0a04SGreg Roach
581bdb3725aSGreg Roach        return $this->getPrimaryName;
582a25f0a04SGreg Roach    }
583a25f0a04SGreg Roach
584a25f0a04SGreg Roach    /**
585a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
586a25f0a04SGreg Roach     *
587cbc1590aSGreg Roach     * @return int
588a25f0a04SGreg Roach     */
5898f53f488SRico Sonntag    public function getSecondaryName(): int
590c1010edaSGreg Roach    {
5918f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
592a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
593bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
594a25f0a04SGreg Roach            // ....except when there are names with different character sets
595a25f0a04SGreg Roach            $all_names = $this->getAllNames();
596a25f0a04SGreg Roach            if (count($all_names) > 1) {
597a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
598a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
599e364afe4SGreg Roach                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
600bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
601a25f0a04SGreg Roach                        break;
602a25f0a04SGreg Roach                    }
603a25f0a04SGreg Roach                }
604a25f0a04SGreg Roach            }
605a25f0a04SGreg Roach        }
606cbc1590aSGreg Roach
607bdb3725aSGreg Roach        return $this->getSecondaryName;
608a25f0a04SGreg Roach    }
609a25f0a04SGreg Roach
610a25f0a04SGreg Roach    /**
611a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
612a25f0a04SGreg Roach     *
61376f666f4SGreg Roach     * @param int|null $n
6147e96c925SGreg Roach     *
6157e96c925SGreg Roach     * @return void
616a25f0a04SGreg Roach     */
617e364afe4SGreg Roach    public function setPrimaryName(int $n = null): void
618c1010edaSGreg Roach    {
619bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
620bdb3725aSGreg Roach        $this->getSecondaryName = null;
621a25f0a04SGreg Roach    }
622a25f0a04SGreg Roach
623a25f0a04SGreg Roach    /**
624a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
625a25f0a04SGreg Roach     *
626a25f0a04SGreg Roach     * @return string
627a25f0a04SGreg Roach     */
628c1010edaSGreg Roach    public function __toString()
629c1010edaSGreg Roach    {
63072cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
631a25f0a04SGreg Roach    }
632a25f0a04SGreg Roach
633a25f0a04SGreg Roach    /**
634c156e8f5SGreg Roach     * /**
635a25f0a04SGreg Roach     * Get variants of the name
636a25f0a04SGreg Roach     *
637a25f0a04SGreg Roach     * @return string
638a25f0a04SGreg Roach     */
639e364afe4SGreg Roach    public function fullName(): string
640c1010edaSGreg Roach    {
641a25f0a04SGreg Roach        if ($this->canShowName()) {
642a25f0a04SGreg Roach            $tmp = $this->getAllNames();
643cbc1590aSGreg Roach
644a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
645a25f0a04SGreg Roach        }
646b2ce94c6SRico Sonntag
647b2ce94c6SRico Sonntag        return I18N::translate('Private');
648a25f0a04SGreg Roach    }
649a25f0a04SGreg Roach
650a25f0a04SGreg Roach    /**
651a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
652a25f0a04SGreg Roach     *
653a25f0a04SGreg Roach     * @return string
654a25f0a04SGreg Roach     */
65539ca88baSGreg Roach    public function sortName(): string
656c1010edaSGreg Roach    {
657a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
658a25f0a04SGreg Roach        $tmp = $this->getAllNames();
659cbc1590aSGreg Roach
660a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
661a25f0a04SGreg Roach    }
662a25f0a04SGreg Roach
663a25f0a04SGreg Roach    /**
664a25f0a04SGreg Roach     * Get the full name in an alternative character set
665a25f0a04SGreg Roach     *
666e364afe4SGreg Roach     * @return string|null
667a25f0a04SGreg Roach     */
668e364afe4SGreg Roach    public function alternateName(): ?string
669c1010edaSGreg Roach    {
670e364afe4SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
671a25f0a04SGreg Roach            $all_names = $this->getAllNames();
672cbc1590aSGreg Roach
673a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
674a25f0a04SGreg Roach        }
675b2ce94c6SRico Sonntag
676b2ce94c6SRico Sonntag        return null;
677a25f0a04SGreg Roach    }
678a25f0a04SGreg Roach
679a25f0a04SGreg Roach    /**
680a25f0a04SGreg Roach     * Format this object for display in a list
681a25f0a04SGreg Roach     *
682a25f0a04SGreg Roach     * @return string
683a25f0a04SGreg Roach     */
6848f53f488SRico Sonntag    public function formatList(): string
685c1010edaSGreg Roach    {
686b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
68739ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
688a25f0a04SGreg Roach        $html .= $this->formatListDetails();
689b165e17cSGreg Roach        $html .= '</a>';
690cbc1590aSGreg Roach
691a25f0a04SGreg Roach        return $html;
692a25f0a04SGreg Roach    }
693a25f0a04SGreg Roach
694a25f0a04SGreg Roach    /**
695a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
696a25f0a04SGreg Roach     * identifying characteristics of this record.
697a25f0a04SGreg Roach     *
698a25f0a04SGreg Roach     * @return string
699a25f0a04SGreg Roach     */
7008f53f488SRico Sonntag    public function formatListDetails(): string
701c1010edaSGreg Roach    {
702a25f0a04SGreg Roach        return '';
703a25f0a04SGreg Roach    }
704a25f0a04SGreg Roach
705a25f0a04SGreg Roach    /**
706a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
707a25f0a04SGreg Roach     *
7088d0ebef0SGreg Roach     * @param string[] $facts
709cbc1590aSGreg Roach     * @param int      $style
710a25f0a04SGreg Roach     *
711a25f0a04SGreg Roach     * @return string
712a25f0a04SGreg Roach     */
7138d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
714c1010edaSGreg Roach    {
71530158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
716a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
717e364afe4SGreg Roach            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
718d93f11b5SGreg Roach                $joiner = ' — ';
719d93f11b5SGreg Roach            } else {
720d93f11b5SGreg Roach                $joiner = '';
721d93f11b5SGreg Roach            }
722e364afe4SGreg Roach            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
723a25f0a04SGreg Roach                switch ($style) {
724a25f0a04SGreg Roach                    case 1:
7257b7d8067SGreg Roach                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
726a25f0a04SGreg Roach                    case 2:
7277b7d8067SGreg Roach                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
728a25f0a04SGreg Roach                }
729a25f0a04SGreg Roach            }
730a25f0a04SGreg Roach        }
731cbc1590aSGreg Roach
732a25f0a04SGreg Roach        return '';
733a25f0a04SGreg Roach    }
734a25f0a04SGreg Roach
735a25f0a04SGreg Roach    /**
736a25f0a04SGreg Roach     * Find individuals linked to this record.
737a25f0a04SGreg Roach     *
738a25f0a04SGreg Roach     * @param string $link
739a25f0a04SGreg Roach     *
740b5c8fd7eSGreg Roach     * @return Collection<Individual>
741a25f0a04SGreg Roach     */
742907c1109SGreg Roach    public function linkedIndividuals(string $link): Collection
743c1010edaSGreg Roach    {
744907c1109SGreg Roach        return DB::table('individuals')
7450b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
746907c1109SGreg Roach                $join
747907c1109SGreg Roach                    ->on('l_file', '=', 'i_file')
748907c1109SGreg Roach                    ->on('l_from', '=', 'i_id');
749ba1c12e8SGreg Roach            })
750ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
751ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
752ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
753907c1109SGreg Roach            ->select(['individuals.*'])
754907c1109SGreg Roach            ->get()
755d5ad3db0SGreg Roach            ->map(Individual::rowMapper($this->tree))
756907c1109SGreg Roach            ->filter(self::accessFilter());
757a25f0a04SGreg Roach    }
758a25f0a04SGreg Roach
759a25f0a04SGreg Roach    /**
760a25f0a04SGreg Roach     * Find families linked to this record.
761a25f0a04SGreg Roach     *
762a25f0a04SGreg Roach     * @param string $link
763a25f0a04SGreg Roach     *
764b5c8fd7eSGreg Roach     * @return Collection<Family>
765a25f0a04SGreg Roach     */
766907c1109SGreg Roach    public function linkedFamilies(string $link): Collection
767c1010edaSGreg Roach    {
768907c1109SGreg Roach        return DB::table('families')
7690b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
770907c1109SGreg Roach                $join
771907c1109SGreg Roach                    ->on('l_file', '=', 'f_file')
772907c1109SGreg Roach                    ->on('l_from', '=', 'f_id');
773ba1c12e8SGreg Roach            })
774ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
775ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
776ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
777907c1109SGreg Roach            ->select(['families.*'])
778907c1109SGreg Roach            ->get()
779d5ad3db0SGreg Roach            ->map(Family::rowMapper($this->tree))
780907c1109SGreg Roach            ->filter(self::accessFilter());
781a25f0a04SGreg Roach    }
782a25f0a04SGreg Roach
783a25f0a04SGreg Roach    /**
784a25f0a04SGreg Roach     * Find sources linked to this record.
785a25f0a04SGreg Roach     *
786a25f0a04SGreg Roach     * @param string $link
787a25f0a04SGreg Roach     *
788b5c8fd7eSGreg Roach     * @return Collection<Source>
789a25f0a04SGreg Roach     */
790907c1109SGreg Roach    public function linkedSources(string $link): Collection
791c1010edaSGreg Roach    {
792907c1109SGreg Roach        return DB::table('sources')
7930b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
794907c1109SGreg Roach                $join
795907c1109SGreg Roach                    ->on('l_file', '=', 's_file')
796907c1109SGreg Roach                    ->on('l_from', '=', 's_id');
797ba1c12e8SGreg Roach            })
798ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
799ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
800ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
801907c1109SGreg Roach            ->select(['sources.*'])
802907c1109SGreg Roach            ->get()
803d5ad3db0SGreg Roach            ->map(Source::rowMapper($this->tree))
804907c1109SGreg Roach            ->filter(self::accessFilter());
805a25f0a04SGreg Roach    }
806a25f0a04SGreg Roach
807a25f0a04SGreg Roach    /**
808a25f0a04SGreg Roach     * Find media objects linked to this record.
809a25f0a04SGreg Roach     *
810a25f0a04SGreg Roach     * @param string $link
811a25f0a04SGreg Roach     *
812b5c8fd7eSGreg Roach     * @return Collection<Media>
813a25f0a04SGreg Roach     */
814907c1109SGreg Roach    public function linkedMedia(string $link): Collection
815c1010edaSGreg Roach    {
816907c1109SGreg Roach        return DB::table('media')
8170b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
818907c1109SGreg Roach                $join
819907c1109SGreg Roach                    ->on('l_file', '=', 'm_file')
820907c1109SGreg Roach                    ->on('l_from', '=', 'm_id');
821ba1c12e8SGreg Roach            })
822ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
823ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
824ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
825907c1109SGreg Roach            ->select(['media.*'])
826907c1109SGreg Roach            ->get()
827d5ad3db0SGreg Roach            ->map(Media::rowMapper($this->tree))
828907c1109SGreg Roach            ->filter(self::accessFilter());
829a25f0a04SGreg Roach    }
830a25f0a04SGreg Roach
831a25f0a04SGreg Roach    /**
832a25f0a04SGreg Roach     * Find notes linked to this record.
833a25f0a04SGreg Roach     *
834a25f0a04SGreg Roach     * @param string $link
835a25f0a04SGreg Roach     *
836b5c8fd7eSGreg Roach     * @return Collection<Note>
837a25f0a04SGreg Roach     */
838907c1109SGreg Roach    public function linkedNotes(string $link): Collection
839c1010edaSGreg Roach    {
840907c1109SGreg Roach        return DB::table('other')
8410b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
842907c1109SGreg Roach                $join
843907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
844907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
845ba1c12e8SGreg Roach            })
846ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
847ba1c12e8SGreg Roach            ->where('o_type', '=', 'NOTE')
848ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
849ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
850907c1109SGreg Roach            ->select(['other.*'])
851907c1109SGreg Roach            ->get()
852d5ad3db0SGreg Roach            ->map(Note::rowMapper($this->tree))
853907c1109SGreg Roach            ->filter(self::accessFilter());
854a25f0a04SGreg Roach    }
855a25f0a04SGreg Roach
856a25f0a04SGreg Roach    /**
857a25f0a04SGreg Roach     * Find repositories linked to this record.
858a25f0a04SGreg Roach     *
859a25f0a04SGreg Roach     * @param string $link
860a25f0a04SGreg Roach     *
861b5c8fd7eSGreg Roach     * @return Collection<Repository>
862a25f0a04SGreg Roach     */
863907c1109SGreg Roach    public function linkedRepositories(string $link): Collection
864c1010edaSGreg Roach    {
865907c1109SGreg Roach        return DB::table('other')
8660b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
867907c1109SGreg Roach                $join
868907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
869907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
870ba1c12e8SGreg Roach            })
871ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
872ba1c12e8SGreg Roach            ->where('o_type', '=', 'REPO')
873ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
874ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
875907c1109SGreg Roach            ->select(['other.*'])
876907c1109SGreg Roach            ->get()
877d5ad3db0SGreg Roach            ->map(Repository::rowMapper($this->tree))
878907c1109SGreg Roach            ->filter(self::accessFilter());
879a25f0a04SGreg Roach    }
880a25f0a04SGreg Roach
881a25f0a04SGreg Roach    /**
882a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
883a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
884a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
885a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
886a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
887a25f0a04SGreg Roach     *
8888d0ebef0SGreg Roach     * @param string[] $events
889a25f0a04SGreg Roach     *
890a25f0a04SGreg Roach     * @return Date[]
891a25f0a04SGreg Roach     */
8928d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
893c1010edaSGreg Roach    {
89413abd6f3SGreg Roach        $dates = [];
8958d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
8962decada7SGreg Roach            if ($event->date()->isOK()) {
8972decada7SGreg Roach                $dates[] = $event->date();
898a25f0a04SGreg Roach            }
899a25f0a04SGreg Roach        }
900a25f0a04SGreg Roach
901a25f0a04SGreg Roach        return $dates;
902a25f0a04SGreg Roach    }
903a25f0a04SGreg Roach
904a25f0a04SGreg Roach    /**
905a25f0a04SGreg Roach     * Get all the places for a particular type of event
906a25f0a04SGreg Roach     *
9078d0ebef0SGreg Roach     * @param string[] $events
908a25f0a04SGreg Roach     *
9094080d558SGreg Roach     * @return Place[]
910a25f0a04SGreg Roach     */
9118d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
912c1010edaSGreg Roach    {
91313abd6f3SGreg Roach        $places = [];
9148d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
915138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
916a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
91716d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
918a25f0a04SGreg Roach                }
919a25f0a04SGreg Roach            }
920a25f0a04SGreg Roach        }
921a25f0a04SGreg Roach
922a25f0a04SGreg Roach        return $places;
923a25f0a04SGreg Roach    }
924a25f0a04SGreg Roach
925a25f0a04SGreg Roach    /**
926a25f0a04SGreg Roach     * The facts and events for this record.
927a25f0a04SGreg Roach     *
9288d0ebef0SGreg Roach     * @param string[] $filter
929cbc1590aSGreg Roach     * @param bool     $sort
930cbc1590aSGreg Roach     * @param int|null $access_level
931ce42304aSGreg Roach     * @param bool     $ignore_deleted
932a25f0a04SGreg Roach     *
933b5c8fd7eSGreg Roach     * @return Collection<Fact>
934a25f0a04SGreg Roach     */
935ce42304aSGreg Roach    public function facts(
936ce42304aSGreg Roach        array $filter = [],
937ce42304aSGreg Roach        bool $sort = false,
938ce42304aSGreg Roach        int $access_level = null,
939ce42304aSGreg Roach        bool $ignore_deleted = false
940ce42304aSGreg Roach    ): Collection {
941d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
9424b9ff166SGreg Roach
9438af3e5c1SGreg Roach        $facts = new Collection();
944ce42304aSGreg Roach        if ($this->canShow($access_level)) {
945a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
94622d65e5aSGreg Roach                if (($filter === [] || in_array($fact->getTag(), $filter, true)) && $fact->canShow($access_level)) {
9478af3e5c1SGreg Roach                    $facts->push($fact);
948a25f0a04SGreg Roach                }
949a25f0a04SGreg Roach            }
950a25f0a04SGreg Roach        }
951d17d7b9eSGreg Roach
952a25f0a04SGreg Roach        if ($sort) {
953580a4d11SGreg Roach            $facts = Fact::sortFacts($facts);
954a25f0a04SGreg Roach        }
955cbc1590aSGreg Roach
956ce42304aSGreg Roach        if ($ignore_deleted) {
957ce42304aSGreg Roach            $facts = $facts->filter(static function (Fact $fact): bool {
958ce42304aSGreg Roach                return !$fact->isPendingDeletion();
959ce42304aSGreg Roach            });
960ce42304aSGreg Roach        }
961ce42304aSGreg Roach
96239ca88baSGreg Roach        return new Collection($facts);
963a25f0a04SGreg Roach    }
964a25f0a04SGreg Roach
965a25f0a04SGreg Roach    /**
9664459dc9aSGreg Roach     * Get the last-change timestamp for this record
967a25f0a04SGreg Roach     *
9684459dc9aSGreg Roach     * @return Carbon
969a25f0a04SGreg Roach     */
9704459dc9aSGreg Roach    public function lastChangeTimestamp(): Carbon
971c1010edaSGreg Roach    {
9724459dc9aSGreg Roach        /** @var Fact|null $chan */
973820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
974a25f0a04SGreg Roach
9754459dc9aSGreg Roach        if ($chan instanceof Fact) {
976a25f0a04SGreg Roach            // The record does have a CHAN event
9772decada7SGreg Roach            $d = $chan->date()->minimumDate();
9784459dc9aSGreg Roach
979138ca96cSGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
9804459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
981e364afe4SGreg Roach            }
982e364afe4SGreg Roach
983e364afe4SGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
9844459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
985b2ce94c6SRico Sonntag            }
986b2ce94c6SRico Sonntag
9874459dc9aSGreg Roach            return Carbon::create($d->year(), $d->month(), $d->day());
988a25f0a04SGreg Roach        }
989b2ce94c6SRico Sonntag
990a25f0a04SGreg Roach        // The record does not have a CHAN event
9914459dc9aSGreg Roach        return Carbon::createFromTimestamp(0);
992a25f0a04SGreg Roach    }
993a25f0a04SGreg Roach
994a25f0a04SGreg Roach    /**
995a25f0a04SGreg Roach     * Get the last-change user for this record
996a25f0a04SGreg Roach     *
997a25f0a04SGreg Roach     * @return string
998a25f0a04SGreg Roach     */
999e364afe4SGreg Roach    public function lastChangeUser(): string
1000c1010edaSGreg Roach    {
1001820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
1002a25f0a04SGreg Roach
1003a25f0a04SGreg Roach        if ($chan === null) {
1004a25f0a04SGreg Roach            return I18N::translate('Unknown');
1005b2ce94c6SRico Sonntag        }
1006b2ce94c6SRico Sonntag
10073425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
1008baacc364SGreg Roach        if ($chan_user === '') {
1009a25f0a04SGreg Roach            return I18N::translate('Unknown');
1010b2ce94c6SRico Sonntag        }
1011b2ce94c6SRico Sonntag
1012a25f0a04SGreg Roach        return $chan_user;
1013a25f0a04SGreg Roach    }
1014a25f0a04SGreg Roach
1015a25f0a04SGreg Roach    /**
1016a25f0a04SGreg Roach     * Add a new fact to this record
1017a25f0a04SGreg Roach     *
1018a25f0a04SGreg Roach     * @param string $gedcom
1019cbc1590aSGreg Roach     * @param bool   $update_chan
10207e96c925SGreg Roach     *
10217e96c925SGreg Roach     * @return void
1022a25f0a04SGreg Roach     */
1023e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
1024c1010edaSGreg Roach    {
1025fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
1026a25f0a04SGreg Roach    }
1027a25f0a04SGreg Roach
1028a25f0a04SGreg Roach    /**
1029a25f0a04SGreg Roach     * Delete a fact from this record
1030a25f0a04SGreg Roach     *
1031a25f0a04SGreg Roach     * @param string $fact_id
1032cbc1590aSGreg Roach     * @param bool   $update_chan
10337e96c925SGreg Roach     *
10347e96c925SGreg Roach     * @return void
1035a25f0a04SGreg Roach     */
1036e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
1037c1010edaSGreg Roach    {
1038db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
1039a25f0a04SGreg Roach    }
1040a25f0a04SGreg Roach
1041a25f0a04SGreg Roach    /**
1042a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
1043a25f0a04SGreg Roach     *
1044a25f0a04SGreg Roach     * @param string $fact_id
1045a25f0a04SGreg Roach     * @param string $gedcom
1046cbc1590aSGreg Roach     * @param bool   $update_chan
1047a25f0a04SGreg Roach     *
10487e96c925SGreg Roach     * @return void
10497e96c925SGreg Roach     * @throws Exception
1050a25f0a04SGreg Roach     */
1051e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
1052c1010edaSGreg Roach    {
1053a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1054a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1055a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1056a25f0a04SGreg Roach
1057a25f0a04SGreg Roach        if ($this->pending === '') {
10587e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
1059a25f0a04SGreg Roach        }
10608d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
10617e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1062a25f0a04SGreg Roach        }
1063a25f0a04SGreg Roach
1064a25f0a04SGreg Roach        if ($this->pending) {
1065a25f0a04SGreg Roach            $old_gedcom = $this->pending;
1066a25f0a04SGreg Roach        } else {
1067a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
1068a25f0a04SGreg Roach        }
1069a25f0a04SGreg Roach
1070a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
107165e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
1072a25f0a04SGreg Roach
1073a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
10748d0ebef0SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) {
1075a25f0a04SGreg Roach            if (!$fact->isPendingDeletion()) {
1076905ab80aSGreg Roach                if ($fact->id() === $fact_id) {
1077db7bb364SGreg Roach                    if ($gedcom !== '') {
1078a25f0a04SGreg Roach                        $new_gedcom .= "\n" . $gedcom;
1079a25f0a04SGreg Roach                    }
1080fc3ccce4SGreg Roach                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1081e364afe4SGreg Roach                } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) {
1082138ca96cSGreg Roach                    $new_gedcom .= "\n" . $fact->gedcom();
1083a25f0a04SGreg Roach                }
1084a25f0a04SGreg Roach            }
1085a25f0a04SGreg Roach        }
1086a25f0a04SGreg Roach        if ($update_chan) {
1087e5a6b4d4SGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1088a25f0a04SGreg Roach        }
1089a25f0a04SGreg Roach
1090a25f0a04SGreg Roach        // Adding a new fact
1091fc3ccce4SGreg Roach        if ($fact_id === '') {
1092a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
1093a25f0a04SGreg Roach        }
1094a25f0a04SGreg Roach
1095e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
1096a25f0a04SGreg Roach            // Save the changes
1097d09b6323SGreg Roach            DB::table('change')->insert([
1098d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1099d09b6323SGreg Roach                'xref'       => $this->xref,
1100d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
1101d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
1102d09b6323SGreg Roach                'user_id'    => Auth::id(),
110313abd6f3SGreg Roach            ]);
1104a25f0a04SGreg Roach
1105a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1106a25f0a04SGreg Roach
11077c4add84SGreg Roach            if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') {
110822e73debSGreg Roach                app(PendingChangesService::class)->acceptRecord($this);
1109a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1110a25f0a04SGreg Roach                $this->pending = null;
1111a25f0a04SGreg Roach            }
1112a25f0a04SGreg Roach        }
1113a25f0a04SGreg Roach        $this->parseFacts();
1114a25f0a04SGreg Roach    }
1115a25f0a04SGreg Roach
1116a25f0a04SGreg Roach    /**
1117a25f0a04SGreg Roach     * Update this record
1118a25f0a04SGreg Roach     *
1119a25f0a04SGreg Roach     * @param string $gedcom
1120cbc1590aSGreg Roach     * @param bool   $update_chan
11217e96c925SGreg Roach     *
11227e96c925SGreg Roach     * @return void
1123a25f0a04SGreg Roach     */
1124e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
1125c1010edaSGreg Roach    {
1126a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1127a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1128a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1129a25f0a04SGreg Roach
1130a25f0a04SGreg Roach        // Update the CHAN record
1131a25f0a04SGreg Roach        if ($update_chan) {
1132a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1133e5a6b4d4SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1134a25f0a04SGreg Roach        }
1135a25f0a04SGreg Roach
1136a25f0a04SGreg Roach        // Create a pending change
1137d09b6323SGreg Roach        DB::table('change')->insert([
1138d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1139d09b6323SGreg Roach            'xref'       => $this->xref,
1140d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1141d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1142d09b6323SGreg Roach            'user_id'    => Auth::id(),
114313abd6f3SGreg Roach        ]);
1144a25f0a04SGreg Roach
1145a25f0a04SGreg Roach        // Clear the cache
1146a25f0a04SGreg Roach        $this->pending = $gedcom;
1147a25f0a04SGreg Roach
1148a25f0a04SGreg Roach        // Accept this pending change
11497c4add84SGreg Roach        if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') {
115022e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1151a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1152a25f0a04SGreg Roach            $this->pending = null;
1153a25f0a04SGreg Roach        }
1154a25f0a04SGreg Roach
1155a25f0a04SGreg Roach        $this->parseFacts();
1156a25f0a04SGreg Roach
1157847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1158a25f0a04SGreg Roach    }
1159a25f0a04SGreg Roach
1160a25f0a04SGreg Roach    /**
1161a25f0a04SGreg Roach     * Delete this record
1162b874da82SGreg Roach     *
1163b874da82SGreg Roach     * @return void
1164a25f0a04SGreg Roach     */
1165e364afe4SGreg Roach    public function deleteRecord(): void
1166c1010edaSGreg Roach    {
1167a25f0a04SGreg Roach        // Create a pending change
11684c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1169d09b6323SGreg Roach            DB::table('change')->insert([
1170d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1171d09b6323SGreg Roach                'xref'       => $this->xref,
1172d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1173d09b6323SGreg Roach                'new_gedcom' => '',
1174d09b6323SGreg Roach                'user_id'    => Auth::id(),
117513abd6f3SGreg Roach            ]);
11764c0b5256SGreg Roach        }
1177a25f0a04SGreg Roach
11784c0b5256SGreg Roach        // Auto-accept this pending change
11797c4add84SGreg Roach        if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') {
118022e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1181a25f0a04SGreg Roach        }
1182a25f0a04SGreg Roach
1183a25f0a04SGreg Roach        // Clear the cache
1184d17d7b9eSGreg Roach        self::$gedcom_record_cache  = [];
1185d17d7b9eSGreg Roach        self::$pending_record_cache = [];
1186a25f0a04SGreg Roach
1187847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1188a25f0a04SGreg Roach    }
1189a25f0a04SGreg Roach
1190a25f0a04SGreg Roach    /**
1191a25f0a04SGreg Roach     * Remove all links from this record to $xref
1192a25f0a04SGreg Roach     *
1193a25f0a04SGreg Roach     * @param string $xref
1194cbc1590aSGreg Roach     * @param bool   $update_chan
11957e96c925SGreg Roach     *
11967e96c925SGreg Roach     * @return void
1197a25f0a04SGreg Roach     */
1198e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
1199c1010edaSGreg Roach    {
1200a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1201a25f0a04SGreg Roach
120230158ae7SGreg Roach        foreach ($this->facts() as $fact) {
120384586c02SGreg Roach            if ($fact->value() === $value) {
1204905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
12058d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1206138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1207a25f0a04SGreg Roach                foreach ($matches as $match) {
1208a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1209a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1210a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1211a25f0a04SGreg Roach                }
1212905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1213a25f0a04SGreg Roach            }
1214a25f0a04SGreg Roach        }
1215a25f0a04SGreg Roach    }
1216bf4eb542SGreg Roach
1217bf4eb542SGreg Roach    /**
1218bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1219bf4eb542SGreg Roach     * also delete all links to it.
1220bf4eb542SGreg Roach     *
1221bf4eb542SGreg Roach     * @return GedcomRecord[]
1222bf4eb542SGreg Roach     */
1223bf4eb542SGreg Roach    public function linkingRecords(): array
1224bf4eb542SGreg Roach    {
1225bf4eb542SGreg Roach        $union = DB::table('change')
1226bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1227fbbe964bSGreg Roach            ->whereContains('new_gedcom', '@' . $this->xref() . '@')
1228bf4eb542SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%')
122983242252SGreg Roach            ->whereIn('change_id', function (Builder $query): void {
123083242252SGreg Roach                $query->select(new Expression('MAX(change_id)'))
123183242252SGreg Roach                    ->from('change')
123283242252SGreg Roach                    ->where('gedcom_id', '=', $this->tree->id())
123383242252SGreg Roach                    ->where('status', '=', 'pending')
12347f5c2944SGreg Roach                    ->groupBy(['xref']);
123583242252SGreg Roach            })
1236bf4eb542SGreg Roach            ->select(['xref']);
1237bf4eb542SGreg Roach
1238bf4eb542SGreg Roach        $xrefs = DB::table('link')
1239bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1240bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
124147256fc5SGreg Roach            ->select(['l_from'])
1242bf4eb542SGreg Roach            ->union($union)
1243bf4eb542SGreg Roach            ->pluck('l_from');
1244bf4eb542SGreg Roach
1245bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
1246ffc0a61fSGreg Roach            $record = GedcomRecord::getInstance($xref, $this->tree);
1247ffc0a61fSGreg Roach            assert($record instanceof GedcomRecord);
1248ffc0a61fSGreg Roach
1249ffc0a61fSGreg Roach            return $record;
1250bf4eb542SGreg Roach        })->all();
1251bf4eb542SGreg Roach    }
125222e73debSGreg Roach
125322e73debSGreg Roach    /**
125422e73debSGreg Roach     * Each object type may have its own special rules, and re-implement this function.
125522e73debSGreg Roach     *
125622e73debSGreg Roach     * @param int $access_level
125722e73debSGreg Roach     *
125822e73debSGreg Roach     * @return bool
125922e73debSGreg Roach     */
126022e73debSGreg Roach    protected function canShowByType(int $access_level): bool
126122e73debSGreg Roach    {
126222e73debSGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
126322e73debSGreg Roach
126422e73debSGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
126522e73debSGreg Roach            // Restriction found
126622e73debSGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
126722e73debSGreg Roach        }
126822e73debSGreg Roach
126922e73debSGreg Roach        // No restriction found - must be public:
127022e73debSGreg Roach        return true;
127122e73debSGreg Roach    }
127222e73debSGreg Roach
127322e73debSGreg Roach    /**
127422e73debSGreg Roach     * Generate a private version of this record
127522e73debSGreg Roach     *
127622e73debSGreg Roach     * @param int $access_level
127722e73debSGreg Roach     *
127822e73debSGreg Roach     * @return string
127922e73debSGreg Roach     */
128022e73debSGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
128122e73debSGreg Roach    {
128222e73debSGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
128322e73debSGreg Roach    }
128422e73debSGreg Roach
128522e73debSGreg Roach    /**
128622e73debSGreg Roach     * Convert a name record into sortable and full/display versions. This default
128722e73debSGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
128822e73debSGreg Roach     *
128922e73debSGreg Roach     * @param string $type
129022e73debSGreg Roach     * @param string $value
129122e73debSGreg Roach     * @param string $gedcom
129222e73debSGreg Roach     *
129322e73debSGreg Roach     * @return void
129422e73debSGreg Roach     */
129522e73debSGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
129622e73debSGreg Roach    {
129722e73debSGreg Roach        $this->getAllNames[] = [
129822e73debSGreg Roach            'type'   => $type,
129922e73debSGreg Roach            'sort'   => preg_replace_callback('/([0-9]+)/', static function (array $matches): string {
130022e73debSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
130122e73debSGreg Roach            }, $value),
130222e73debSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
130322e73debSGreg Roach            // This is used for display
130422e73debSGreg Roach            'fullNN' => $value,
130522e73debSGreg Roach            // This goes into the database
130622e73debSGreg Roach        ];
130722e73debSGreg Roach    }
130822e73debSGreg Roach
130922e73debSGreg Roach    /**
131022e73debSGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
131122e73debSGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
131222e73debSGreg Roach     * Parameters: the level 1 fact containing the name.
131322e73debSGreg Roach     * Return value: an array of name structures, each containing
131422e73debSGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
131522e73debSGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
131622e73debSGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
131722e73debSGreg Roach     *
131822e73debSGreg Roach     * @param int        $level
131922e73debSGreg Roach     * @param string     $fact_type
132022e73debSGreg Roach     * @param Collection $facts
132122e73debSGreg Roach     *
132222e73debSGreg Roach     * @return void
132322e73debSGreg Roach     */
132422e73debSGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
132522e73debSGreg Roach    {
132622e73debSGreg Roach        $sublevel    = $level + 1;
132722e73debSGreg Roach        $subsublevel = $sublevel + 1;
132822e73debSGreg Roach        foreach ($facts as $fact) {
132922e73debSGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
133022e73debSGreg Roach                foreach ($matches as $match) {
133122e73debSGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
133222e73debSGreg Roach                    if ($match[1] === 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
133322e73debSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
133422e73debSGreg Roach                    } else {
133522e73debSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
133622e73debSGreg Roach                    }
133722e73debSGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
133822e73debSGreg Roach                        foreach ($submatches as $submatch) {
133922e73debSGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
134022e73debSGreg Roach                        }
134122e73debSGreg Roach                    }
134222e73debSGreg Roach                }
134322e73debSGreg Roach            }
134422e73debSGreg Roach        }
134522e73debSGreg Roach    }
134622e73debSGreg Roach
134722e73debSGreg Roach    /**
134822e73debSGreg Roach     * Split the record into facts
134922e73debSGreg Roach     *
135022e73debSGreg Roach     * @return void
135122e73debSGreg Roach     */
135222e73debSGreg Roach    private function parseFacts(): void
135322e73debSGreg Roach    {
135422e73debSGreg Roach        // Split the record into facts
135522e73debSGreg Roach        if ($this->gedcom) {
135622e73debSGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
135722e73debSGreg Roach            array_shift($gedcom_facts);
135822e73debSGreg Roach        } else {
135922e73debSGreg Roach            $gedcom_facts = [];
136022e73debSGreg Roach        }
136122e73debSGreg Roach        if ($this->pending) {
136222e73debSGreg Roach            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
136322e73debSGreg Roach            array_shift($pending_facts);
136422e73debSGreg Roach        } else {
136522e73debSGreg Roach            $pending_facts = [];
136622e73debSGreg Roach        }
136722e73debSGreg Roach
136822e73debSGreg Roach        $this->facts = [];
136922e73debSGreg Roach
137022e73debSGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
137122e73debSGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
137222e73debSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
137322e73debSGreg Roach                $fact->setPendingDeletion();
137422e73debSGreg Roach            }
137522e73debSGreg Roach            $this->facts[] = $fact;
137622e73debSGreg Roach        }
137722e73debSGreg Roach        foreach ($pending_facts as $pending_fact) {
137822e73debSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
137922e73debSGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
138022e73debSGreg Roach                $fact->setPendingAddition();
138122e73debSGreg Roach                $this->facts[] = $fact;
138222e73debSGreg Roach            }
138322e73debSGreg Roach        }
138422e73debSGreg Roach    }
138522e73debSGreg Roach
138622e73debSGreg Roach    /**
138722e73debSGreg Roach     * Work out whether this record can be shown to a user with a given access level
138822e73debSGreg Roach     *
138922e73debSGreg Roach     * @param int $access_level
139022e73debSGreg Roach     *
139122e73debSGreg Roach     * @return bool
139222e73debSGreg Roach     */
139322e73debSGreg Roach    private function canShowRecord(int $access_level): bool
139422e73debSGreg Roach    {
139522e73debSGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
139622e73debSGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
139722e73debSGreg Roach            return true;
139822e73debSGreg Roach        }
139922e73debSGreg Roach
140022e73debSGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
14017c4add84SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), User::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
140222e73debSGreg Roach            return true;
140322e73debSGreg Roach        }
140422e73debSGreg Roach
140522e73debSGreg Roach        // Does this record have a RESN?
140622e73debSGreg Roach        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
140722e73debSGreg Roach            return Auth::PRIV_NONE >= $access_level;
140822e73debSGreg Roach        }
140922e73debSGreg Roach        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
141022e73debSGreg Roach            return Auth::PRIV_USER >= $access_level;
141122e73debSGreg Roach        }
141222e73debSGreg Roach        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
141322e73debSGreg Roach            return true;
141422e73debSGreg Roach        }
141522e73debSGreg Roach
141622e73debSGreg Roach        // Does this record have a default RESN?
141722e73debSGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
141822e73debSGreg Roach        if (isset($individual_privacy[$this->xref()])) {
141922e73debSGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
142022e73debSGreg Roach        }
142122e73debSGreg Roach
142222e73debSGreg Roach        // Privacy rules do not apply to admins
142322e73debSGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
142422e73debSGreg Roach            return true;
142522e73debSGreg Roach        }
142622e73debSGreg Roach
142722e73debSGreg Roach        // Different types of record have different privacy rules
142822e73debSGreg Roach        return $this->canShowByType($access_level);
142922e73debSGreg Roach    }
1430a25f0a04SGreg Roach}
1431