xref: /webtrees/app/GedcomRecord.php (revision 534324768cedfc260deb392aa6a125c6cffc46e8)
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;
3374670d65SGreg Roachuse Throwable;
345ab92b3fSGreg Roachuse Transliterator;
35a25f0a04SGreg Roach
3622e73debSGreg Roachuse function app;
37f7440925SGreg Roachuse function array_shift;
38f7440925SGreg Roachuse function assert;
39f7440925SGreg Roachuse function count;
40f7440925SGreg Roachuse function date;
41f7440925SGreg Roachuse function e;
42f7440925SGreg Roachuse function explode;
43f7440925SGreg Roachuse function in_array;
44f7440925SGreg Roachuse function md5;
45f7440925SGreg Roachuse function preg_match;
46f7440925SGreg Roachuse function preg_match_all;
47f7440925SGreg Roachuse function preg_replace;
48f7440925SGreg Roachuse function preg_replace_callback;
49f7440925SGreg Roachuse function preg_split;
50f7440925SGreg Roachuse function route;
51f7440925SGreg Roachuse function str_pad;
52f7440925SGreg Roachuse function strip_tags;
53f7440925SGreg Roachuse function strpos;
54f7440925SGreg Roachuse function strtoupper;
55f7440925SGreg Roachuse function trim;
56f7440925SGreg Roach
57f7440925SGreg Roachuse const PREG_SET_ORDER;
58f7440925SGreg Roachuse const STR_PAD_LEFT;
5922e73debSGreg Roach
60a25f0a04SGreg Roach/**
6176692c8bSGreg Roach * A GEDCOM object.
62a25f0a04SGreg Roach */
63c1010edaSGreg Roachclass GedcomRecord
64c1010edaSGreg Roach{
6516d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
6616d6367aSGreg Roach
675818a371SGreg Roach    protected const ROUTE_NAME = GedcomRecordPage::class;
685818a371SGreg Roach
6976692c8bSGreg Roach    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
70bec87e94SGreg Roach    public static $gedcom_record_cache;
7179529c87SGreg Roach    /** @var stdClass[][] Fetch all pending edits in one database query */
72bec87e94SGreg Roach    public static $pending_record_cache;
7322e73debSGreg Roach    /** @var string The record identifier */
7422e73debSGreg Roach    protected $xref;
7522e73debSGreg Roach    /** @var Tree  The family tree to which this record belongs */
7622e73debSGreg Roach    protected $tree;
7722e73debSGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
7822e73debSGreg Roach    protected $gedcom;
7922e73debSGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
8022e73debSGreg Roach    protected $pending;
8122e73debSGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
8222e73debSGreg Roach    protected $facts;
8322e73debSGreg Roach    /** @var string[][] All the names of this individual */
8422e73debSGreg Roach    protected $getAllNames;
8522e73debSGreg Roach    /** @var int|null Cached result */
8622e73debSGreg Roach    protected $getPrimaryName;
8722e73debSGreg Roach    /** @var int|null Cached result */
8822e73debSGreg Roach    protected $getSecondaryName;
89a25f0a04SGreg Roach
90a25f0a04SGreg Roach    /**
91a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
92a25f0a04SGreg Roach     *
93a25f0a04SGreg Roach     * @param string      $xref
94a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
95a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
96a25f0a04SGreg Roach     *                             empty string for records with pending deletions
9724ec66ceSGreg Roach     * @param Tree        $tree
98a25f0a04SGreg Roach     */
99e364afe4SGreg Roach    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
100c1010edaSGreg Roach    {
101a25f0a04SGreg Roach        $this->xref    = $xref;
102a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
103a25f0a04SGreg Roach        $this->pending = $pending;
10424ec66ceSGreg Roach        $this->tree    = $tree;
105a25f0a04SGreg Roach
106a25f0a04SGreg Roach        $this->parseFacts();
107a25f0a04SGreg Roach    }
108a25f0a04SGreg Roach
109a25f0a04SGreg Roach    /**
110886b77daSGreg Roach     * A closure which will create a record from a database row.
111886b77daSGreg Roach     *
112d5ad3db0SGreg Roach     * @param Tree $tree
113d5ad3db0SGreg Roach     *
114886b77daSGreg Roach     * @return Closure
115886b77daSGreg Roach     */
116d5ad3db0SGreg Roach    public static function rowMapper(Tree $tree): Closure
117886b77daSGreg Roach    {
118d5ad3db0SGreg Roach        return static function (stdClass $row) use ($tree): GedcomRecord {
119ffc0a61fSGreg Roach            $record = GedcomRecord::getInstance($row->o_id, $tree, $row->o_gedcom);
120ffc0a61fSGreg Roach            assert($record instanceof GedcomRecord);
121ffc0a61fSGreg Roach
122ffc0a61fSGreg Roach            return $record;
123886b77daSGreg Roach        };
124886b77daSGreg Roach    }
125886b77daSGreg Roach
126886b77daSGreg Roach    /**
127886b77daSGreg Roach     * A closure which will filter out private records.
128886b77daSGreg Roach     *
129886b77daSGreg Roach     * @return Closure
130886b77daSGreg Roach     */
1314146fabcSGreg Roach    public static function accessFilter(): Closure
132886b77daSGreg Roach    {
1336c2179e2SGreg Roach        return static function (GedcomRecord $record): bool {
134886b77daSGreg Roach            return $record->canShow();
135886b77daSGreg Roach        };
136886b77daSGreg Roach    }
137886b77daSGreg Roach
138886b77daSGreg Roach    /**
139c156e8f5SGreg Roach     * A closure which will compare records by name.
140c156e8f5SGreg Roach     *
141c156e8f5SGreg Roach     * @return Closure
142c156e8f5SGreg Roach     */
143c156e8f5SGreg Roach    public static function nameComparator(): Closure
144c156e8f5SGreg Roach    {
1456c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y): int {
146c156e8f5SGreg Roach            if ($x->canShowName()) {
147c156e8f5SGreg Roach                if ($y->canShowName()) {
14839ca88baSGreg Roach                    return I18N::strcasecmp($x->sortName(), $y->sortName());
149c156e8f5SGreg Roach                }
150c156e8f5SGreg Roach
151c156e8f5SGreg Roach                return -1; // only $y is private
152c156e8f5SGreg Roach            }
153c156e8f5SGreg Roach
154c156e8f5SGreg Roach            if ($y->canShowName()) {
155c156e8f5SGreg Roach                return 1; // only $x is private
156c156e8f5SGreg Roach            }
157c156e8f5SGreg Roach
158c156e8f5SGreg Roach            return 0; // both $x and $y private
159c156e8f5SGreg Roach        };
160c156e8f5SGreg Roach    }
161c156e8f5SGreg Roach
162c156e8f5SGreg Roach    /**
163c156e8f5SGreg Roach     * A closure which will compare records by change time.
164c156e8f5SGreg Roach     *
165c156e8f5SGreg Roach     * @param int $direction +1 to sort ascending, -1 to sort descending
166c156e8f5SGreg Roach     *
167c156e8f5SGreg Roach     * @return Closure
168c156e8f5SGreg Roach     */
169c156e8f5SGreg Roach    public static function lastChangeComparator(int $direction = 1): Closure
170c156e8f5SGreg Roach    {
1716c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
1724459dc9aSGreg Roach            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
173c156e8f5SGreg Roach        };
174c156e8f5SGreg Roach    }
175c156e8f5SGreg Roach
176c156e8f5SGreg Roach    /**
177a25f0a04SGreg Roach     * Get an instance of a GedcomRecord object. For single records,
178a25f0a04SGreg Roach     * we just receive the XREF. For bulk records (such as lists
179a25f0a04SGreg Roach     * and search results) we can receive the GEDCOM data as well.
180a25f0a04SGreg Roach     *
181a25f0a04SGreg Roach     * @param string      $xref
18224ec66ceSGreg Roach     * @param Tree        $tree
183a25f0a04SGreg Roach     * @param string|null $gedcom
184a25f0a04SGreg Roach     *
185ffc0a61fSGreg Roach     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|Submitter|null
18622e73debSGreg Roach     * @throws Exception
187a25f0a04SGreg Roach     */
18876f666f4SGreg Roach    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
189c1010edaSGreg Roach    {
19072cf66d4SGreg Roach        $tree_id = $tree->id();
19124ec66ceSGreg Roach
192e71ef9d2SGreg Roach        // Is this record already in the cache?
19324ec66ceSGreg Roach        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
194e71ef9d2SGreg Roach            return self::$gedcom_record_cache[$xref][$tree_id];
195a25f0a04SGreg Roach        }
196a25f0a04SGreg Roach
197a25f0a04SGreg Roach        // Do we need to fetch the record from the database?
198a25f0a04SGreg Roach        if ($gedcom === null) {
19924ec66ceSGreg Roach            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
200a25f0a04SGreg Roach        }
201a25f0a04SGreg Roach
202a25f0a04SGreg Roach        // If we can edit, then we also need to be able to see pending records.
20394075df0SGreg Roach        if (Auth::isEditor($tree)) {
20424ec66ceSGreg Roach            if (!isset(self::$pending_record_cache[$tree_id])) {
205a25f0a04SGreg Roach                // Fetch all pending records in one database query
20613abd6f3SGreg Roach                self::$pending_record_cache[$tree_id] = [];
20785fc8064SGreg Roach                $rows                                 = DB::table('change')
20885fc8064SGreg Roach                    ->where('gedcom_id', '=', $tree_id)
20985fc8064SGreg Roach                    ->where('status', '=', 'pending')
21085fc8064SGreg Roach                    ->orderBy('change_id')
21185fc8064SGreg Roach                    ->select(['xref', 'new_gedcom'])
21285fc8064SGreg Roach                    ->get();
213d17d7b9eSGreg Roach
214a25f0a04SGreg Roach                foreach ($rows as $row) {
21524ec66ceSGreg Roach                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
216a25f0a04SGreg Roach                }
217a25f0a04SGreg Roach            }
218a25f0a04SGreg Roach
219d17d7b9eSGreg Roach            $pending = self::$pending_record_cache[$tree_id][$xref] ?? null;
220a25f0a04SGreg Roach        } else {
221a25f0a04SGreg Roach            // There are no pending changes for this record
222a25f0a04SGreg Roach            $pending = null;
223a25f0a04SGreg Roach        }
224a25f0a04SGreg Roach
225a25f0a04SGreg Roach        // No such record exists
226a25f0a04SGreg Roach        if ($gedcom === null && $pending === null) {
227a25f0a04SGreg Roach            return null;
228a25f0a04SGreg Roach        }
229a25f0a04SGreg Roach
230fc3ccce4SGreg Roach        // No such record, but a pending creation exists
231fc3ccce4SGreg Roach        if ($gedcom === null) {
232fc3ccce4SGreg Roach            $gedcom = '';
233fc3ccce4SGreg Roach        }
234fc3ccce4SGreg Roach
235a25f0a04SGreg Roach        // Create the object
2368d0ebef0SGreg Roach        if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedcom . $pending, $match)) {
237a25f0a04SGreg Roach            $xref = $match[1]; // Collation - we may have requested I123 and found i123
238a25f0a04SGreg Roach            $type = $match[2];
239a25f0a04SGreg Roach        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
240a25f0a04SGreg Roach            $xref = $match[1];
241a25f0a04SGreg Roach            $type = $match[1];
242a25f0a04SGreg Roach        } elseif ($gedcom . $pending) {
2437e96c925SGreg Roach            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
244a25f0a04SGreg Roach        } else {
245a25f0a04SGreg Roach            // A record with both pending creation and pending deletion
246a25f0a04SGreg Roach            $type = static::RECORD_TYPE;
247a25f0a04SGreg Roach        }
248a25f0a04SGreg Roach
249a25f0a04SGreg Roach        switch ($type) {
250ac107fcfSGreg Roach            case Individual::RECORD_TYPE:
25124ec66ceSGreg Roach                $record = new Individual($xref, $gedcom, $pending, $tree);
252a25f0a04SGreg Roach                break;
253ac107fcfSGreg Roach
254ac107fcfSGreg Roach            case Family::RECORD_TYPE:
25524ec66ceSGreg Roach                $record = new Family($xref, $gedcom, $pending, $tree);
256a25f0a04SGreg Roach                break;
257ac107fcfSGreg Roach
258ac107fcfSGreg Roach            case Source::RECORD_TYPE:
25924ec66ceSGreg Roach                $record = new Source($xref, $gedcom, $pending, $tree);
260a25f0a04SGreg Roach                break;
261ac107fcfSGreg Roach
262ac107fcfSGreg Roach            case Media::RECORD_TYPE:
26324ec66ceSGreg Roach                $record = new Media($xref, $gedcom, $pending, $tree);
264a25f0a04SGreg Roach                break;
265ac107fcfSGreg Roach
266ac107fcfSGreg Roach            case Repository::RECORD_TYPE:
26724ec66ceSGreg Roach                $record = new Repository($xref, $gedcom, $pending, $tree);
268a25f0a04SGreg Roach                break;
269ac107fcfSGreg Roach
270ac107fcfSGreg Roach            case Note::RECORD_TYPE:
27124ec66ceSGreg Roach                $record = new Note($xref, $gedcom, $pending, $tree);
272a25f0a04SGreg Roach                break;
273ac107fcfSGreg Roach
274ac107fcfSGreg Roach            case Submitter::RECORD_TYPE:
275ffc0a61fSGreg Roach                $record = new Submitter($xref, $gedcom, $pending, $tree);
276ffc0a61fSGreg Roach                break;
277ac107fcfSGreg Roach
2781635452cSGreg Roach            case Submission::RECORD_TYPE:
2791635452cSGreg Roach                $record = new Submission($xref, $gedcom, $pending, $tree);
2801635452cSGreg Roach                break;
2811635452cSGreg Roach
2821635452cSGreg Roach            case Header::RECORD_TYPE:
2831635452cSGreg Roach                $record = new Header($xref, $gedcom, $pending, $tree);
2841635452cSGreg Roach                break;
2851635452cSGreg Roach
286a25f0a04SGreg Roach            default:
28706ef8e02SGreg Roach                $record = new self($xref, $gedcom, $pending, $tree);
288a25f0a04SGreg Roach                break;
289a25f0a04SGreg Roach        }
290a25f0a04SGreg Roach
291a25f0a04SGreg Roach        // Store it in the cache
29224ec66ceSGreg Roach        self::$gedcom_record_cache[$xref][$tree_id] = $record;
293a25f0a04SGreg Roach
294a25f0a04SGreg Roach        return $record;
295a25f0a04SGreg Roach    }
296a25f0a04SGreg Roach
297a25f0a04SGreg Roach    /**
298a25f0a04SGreg Roach     * Fetch data from the database
299a25f0a04SGreg Roach     *
300a25f0a04SGreg Roach     * @param string $xref
301cbc1590aSGreg Roach     * @param int    $tree_id
302a25f0a04SGreg Roach     *
303e364afe4SGreg Roach     * @return string|null
304a25f0a04SGreg Roach     */
305e364afe4SGreg Roach    protected static function fetchGedcomRecord(string $xref, int $tree_id): ?string
306c1010edaSGreg Roach    {
307a25f0a04SGreg Roach        // We don't know what type of object this is. Try each one in turn.
3081635452cSGreg Roach        return
3091635452cSGreg Roach            Individual::fetchGedcomRecord($xref, $tree_id) ??
3101635452cSGreg Roach            Family::fetchGedcomRecord($xref, $tree_id) ??
3111635452cSGreg Roach            Source::fetchGedcomRecord($xref, $tree_id) ??
3121635452cSGreg Roach            Repository::fetchGedcomRecord($xref, $tree_id) ??
3131635452cSGreg Roach            Media::fetchGedcomRecord($xref, $tree_id) ??
3141635452cSGreg Roach            Note::fetchGedcomRecord($xref, $tree_id) ??
3151635452cSGreg Roach            Submitter::fetchGedcomRecord($xref, $tree_id) ??
3161635452cSGreg Roach            Submission::fetchGedcomRecord($xref, $tree_id) ??
3171635452cSGreg Roach            Header::fetchGedcomRecord($xref, $tree_id) ??
3181635452cSGreg Roach            DB::table('other')
31985fc8064SGreg Roach            ->where('o_file', '=', $tree_id)
32085fc8064SGreg Roach            ->where('o_id', '=', $xref)
32185fc8064SGreg Roach            ->value('o_gedcom');
322a25f0a04SGreg Roach    }
323a25f0a04SGreg Roach
324a25f0a04SGreg Roach    /**
325a25f0a04SGreg Roach     * Get the XREF for this record
326a25f0a04SGreg Roach     *
327a25f0a04SGreg Roach     * @return string
328a25f0a04SGreg Roach     */
329c0935879SGreg Roach    public function xref(): string
330c1010edaSGreg Roach    {
331a25f0a04SGreg Roach        return $this->xref;
332a25f0a04SGreg Roach    }
333a25f0a04SGreg Roach
334a25f0a04SGreg Roach    /**
335000959d9SGreg Roach     * Get the tree to which this record belongs
336000959d9SGreg Roach     *
337000959d9SGreg Roach     * @return Tree
338000959d9SGreg Roach     */
339f4afa648SGreg Roach    public function tree(): Tree
340c1010edaSGreg Roach    {
341518bbdc1SGreg Roach        return $this->tree;
342000959d9SGreg Roach    }
343000959d9SGreg Roach
344000959d9SGreg Roach    /**
345a25f0a04SGreg Roach     * Application code should access data via Fact objects.
346a25f0a04SGreg Roach     * This function exists to support old code.
347a25f0a04SGreg Roach     *
348a25f0a04SGreg Roach     * @return string
349a25f0a04SGreg Roach     */
350e364afe4SGreg Roach    public function gedcom(): string
351c1010edaSGreg Roach    {
352b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
353a25f0a04SGreg Roach    }
354a25f0a04SGreg Roach
355a25f0a04SGreg Roach    /**
356a25f0a04SGreg Roach     * Does this record have a pending change?
357a25f0a04SGreg Roach     *
358cbc1590aSGreg Roach     * @return bool
359a25f0a04SGreg Roach     */
3608f53f488SRico Sonntag    public function isPendingAddition(): bool
361c1010edaSGreg Roach    {
362a25f0a04SGreg Roach        return $this->pending !== null;
363a25f0a04SGreg Roach    }
364a25f0a04SGreg Roach
365a25f0a04SGreg Roach    /**
366a25f0a04SGreg Roach     * Does this record have a pending deletion?
367a25f0a04SGreg Roach     *
368cbc1590aSGreg Roach     * @return bool
369a25f0a04SGreg Roach     */
3708f53f488SRico Sonntag    public function isPendingDeletion(): bool
371c1010edaSGreg Roach    {
372a25f0a04SGreg Roach        return $this->pending === '';
373a25f0a04SGreg Roach    }
374a25f0a04SGreg Roach
375a25f0a04SGreg Roach    /**
376ee4364daSGreg Roach     * Generate a "slug" to use in pretty URLs.
377ee4364daSGreg Roach     *
378ee4364daSGreg Roach     * @return string
379ee4364daSGreg Roach     */
380ee4364daSGreg Roach    public function slug(): string
381ee4364daSGreg Roach    {
3825ab92b3fSGreg Roach        $slug = strip_tags($this->fullName());
383f7440925SGreg Roach
38474670d65SGreg Roach        try {
385f7440925SGreg Roach            $transliterator = Transliterator::create('Any-Latin;Latin-ASCII');
3865ab92b3fSGreg Roach            $slug           = $transliterator->transliterate($slug);
38774670d65SGreg Roach        } catch (Throwable $ex) {
38874670d65SGreg Roach            // ext-intl not installed?
38974670d65SGreg Roach            // Transliteration algorithms not present in lib-icu?
390f7440925SGreg Roach        }
391f7440925SGreg Roach
3925ab92b3fSGreg Roach        $slug = preg_replace('/[^A-Za-z0-9]+/', '-', $slug);
3935ab92b3fSGreg Roach
3945ab92b3fSGreg Roach        return trim($slug, '-') ?: '-';
395ee4364daSGreg Roach    }
396ee4364daSGreg Roach
397ee4364daSGreg Roach    /**
398225e381fSGreg Roach     * Generate a URL to this record.
399a25f0a04SGreg Roach     *
400a25f0a04SGreg Roach     * @return string
401a25f0a04SGreg Roach     */
4028f53f488SRico Sonntag    public function url(): string
403c1010edaSGreg Roach    {
404225e381fSGreg Roach        return route(static::ROUTE_NAME, [
405c0935879SGreg Roach            'xref' => $this->xref(),
406ee4364daSGreg Roach            'tree' => $this->tree->name(),
407ee4364daSGreg Roach            'slug' => $this->slug(),
408225e381fSGreg Roach        ]);
409a25f0a04SGreg Roach    }
410a25f0a04SGreg Roach
411a25f0a04SGreg Roach    /**
412a25f0a04SGreg Roach     * Can the details of this record be shown?
413a25f0a04SGreg Roach     *
414cbc1590aSGreg Roach     * @param int|null $access_level
415a25f0a04SGreg Roach     *
416cbc1590aSGreg Roach     * @return bool
417a25f0a04SGreg Roach     */
41835584196SGreg Roach    public function canShow(int $access_level = null): bool
419c1010edaSGreg Roach    {
420f0b9c048SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
4214b9ff166SGreg Roach
422a25f0a04SGreg Roach        // We use this value to bypass privacy checks. For example,
423a25f0a04SGreg Roach        // when downloading data or when calculating privacy itself.
424f0b9c048SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
425a25f0a04SGreg Roach            return true;
426a25f0a04SGreg Roach        }
427f0b9c048SGreg Roach
4287476e8a5SGreg Roach        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
429f0b9c048SGreg Roach
430c692965aSGreg Roach        return app('cache.array')->remember($cache_key, function () use ($access_level) {
431f0b9c048SGreg Roach            return $this->canShowRecord($access_level);
432f0b9c048SGreg Roach        });
433a25f0a04SGreg Roach    }
434a25f0a04SGreg Roach
435a25f0a04SGreg Roach    /**
436a25f0a04SGreg Roach     * Can the name of this record be shown?
437a25f0a04SGreg Roach     *
438cbc1590aSGreg Roach     * @param int|null $access_level
439a25f0a04SGreg Roach     *
440cbc1590aSGreg Roach     * @return bool
441a25f0a04SGreg Roach     */
44276f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
443c1010edaSGreg Roach    {
444a25f0a04SGreg Roach        return $this->canShow($access_level);
445a25f0a04SGreg Roach    }
446a25f0a04SGreg Roach
447a25f0a04SGreg Roach    /**
448a25f0a04SGreg Roach     * Can we edit this record?
449a25f0a04SGreg Roach     *
450cbc1590aSGreg Roach     * @return bool
451a25f0a04SGreg Roach     */
4528f53f488SRico Sonntag    public function canEdit(): bool
453c1010edaSGreg Roach    {
4541450f098SGreg Roach        if ($this->isPendingDeletion()) {
4551450f098SGreg Roach            return false;
4561450f098SGreg Roach        }
4571450f098SGreg Roach
4581450f098SGreg Roach        if (Auth::isManager($this->tree)) {
4591450f098SGreg Roach            return true;
4601450f098SGreg Roach        }
4611450f098SGreg Roach
4621450f098SGreg Roach        return Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
463a25f0a04SGreg Roach    }
464a25f0a04SGreg Roach
465a25f0a04SGreg Roach    /**
466a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
467a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
468a25f0a04SGreg Roach     *
469cbc1590aSGreg Roach     * @param int $access_level
470a25f0a04SGreg Roach     *
471a25f0a04SGreg Roach     * @return string
472a25f0a04SGreg Roach     */
473e364afe4SGreg Roach    public function privatizeGedcom(int $access_level): string
474c1010edaSGreg Roach    {
475e364afe4SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
476a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
477a25f0a04SGreg Roach            return $this->gedcom;
478b2ce94c6SRico Sonntag        }
479b2ce94c6SRico Sonntag
480b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
481a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
482a25f0a04SGreg Roach
483a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
484dc141db3SGreg Roach            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
485a25f0a04SGreg Roach
486a25f0a04SGreg Roach            // Check each of the facts for access
4878d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
488138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
489a25f0a04SGreg Roach            }
490cbc1590aSGreg Roach
491a25f0a04SGreg Roach            return $gedrec;
492b2ce94c6SRico Sonntag        }
493b2ce94c6SRico Sonntag
494a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
495a25f0a04SGreg Roach        // limited data, such as links to other records.
496a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
497a25f0a04SGreg Roach    }
498a25f0a04SGreg Roach
499a25f0a04SGreg Roach    /**
500a25f0a04SGreg Roach     * Default for "other" object types
501c7ff4153SGreg Roach     *
502c7ff4153SGreg Roach     * @return void
503a25f0a04SGreg Roach     */
504e364afe4SGreg Roach    public function extractNames(): void
505c1010edaSGreg Roach    {
50676f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
507a25f0a04SGreg Roach    }
508a25f0a04SGreg Roach
509a25f0a04SGreg Roach    /**
510a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
511a25f0a04SGreg Roach     *
512a25f0a04SGreg Roach     * @return string[][]
513a25f0a04SGreg Roach     */
5148f53f488SRico Sonntag    public function getAllNames(): array
515c1010edaSGreg Roach    {
516bdb3725aSGreg Roach        if ($this->getAllNames === null) {
517bdb3725aSGreg Roach            $this->getAllNames = [];
518a25f0a04SGreg Roach            if ($this->canShowName()) {
519a25f0a04SGreg Roach                // Ask the record to extract its names
520a25f0a04SGreg Roach                $this->extractNames();
521a25f0a04SGreg Roach                // No name found? Use a fallback.
522bdb3725aSGreg Roach                if (!$this->getAllNames) {
523db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
524a25f0a04SGreg Roach                }
525a25f0a04SGreg Roach            } else {
526db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
527a25f0a04SGreg Roach            }
528a25f0a04SGreg Roach        }
529cbc1590aSGreg Roach
530bdb3725aSGreg Roach        return $this->getAllNames;
531a25f0a04SGreg Roach    }
532a25f0a04SGreg Roach
533a25f0a04SGreg Roach    /**
534a25f0a04SGreg Roach     * If this object has no name, what do we call it?
535a25f0a04SGreg Roach     *
536a25f0a04SGreg Roach     * @return string
537a25f0a04SGreg Roach     */
5388f53f488SRico Sonntag    public function getFallBackName(): string
539c1010edaSGreg Roach    {
540c0935879SGreg Roach        return e($this->xref());
541a25f0a04SGreg Roach    }
542a25f0a04SGreg Roach
543a25f0a04SGreg Roach    /**
544a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
545a25f0a04SGreg Roach     *
546cbc1590aSGreg Roach     * @return int
547a25f0a04SGreg Roach     */
5488f53f488SRico Sonntag    public function getPrimaryName(): int
549c1010edaSGreg Roach    {
550a25f0a04SGreg Roach        static $language_script;
551a25f0a04SGreg Roach
552a25f0a04SGreg Roach        if ($language_script === null) {
55365cf5706SGreg Roach            $language_script = $language_script ?? I18N::locale()->script()->code();
554a25f0a04SGreg Roach        }
555a25f0a04SGreg Roach
556bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
557a25f0a04SGreg Roach            // Generally, the first name is the primary one....
558bdb3725aSGreg Roach            $this->getPrimaryName = 0;
559a25f0a04SGreg Roach            // ...except when the language/name use different character sets
560a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
56169546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
562bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
563a25f0a04SGreg Roach                    break;
564a25f0a04SGreg Roach                }
565a25f0a04SGreg Roach            }
566a25f0a04SGreg Roach        }
567a25f0a04SGreg Roach
568bdb3725aSGreg Roach        return $this->getPrimaryName;
569a25f0a04SGreg Roach    }
570a25f0a04SGreg Roach
571a25f0a04SGreg Roach    /**
572a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
573a25f0a04SGreg Roach     *
574cbc1590aSGreg Roach     * @return int
575a25f0a04SGreg Roach     */
5768f53f488SRico Sonntag    public function getSecondaryName(): int
577c1010edaSGreg Roach    {
5788f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
579a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
580bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
581a25f0a04SGreg Roach            // ....except when there are names with different character sets
582a25f0a04SGreg Roach            $all_names = $this->getAllNames();
583a25f0a04SGreg Roach            if (count($all_names) > 1) {
584a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
585a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
586e364afe4SGreg Roach                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
587bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
588a25f0a04SGreg Roach                        break;
589a25f0a04SGreg Roach                    }
590a25f0a04SGreg Roach                }
591a25f0a04SGreg Roach            }
592a25f0a04SGreg Roach        }
593cbc1590aSGreg Roach
594bdb3725aSGreg Roach        return $this->getSecondaryName;
595a25f0a04SGreg Roach    }
596a25f0a04SGreg Roach
597a25f0a04SGreg Roach    /**
598a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
599a25f0a04SGreg Roach     *
60076f666f4SGreg Roach     * @param int|null $n
6017e96c925SGreg Roach     *
6027e96c925SGreg Roach     * @return void
603a25f0a04SGreg Roach     */
604e364afe4SGreg Roach    public function setPrimaryName(int $n = null): void
605c1010edaSGreg Roach    {
606bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
607bdb3725aSGreg Roach        $this->getSecondaryName = null;
608a25f0a04SGreg Roach    }
609a25f0a04SGreg Roach
610a25f0a04SGreg Roach    /**
611a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
612a25f0a04SGreg Roach     *
613a25f0a04SGreg Roach     * @return string
614a25f0a04SGreg Roach     */
615c1010edaSGreg Roach    public function __toString()
616c1010edaSGreg Roach    {
61772cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
618a25f0a04SGreg Roach    }
619a25f0a04SGreg Roach
620a25f0a04SGreg Roach    /**
621c156e8f5SGreg Roach     * /**
622a25f0a04SGreg Roach     * Get variants of the name
623a25f0a04SGreg Roach     *
624a25f0a04SGreg Roach     * @return string
625a25f0a04SGreg Roach     */
626e364afe4SGreg Roach    public function fullName(): string
627c1010edaSGreg Roach    {
628a25f0a04SGreg Roach        if ($this->canShowName()) {
629a25f0a04SGreg Roach            $tmp = $this->getAllNames();
630cbc1590aSGreg Roach
631a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
632a25f0a04SGreg Roach        }
633b2ce94c6SRico Sonntag
634b2ce94c6SRico Sonntag        return I18N::translate('Private');
635a25f0a04SGreg Roach    }
636a25f0a04SGreg Roach
637a25f0a04SGreg Roach    /**
638a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
639a25f0a04SGreg Roach     *
640a25f0a04SGreg Roach     * @return string
641a25f0a04SGreg Roach     */
64239ca88baSGreg Roach    public function sortName(): string
643c1010edaSGreg Roach    {
644a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
645a25f0a04SGreg Roach        $tmp = $this->getAllNames();
646cbc1590aSGreg Roach
647a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
648a25f0a04SGreg Roach    }
649a25f0a04SGreg Roach
650a25f0a04SGreg Roach    /**
651a25f0a04SGreg Roach     * Get the full name in an alternative character set
652a25f0a04SGreg Roach     *
653e364afe4SGreg Roach     * @return string|null
654a25f0a04SGreg Roach     */
655e364afe4SGreg Roach    public function alternateName(): ?string
656c1010edaSGreg Roach    {
657e364afe4SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
658a25f0a04SGreg Roach            $all_names = $this->getAllNames();
659cbc1590aSGreg Roach
660a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
661a25f0a04SGreg Roach        }
662b2ce94c6SRico Sonntag
663b2ce94c6SRico Sonntag        return null;
664a25f0a04SGreg Roach    }
665a25f0a04SGreg Roach
666a25f0a04SGreg Roach    /**
667a25f0a04SGreg Roach     * Format this object for display in a list
668a25f0a04SGreg Roach     *
669a25f0a04SGreg Roach     * @return string
670a25f0a04SGreg Roach     */
6718f53f488SRico Sonntag    public function formatList(): string
672c1010edaSGreg Roach    {
673b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
67439ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
675a25f0a04SGreg Roach        $html .= $this->formatListDetails();
676b165e17cSGreg Roach        $html .= '</a>';
677cbc1590aSGreg Roach
678a25f0a04SGreg Roach        return $html;
679a25f0a04SGreg Roach    }
680a25f0a04SGreg Roach
681a25f0a04SGreg Roach    /**
682a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
683a25f0a04SGreg Roach     * identifying characteristics of this record.
684a25f0a04SGreg Roach     *
685a25f0a04SGreg Roach     * @return string
686a25f0a04SGreg Roach     */
6878f53f488SRico Sonntag    public function formatListDetails(): string
688c1010edaSGreg Roach    {
689a25f0a04SGreg Roach        return '';
690a25f0a04SGreg Roach    }
691a25f0a04SGreg Roach
692a25f0a04SGreg Roach    /**
693a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
694a25f0a04SGreg Roach     *
6958d0ebef0SGreg Roach     * @param string[] $facts
696cbc1590aSGreg Roach     * @param int      $style
697a25f0a04SGreg Roach     *
698a25f0a04SGreg Roach     * @return string
699a25f0a04SGreg Roach     */
7008d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
701c1010edaSGreg Roach    {
70230158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
703a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
704e364afe4SGreg Roach            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
705d93f11b5SGreg Roach                $joiner = ' — ';
706d93f11b5SGreg Roach            } else {
707d93f11b5SGreg Roach                $joiner = '';
708d93f11b5SGreg Roach            }
709e364afe4SGreg Roach            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
710a25f0a04SGreg Roach                switch ($style) {
711a25f0a04SGreg Roach                    case 1:
7127b7d8067SGreg Roach                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
713a25f0a04SGreg Roach                    case 2:
7147b7d8067SGreg Roach                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
715a25f0a04SGreg Roach                }
716a25f0a04SGreg Roach            }
717a25f0a04SGreg Roach        }
718cbc1590aSGreg Roach
719a25f0a04SGreg Roach        return '';
720a25f0a04SGreg Roach    }
721a25f0a04SGreg Roach
722a25f0a04SGreg Roach    /**
723a25f0a04SGreg Roach     * Find individuals linked to this record.
724a25f0a04SGreg Roach     *
725a25f0a04SGreg Roach     * @param string $link
726a25f0a04SGreg Roach     *
727b5c8fd7eSGreg Roach     * @return Collection<Individual>
728a25f0a04SGreg Roach     */
729907c1109SGreg Roach    public function linkedIndividuals(string $link): Collection
730c1010edaSGreg Roach    {
731907c1109SGreg Roach        return DB::table('individuals')
7320b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
733907c1109SGreg Roach                $join
734907c1109SGreg Roach                    ->on('l_file', '=', 'i_file')
735907c1109SGreg Roach                    ->on('l_from', '=', 'i_id');
736ba1c12e8SGreg Roach            })
737ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
738ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
739ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
740907c1109SGreg Roach            ->select(['individuals.*'])
741907c1109SGreg Roach            ->get()
742d5ad3db0SGreg Roach            ->map(Individual::rowMapper($this->tree))
743907c1109SGreg Roach            ->filter(self::accessFilter());
744a25f0a04SGreg Roach    }
745a25f0a04SGreg Roach
746a25f0a04SGreg Roach    /**
747a25f0a04SGreg Roach     * Find families linked to this record.
748a25f0a04SGreg Roach     *
749a25f0a04SGreg Roach     * @param string $link
750a25f0a04SGreg Roach     *
751b5c8fd7eSGreg Roach     * @return Collection<Family>
752a25f0a04SGreg Roach     */
753907c1109SGreg Roach    public function linkedFamilies(string $link): Collection
754c1010edaSGreg Roach    {
755907c1109SGreg Roach        return DB::table('families')
7560b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
757907c1109SGreg Roach                $join
758907c1109SGreg Roach                    ->on('l_file', '=', 'f_file')
759907c1109SGreg Roach                    ->on('l_from', '=', 'f_id');
760ba1c12e8SGreg Roach            })
761ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
762ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
763ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
764907c1109SGreg Roach            ->select(['families.*'])
765907c1109SGreg Roach            ->get()
766d5ad3db0SGreg Roach            ->map(Family::rowMapper($this->tree))
767907c1109SGreg Roach            ->filter(self::accessFilter());
768a25f0a04SGreg Roach    }
769a25f0a04SGreg Roach
770a25f0a04SGreg Roach    /**
771a25f0a04SGreg Roach     * Find sources linked to this record.
772a25f0a04SGreg Roach     *
773a25f0a04SGreg Roach     * @param string $link
774a25f0a04SGreg Roach     *
775b5c8fd7eSGreg Roach     * @return Collection<Source>
776a25f0a04SGreg Roach     */
777907c1109SGreg Roach    public function linkedSources(string $link): Collection
778c1010edaSGreg Roach    {
779907c1109SGreg Roach        return DB::table('sources')
7800b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
781907c1109SGreg Roach                $join
782907c1109SGreg Roach                    ->on('l_file', '=', 's_file')
783907c1109SGreg Roach                    ->on('l_from', '=', 's_id');
784ba1c12e8SGreg Roach            })
785ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
786ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
787ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
788907c1109SGreg Roach            ->select(['sources.*'])
789907c1109SGreg Roach            ->get()
790d5ad3db0SGreg Roach            ->map(Source::rowMapper($this->tree))
791907c1109SGreg Roach            ->filter(self::accessFilter());
792a25f0a04SGreg Roach    }
793a25f0a04SGreg Roach
794a25f0a04SGreg Roach    /**
795a25f0a04SGreg Roach     * Find media objects linked to this record.
796a25f0a04SGreg Roach     *
797a25f0a04SGreg Roach     * @param string $link
798a25f0a04SGreg Roach     *
799b5c8fd7eSGreg Roach     * @return Collection<Media>
800a25f0a04SGreg Roach     */
801907c1109SGreg Roach    public function linkedMedia(string $link): Collection
802c1010edaSGreg Roach    {
803907c1109SGreg Roach        return DB::table('media')
8040b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
805907c1109SGreg Roach                $join
806907c1109SGreg Roach                    ->on('l_file', '=', 'm_file')
807907c1109SGreg Roach                    ->on('l_from', '=', 'm_id');
808ba1c12e8SGreg Roach            })
809ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
810ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
811ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
812907c1109SGreg Roach            ->select(['media.*'])
813907c1109SGreg Roach            ->get()
814d5ad3db0SGreg Roach            ->map(Media::rowMapper($this->tree))
815907c1109SGreg Roach            ->filter(self::accessFilter());
816a25f0a04SGreg Roach    }
817a25f0a04SGreg Roach
818a25f0a04SGreg Roach    /**
819a25f0a04SGreg Roach     * Find notes linked to this record.
820a25f0a04SGreg Roach     *
821a25f0a04SGreg Roach     * @param string $link
822a25f0a04SGreg Roach     *
823b5c8fd7eSGreg Roach     * @return Collection<Note>
824a25f0a04SGreg Roach     */
825907c1109SGreg Roach    public function linkedNotes(string $link): Collection
826c1010edaSGreg Roach    {
827907c1109SGreg Roach        return DB::table('other')
8280b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
829907c1109SGreg Roach                $join
830907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
831907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
832ba1c12e8SGreg Roach            })
833ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
834ba1c12e8SGreg Roach            ->where('o_type', '=', 'NOTE')
835ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
836ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
837907c1109SGreg Roach            ->select(['other.*'])
838907c1109SGreg Roach            ->get()
839d5ad3db0SGreg Roach            ->map(Note::rowMapper($this->tree))
840907c1109SGreg Roach            ->filter(self::accessFilter());
841a25f0a04SGreg Roach    }
842a25f0a04SGreg Roach
843a25f0a04SGreg Roach    /**
844a25f0a04SGreg Roach     * Find repositories linked to this record.
845a25f0a04SGreg Roach     *
846a25f0a04SGreg Roach     * @param string $link
847a25f0a04SGreg Roach     *
848b5c8fd7eSGreg Roach     * @return Collection<Repository>
849a25f0a04SGreg Roach     */
850907c1109SGreg Roach    public function linkedRepositories(string $link): Collection
851c1010edaSGreg Roach    {
852907c1109SGreg Roach        return DB::table('other')
8530b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
854907c1109SGreg Roach                $join
855907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
856907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
857ba1c12e8SGreg Roach            })
858ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
859ba1c12e8SGreg Roach            ->where('o_type', '=', 'REPO')
860ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
861ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
862907c1109SGreg Roach            ->select(['other.*'])
863907c1109SGreg Roach            ->get()
864d5ad3db0SGreg Roach            ->map(Repository::rowMapper($this->tree))
865907c1109SGreg Roach            ->filter(self::accessFilter());
866a25f0a04SGreg Roach    }
867a25f0a04SGreg Roach
868a25f0a04SGreg Roach    /**
869a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
870a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
871a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
872a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
873a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
874a25f0a04SGreg Roach     *
8758d0ebef0SGreg Roach     * @param string[] $events
876a25f0a04SGreg Roach     *
877a25f0a04SGreg Roach     * @return Date[]
878a25f0a04SGreg Roach     */
8798d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
880c1010edaSGreg Roach    {
88113abd6f3SGreg Roach        $dates = [];
8828d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
8832decada7SGreg Roach            if ($event->date()->isOK()) {
8842decada7SGreg Roach                $dates[] = $event->date();
885a25f0a04SGreg Roach            }
886a25f0a04SGreg Roach        }
887a25f0a04SGreg Roach
888a25f0a04SGreg Roach        return $dates;
889a25f0a04SGreg Roach    }
890a25f0a04SGreg Roach
891a25f0a04SGreg Roach    /**
892a25f0a04SGreg Roach     * Get all the places for a particular type of event
893a25f0a04SGreg Roach     *
8948d0ebef0SGreg Roach     * @param string[] $events
895a25f0a04SGreg Roach     *
8964080d558SGreg Roach     * @return Place[]
897a25f0a04SGreg Roach     */
8988d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
899c1010edaSGreg Roach    {
90013abd6f3SGreg Roach        $places = [];
9018d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
902138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
903a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
90416d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
905a25f0a04SGreg Roach                }
906a25f0a04SGreg Roach            }
907a25f0a04SGreg Roach        }
908a25f0a04SGreg Roach
909a25f0a04SGreg Roach        return $places;
910a25f0a04SGreg Roach    }
911a25f0a04SGreg Roach
912a25f0a04SGreg Roach    /**
913a25f0a04SGreg Roach     * The facts and events for this record.
914a25f0a04SGreg Roach     *
9158d0ebef0SGreg Roach     * @param string[] $filter
916cbc1590aSGreg Roach     * @param bool     $sort
917cbc1590aSGreg Roach     * @param int|null $access_level
918ce42304aSGreg Roach     * @param bool     $ignore_deleted
919a25f0a04SGreg Roach     *
920b5c8fd7eSGreg Roach     * @return Collection<Fact>
921a25f0a04SGreg Roach     */
922ce42304aSGreg Roach    public function facts(
923ce42304aSGreg Roach        array $filter = [],
924ce42304aSGreg Roach        bool $sort = false,
925ce42304aSGreg Roach        int $access_level = null,
926ce42304aSGreg Roach        bool $ignore_deleted = false
927ce42304aSGreg Roach    ): Collection {
928d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
9294b9ff166SGreg Roach
9308af3e5c1SGreg Roach        $facts = new Collection();
931ce42304aSGreg Roach        if ($this->canShow($access_level)) {
932a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
93322d65e5aSGreg Roach                if (($filter === [] || in_array($fact->getTag(), $filter, true)) && $fact->canShow($access_level)) {
9348af3e5c1SGreg Roach                    $facts->push($fact);
935a25f0a04SGreg Roach                }
936a25f0a04SGreg Roach            }
937a25f0a04SGreg Roach        }
938d17d7b9eSGreg Roach
939a25f0a04SGreg Roach        if ($sort) {
940580a4d11SGreg Roach            $facts = Fact::sortFacts($facts);
941a25f0a04SGreg Roach        }
942cbc1590aSGreg Roach
943ce42304aSGreg Roach        if ($ignore_deleted) {
944ce42304aSGreg Roach            $facts = $facts->filter(static function (Fact $fact): bool {
945ce42304aSGreg Roach                return !$fact->isPendingDeletion();
946ce42304aSGreg Roach            });
947ce42304aSGreg Roach        }
948ce42304aSGreg Roach
94939ca88baSGreg Roach        return new Collection($facts);
950a25f0a04SGreg Roach    }
951a25f0a04SGreg Roach
952a25f0a04SGreg Roach    /**
9534459dc9aSGreg Roach     * Get the last-change timestamp for this record
954a25f0a04SGreg Roach     *
9554459dc9aSGreg Roach     * @return Carbon
956a25f0a04SGreg Roach     */
9574459dc9aSGreg Roach    public function lastChangeTimestamp(): Carbon
958c1010edaSGreg Roach    {
9594459dc9aSGreg Roach        /** @var Fact|null $chan */
960820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
961a25f0a04SGreg Roach
9624459dc9aSGreg Roach        if ($chan instanceof Fact) {
963a25f0a04SGreg Roach            // The record does have a CHAN event
9642decada7SGreg Roach            $d = $chan->date()->minimumDate();
9654459dc9aSGreg Roach
966138ca96cSGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
9674459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
968e364afe4SGreg Roach            }
969e364afe4SGreg Roach
970e364afe4SGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
9714459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
972b2ce94c6SRico Sonntag            }
973b2ce94c6SRico Sonntag
9744459dc9aSGreg Roach            return Carbon::create($d->year(), $d->month(), $d->day());
975a25f0a04SGreg Roach        }
976b2ce94c6SRico Sonntag
977a25f0a04SGreg Roach        // The record does not have a CHAN event
9784459dc9aSGreg Roach        return Carbon::createFromTimestamp(0);
979a25f0a04SGreg Roach    }
980a25f0a04SGreg Roach
981a25f0a04SGreg Roach    /**
982a25f0a04SGreg Roach     * Get the last-change user for this record
983a25f0a04SGreg Roach     *
984a25f0a04SGreg Roach     * @return string
985a25f0a04SGreg Roach     */
986e364afe4SGreg Roach    public function lastChangeUser(): string
987c1010edaSGreg Roach    {
988820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
989a25f0a04SGreg Roach
990a25f0a04SGreg Roach        if ($chan === null) {
991a25f0a04SGreg Roach            return I18N::translate('Unknown');
992b2ce94c6SRico Sonntag        }
993b2ce94c6SRico Sonntag
9943425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
995baacc364SGreg Roach        if ($chan_user === '') {
996a25f0a04SGreg Roach            return I18N::translate('Unknown');
997b2ce94c6SRico Sonntag        }
998b2ce94c6SRico Sonntag
999a25f0a04SGreg Roach        return $chan_user;
1000a25f0a04SGreg Roach    }
1001a25f0a04SGreg Roach
1002a25f0a04SGreg Roach    /**
1003a25f0a04SGreg Roach     * Add a new fact to this record
1004a25f0a04SGreg Roach     *
1005a25f0a04SGreg Roach     * @param string $gedcom
1006cbc1590aSGreg Roach     * @param bool   $update_chan
10077e96c925SGreg Roach     *
10087e96c925SGreg Roach     * @return void
1009a25f0a04SGreg Roach     */
1010e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
1011c1010edaSGreg Roach    {
1012fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
1013a25f0a04SGreg Roach    }
1014a25f0a04SGreg Roach
1015a25f0a04SGreg Roach    /**
1016a25f0a04SGreg Roach     * Delete a fact from this record
1017a25f0a04SGreg Roach     *
1018a25f0a04SGreg Roach     * @param string $fact_id
1019cbc1590aSGreg Roach     * @param bool   $update_chan
10207e96c925SGreg Roach     *
10217e96c925SGreg Roach     * @return void
1022a25f0a04SGreg Roach     */
1023e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
1024c1010edaSGreg Roach    {
1025db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
1026a25f0a04SGreg Roach    }
1027a25f0a04SGreg Roach
1028a25f0a04SGreg Roach    /**
1029a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
1030a25f0a04SGreg Roach     *
1031a25f0a04SGreg Roach     * @param string $fact_id
1032a25f0a04SGreg Roach     * @param string $gedcom
1033cbc1590aSGreg Roach     * @param bool   $update_chan
1034a25f0a04SGreg Roach     *
10357e96c925SGreg Roach     * @return void
10367e96c925SGreg Roach     * @throws Exception
1037a25f0a04SGreg Roach     */
1038e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
1039c1010edaSGreg Roach    {
104071f696adSGreg Roach        // Not all record types allow a CHAN event.
104171f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
104271f696adSGreg Roach
1043a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1044a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1045a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1046a25f0a04SGreg Roach
1047a25f0a04SGreg Roach        if ($this->pending === '') {
10487e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
1049a25f0a04SGreg Roach        }
10508d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
10517e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1052a25f0a04SGreg Roach        }
1053a25f0a04SGreg Roach
1054a25f0a04SGreg Roach        if ($this->pending) {
1055a25f0a04SGreg Roach            $old_gedcom = $this->pending;
1056a25f0a04SGreg Roach        } else {
1057a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
1058a25f0a04SGreg Roach        }
1059a25f0a04SGreg Roach
1060a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
106165e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
1062a25f0a04SGreg Roach
1063a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
10648d0ebef0SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) {
1065a25f0a04SGreg Roach            if (!$fact->isPendingDeletion()) {
1066905ab80aSGreg Roach                if ($fact->id() === $fact_id) {
1067db7bb364SGreg Roach                    if ($gedcom !== '') {
1068a25f0a04SGreg Roach                        $new_gedcom .= "\n" . $gedcom;
1069a25f0a04SGreg Roach                    }
1070fc3ccce4SGreg Roach                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1071e364afe4SGreg Roach                } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) {
1072138ca96cSGreg Roach                    $new_gedcom .= "\n" . $fact->gedcom();
1073a25f0a04SGreg Roach                }
1074a25f0a04SGreg Roach            }
1075a25f0a04SGreg Roach        }
1076a25f0a04SGreg Roach        if ($update_chan) {
1077*53432476SGreg Roach            $today = strtoupper(date('d M Y'));
1078*53432476SGreg Roach            $now   = date('H:i:s');
1079*53432476SGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
1080a25f0a04SGreg Roach        }
1081a25f0a04SGreg Roach
1082a25f0a04SGreg Roach        // Adding a new fact
1083fc3ccce4SGreg Roach        if ($fact_id === '') {
1084a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
1085a25f0a04SGreg Roach        }
1086a25f0a04SGreg Roach
1087e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
1088a25f0a04SGreg Roach            // Save the changes
1089d09b6323SGreg Roach            DB::table('change')->insert([
1090d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1091d09b6323SGreg Roach                'xref'       => $this->xref,
1092d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
1093d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
1094d09b6323SGreg Roach                'user_id'    => Auth::id(),
109513abd6f3SGreg Roach            ]);
1096a25f0a04SGreg Roach
1097a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1098a25f0a04SGreg Roach
10997c4add84SGreg Roach            if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') {
110022e73debSGreg Roach                app(PendingChangesService::class)->acceptRecord($this);
1101a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1102a25f0a04SGreg Roach                $this->pending = null;
1103a25f0a04SGreg Roach            }
1104a25f0a04SGreg Roach        }
1105a25f0a04SGreg Roach        $this->parseFacts();
1106a25f0a04SGreg Roach    }
1107a25f0a04SGreg Roach
1108a25f0a04SGreg Roach    /**
1109a25f0a04SGreg Roach     * Update this record
1110a25f0a04SGreg Roach     *
1111a25f0a04SGreg Roach     * @param string $gedcom
1112cbc1590aSGreg Roach     * @param bool   $update_chan
11137e96c925SGreg Roach     *
11147e96c925SGreg Roach     * @return void
1115a25f0a04SGreg Roach     */
1116e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
1117c1010edaSGreg Roach    {
111871f696adSGreg Roach        // Not all record types allow a CHAN event.
111971f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
112071f696adSGreg Roach
1121a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1122a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1123a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1124a25f0a04SGreg Roach
1125a25f0a04SGreg Roach        // Update the CHAN record
1126a25f0a04SGreg Roach        if ($update_chan) {
1127a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1128*53432476SGreg Roach            $today = strtoupper(date('d M Y'));
1129*53432476SGreg Roach            $now   = date('H:i:s');
1130*53432476SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
1131a25f0a04SGreg Roach        }
1132a25f0a04SGreg Roach
1133a25f0a04SGreg Roach        // Create a pending change
1134d09b6323SGreg Roach        DB::table('change')->insert([
1135d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1136d09b6323SGreg Roach            'xref'       => $this->xref,
1137d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1138d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1139d09b6323SGreg Roach            'user_id'    => Auth::id(),
114013abd6f3SGreg Roach        ]);
1141a25f0a04SGreg Roach
1142a25f0a04SGreg Roach        // Clear the cache
1143a25f0a04SGreg Roach        $this->pending = $gedcom;
1144a25f0a04SGreg Roach
1145a25f0a04SGreg Roach        // Accept this pending change
11467c4add84SGreg Roach        if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') {
114722e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1148a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1149a25f0a04SGreg Roach            $this->pending = null;
1150a25f0a04SGreg Roach        }
1151a25f0a04SGreg Roach
1152a25f0a04SGreg Roach        $this->parseFacts();
1153a25f0a04SGreg Roach
1154847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1155a25f0a04SGreg Roach    }
1156a25f0a04SGreg Roach
1157a25f0a04SGreg Roach    /**
1158a25f0a04SGreg Roach     * Delete this record
1159b874da82SGreg Roach     *
1160b874da82SGreg Roach     * @return void
1161a25f0a04SGreg Roach     */
1162e364afe4SGreg Roach    public function deleteRecord(): void
1163c1010edaSGreg Roach    {
1164a25f0a04SGreg Roach        // Create a pending change
11654c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1166d09b6323SGreg Roach            DB::table('change')->insert([
1167d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1168d09b6323SGreg Roach                'xref'       => $this->xref,
1169d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1170d09b6323SGreg Roach                'new_gedcom' => '',
1171d09b6323SGreg Roach                'user_id'    => Auth::id(),
117213abd6f3SGreg Roach            ]);
11734c0b5256SGreg Roach        }
1174a25f0a04SGreg Roach
11754c0b5256SGreg Roach        // Auto-accept this pending change
11767c4add84SGreg Roach        if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') {
117722e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1178a25f0a04SGreg Roach        }
1179a25f0a04SGreg Roach
1180a25f0a04SGreg Roach        // Clear the cache
1181d17d7b9eSGreg Roach        self::$gedcom_record_cache  = [];
1182d17d7b9eSGreg Roach        self::$pending_record_cache = [];
1183a25f0a04SGreg Roach
1184847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1185a25f0a04SGreg Roach    }
1186a25f0a04SGreg Roach
1187a25f0a04SGreg Roach    /**
1188a25f0a04SGreg Roach     * Remove all links from this record to $xref
1189a25f0a04SGreg Roach     *
1190a25f0a04SGreg Roach     * @param string $xref
1191cbc1590aSGreg Roach     * @param bool   $update_chan
11927e96c925SGreg Roach     *
11937e96c925SGreg Roach     * @return void
1194a25f0a04SGreg Roach     */
1195e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
1196c1010edaSGreg Roach    {
1197a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1198a25f0a04SGreg Roach
119930158ae7SGreg Roach        foreach ($this->facts() as $fact) {
120084586c02SGreg Roach            if ($fact->value() === $value) {
1201905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
12028d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1203138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1204a25f0a04SGreg Roach                foreach ($matches as $match) {
1205a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1206a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1207a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1208a25f0a04SGreg Roach                }
1209905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1210a25f0a04SGreg Roach            }
1211a25f0a04SGreg Roach        }
1212a25f0a04SGreg Roach    }
1213bf4eb542SGreg Roach
1214bf4eb542SGreg Roach    /**
1215bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1216bf4eb542SGreg Roach     * also delete all links to it.
1217bf4eb542SGreg Roach     *
1218bf4eb542SGreg Roach     * @return GedcomRecord[]
1219bf4eb542SGreg Roach     */
1220bf4eb542SGreg Roach    public function linkingRecords(): array
1221bf4eb542SGreg Roach    {
1222bf4eb542SGreg Roach        $union = DB::table('change')
1223bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1224fbbe964bSGreg Roach            ->whereContains('new_gedcom', '@' . $this->xref() . '@')
1225bf4eb542SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%')
122683242252SGreg Roach            ->whereIn('change_id', function (Builder $query): void {
122783242252SGreg Roach                $query->select(new Expression('MAX(change_id)'))
122883242252SGreg Roach                    ->from('change')
122983242252SGreg Roach                    ->where('gedcom_id', '=', $this->tree->id())
123083242252SGreg Roach                    ->where('status', '=', 'pending')
12317f5c2944SGreg Roach                    ->groupBy(['xref']);
123283242252SGreg Roach            })
1233bf4eb542SGreg Roach            ->select(['xref']);
1234bf4eb542SGreg Roach
1235bf4eb542SGreg Roach        $xrefs = DB::table('link')
1236bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1237bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
123847256fc5SGreg Roach            ->select(['l_from'])
1239bf4eb542SGreg Roach            ->union($union)
1240bf4eb542SGreg Roach            ->pluck('l_from');
1241bf4eb542SGreg Roach
1242bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
1243ffc0a61fSGreg Roach            $record = GedcomRecord::getInstance($xref, $this->tree);
1244ffc0a61fSGreg Roach            assert($record instanceof GedcomRecord);
1245ffc0a61fSGreg Roach
1246ffc0a61fSGreg Roach            return $record;
1247bf4eb542SGreg Roach        })->all();
1248bf4eb542SGreg Roach    }
124922e73debSGreg Roach
125022e73debSGreg Roach    /**
125122e73debSGreg Roach     * Each object type may have its own special rules, and re-implement this function.
125222e73debSGreg Roach     *
125322e73debSGreg Roach     * @param int $access_level
125422e73debSGreg Roach     *
125522e73debSGreg Roach     * @return bool
125622e73debSGreg Roach     */
125722e73debSGreg Roach    protected function canShowByType(int $access_level): bool
125822e73debSGreg Roach    {
125922e73debSGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
126022e73debSGreg Roach
126122e73debSGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
126222e73debSGreg Roach            // Restriction found
126322e73debSGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
126422e73debSGreg Roach        }
126522e73debSGreg Roach
126622e73debSGreg Roach        // No restriction found - must be public:
126722e73debSGreg Roach        return true;
126822e73debSGreg Roach    }
126922e73debSGreg Roach
127022e73debSGreg Roach    /**
127122e73debSGreg Roach     * Generate a private version of this record
127222e73debSGreg Roach     *
127322e73debSGreg Roach     * @param int $access_level
127422e73debSGreg Roach     *
127522e73debSGreg Roach     * @return string
127622e73debSGreg Roach     */
127722e73debSGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
127822e73debSGreg Roach    {
127922e73debSGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
128022e73debSGreg Roach    }
128122e73debSGreg Roach
128222e73debSGreg Roach    /**
128322e73debSGreg Roach     * Convert a name record into sortable and full/display versions. This default
128422e73debSGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
128522e73debSGreg Roach     *
128622e73debSGreg Roach     * @param string $type
128722e73debSGreg Roach     * @param string $value
128822e73debSGreg Roach     * @param string $gedcom
128922e73debSGreg Roach     *
129022e73debSGreg Roach     * @return void
129122e73debSGreg Roach     */
129222e73debSGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
129322e73debSGreg Roach    {
129422e73debSGreg Roach        $this->getAllNames[] = [
129522e73debSGreg Roach            'type'   => $type,
129622e73debSGreg Roach            'sort'   => preg_replace_callback('/([0-9]+)/', static function (array $matches): string {
129722e73debSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
129822e73debSGreg Roach            }, $value),
129922e73debSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
130022e73debSGreg Roach            // This is used for display
130122e73debSGreg Roach            'fullNN' => $value,
130222e73debSGreg Roach            // This goes into the database
130322e73debSGreg Roach        ];
130422e73debSGreg Roach    }
130522e73debSGreg Roach
130622e73debSGreg Roach    /**
130722e73debSGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
130822e73debSGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
130922e73debSGreg Roach     * Parameters: the level 1 fact containing the name.
131022e73debSGreg Roach     * Return value: an array of name structures, each containing
131122e73debSGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
131222e73debSGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
131322e73debSGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
131422e73debSGreg Roach     *
131522e73debSGreg Roach     * @param int        $level
131622e73debSGreg Roach     * @param string     $fact_type
131722e73debSGreg Roach     * @param Collection $facts
131822e73debSGreg Roach     *
131922e73debSGreg Roach     * @return void
132022e73debSGreg Roach     */
132122e73debSGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
132222e73debSGreg Roach    {
132322e73debSGreg Roach        $sublevel    = $level + 1;
132422e73debSGreg Roach        $subsublevel = $sublevel + 1;
132522e73debSGreg Roach        foreach ($facts as $fact) {
132622e73debSGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
132722e73debSGreg Roach                foreach ($matches as $match) {
132822e73debSGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
132922e73debSGreg Roach                    if ($match[1] === 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
133022e73debSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
133122e73debSGreg Roach                    } else {
133222e73debSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
133322e73debSGreg Roach                    }
133422e73debSGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
133522e73debSGreg Roach                        foreach ($submatches as $submatch) {
133622e73debSGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
133722e73debSGreg Roach                        }
133822e73debSGreg Roach                    }
133922e73debSGreg Roach                }
134022e73debSGreg Roach            }
134122e73debSGreg Roach        }
134222e73debSGreg Roach    }
134322e73debSGreg Roach
134422e73debSGreg Roach    /**
134522e73debSGreg Roach     * Split the record into facts
134622e73debSGreg Roach     *
134722e73debSGreg Roach     * @return void
134822e73debSGreg Roach     */
134922e73debSGreg Roach    private function parseFacts(): void
135022e73debSGreg Roach    {
135122e73debSGreg Roach        // Split the record into facts
135222e73debSGreg Roach        if ($this->gedcom) {
135322e73debSGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
135422e73debSGreg Roach            array_shift($gedcom_facts);
135522e73debSGreg Roach        } else {
135622e73debSGreg Roach            $gedcom_facts = [];
135722e73debSGreg Roach        }
135822e73debSGreg Roach        if ($this->pending) {
135922e73debSGreg Roach            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
136022e73debSGreg Roach            array_shift($pending_facts);
136122e73debSGreg Roach        } else {
136222e73debSGreg Roach            $pending_facts = [];
136322e73debSGreg Roach        }
136422e73debSGreg Roach
136522e73debSGreg Roach        $this->facts = [];
136622e73debSGreg Roach
136722e73debSGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
136822e73debSGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
136922e73debSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
137022e73debSGreg Roach                $fact->setPendingDeletion();
137122e73debSGreg Roach            }
137222e73debSGreg Roach            $this->facts[] = $fact;
137322e73debSGreg Roach        }
137422e73debSGreg Roach        foreach ($pending_facts as $pending_fact) {
137522e73debSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
137622e73debSGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
137722e73debSGreg Roach                $fact->setPendingAddition();
137822e73debSGreg Roach                $this->facts[] = $fact;
137922e73debSGreg Roach            }
138022e73debSGreg Roach        }
138122e73debSGreg Roach    }
138222e73debSGreg Roach
138322e73debSGreg Roach    /**
138422e73debSGreg Roach     * Work out whether this record can be shown to a user with a given access level
138522e73debSGreg Roach     *
138622e73debSGreg Roach     * @param int $access_level
138722e73debSGreg Roach     *
138822e73debSGreg Roach     * @return bool
138922e73debSGreg Roach     */
139022e73debSGreg Roach    private function canShowRecord(int $access_level): bool
139122e73debSGreg Roach    {
139222e73debSGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
139322e73debSGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
139422e73debSGreg Roach            return true;
139522e73debSGreg Roach        }
139622e73debSGreg Roach
139722e73debSGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
13987c4add84SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), User::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
139922e73debSGreg Roach            return true;
140022e73debSGreg Roach        }
140122e73debSGreg Roach
140222e73debSGreg Roach        // Does this record have a RESN?
140322e73debSGreg Roach        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
140422e73debSGreg Roach            return Auth::PRIV_NONE >= $access_level;
140522e73debSGreg Roach        }
140622e73debSGreg Roach        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
140722e73debSGreg Roach            return Auth::PRIV_USER >= $access_level;
140822e73debSGreg Roach        }
140922e73debSGreg Roach        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
141022e73debSGreg Roach            return true;
141122e73debSGreg Roach        }
141222e73debSGreg Roach
141322e73debSGreg Roach        // Does this record have a default RESN?
141422e73debSGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
141522e73debSGreg Roach        if (isset($individual_privacy[$this->xref()])) {
141622e73debSGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
141722e73debSGreg Roach        }
141822e73debSGreg Roach
141922e73debSGreg Roach        // Privacy rules do not apply to admins
142022e73debSGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
142122e73debSGreg Roach            return true;
142222e73debSGreg Roach        }
142322e73debSGreg Roach
142422e73debSGreg Roach        // Different types of record have different privacy rules
142522e73debSGreg Roach        return $this->canShowByType($access_level);
142622e73debSGreg Roach    }
1427a25f0a04SGreg Roach}
1428