xref: /webtrees/app/GedcomRecord.php (revision 36779af1bd0601de7819554b13a393f6edb92507)
1a25f0a04SGreg Roach<?php
23976b470SGreg Roach
3a25f0a04SGreg Roach/**
4a25f0a04SGreg Roach * webtrees: online genealogy
51fe542e9SGreg Roach * Copyright (C) 2021 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
1589f7189bSGreg Roach * along with this program. If not, see <https://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;
241fe542e9SGreg Roachuse Fisharebest\Webtrees\Contracts\UserInterface;
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;
32a25f0a04SGreg Roach
33b5961194SGreg Roachuse function addcslashes;
3422e73debSGreg Roachuse function app;
350f5fd22fSGreg Roachuse function array_combine;
360f5fd22fSGreg Roachuse function array_keys;
370f5fd22fSGreg Roachuse function array_map;
380f5fd22fSGreg Roachuse function array_search;
39f7440925SGreg Roachuse function array_shift;
40f7440925SGreg Roachuse function assert;
41f7440925SGreg Roachuse function count;
42f7440925SGreg Roachuse function date;
43f7440925SGreg Roachuse function e;
44f7440925SGreg Roachuse function explode;
45f7440925SGreg Roachuse function in_array;
46f7440925SGreg Roachuse function md5;
47f7440925SGreg Roachuse function preg_match;
48f7440925SGreg Roachuse function preg_match_all;
49f7440925SGreg Roachuse function preg_replace;
50f7440925SGreg Roachuse function preg_replace_callback;
51f7440925SGreg Roachuse function preg_split;
520f5fd22fSGreg Roachuse function range;
53f7440925SGreg Roachuse function route;
54dec352c1SGreg Roachuse function str_contains;
55d0889c63SGreg Roachuse function str_ends_with;
56f7440925SGreg Roachuse function str_pad;
57f7440925SGreg Roachuse function strtoupper;
58f7440925SGreg Roachuse function trim;
59b315f3e1SGreg Roachuse function view;
60b315f3e1SGreg Roach
61c2ed51d1SGreg Roachuse const PHP_INT_MAX;
62f7440925SGreg Roachuse const PREG_SET_ORDER;
63f7440925SGreg Roachuse const STR_PAD_LEFT;
6422e73debSGreg Roach
65a25f0a04SGreg Roach/**
6676692c8bSGreg Roach * A GEDCOM object.
67a25f0a04SGreg Roach */
68c1010edaSGreg Roachclass GedcomRecord
69c1010edaSGreg Roach{
7016d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
7116d6367aSGreg Roach
725818a371SGreg Roach    protected const ROUTE_NAME = GedcomRecordPage::class;
735818a371SGreg Roach
749599771eSGreg Roach    protected string $xref;
75bb03c9f0SGreg Roach
769599771eSGreg Roach    protected Tree $tree;
77bb03c9f0SGreg Roach
789599771eSGreg Roach    // GEDCOM data (before any pending edits)
799599771eSGreg Roach    protected string $gedcom;
80bb03c9f0SGreg Roach
819599771eSGreg Roach    // GEDCOM data (after any pending edits)
829599771eSGreg Roach    protected ?string $pending;
83bb03c9f0SGreg Roach
849599771eSGreg Roach    /** @var array<Fact> Facts extracted from $gedcom/$pending */
859599771eSGreg Roach    protected array $facts;
86bb03c9f0SGreg Roach
8709482a55SGreg Roach    /** @var array<array<string>> All the names of this individual */
889599771eSGreg Roach    protected array $getAllNames = [];
89bb03c9f0SGreg Roach
9022e73debSGreg Roach    /** @var int|null Cached result */
919599771eSGreg Roach    private ?int $getPrimaryName = null;
92c4943cffSGreg Roach
9322e73debSGreg Roach    /** @var int|null Cached result */
949599771eSGreg Roach    private ?int $getSecondaryName = null;
95a25f0a04SGreg Roach
96a25f0a04SGreg Roach    /**
97a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
98a25f0a04SGreg Roach     *
99a25f0a04SGreg Roach     * @param string      $xref
100a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
101a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
102a25f0a04SGreg Roach     *                             empty string for records with pending deletions
10324ec66ceSGreg Roach     * @param Tree        $tree
104a25f0a04SGreg Roach     */
105e364afe4SGreg Roach    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
106c1010edaSGreg Roach    {
107a25f0a04SGreg Roach        $this->xref    = $xref;
108a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
109a25f0a04SGreg Roach        $this->pending = $pending;
11024ec66ceSGreg Roach        $this->tree    = $tree;
1119599771eSGreg Roach        $this->facts   = $this->parseFacts();
112a25f0a04SGreg Roach    }
113a25f0a04SGreg Roach
114a25f0a04SGreg Roach    /**
115886b77daSGreg Roach     * A closure which will filter out private records.
116886b77daSGreg Roach     *
117886b77daSGreg Roach     * @return Closure
118886b77daSGreg Roach     */
1194146fabcSGreg Roach    public static function accessFilter(): Closure
120886b77daSGreg Roach    {
1216c2179e2SGreg Roach        return static function (GedcomRecord $record): bool {
122886b77daSGreg Roach            return $record->canShow();
123886b77daSGreg Roach        };
124886b77daSGreg Roach    }
125886b77daSGreg Roach
126886b77daSGreg Roach    /**
127c156e8f5SGreg Roach     * A closure which will compare records by name.
128c156e8f5SGreg Roach     *
129c156e8f5SGreg Roach     * @return Closure
130c156e8f5SGreg Roach     */
131c156e8f5SGreg Roach    public static function nameComparator(): Closure
132c156e8f5SGreg Roach    {
1336c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y): int {
134c156e8f5SGreg Roach            if ($x->canShowName()) {
135c156e8f5SGreg Roach                if ($y->canShowName()) {
13637646143SGreg Roach                    return I18N::comparator()($x->sortName(), $y->sortName());
137c156e8f5SGreg Roach                }
138c156e8f5SGreg Roach
139c156e8f5SGreg Roach                return -1; // only $y is private
140c156e8f5SGreg Roach            }
141c156e8f5SGreg Roach
142c156e8f5SGreg Roach            if ($y->canShowName()) {
143c156e8f5SGreg Roach                return 1; // only $x is private
144c156e8f5SGreg Roach            }
145c156e8f5SGreg Roach
146c156e8f5SGreg Roach            return 0; // both $x and $y private
147c156e8f5SGreg Roach        };
148c156e8f5SGreg Roach    }
149c156e8f5SGreg Roach
150c156e8f5SGreg Roach    /**
151c156e8f5SGreg Roach     * A closure which will compare records by change time.
152c156e8f5SGreg Roach     *
153c156e8f5SGreg Roach     * @param int $direction +1 to sort ascending, -1 to sort descending
154c156e8f5SGreg Roach     *
155c156e8f5SGreg Roach     * @return Closure
156c156e8f5SGreg Roach     */
157c156e8f5SGreg Roach    public static function lastChangeComparator(int $direction = 1): Closure
158c156e8f5SGreg Roach    {
1596c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
1604459dc9aSGreg Roach            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
161c156e8f5SGreg Roach        };
162c156e8f5SGreg Roach    }
163c156e8f5SGreg Roach
164c156e8f5SGreg Roach    /**
16502467d32SGreg Roach     * Get the GEDCOM tag for this record.
16602467d32SGreg Roach     *
16702467d32SGreg Roach     * @return string
16802467d32SGreg Roach     */
16902467d32SGreg Roach    public function tag(): string
17002467d32SGreg Roach    {
17102467d32SGreg Roach        preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
17202467d32SGreg Roach
17302467d32SGreg Roach        return $match[1] ?? static::RECORD_TYPE;
17402467d32SGreg Roach    }
17502467d32SGreg Roach
17602467d32SGreg Roach    /**
177a25f0a04SGreg Roach     * Get the XREF for this record
178a25f0a04SGreg Roach     *
179a25f0a04SGreg Roach     * @return string
180a25f0a04SGreg Roach     */
181c0935879SGreg Roach    public function xref(): string
182c1010edaSGreg Roach    {
183a25f0a04SGreg Roach        return $this->xref;
184a25f0a04SGreg Roach    }
185a25f0a04SGreg Roach
186a25f0a04SGreg Roach    /**
187000959d9SGreg Roach     * Get the tree to which this record belongs
188000959d9SGreg Roach     *
189000959d9SGreg Roach     * @return Tree
190000959d9SGreg Roach     */
191f4afa648SGreg Roach    public function tree(): Tree
192c1010edaSGreg Roach    {
193518bbdc1SGreg Roach        return $this->tree;
194000959d9SGreg Roach    }
195000959d9SGreg Roach
196000959d9SGreg Roach    /**
197a25f0a04SGreg Roach     * Application code should access data via Fact objects.
198a25f0a04SGreg Roach     * This function exists to support old code.
199a25f0a04SGreg Roach     *
200a25f0a04SGreg Roach     * @return string
201a25f0a04SGreg Roach     */
202e364afe4SGreg Roach    public function gedcom(): string
203c1010edaSGreg Roach    {
204b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
205a25f0a04SGreg Roach    }
206a25f0a04SGreg Roach
207a25f0a04SGreg Roach    /**
208a25f0a04SGreg Roach     * Does this record have a pending change?
209a25f0a04SGreg Roach     *
210cbc1590aSGreg Roach     * @return bool
211a25f0a04SGreg Roach     */
2128f53f488SRico Sonntag    public function isPendingAddition(): bool
213c1010edaSGreg Roach    {
214a25f0a04SGreg Roach        return $this->pending !== null;
215a25f0a04SGreg Roach    }
216a25f0a04SGreg Roach
217a25f0a04SGreg Roach    /**
218a25f0a04SGreg Roach     * Does this record have a pending deletion?
219a25f0a04SGreg Roach     *
220cbc1590aSGreg Roach     * @return bool
221a25f0a04SGreg Roach     */
2228f53f488SRico Sonntag    public function isPendingDeletion(): bool
223c1010edaSGreg Roach    {
224a25f0a04SGreg Roach        return $this->pending === '';
225a25f0a04SGreg Roach    }
226a25f0a04SGreg Roach
227a25f0a04SGreg Roach    /**
228225e381fSGreg Roach     * Generate a URL to this record.
229a25f0a04SGreg Roach     *
230a25f0a04SGreg Roach     * @return string
231a25f0a04SGreg Roach     */
2328f53f488SRico Sonntag    public function url(): string
233c1010edaSGreg Roach    {
234225e381fSGreg Roach        return route(static::ROUTE_NAME, [
235c0935879SGreg Roach            'xref' => $this->xref(),
236ee4364daSGreg Roach            'tree' => $this->tree->name(),
237194b0938SGreg Roach            'slug' => Registry::slugFactory()->make($this),
238225e381fSGreg Roach        ]);
239a25f0a04SGreg Roach    }
240a25f0a04SGreg Roach
241a25f0a04SGreg Roach    /**
242a25f0a04SGreg Roach     * Can the details of this record be shown?
243a25f0a04SGreg Roach     *
244cbc1590aSGreg Roach     * @param int|null $access_level
245a25f0a04SGreg Roach     *
246cbc1590aSGreg Roach     * @return bool
247a25f0a04SGreg Roach     */
24835584196SGreg Roach    public function canShow(int $access_level = null): bool
249c1010edaSGreg Roach    {
250f0b9c048SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
2514b9ff166SGreg Roach
252a25f0a04SGreg Roach        // We use this value to bypass privacy checks. For example,
253a25f0a04SGreg Roach        // when downloading data or when calculating privacy itself.
254f0b9c048SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
255a25f0a04SGreg Roach            return true;
256a25f0a04SGreg Roach        }
257f0b9c048SGreg Roach
2587476e8a5SGreg Roach        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
259f0b9c048SGreg Roach
2606b9cb339SGreg Roach        return Registry::cache()->array()->remember($cache_key, function () use ($access_level) {
261f0b9c048SGreg Roach            return $this->canShowRecord($access_level);
262f0b9c048SGreg Roach        });
263a25f0a04SGreg Roach    }
264a25f0a04SGreg Roach
265a25f0a04SGreg Roach    /**
266a25f0a04SGreg Roach     * Can the name of this record be shown?
267a25f0a04SGreg Roach     *
268cbc1590aSGreg Roach     * @param int|null $access_level
269a25f0a04SGreg Roach     *
270cbc1590aSGreg Roach     * @return bool
271a25f0a04SGreg Roach     */
27276f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
273c1010edaSGreg Roach    {
274a25f0a04SGreg Roach        return $this->canShow($access_level);
275a25f0a04SGreg Roach    }
276a25f0a04SGreg Roach
277a25f0a04SGreg Roach    /**
278a25f0a04SGreg Roach     * Can we edit this record?
279a25f0a04SGreg Roach     *
280cbc1590aSGreg Roach     * @return bool
281a25f0a04SGreg Roach     */
2828f53f488SRico Sonntag    public function canEdit(): bool
283c1010edaSGreg Roach    {
2841450f098SGreg Roach        if ($this->isPendingDeletion()) {
2851450f098SGreg Roach            return false;
2861450f098SGreg Roach        }
2871450f098SGreg Roach
2881450f098SGreg Roach        if (Auth::isManager($this->tree)) {
2891450f098SGreg Roach            return true;
2901450f098SGreg Roach        }
2911450f098SGreg Roach
292dec352c1SGreg Roach        return Auth::isEditor($this->tree) && !str_contains($this->gedcom, "\n1 RESN locked");
293a25f0a04SGreg Roach    }
294a25f0a04SGreg Roach
295a25f0a04SGreg Roach    /**
296a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
297a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
298a25f0a04SGreg Roach     *
299cbc1590aSGreg Roach     * @param int $access_level
300a25f0a04SGreg Roach     *
301a25f0a04SGreg Roach     * @return string
302a25f0a04SGreg Roach     */
303e364afe4SGreg Roach    public function privatizeGedcom(int $access_level): string
304c1010edaSGreg Roach    {
305e364afe4SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
306a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
307a25f0a04SGreg Roach            return $this->gedcom;
308b2ce94c6SRico Sonntag        }
309b2ce94c6SRico Sonntag
310b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
311a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
312a25f0a04SGreg Roach
313a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
314dc141db3SGreg Roach            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
315a25f0a04SGreg Roach
316a25f0a04SGreg Roach            // Check each of the facts for access
3178d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
318138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
319a25f0a04SGreg Roach            }
320cbc1590aSGreg Roach
321a25f0a04SGreg Roach            return $gedrec;
322b2ce94c6SRico Sonntag        }
323b2ce94c6SRico Sonntag
324a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
325a25f0a04SGreg Roach        // limited data, such as links to other records.
326a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
327a25f0a04SGreg Roach    }
328a25f0a04SGreg Roach
329a25f0a04SGreg Roach    /**
330a25f0a04SGreg Roach     * Default for "other" object types
331c7ff4153SGreg Roach     *
332c7ff4153SGreg Roach     * @return void
333a25f0a04SGreg Roach     */
334e364afe4SGreg Roach    public function extractNames(): void
335c1010edaSGreg Roach    {
33676f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
337a25f0a04SGreg Roach    }
338a25f0a04SGreg Roach
339a25f0a04SGreg Roach    /**
340a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
341a25f0a04SGreg Roach     *
342870ec5a3SGreg Roach     * @return array<int,array<string,string>>
343a25f0a04SGreg Roach     */
3448f53f488SRico Sonntag    public function getAllNames(): array
345c1010edaSGreg Roach    {
3469599771eSGreg Roach        if ($this->getAllNames === []) {
347a25f0a04SGreg Roach            if ($this->canShowName()) {
348a25f0a04SGreg Roach                // Ask the record to extract its names
349a25f0a04SGreg Roach                $this->extractNames();
350a25f0a04SGreg Roach                // No name found? Use a fallback.
351ec124fd2SGreg Roach                if ($this->getAllNames === []) {
352db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
353a25f0a04SGreg Roach                }
354a25f0a04SGreg Roach            } else {
355db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
356a25f0a04SGreg Roach            }
357a25f0a04SGreg Roach        }
358cbc1590aSGreg Roach
359bdb3725aSGreg Roach        return $this->getAllNames;
360a25f0a04SGreg Roach    }
361a25f0a04SGreg Roach
362a25f0a04SGreg Roach    /**
363a25f0a04SGreg Roach     * If this object has no name, what do we call it?
364a25f0a04SGreg Roach     *
365a25f0a04SGreg Roach     * @return string
366a25f0a04SGreg Roach     */
3678f53f488SRico Sonntag    public function getFallBackName(): string
368c1010edaSGreg Roach    {
369c0935879SGreg Roach        return e($this->xref());
370a25f0a04SGreg Roach    }
371a25f0a04SGreg Roach
372a25f0a04SGreg Roach    /**
373a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
374a25f0a04SGreg Roach     *
375cbc1590aSGreg Roach     * @return int
376a25f0a04SGreg Roach     */
3778f53f488SRico Sonntag    public function getPrimaryName(): int
378c1010edaSGreg Roach    {
379a25f0a04SGreg Roach        static $language_script;
380a25f0a04SGreg Roach
381448d466cSGreg Roach        $language_script ??= I18N::locale()->script()->code();
382a25f0a04SGreg Roach
383bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
384a25f0a04SGreg Roach            // Generally, the first name is the primary one....
385bdb3725aSGreg Roach            $this->getPrimaryName = 0;
386a25f0a04SGreg Roach            // ...except when the language/name use different character sets
387a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
38869546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
389bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
390a25f0a04SGreg Roach                    break;
391a25f0a04SGreg Roach                }
392a25f0a04SGreg Roach            }
393a25f0a04SGreg Roach        }
394a25f0a04SGreg Roach
395bdb3725aSGreg Roach        return $this->getPrimaryName;
396a25f0a04SGreg Roach    }
397a25f0a04SGreg Roach
398a25f0a04SGreg Roach    /**
399a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
400a25f0a04SGreg Roach     *
401cbc1590aSGreg Roach     * @return int
402a25f0a04SGreg Roach     */
4038f53f488SRico Sonntag    public function getSecondaryName(): int
404c1010edaSGreg Roach    {
4058f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
406a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
407bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
408a25f0a04SGreg Roach            // ....except when there are names with different character sets
409a25f0a04SGreg Roach            $all_names = $this->getAllNames();
410a25f0a04SGreg Roach            if (count($all_names) > 1) {
411a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
412a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
413e364afe4SGreg Roach                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
414bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
415a25f0a04SGreg Roach                        break;
416a25f0a04SGreg Roach                    }
417a25f0a04SGreg Roach                }
418a25f0a04SGreg Roach            }
419a25f0a04SGreg Roach        }
420cbc1590aSGreg Roach
421bdb3725aSGreg Roach        return $this->getSecondaryName;
422a25f0a04SGreg Roach    }
423a25f0a04SGreg Roach
424a25f0a04SGreg Roach    /**
425a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
426a25f0a04SGreg Roach     *
42776f666f4SGreg Roach     * @param int|null $n
4287e96c925SGreg Roach     *
4297e96c925SGreg Roach     * @return void
430a25f0a04SGreg Roach     */
431e364afe4SGreg Roach    public function setPrimaryName(int $n = null): void
432c1010edaSGreg Roach    {
433bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
434bdb3725aSGreg Roach        $this->getSecondaryName = null;
435a25f0a04SGreg Roach    }
436a25f0a04SGreg Roach
437a25f0a04SGreg Roach    /**
438a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
439a25f0a04SGreg Roach     *
440a25f0a04SGreg Roach     * @return string
441a25f0a04SGreg Roach     */
44224f2a3afSGreg Roach    public function __toString(): string
443c1010edaSGreg Roach    {
44472cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
445a25f0a04SGreg Roach    }
446a25f0a04SGreg Roach
447a25f0a04SGreg Roach    /**
448c156e8f5SGreg Roach     * /**
449a25f0a04SGreg Roach     * Get variants of the name
450a25f0a04SGreg Roach     *
451a25f0a04SGreg Roach     * @return string
452a25f0a04SGreg Roach     */
453e364afe4SGreg Roach    public function fullName(): string
454c1010edaSGreg Roach    {
455a25f0a04SGreg Roach        if ($this->canShowName()) {
456a25f0a04SGreg Roach            $tmp = $this->getAllNames();
457cbc1590aSGreg Roach
458a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
459a25f0a04SGreg Roach        }
460b2ce94c6SRico Sonntag
461b2ce94c6SRico Sonntag        return I18N::translate('Private');
462a25f0a04SGreg Roach    }
463a25f0a04SGreg Roach
464a25f0a04SGreg Roach    /**
465a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
466a25f0a04SGreg Roach     *
467a25f0a04SGreg Roach     * @return string
468a25f0a04SGreg Roach     */
46939ca88baSGreg Roach    public function sortName(): string
470c1010edaSGreg Roach    {
471a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
472a25f0a04SGreg Roach        $tmp = $this->getAllNames();
473cbc1590aSGreg Roach
474a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
475a25f0a04SGreg Roach    }
476a25f0a04SGreg Roach
477a25f0a04SGreg Roach    /**
478a25f0a04SGreg Roach     * Get the full name in an alternative character set
479a25f0a04SGreg Roach     *
480e364afe4SGreg Roach     * @return string|null
481a25f0a04SGreg Roach     */
482e364afe4SGreg Roach    public function alternateName(): ?string
483c1010edaSGreg Roach    {
484e364afe4SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
485a25f0a04SGreg Roach            $all_names = $this->getAllNames();
486cbc1590aSGreg Roach
487a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
488a25f0a04SGreg Roach        }
489b2ce94c6SRico Sonntag
490b2ce94c6SRico Sonntag        return null;
491a25f0a04SGreg Roach    }
492a25f0a04SGreg Roach
493a25f0a04SGreg Roach    /**
494a25f0a04SGreg Roach     * Format this object for display in a list
495a25f0a04SGreg Roach     *
496a25f0a04SGreg Roach     * @return string
497a25f0a04SGreg Roach     */
4988f53f488SRico Sonntag    public function formatList(): string
499c1010edaSGreg Roach    {
500b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
50139ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
502a25f0a04SGreg Roach        $html .= $this->formatListDetails();
503b165e17cSGreg Roach        $html .= '</a>';
504cbc1590aSGreg Roach
505a25f0a04SGreg Roach        return $html;
506a25f0a04SGreg Roach    }
507a25f0a04SGreg Roach
508a25f0a04SGreg Roach    /**
509a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
510a25f0a04SGreg Roach     * identifying characteristics of this record.
511a25f0a04SGreg Roach     *
512a25f0a04SGreg Roach     * @return string
513a25f0a04SGreg Roach     */
5148f53f488SRico Sonntag    public function formatListDetails(): string
515c1010edaSGreg Roach    {
516a25f0a04SGreg Roach        return '';
517a25f0a04SGreg Roach    }
518a25f0a04SGreg Roach
519a25f0a04SGreg Roach    /**
520a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
521a25f0a04SGreg Roach     *
52209482a55SGreg Roach     * @param array<string> $facts
523cbc1590aSGreg Roach     * @param int           $style
524a25f0a04SGreg Roach     *
525a25f0a04SGreg Roach     * @return string
526a25f0a04SGreg Roach     */
5278d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
528c1010edaSGreg Roach    {
52930158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
530a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
531e364afe4SGreg Roach            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
532d93f11b5SGreg Roach                $joiner = ' — ';
533d93f11b5SGreg Roach            } else {
534d93f11b5SGreg Roach                $joiner = '';
535d93f11b5SGreg Roach            }
536e364afe4SGreg Roach            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
537a25f0a04SGreg Roach                switch ($style) {
538a25f0a04SGreg Roach                    case 1:
539b315f3e1SGreg Roach                        return '<br><em>' . $event->label() . ' ' . view('fact-date', ['cal_link' => 'false', 'fact' => $event, 'record' => $event->record(), 'time' => false]) . '</em>';
540a25f0a04SGreg Roach                    case 2:
541b315f3e1SGreg Roach                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . view('fact-date', ['cal_link' => 'false', 'fact' => $event, 'record' => $event->record(), 'time' => false]) . $joiner . $event->place()->shortName() . '</dd></dl>';
542a25f0a04SGreg Roach                }
543a25f0a04SGreg Roach            }
544a25f0a04SGreg Roach        }
545cbc1590aSGreg Roach
546a25f0a04SGreg Roach        return '';
547a25f0a04SGreg Roach    }
548a25f0a04SGreg Roach
549a25f0a04SGreg Roach    /**
550a25f0a04SGreg Roach     * Find individuals linked to this record.
551a25f0a04SGreg Roach     *
552a25f0a04SGreg Roach     * @param string $link
553a25f0a04SGreg Roach     *
554*36779af1SGreg Roach     * @return Collection<int,Individual>
555a25f0a04SGreg Roach     */
556907c1109SGreg Roach    public function linkedIndividuals(string $link): Collection
557c1010edaSGreg Roach    {
558907c1109SGreg Roach        return DB::table('individuals')
5590b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
560907c1109SGreg Roach                $join
561907c1109SGreg Roach                    ->on('l_file', '=', 'i_file')
562907c1109SGreg Roach                    ->on('l_from', '=', 'i_id');
563ba1c12e8SGreg Roach            })
564ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
565ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
566ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
567907c1109SGreg Roach            ->select(['individuals.*'])
568907c1109SGreg Roach            ->get()
5696b9cb339SGreg Roach            ->map(Registry::individualFactory()->mapper($this->tree))
570907c1109SGreg Roach            ->filter(self::accessFilter());
571a25f0a04SGreg Roach    }
572a25f0a04SGreg Roach
573a25f0a04SGreg Roach    /**
574a25f0a04SGreg Roach     * Find families linked to this record.
575a25f0a04SGreg Roach     *
576a25f0a04SGreg Roach     * @param string $link
577a25f0a04SGreg Roach     *
578*36779af1SGreg Roach     * @return Collection<int,Family>
579a25f0a04SGreg Roach     */
580907c1109SGreg Roach    public function linkedFamilies(string $link): Collection
581c1010edaSGreg Roach    {
582907c1109SGreg Roach        return DB::table('families')
5830b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
584907c1109SGreg Roach                $join
585907c1109SGreg Roach                    ->on('l_file', '=', 'f_file')
586907c1109SGreg Roach                    ->on('l_from', '=', 'f_id');
587ba1c12e8SGreg Roach            })
588ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
589ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
590ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
591907c1109SGreg Roach            ->select(['families.*'])
592907c1109SGreg Roach            ->get()
5936b9cb339SGreg Roach            ->map(Registry::familyFactory()->mapper($this->tree))
594907c1109SGreg Roach            ->filter(self::accessFilter());
595a25f0a04SGreg Roach    }
596a25f0a04SGreg Roach
597a25f0a04SGreg Roach    /**
598a25f0a04SGreg Roach     * Find sources linked to this record.
599a25f0a04SGreg Roach     *
600a25f0a04SGreg Roach     * @param string $link
601a25f0a04SGreg Roach     *
602*36779af1SGreg Roach     * @return Collection<int,Source>
603a25f0a04SGreg Roach     */
604907c1109SGreg Roach    public function linkedSources(string $link): Collection
605c1010edaSGreg Roach    {
606907c1109SGreg Roach        return DB::table('sources')
6070b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
608907c1109SGreg Roach                $join
609907c1109SGreg Roach                    ->on('l_file', '=', 's_file')
610907c1109SGreg Roach                    ->on('l_from', '=', 's_id');
611ba1c12e8SGreg Roach            })
612ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
613ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
614ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
615907c1109SGreg Roach            ->select(['sources.*'])
616907c1109SGreg Roach            ->get()
6176b9cb339SGreg Roach            ->map(Registry::sourceFactory()->mapper($this->tree))
618907c1109SGreg Roach            ->filter(self::accessFilter());
619a25f0a04SGreg Roach    }
620a25f0a04SGreg Roach
621a25f0a04SGreg Roach    /**
622a25f0a04SGreg Roach     * Find media objects linked to this record.
623a25f0a04SGreg Roach     *
624a25f0a04SGreg Roach     * @param string $link
625a25f0a04SGreg Roach     *
626*36779af1SGreg Roach     * @return Collection<int,Media>
627a25f0a04SGreg Roach     */
628907c1109SGreg Roach    public function linkedMedia(string $link): Collection
629c1010edaSGreg Roach    {
630907c1109SGreg Roach        return DB::table('media')
6310b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
632907c1109SGreg Roach                $join
633907c1109SGreg Roach                    ->on('l_file', '=', 'm_file')
634907c1109SGreg Roach                    ->on('l_from', '=', 'm_id');
635ba1c12e8SGreg Roach            })
636ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
637ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
638ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
639907c1109SGreg Roach            ->select(['media.*'])
640907c1109SGreg Roach            ->get()
6416b9cb339SGreg Roach            ->map(Registry::mediaFactory()->mapper($this->tree))
642907c1109SGreg Roach            ->filter(self::accessFilter());
643a25f0a04SGreg Roach    }
644a25f0a04SGreg Roach
645a25f0a04SGreg Roach    /**
646a25f0a04SGreg Roach     * Find notes linked to this record.
647a25f0a04SGreg Roach     *
648a25f0a04SGreg Roach     * @param string $link
649a25f0a04SGreg Roach     *
650*36779af1SGreg Roach     * @return Collection<int,Note>
651a25f0a04SGreg Roach     */
652907c1109SGreg Roach    public function linkedNotes(string $link): Collection
653c1010edaSGreg Roach    {
654907c1109SGreg Roach        return DB::table('other')
6550b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
656907c1109SGreg Roach                $join
657907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
658907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
659ba1c12e8SGreg Roach            })
660ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
6617a8cbeebSGreg Roach            ->where('o_type', '=', Note::RECORD_TYPE)
662ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
663ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
664907c1109SGreg Roach            ->select(['other.*'])
665907c1109SGreg Roach            ->get()
6666b9cb339SGreg Roach            ->map(Registry::noteFactory()->mapper($this->tree))
667907c1109SGreg Roach            ->filter(self::accessFilter());
668a25f0a04SGreg Roach    }
669a25f0a04SGreg Roach
670a25f0a04SGreg Roach    /**
671a25f0a04SGreg Roach     * Find repositories linked to this record.
672a25f0a04SGreg Roach     *
673a25f0a04SGreg Roach     * @param string $link
674a25f0a04SGreg Roach     *
675*36779af1SGreg Roach     * @return Collection<int,Repository>
676a25f0a04SGreg Roach     */
677907c1109SGreg Roach    public function linkedRepositories(string $link): Collection
678c1010edaSGreg Roach    {
679907c1109SGreg Roach        return DB::table('other')
6800b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
681907c1109SGreg Roach                $join
682907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
683907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
684ba1c12e8SGreg Roach            })
685ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
6867a8cbeebSGreg Roach            ->where('o_type', '=', Repository::RECORD_TYPE)
687ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
688ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
689907c1109SGreg Roach            ->select(['other.*'])
690907c1109SGreg Roach            ->get()
6916b9cb339SGreg Roach            ->map(Registry::repositoryFactory()->mapper($this->tree))
692907c1109SGreg Roach            ->filter(self::accessFilter());
693a25f0a04SGreg Roach    }
694a25f0a04SGreg Roach
695a25f0a04SGreg Roach    /**
69636254e3dSRichard Cissée     * Find locations linked to this record.
69736254e3dSRichard Cissée     *
69836254e3dSRichard Cissée     * @param string $link
69936254e3dSRichard Cissée     *
700*36779af1SGreg Roach     * @return Collection<int,Location>
70136254e3dSRichard Cissée     */
70236254e3dSRichard Cissée    public function linkedLocations(string $link): Collection
70336254e3dSRichard Cissée    {
70436254e3dSRichard Cissée        return DB::table('other')
70536254e3dSRichard Cissée            ->join('link', static function (JoinClause $join): void {
70636254e3dSRichard Cissée                $join
70736254e3dSRichard Cissée                    ->on('l_file', '=', 'o_file')
70836254e3dSRichard Cissée                    ->on('l_from', '=', 'o_id');
70936254e3dSRichard Cissée            })
71036254e3dSRichard Cissée            ->where('o_file', '=', $this->tree->id())
7117a8cbeebSGreg Roach            ->where('o_type', '=', Location::RECORD_TYPE)
71236254e3dSRichard Cissée            ->where('l_type', '=', $link)
71336254e3dSRichard Cissée            ->where('l_to', '=', $this->xref)
71436254e3dSRichard Cissée            ->select(['other.*'])
71536254e3dSRichard Cissée            ->get()
7166b9cb339SGreg Roach            ->map(Registry::locationFactory()->mapper($this->tree))
71736254e3dSRichard Cissée            ->filter(self::accessFilter());
71836254e3dSRichard Cissée    }
71936254e3dSRichard Cissée
72036254e3dSRichard Cissée    /**
721a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
722a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
723a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
724a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
725a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
726a25f0a04SGreg Roach     *
72709482a55SGreg Roach     * @param array<string> $events
728a25f0a04SGreg Roach     *
72909482a55SGreg Roach     * @return array<Date>
730a25f0a04SGreg Roach     */
7318d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
732c1010edaSGreg Roach    {
73313abd6f3SGreg Roach        $dates = [];
7341385b8caSGreg Roach        foreach ($this->facts($events, false, null, true) as $event) {
7352decada7SGreg Roach            if ($event->date()->isOK()) {
7362decada7SGreg Roach                $dates[] = $event->date();
737a25f0a04SGreg Roach            }
738a25f0a04SGreg Roach        }
739a25f0a04SGreg Roach
740a25f0a04SGreg Roach        return $dates;
741a25f0a04SGreg Roach    }
742a25f0a04SGreg Roach
743a25f0a04SGreg Roach    /**
744a25f0a04SGreg Roach     * Get all the places for a particular type of event
745a25f0a04SGreg Roach     *
74609482a55SGreg Roach     * @param array<string> $events
747a25f0a04SGreg Roach     *
74809482a55SGreg Roach     * @return array<Place>
749a25f0a04SGreg Roach     */
7508d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
751c1010edaSGreg Roach    {
75213abd6f3SGreg Roach        $places = [];
7538d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
754138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
755a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
75616d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
757a25f0a04SGreg Roach                }
758a25f0a04SGreg Roach            }
759a25f0a04SGreg Roach        }
760a25f0a04SGreg Roach
761a25f0a04SGreg Roach        return $places;
762a25f0a04SGreg Roach    }
763a25f0a04SGreg Roach
764a25f0a04SGreg Roach    /**
765a25f0a04SGreg Roach     * The facts and events for this record.
766a25f0a04SGreg Roach     *
76709482a55SGreg Roach     * @param array<string> $filter
768cbc1590aSGreg Roach     * @param bool          $sort
769cbc1590aSGreg Roach     * @param int|null      $access_level
770ce42304aSGreg Roach     * @param bool          $ignore_deleted
771a25f0a04SGreg Roach     *
772*36779af1SGreg Roach     * @return Collection<int,Fact>
773a25f0a04SGreg Roach     */
774ce42304aSGreg Roach    public function facts(
775ce42304aSGreg Roach        array $filter = [],
776ce42304aSGreg Roach        bool $sort = false,
777ce42304aSGreg Roach        int $access_level = null,
778ce42304aSGreg Roach        bool $ignore_deleted = false
779ce42304aSGreg Roach    ): Collection {
780d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
7814b9ff166SGreg Roach
782d0889c63SGreg Roach        // Convert BIRT into INDI:BIRT, etc.
783d0889c63SGreg Roach        $filter = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, $filter);
784d0889c63SGreg Roach
7858af3e5c1SGreg Roach        $facts = new Collection();
786ce42304aSGreg Roach        if ($this->canShow($access_level)) {
787a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
788d0889c63SGreg Roach                if (($filter === [] || in_array($fact->tag(), $filter, true)) && $fact->canShow($access_level)) {
7898af3e5c1SGreg Roach                    $facts->push($fact);
790a25f0a04SGreg Roach                }
791a25f0a04SGreg Roach            }
792a25f0a04SGreg Roach        }
793d17d7b9eSGreg Roach
794a25f0a04SGreg Roach        if ($sort) {
7950f5fd22fSGreg Roach            switch ($this->tag()) {
7960f5fd22fSGreg Roach                case Family::RECORD_TYPE:
7970f5fd22fSGreg Roach                case Individual::RECORD_TYPE:
798580a4d11SGreg Roach                    $facts = Fact::sortFacts($facts);
7990f5fd22fSGreg Roach                    break;
8000f5fd22fSGreg Roach
8010f5fd22fSGreg Roach                default:
8020f5fd22fSGreg Roach                    $subtags = Registry::elementFactory()->make($this->tag())->subtags();
8030f5fd22fSGreg Roach                    $subtags = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, array_keys($subtags));
8040f5fd22fSGreg Roach                    $subtags = array_combine(range(1, count($subtags)), $subtags);
8050f5fd22fSGreg Roach
8060f5fd22fSGreg Roach                    $facts = $facts
8070f5fd22fSGreg Roach                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
8080f5fd22fSGreg Roach                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
8090f5fd22fSGreg Roach                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
8100f5fd22fSGreg Roach
8110f5fd22fSGreg Roach                            return $sort_x <=> $sort_y;
8120f5fd22fSGreg Roach                        });
8130f5fd22fSGreg Roach                    break;
8140f5fd22fSGreg Roach            }
815a25f0a04SGreg Roach        }
816cbc1590aSGreg Roach
817ce42304aSGreg Roach        if ($ignore_deleted) {
818ce42304aSGreg Roach            $facts = $facts->filter(static function (Fact $fact): bool {
819ce42304aSGreg Roach                return !$fact->isPendingDeletion();
820ce42304aSGreg Roach            });
821ce42304aSGreg Roach        }
822ce42304aSGreg Roach
82339ca88baSGreg Roach        return new Collection($facts);
824a25f0a04SGreg Roach    }
825a25f0a04SGreg Roach
826a25f0a04SGreg Roach    /**
8270f5fd22fSGreg Roach     * @return array<string,string>
8280f5fd22fSGreg Roach     */
8290f5fd22fSGreg Roach    public function missingFacts(): array
8300f5fd22fSGreg Roach    {
8310f5fd22fSGreg Roach        $missing_facts = [];
8320f5fd22fSGreg Roach
8330f5fd22fSGreg Roach        foreach (Registry::elementFactory()->make($this->tag())->subtags() as $subtag => $repeat) {
8340f5fd22fSGreg Roach            [, $max] = explode(':', $repeat);
8350f5fd22fSGreg Roach            $max = $max === 'M' ? PHP_INT_MAX : (int) $max;
8360f5fd22fSGreg Roach
83798f93f3aSGreg Roach            if ($this->facts([$subtag], false, null, true)->count() < $max) {
8380f5fd22fSGreg Roach                $missing_facts[$subtag] = $subtag;
8390f5fd22fSGreg Roach                $missing_facts[$subtag] = Registry::elementFactory()->make($this->tag() . ':' . $subtag)->label();
8400f5fd22fSGreg Roach            }
8410f5fd22fSGreg Roach        }
8420f5fd22fSGreg Roach
8430f5fd22fSGreg Roach        uasort($missing_facts, I18N::comparator());
8440f5fd22fSGreg Roach
8455416d6ddSGreg Roach        if (!Auth::canUploadMedia($this->tree, Auth::user())) {
8460f5fd22fSGreg Roach            unset($missing_facts['OBJE']);
8470f5fd22fSGreg Roach        }
8480f5fd22fSGreg Roach
8490f5fd22fSGreg Roach        // We have special code for this.
8500f5fd22fSGreg Roach        unset($missing_facts['FILE']);
8510f5fd22fSGreg Roach
8520f5fd22fSGreg Roach        return $missing_facts;
8530f5fd22fSGreg Roach    }
8540f5fd22fSGreg Roach
8550f5fd22fSGreg Roach    /**
8564459dc9aSGreg Roach     * Get the last-change timestamp for this record
857a25f0a04SGreg Roach     *
8584459dc9aSGreg Roach     * @return Carbon
859a25f0a04SGreg Roach     */
8604459dc9aSGreg Roach    public function lastChangeTimestamp(): Carbon
861c1010edaSGreg Roach    {
8624459dc9aSGreg Roach        /** @var Fact|null $chan */
863820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
864a25f0a04SGreg Roach
8654459dc9aSGreg Roach        if ($chan instanceof Fact) {
866a25f0a04SGreg Roach            // The record does have a CHAN event
8672decada7SGreg Roach            $d = $chan->date()->minimumDate();
8684459dc9aSGreg Roach
869138ca96cSGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
8704459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
871e364afe4SGreg Roach            }
872e364afe4SGreg Roach
873e364afe4SGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
8744459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
875b2ce94c6SRico Sonntag            }
876b2ce94c6SRico Sonntag
8774459dc9aSGreg Roach            return Carbon::create($d->year(), $d->month(), $d->day());
878a25f0a04SGreg Roach        }
879b2ce94c6SRico Sonntag
880a25f0a04SGreg Roach        // The record does not have a CHAN event
8814459dc9aSGreg Roach        return Carbon::createFromTimestamp(0);
882a25f0a04SGreg Roach    }
883a25f0a04SGreg Roach
884a25f0a04SGreg Roach    /**
885a25f0a04SGreg Roach     * Get the last-change user for this record
886a25f0a04SGreg Roach     *
887a25f0a04SGreg Roach     * @return string
888a25f0a04SGreg Roach     */
889e364afe4SGreg Roach    public function lastChangeUser(): string
890c1010edaSGreg Roach    {
891820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
892a25f0a04SGreg Roach
893a25f0a04SGreg Roach        if ($chan === null) {
894a25f0a04SGreg Roach            return I18N::translate('Unknown');
895b2ce94c6SRico Sonntag        }
896b2ce94c6SRico Sonntag
8973425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
898baacc364SGreg Roach        if ($chan_user === '') {
899a25f0a04SGreg Roach            return I18N::translate('Unknown');
900b2ce94c6SRico Sonntag        }
901b2ce94c6SRico Sonntag
902a25f0a04SGreg Roach        return $chan_user;
903a25f0a04SGreg Roach    }
904a25f0a04SGreg Roach
905a25f0a04SGreg Roach    /**
906a25f0a04SGreg Roach     * Add a new fact to this record
907a25f0a04SGreg Roach     *
908a25f0a04SGreg Roach     * @param string $gedcom
909cbc1590aSGreg Roach     * @param bool   $update_chan
9107e96c925SGreg Roach     *
9117e96c925SGreg Roach     * @return void
912a25f0a04SGreg Roach     */
913e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
914c1010edaSGreg Roach    {
915fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
916a25f0a04SGreg Roach    }
917a25f0a04SGreg Roach
918a25f0a04SGreg Roach    /**
919a25f0a04SGreg Roach     * Delete a fact from this record
920a25f0a04SGreg Roach     *
921a25f0a04SGreg Roach     * @param string $fact_id
922cbc1590aSGreg Roach     * @param bool   $update_chan
9237e96c925SGreg Roach     *
9247e96c925SGreg Roach     * @return void
925a25f0a04SGreg Roach     */
926e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
927c1010edaSGreg Roach    {
928db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
929a25f0a04SGreg Roach    }
930a25f0a04SGreg Roach
931a25f0a04SGreg Roach    /**
932a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
933a25f0a04SGreg Roach     *
934a25f0a04SGreg Roach     * @param string $fact_id
935a25f0a04SGreg Roach     * @param string $gedcom
936cbc1590aSGreg Roach     * @param bool   $update_chan
937a25f0a04SGreg Roach     *
9387e96c925SGreg Roach     * @return void
9397e96c925SGreg Roach     * @throws Exception
940a25f0a04SGreg Roach     */
941e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
942c1010edaSGreg Roach    {
94371f696adSGreg Roach        // Not all record types allow a CHAN event.
94471f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
94571f696adSGreg Roach
946a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
947a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
948a25f0a04SGreg Roach        $gedcom = trim($gedcom);
949a25f0a04SGreg Roach
950a25f0a04SGreg Roach        if ($this->pending === '') {
9517e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
952a25f0a04SGreg Roach        }
9538d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
9547e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
955a25f0a04SGreg Roach        }
956a25f0a04SGreg Roach
957a25f0a04SGreg Roach        if ($this->pending) {
958a25f0a04SGreg Roach            $old_gedcom = $this->pending;
959a25f0a04SGreg Roach        } else {
960a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
961a25f0a04SGreg Roach        }
962a25f0a04SGreg Roach
963a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
96465e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
965a25f0a04SGreg Roach
966a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
96719aed3a1SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
968905ab80aSGreg Roach            if ($fact->id() === $fact_id) {
969db7bb364SGreg Roach                if ($gedcom !== '') {
970a25f0a04SGreg Roach                    $new_gedcom .= "\n" . $gedcom;
971a25f0a04SGreg Roach                }
972fc3ccce4SGreg Roach                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
973d0889c63SGreg Roach            } elseif (!str_ends_with($fact->tag(), ':CHAN') || !$update_chan) {
974138ca96cSGreg Roach                $new_gedcom .= "\n" . $fact->gedcom();
975a25f0a04SGreg Roach            }
976a25f0a04SGreg Roach        }
977a25f0a04SGreg Roach
978a25f0a04SGreg Roach        // Adding a new fact
979fc3ccce4SGreg Roach        if ($fact_id === '') {
980a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
981a25f0a04SGreg Roach        }
982a25f0a04SGreg Roach
983dec352c1SGreg Roach        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
98419aed3a1SGreg Roach            $today = strtoupper(date('d M Y'));
98519aed3a1SGreg Roach            $now   = date('H:i:s');
98619aed3a1SGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
98719aed3a1SGreg Roach        }
98819aed3a1SGreg Roach
989e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
990a25f0a04SGreg Roach            // Save the changes
991d09b6323SGreg Roach            DB::table('change')->insert([
992d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
993d09b6323SGreg Roach                'xref'       => $this->xref,
994d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
995d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
996d09b6323SGreg Roach                'user_id'    => Auth::id(),
99713abd6f3SGreg Roach            ]);
998a25f0a04SGreg Roach
999a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1000a25f0a04SGreg Roach
10011fe542e9SGreg Roach            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
100222e73debSGreg Roach                app(PendingChangesService::class)->acceptRecord($this);
1003a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1004a25f0a04SGreg Roach                $this->pending = null;
1005a25f0a04SGreg Roach            }
1006a25f0a04SGreg Roach        }
10079599771eSGreg Roach
10089599771eSGreg Roach        $this->facts = $this->parseFacts();
1009a25f0a04SGreg Roach    }
1010a25f0a04SGreg Roach
1011a25f0a04SGreg Roach    /**
1012a25f0a04SGreg Roach     * Update this record
1013a25f0a04SGreg Roach     *
1014a25f0a04SGreg Roach     * @param string $gedcom
1015cbc1590aSGreg Roach     * @param bool   $update_chan
10167e96c925SGreg Roach     *
10177e96c925SGreg Roach     * @return void
1018a25f0a04SGreg Roach     */
1019e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
1020c1010edaSGreg Roach    {
102171f696adSGreg Roach        // Not all record types allow a CHAN event.
102271f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
102371f696adSGreg Roach
1024a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1025a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1026a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1027a25f0a04SGreg Roach
1028a25f0a04SGreg Roach        // Update the CHAN record
1029a25f0a04SGreg Roach        if ($update_chan) {
1030a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
103153432476SGreg Roach            $today = strtoupper(date('d M Y'));
103253432476SGreg Roach            $now   = date('H:i:s');
103353432476SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
1034a25f0a04SGreg Roach        }
1035a25f0a04SGreg Roach
1036a25f0a04SGreg Roach        // Create a pending change
1037d09b6323SGreg Roach        DB::table('change')->insert([
1038d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1039d09b6323SGreg Roach            'xref'       => $this->xref,
1040d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1041d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1042d09b6323SGreg Roach            'user_id'    => Auth::id(),
104313abd6f3SGreg Roach        ]);
1044a25f0a04SGreg Roach
1045a25f0a04SGreg Roach        // Clear the cache
1046a25f0a04SGreg Roach        $this->pending = $gedcom;
1047a25f0a04SGreg Roach
1048a25f0a04SGreg Roach        // Accept this pending change
10491fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
105022e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1051a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1052a25f0a04SGreg Roach            $this->pending = null;
1053a25f0a04SGreg Roach        }
1054a25f0a04SGreg Roach
10559599771eSGreg Roach        $this->facts = $this->parseFacts();
1056a25f0a04SGreg Roach
1057847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1058a25f0a04SGreg Roach    }
1059a25f0a04SGreg Roach
1060a25f0a04SGreg Roach    /**
1061a25f0a04SGreg Roach     * Delete this record
1062b874da82SGreg Roach     *
1063b874da82SGreg Roach     * @return void
1064a25f0a04SGreg Roach     */
1065e364afe4SGreg Roach    public function deleteRecord(): void
1066c1010edaSGreg Roach    {
1067a25f0a04SGreg Roach        // Create a pending change
10684c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1069d09b6323SGreg Roach            DB::table('change')->insert([
1070d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1071d09b6323SGreg Roach                'xref'       => $this->xref,
1072d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1073d09b6323SGreg Roach                'new_gedcom' => '',
1074d09b6323SGreg Roach                'user_id'    => Auth::id(),
107513abd6f3SGreg Roach            ]);
10764c0b5256SGreg Roach        }
1077a25f0a04SGreg Roach
10784c0b5256SGreg Roach        // Auto-accept this pending change
10791fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
108022e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1081a25f0a04SGreg Roach        }
1082a25f0a04SGreg Roach
1083847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1084a25f0a04SGreg Roach    }
1085a25f0a04SGreg Roach
1086a25f0a04SGreg Roach    /**
1087a25f0a04SGreg Roach     * Remove all links from this record to $xref
1088a25f0a04SGreg Roach     *
1089a25f0a04SGreg Roach     * @param string $xref
1090cbc1590aSGreg Roach     * @param bool   $update_chan
10917e96c925SGreg Roach     *
10927e96c925SGreg Roach     * @return void
1093a25f0a04SGreg Roach     */
1094e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
1095c1010edaSGreg Roach    {
1096a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1097a25f0a04SGreg Roach
109830158ae7SGreg Roach        foreach ($this->facts() as $fact) {
109984586c02SGreg Roach            if ($fact->value() === $value) {
1100905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
11018d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1102138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1103a25f0a04SGreg Roach                foreach ($matches as $match) {
1104a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1105a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1106a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1107a25f0a04SGreg Roach                }
1108905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1109a25f0a04SGreg Roach            }
1110a25f0a04SGreg Roach        }
1111a25f0a04SGreg Roach    }
1112bf4eb542SGreg Roach
1113bf4eb542SGreg Roach    /**
1114bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1115bf4eb542SGreg Roach     * also delete all links to it.
1116bf4eb542SGreg Roach     *
111709482a55SGreg Roach     * @return array<GedcomRecord>
1118bf4eb542SGreg Roach     */
1119bf4eb542SGreg Roach    public function linkingRecords(): array
1120bf4eb542SGreg Roach    {
1121b5961194SGreg Roach        $like = addcslashes($this->xref(), '\\%_');
1122b5961194SGreg Roach
1123bf4eb542SGreg Roach        $union = DB::table('change')
1124bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1125b5961194SGreg Roach            ->where('new_gedcom', 'LIKE', '%@' . $like . '@%')
1126b5961194SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $like . '@%')
112783242252SGreg Roach            ->whereIn('change_id', function (Builder $query): void {
112883242252SGreg Roach                $query->select(new Expression('MAX(change_id)'))
112983242252SGreg Roach                    ->from('change')
113083242252SGreg Roach                    ->where('gedcom_id', '=', $this->tree->id())
113183242252SGreg Roach                    ->where('status', '=', 'pending')
11327f5c2944SGreg Roach                    ->groupBy(['xref']);
113383242252SGreg Roach            })
1134bf4eb542SGreg Roach            ->select(['xref']);
1135bf4eb542SGreg Roach
1136bf4eb542SGreg Roach        $xrefs = DB::table('link')
1137bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1138bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
113947256fc5SGreg Roach            ->select(['l_from'])
1140bf4eb542SGreg Roach            ->union($union)
1141bf4eb542SGreg Roach            ->pluck('l_from');
1142bf4eb542SGreg Roach
1143bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
11446b9cb339SGreg Roach            $record = Registry::gedcomRecordFactory()->make($xref, $this->tree);
1145ffc0a61fSGreg Roach            assert($record instanceof GedcomRecord);
1146ffc0a61fSGreg Roach
1147ffc0a61fSGreg Roach            return $record;
1148bf4eb542SGreg Roach        })->all();
1149bf4eb542SGreg Roach    }
115022e73debSGreg Roach
115122e73debSGreg Roach    /**
115222e73debSGreg Roach     * Each object type may have its own special rules, and re-implement this function.
115322e73debSGreg Roach     *
115422e73debSGreg Roach     * @param int $access_level
115522e73debSGreg Roach     *
115622e73debSGreg Roach     * @return bool
115722e73debSGreg Roach     */
115822e73debSGreg Roach    protected function canShowByType(int $access_level): bool
115922e73debSGreg Roach    {
116022e73debSGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
116122e73debSGreg Roach
116222e73debSGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
116322e73debSGreg Roach            // Restriction found
116422e73debSGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
116522e73debSGreg Roach        }
116622e73debSGreg Roach
116722e73debSGreg Roach        // No restriction found - must be public:
116822e73debSGreg Roach        return true;
116922e73debSGreg Roach    }
117022e73debSGreg Roach
117122e73debSGreg Roach    /**
117222e73debSGreg Roach     * Generate a private version of this record
117322e73debSGreg Roach     *
117422e73debSGreg Roach     * @param int $access_level
117522e73debSGreg Roach     *
117622e73debSGreg Roach     * @return string
117722e73debSGreg Roach     */
117822e73debSGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
117922e73debSGreg Roach    {
1180228ede81SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
118122e73debSGreg Roach    }
118222e73debSGreg Roach
118322e73debSGreg Roach    /**
118422e73debSGreg Roach     * Convert a name record into sortable and full/display versions. This default
118522e73debSGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
118622e73debSGreg Roach     *
118722e73debSGreg Roach     * @param string $type
118822e73debSGreg Roach     * @param string $value
118922e73debSGreg Roach     * @param string $gedcom
119022e73debSGreg Roach     *
119122e73debSGreg Roach     * @return void
119222e73debSGreg Roach     */
119322e73debSGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
119422e73debSGreg Roach    {
119522e73debSGreg Roach        $this->getAllNames[] = [
119622e73debSGreg Roach            'type'   => $type,
1197dbf91548SGreg Roach            'sort'   => preg_replace_callback('/(\d+)/', static function (array $matches): string {
119822e73debSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
119922e73debSGreg Roach            }, $value),
1200315eb316SGreg Roach            'full'   => '<bdi>' . e($value) . '</bdi>',
120122e73debSGreg Roach            // This is used for display
120222e73debSGreg Roach            'fullNN' => $value,
120322e73debSGreg Roach            // This goes into the database
120422e73debSGreg Roach        ];
120522e73debSGreg Roach    }
120622e73debSGreg Roach
120722e73debSGreg Roach    /**
120822e73debSGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
120922e73debSGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
121022e73debSGreg Roach     * Parameters: the level 1 fact containing the name.
121122e73debSGreg Roach     * Return value: an array of name structures, each containing
121222e73debSGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
121322e73debSGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
121422e73debSGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
121522e73debSGreg Roach     *
121622e73debSGreg Roach     * @param int              $level
121722e73debSGreg Roach     * @param string           $fact_type
1218*36779af1SGreg Roach     * @param Collection<int,Fact> $facts
121922e73debSGreg Roach     *
122022e73debSGreg Roach     * @return void
122122e73debSGreg Roach     */
122222e73debSGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
122322e73debSGreg Roach    {
122422e73debSGreg Roach        $sublevel    = $level + 1;
122522e73debSGreg Roach        $subsublevel = $sublevel + 1;
122622e73debSGreg Roach        foreach ($facts as $fact) {
1227c8ff5fdcSGreg Roach            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
122822e73debSGreg Roach                foreach ($matches as $match) {
122922e73debSGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1230dec352c1SGreg Roach                    if ($match[1] === 'NAME' && str_contains($match[3], "\n2 TYPE married")) {
123122e73debSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
123222e73debSGreg Roach                    } else {
123322e73debSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
123422e73debSGreg Roach                    }
1235c8ff5fdcSGreg Roach                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
123622e73debSGreg Roach                        foreach ($submatches as $submatch) {
123722e73debSGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
123822e73debSGreg Roach                        }
123922e73debSGreg Roach                    }
124022e73debSGreg Roach                }
124122e73debSGreg Roach            }
124222e73debSGreg Roach        }
124322e73debSGreg Roach    }
124422e73debSGreg Roach
124522e73debSGreg Roach    /**
124622e73debSGreg Roach     * Split the record into facts
124722e73debSGreg Roach     *
12489599771eSGreg Roach     * @return array<Fact>
124922e73debSGreg Roach     */
12509599771eSGreg Roach    private function parseFacts(): array
125122e73debSGreg Roach    {
125222e73debSGreg Roach        // Split the record into facts
125322e73debSGreg Roach        if ($this->gedcom) {
1254d823340dSGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
125522e73debSGreg Roach            array_shift($gedcom_facts);
125622e73debSGreg Roach        } else {
125722e73debSGreg Roach            $gedcom_facts = [];
125822e73debSGreg Roach        }
125922e73debSGreg Roach        if ($this->pending) {
1260d823340dSGreg Roach            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
126122e73debSGreg Roach            array_shift($pending_facts);
126222e73debSGreg Roach        } else {
126322e73debSGreg Roach            $pending_facts = [];
126422e73debSGreg Roach        }
126522e73debSGreg Roach
12669599771eSGreg Roach        $facts = [];
126722e73debSGreg Roach
126822e73debSGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
126922e73debSGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
127022e73debSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
127122e73debSGreg Roach                $fact->setPendingDeletion();
127222e73debSGreg Roach            }
12739599771eSGreg Roach            $facts[] = $fact;
127422e73debSGreg Roach        }
127522e73debSGreg Roach        foreach ($pending_facts as $pending_fact) {
127622e73debSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
127722e73debSGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
127822e73debSGreg Roach                $fact->setPendingAddition();
12799599771eSGreg Roach                $facts[] = $fact;
128022e73debSGreg Roach            }
128122e73debSGreg Roach        }
12829599771eSGreg Roach
12839599771eSGreg Roach        return $facts;
128422e73debSGreg Roach    }
128522e73debSGreg Roach
128622e73debSGreg Roach    /**
128722e73debSGreg Roach     * Work out whether this record can be shown to a user with a given access level
128822e73debSGreg Roach     *
128922e73debSGreg Roach     * @param int $access_level
129022e73debSGreg Roach     *
129122e73debSGreg Roach     * @return bool
129222e73debSGreg Roach     */
129322e73debSGreg Roach    private function canShowRecord(int $access_level): bool
129422e73debSGreg Roach    {
129522e73debSGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
129622e73debSGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
129722e73debSGreg Roach            return true;
129822e73debSGreg Roach        }
129922e73debSGreg Roach
130022e73debSGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
13011fe542e9SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
130222e73debSGreg Roach            return true;
130322e73debSGreg Roach        }
130422e73debSGreg Roach
130522e73debSGreg Roach        // Does this record have a RESN?
1306dec352c1SGreg Roach        if (str_contains($this->gedcom, "\n1 RESN confidential")) {
130722e73debSGreg Roach            return Auth::PRIV_NONE >= $access_level;
130822e73debSGreg Roach        }
1309dec352c1SGreg Roach        if (str_contains($this->gedcom, "\n1 RESN privacy")) {
131022e73debSGreg Roach            return Auth::PRIV_USER >= $access_level;
131122e73debSGreg Roach        }
1312dec352c1SGreg Roach        if (str_contains($this->gedcom, "\n1 RESN none")) {
131322e73debSGreg Roach            return true;
131422e73debSGreg Roach        }
131522e73debSGreg Roach
131622e73debSGreg Roach        // Does this record have a default RESN?
131722e73debSGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
131822e73debSGreg Roach        if (isset($individual_privacy[$this->xref()])) {
131922e73debSGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
132022e73debSGreg Roach        }
132122e73debSGreg Roach
132222e73debSGreg Roach        // Privacy rules do not apply to admins
132322e73debSGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
132422e73debSGreg Roach            return true;
132522e73debSGreg Roach        }
132622e73debSGreg Roach
132722e73debSGreg Roach        // Different types of record have different privacy rules
132822e73debSGreg Roach        return $this->canShowByType($access_level);
132922e73debSGreg Roach    }
13308091bfd1SGreg Roach
13318091bfd1SGreg Roach    /**
13328091bfd1SGreg Roach     * Lock the database row, to prevent concurrent edits.
13338091bfd1SGreg Roach     */
13348091bfd1SGreg Roach    public function lock(): void
13358091bfd1SGreg Roach    {
13368091bfd1SGreg Roach        DB::table('other')
13378091bfd1SGreg Roach            ->where('o_file', '=', $this->tree->id())
13388091bfd1SGreg Roach            ->where('o_id', '=', $this->xref())
13398091bfd1SGreg Roach            ->lockForUpdate()
13408091bfd1SGreg Roach            ->get();
13418091bfd1SGreg Roach    }
1342a25f0a04SGreg Roach}
1343