xref: /webtrees/app/GedcomRecord.php (revision dbf915489e0c58138b9f654a0b247ac9c1aac717)
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;
253d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsPrint;
265818a371SGreg Roachuse Fisharebest\Webtrees\Http\RequestHandlers\GedcomRecordPage;
2722e73debSGreg Roachuse Fisharebest\Webtrees\Services\PendingChangesService;
28bf4eb542SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
2983242252SGreg Roachuse Illuminate\Database\Query\Builder;
3083242252SGreg Roachuse Illuminate\Database\Query\Expression;
31ba1c12e8SGreg Roachuse Illuminate\Database\Query\JoinClause;
3239ca88baSGreg Roachuse Illuminate\Support\Collection;
3374670d65SGreg Roachuse Throwable;
345ab92b3fSGreg Roachuse Transliterator;
35a25f0a04SGreg Roach
36b5961194SGreg Roachuse function addcslashes;
3722e73debSGreg Roachuse function app;
38f7440925SGreg Roachuse function array_shift;
39f7440925SGreg Roachuse function assert;
40f7440925SGreg Roachuse function count;
41f7440925SGreg Roachuse function date;
42f7440925SGreg Roachuse function e;
43f7440925SGreg Roachuse function explode;
44c2ed51d1SGreg Roachuse function implode;
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;
52f7440925SGreg Roachuse function route;
53dec352c1SGreg Roachuse function str_contains;
54f7440925SGreg Roachuse function str_pad;
55c2ed51d1SGreg Roachuse function str_starts_with;
56f7440925SGreg Roachuse function strip_tags;
57f7440925SGreg Roachuse function strtoupper;
58c2ed51d1SGreg Roachuse function substr_count;
59f7440925SGreg Roachuse function trim;
60f7440925SGreg 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
7422e73debSGreg Roach    /** @var string The record identifier */
7522e73debSGreg Roach    protected $xref;
76bb03c9f0SGreg Roach
7722e73debSGreg Roach    /** @var Tree  The family tree to which this record belongs */
7822e73debSGreg Roach    protected $tree;
79bb03c9f0SGreg Roach
8022e73debSGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
8122e73debSGreg Roach    protected $gedcom;
82bb03c9f0SGreg Roach
8322e73debSGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
8422e73debSGreg Roach    protected $pending;
85bb03c9f0SGreg Roach
8622e73debSGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
8722e73debSGreg Roach    protected $facts;
88bb03c9f0SGreg Roach
8922e73debSGreg Roach    /** @var string[][] All the names of this individual */
9022e73debSGreg Roach    protected $getAllNames;
91bb03c9f0SGreg Roach
9222e73debSGreg Roach    /** @var int|null Cached result */
9322e73debSGreg Roach    protected $getPrimaryName;
9422e73debSGreg Roach    /** @var int|null Cached result */
9522e73debSGreg Roach    protected $getSecondaryName;
96a25f0a04SGreg Roach
97a25f0a04SGreg Roach    /**
98a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
99a25f0a04SGreg Roach     *
100a25f0a04SGreg Roach     * @param string      $xref
101a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
102a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
103a25f0a04SGreg Roach     *                             empty string for records with pending deletions
10424ec66ceSGreg Roach     * @param Tree        $tree
105a25f0a04SGreg Roach     */
106e364afe4SGreg Roach    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
107c1010edaSGreg Roach    {
108a25f0a04SGreg Roach        $this->xref    = $xref;
109a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
110a25f0a04SGreg Roach        $this->pending = $pending;
11124ec66ceSGreg Roach        $this->tree    = $tree;
112a25f0a04SGreg Roach
113a25f0a04SGreg Roach        $this->parseFacts();
114a25f0a04SGreg Roach    }
115a25f0a04SGreg Roach
116a25f0a04SGreg Roach    /**
117886b77daSGreg Roach     * A closure which will filter out private records.
118886b77daSGreg Roach     *
119886b77daSGreg Roach     * @return Closure
120886b77daSGreg Roach     */
1214146fabcSGreg Roach    public static function accessFilter(): Closure
122886b77daSGreg Roach    {
1236c2179e2SGreg Roach        return static function (GedcomRecord $record): bool {
124886b77daSGreg Roach            return $record->canShow();
125886b77daSGreg Roach        };
126886b77daSGreg Roach    }
127886b77daSGreg Roach
128886b77daSGreg Roach    /**
129c156e8f5SGreg Roach     * A closure which will compare records by name.
130c156e8f5SGreg Roach     *
131c156e8f5SGreg Roach     * @return Closure
132c156e8f5SGreg Roach     */
133c156e8f5SGreg Roach    public static function nameComparator(): Closure
134c156e8f5SGreg Roach    {
1356c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y): int {
136c156e8f5SGreg Roach            if ($x->canShowName()) {
137c156e8f5SGreg Roach                if ($y->canShowName()) {
13837646143SGreg Roach                    return I18N::comparator()($x->sortName(), $y->sortName());
139c156e8f5SGreg Roach                }
140c156e8f5SGreg Roach
141c156e8f5SGreg Roach                return -1; // only $y is private
142c156e8f5SGreg Roach            }
143c156e8f5SGreg Roach
144c156e8f5SGreg Roach            if ($y->canShowName()) {
145c156e8f5SGreg Roach                return 1; // only $x is private
146c156e8f5SGreg Roach            }
147c156e8f5SGreg Roach
148c156e8f5SGreg Roach            return 0; // both $x and $y private
149c156e8f5SGreg Roach        };
150c156e8f5SGreg Roach    }
151c156e8f5SGreg Roach
152c156e8f5SGreg Roach    /**
153c156e8f5SGreg Roach     * A closure which will compare records by change time.
154c156e8f5SGreg Roach     *
155c156e8f5SGreg Roach     * @param int $direction +1 to sort ascending, -1 to sort descending
156c156e8f5SGreg Roach     *
157c156e8f5SGreg Roach     * @return Closure
158c156e8f5SGreg Roach     */
159c156e8f5SGreg Roach    public static function lastChangeComparator(int $direction = 1): Closure
160c156e8f5SGreg Roach    {
1616c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
1624459dc9aSGreg Roach            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
163c156e8f5SGreg Roach        };
164c156e8f5SGreg Roach    }
165c156e8f5SGreg Roach
166c156e8f5SGreg Roach    /**
16702467d32SGreg Roach     * Get the GEDCOM tag for this record.
16802467d32SGreg Roach     *
16902467d32SGreg Roach     * @return string
17002467d32SGreg Roach     */
17102467d32SGreg Roach    public function tag(): string
17202467d32SGreg Roach    {
17302467d32SGreg Roach        preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
17402467d32SGreg Roach
17502467d32SGreg Roach        return $match[1] ?? static::RECORD_TYPE;
17602467d32SGreg Roach    }
17702467d32SGreg Roach
17802467d32SGreg Roach    /**
179a25f0a04SGreg Roach     * Get the XREF for this record
180a25f0a04SGreg Roach     *
181a25f0a04SGreg Roach     * @return string
182a25f0a04SGreg Roach     */
183c0935879SGreg Roach    public function xref(): string
184c1010edaSGreg Roach    {
185a25f0a04SGreg Roach        return $this->xref;
186a25f0a04SGreg Roach    }
187a25f0a04SGreg Roach
188a25f0a04SGreg Roach    /**
189000959d9SGreg Roach     * Get the tree to which this record belongs
190000959d9SGreg Roach     *
191000959d9SGreg Roach     * @return Tree
192000959d9SGreg Roach     */
193f4afa648SGreg Roach    public function tree(): Tree
194c1010edaSGreg Roach    {
195518bbdc1SGreg Roach        return $this->tree;
196000959d9SGreg Roach    }
197000959d9SGreg Roach
198000959d9SGreg Roach    /**
199a25f0a04SGreg Roach     * Application code should access data via Fact objects.
200a25f0a04SGreg Roach     * This function exists to support old code.
201a25f0a04SGreg Roach     *
202a25f0a04SGreg Roach     * @return string
203a25f0a04SGreg Roach     */
204e364afe4SGreg Roach    public function gedcom(): string
205c1010edaSGreg Roach    {
206b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
207a25f0a04SGreg Roach    }
208a25f0a04SGreg Roach
209a25f0a04SGreg Roach    /**
210a25f0a04SGreg Roach     * Does this record have a pending change?
211a25f0a04SGreg Roach     *
212cbc1590aSGreg Roach     * @return bool
213a25f0a04SGreg Roach     */
2148f53f488SRico Sonntag    public function isPendingAddition(): bool
215c1010edaSGreg Roach    {
216a25f0a04SGreg Roach        return $this->pending !== null;
217a25f0a04SGreg Roach    }
218a25f0a04SGreg Roach
219a25f0a04SGreg Roach    /**
220a25f0a04SGreg Roach     * Does this record have a pending deletion?
221a25f0a04SGreg Roach     *
222cbc1590aSGreg Roach     * @return bool
223a25f0a04SGreg Roach     */
2248f53f488SRico Sonntag    public function isPendingDeletion(): bool
225c1010edaSGreg Roach    {
226a25f0a04SGreg Roach        return $this->pending === '';
227a25f0a04SGreg Roach    }
228a25f0a04SGreg Roach
229a25f0a04SGreg Roach    /**
230ee4364daSGreg Roach     * Generate a "slug" to use in pretty URLs.
231ee4364daSGreg Roach     *
232ee4364daSGreg Roach     * @return string
233ee4364daSGreg Roach     */
234ee4364daSGreg Roach    public function slug(): string
235ee4364daSGreg Roach    {
2365ab92b3fSGreg Roach        $slug = strip_tags($this->fullName());
237f7440925SGreg Roach
23874670d65SGreg Roach        try {
239f7440925SGreg Roach            $transliterator = Transliterator::create('Any-Latin;Latin-ASCII');
2405ab92b3fSGreg Roach            $slug           = $transliterator->transliterate($slug);
24174670d65SGreg Roach        } catch (Throwable $ex) {
24274670d65SGreg Roach            // ext-intl not installed?
24374670d65SGreg Roach            // Transliteration algorithms not present in lib-icu?
244f7440925SGreg Roach        }
245f7440925SGreg Roach
2465ab92b3fSGreg Roach        $slug = preg_replace('/[^A-Za-z0-9]+/', '-', $slug);
2475ab92b3fSGreg Roach
2485ab92b3fSGreg Roach        return trim($slug, '-') ?: '-';
249ee4364daSGreg Roach    }
250ee4364daSGreg Roach
251ee4364daSGreg Roach    /**
252225e381fSGreg Roach     * Generate a URL to this record.
253a25f0a04SGreg Roach     *
254a25f0a04SGreg Roach     * @return string
255a25f0a04SGreg Roach     */
2568f53f488SRico Sonntag    public function url(): string
257c1010edaSGreg Roach    {
258225e381fSGreg Roach        return route(static::ROUTE_NAME, [
259c0935879SGreg Roach            'xref' => $this->xref(),
260ee4364daSGreg Roach            'tree' => $this->tree->name(),
261ee4364daSGreg Roach            'slug' => $this->slug(),
262225e381fSGreg Roach        ]);
263a25f0a04SGreg Roach    }
264a25f0a04SGreg Roach
265a25f0a04SGreg Roach    /**
266a25f0a04SGreg Roach     * Can the details of this record be shown?
267a25f0a04SGreg Roach     *
268cbc1590aSGreg Roach     * @param int|null $access_level
269a25f0a04SGreg Roach     *
270cbc1590aSGreg Roach     * @return bool
271a25f0a04SGreg Roach     */
27235584196SGreg Roach    public function canShow(int $access_level = null): bool
273c1010edaSGreg Roach    {
274f0b9c048SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
2754b9ff166SGreg Roach
276a25f0a04SGreg Roach        // We use this value to bypass privacy checks. For example,
277a25f0a04SGreg Roach        // when downloading data or when calculating privacy itself.
278f0b9c048SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
279a25f0a04SGreg Roach            return true;
280a25f0a04SGreg Roach        }
281f0b9c048SGreg Roach
2827476e8a5SGreg Roach        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
283f0b9c048SGreg Roach
2846b9cb339SGreg Roach        return Registry::cache()->array()->remember($cache_key, function () use ($access_level) {
285f0b9c048SGreg Roach            return $this->canShowRecord($access_level);
286f0b9c048SGreg Roach        });
287a25f0a04SGreg Roach    }
288a25f0a04SGreg Roach
289a25f0a04SGreg Roach    /**
290a25f0a04SGreg Roach     * Can the name of this record be shown?
291a25f0a04SGreg Roach     *
292cbc1590aSGreg Roach     * @param int|null $access_level
293a25f0a04SGreg Roach     *
294cbc1590aSGreg Roach     * @return bool
295a25f0a04SGreg Roach     */
29676f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
297c1010edaSGreg Roach    {
298a25f0a04SGreg Roach        return $this->canShow($access_level);
299a25f0a04SGreg Roach    }
300a25f0a04SGreg Roach
301a25f0a04SGreg Roach    /**
302a25f0a04SGreg Roach     * Can we edit this record?
303a25f0a04SGreg Roach     *
304cbc1590aSGreg Roach     * @return bool
305a25f0a04SGreg Roach     */
3068f53f488SRico Sonntag    public function canEdit(): bool
307c1010edaSGreg Roach    {
3081450f098SGreg Roach        if ($this->isPendingDeletion()) {
3091450f098SGreg Roach            return false;
3101450f098SGreg Roach        }
3111450f098SGreg Roach
3121450f098SGreg Roach        if (Auth::isManager($this->tree)) {
3131450f098SGreg Roach            return true;
3141450f098SGreg Roach        }
3151450f098SGreg Roach
316dec352c1SGreg Roach        return Auth::isEditor($this->tree) && !str_contains($this->gedcom, "\n1 RESN locked");
317a25f0a04SGreg Roach    }
318a25f0a04SGreg Roach
319a25f0a04SGreg Roach    /**
320a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
321a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
322a25f0a04SGreg Roach     *
323cbc1590aSGreg Roach     * @param int $access_level
324a25f0a04SGreg Roach     *
325a25f0a04SGreg Roach     * @return string
326a25f0a04SGreg Roach     */
327e364afe4SGreg Roach    public function privatizeGedcom(int $access_level): string
328c1010edaSGreg Roach    {
329e364afe4SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
330a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
331a25f0a04SGreg Roach            return $this->gedcom;
332b2ce94c6SRico Sonntag        }
333b2ce94c6SRico Sonntag
334b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
335a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
336a25f0a04SGreg Roach
337a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
338dc141db3SGreg Roach            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
339a25f0a04SGreg Roach
340a25f0a04SGreg Roach            // Check each of the facts for access
3418d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
342138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
343a25f0a04SGreg Roach            }
344cbc1590aSGreg Roach
345a25f0a04SGreg Roach            return $gedrec;
346b2ce94c6SRico Sonntag        }
347b2ce94c6SRico Sonntag
348a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
349a25f0a04SGreg Roach        // limited data, such as links to other records.
350a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
351a25f0a04SGreg Roach    }
352a25f0a04SGreg Roach
353a25f0a04SGreg Roach    /**
354a25f0a04SGreg Roach     * Default for "other" object types
355c7ff4153SGreg Roach     *
356c7ff4153SGreg Roach     * @return void
357a25f0a04SGreg Roach     */
358e364afe4SGreg Roach    public function extractNames(): void
359c1010edaSGreg Roach    {
36076f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
361a25f0a04SGreg Roach    }
362a25f0a04SGreg Roach
363a25f0a04SGreg Roach    /**
364a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
365a25f0a04SGreg Roach     *
366870ec5a3SGreg Roach     * @return array<int,array<string,string>>
367a25f0a04SGreg Roach     */
3688f53f488SRico Sonntag    public function getAllNames(): array
369c1010edaSGreg Roach    {
370bdb3725aSGreg Roach        if ($this->getAllNames === null) {
371bdb3725aSGreg Roach            $this->getAllNames = [];
372a25f0a04SGreg Roach            if ($this->canShowName()) {
373a25f0a04SGreg Roach                // Ask the record to extract its names
374a25f0a04SGreg Roach                $this->extractNames();
375a25f0a04SGreg Roach                // No name found? Use a fallback.
376ec124fd2SGreg Roach                if ($this->getAllNames === []) {
377db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
378a25f0a04SGreg Roach                }
379a25f0a04SGreg Roach            } else {
380db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
381a25f0a04SGreg Roach            }
382a25f0a04SGreg Roach        }
383cbc1590aSGreg Roach
384bdb3725aSGreg Roach        return $this->getAllNames;
385a25f0a04SGreg Roach    }
386a25f0a04SGreg Roach
387a25f0a04SGreg Roach    /**
388a25f0a04SGreg Roach     * If this object has no name, what do we call it?
389a25f0a04SGreg Roach     *
390a25f0a04SGreg Roach     * @return string
391a25f0a04SGreg Roach     */
3928f53f488SRico Sonntag    public function getFallBackName(): string
393c1010edaSGreg Roach    {
394c0935879SGreg Roach        return e($this->xref());
395a25f0a04SGreg Roach    }
396a25f0a04SGreg Roach
397a25f0a04SGreg Roach    /**
398a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
399a25f0a04SGreg Roach     *
400cbc1590aSGreg Roach     * @return int
401a25f0a04SGreg Roach     */
4028f53f488SRico Sonntag    public function getPrimaryName(): int
403c1010edaSGreg Roach    {
404a25f0a04SGreg Roach        static $language_script;
405a25f0a04SGreg Roach
406a25f0a04SGreg Roach        if ($language_script === null) {
40765cf5706SGreg Roach            $language_script = $language_script ?? I18N::locale()->script()->code();
408a25f0a04SGreg Roach        }
409a25f0a04SGreg Roach
410bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
411a25f0a04SGreg Roach            // Generally, the first name is the primary one....
412bdb3725aSGreg Roach            $this->getPrimaryName = 0;
413a25f0a04SGreg Roach            // ...except when the language/name use different character sets
414a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
41569546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
416bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
417a25f0a04SGreg Roach                    break;
418a25f0a04SGreg Roach                }
419a25f0a04SGreg Roach            }
420a25f0a04SGreg Roach        }
421a25f0a04SGreg Roach
422bdb3725aSGreg Roach        return $this->getPrimaryName;
423a25f0a04SGreg Roach    }
424a25f0a04SGreg Roach
425a25f0a04SGreg Roach    /**
426a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
427a25f0a04SGreg Roach     *
428cbc1590aSGreg Roach     * @return int
429a25f0a04SGreg Roach     */
4308f53f488SRico Sonntag    public function getSecondaryName(): int
431c1010edaSGreg Roach    {
4328f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
433a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
434bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
435a25f0a04SGreg Roach            // ....except when there are names with different character sets
436a25f0a04SGreg Roach            $all_names = $this->getAllNames();
437a25f0a04SGreg Roach            if (count($all_names) > 1) {
438a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
439a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
440e364afe4SGreg Roach                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
441bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
442a25f0a04SGreg Roach                        break;
443a25f0a04SGreg Roach                    }
444a25f0a04SGreg Roach                }
445a25f0a04SGreg Roach            }
446a25f0a04SGreg Roach        }
447cbc1590aSGreg Roach
448bdb3725aSGreg Roach        return $this->getSecondaryName;
449a25f0a04SGreg Roach    }
450a25f0a04SGreg Roach
451a25f0a04SGreg Roach    /**
452a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
453a25f0a04SGreg Roach     *
45476f666f4SGreg Roach     * @param int|null $n
4557e96c925SGreg Roach     *
4567e96c925SGreg Roach     * @return void
457a25f0a04SGreg Roach     */
458e364afe4SGreg Roach    public function setPrimaryName(int $n = null): void
459c1010edaSGreg Roach    {
460bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
461bdb3725aSGreg Roach        $this->getSecondaryName = null;
462a25f0a04SGreg Roach    }
463a25f0a04SGreg Roach
464a25f0a04SGreg Roach    /**
465a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
466a25f0a04SGreg Roach     *
467a25f0a04SGreg Roach     * @return string
468a25f0a04SGreg Roach     */
46924f2a3afSGreg Roach    public function __toString(): string
470c1010edaSGreg Roach    {
47172cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
472a25f0a04SGreg Roach    }
473a25f0a04SGreg Roach
474a25f0a04SGreg Roach    /**
475c156e8f5SGreg Roach     * /**
476a25f0a04SGreg Roach     * Get variants of the name
477a25f0a04SGreg Roach     *
478a25f0a04SGreg Roach     * @return string
479a25f0a04SGreg Roach     */
480e364afe4SGreg Roach    public function fullName(): string
481c1010edaSGreg Roach    {
482a25f0a04SGreg Roach        if ($this->canShowName()) {
483a25f0a04SGreg Roach            $tmp = $this->getAllNames();
484cbc1590aSGreg Roach
485a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
486a25f0a04SGreg Roach        }
487b2ce94c6SRico Sonntag
488b2ce94c6SRico Sonntag        return I18N::translate('Private');
489a25f0a04SGreg Roach    }
490a25f0a04SGreg Roach
491a25f0a04SGreg Roach    /**
492a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
493a25f0a04SGreg Roach     *
494a25f0a04SGreg Roach     * @return string
495a25f0a04SGreg Roach     */
49639ca88baSGreg Roach    public function sortName(): string
497c1010edaSGreg Roach    {
498a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
499a25f0a04SGreg Roach        $tmp = $this->getAllNames();
500cbc1590aSGreg Roach
501a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
502a25f0a04SGreg Roach    }
503a25f0a04SGreg Roach
504a25f0a04SGreg Roach    /**
505a25f0a04SGreg Roach     * Get the full name in an alternative character set
506a25f0a04SGreg Roach     *
507e364afe4SGreg Roach     * @return string|null
508a25f0a04SGreg Roach     */
509e364afe4SGreg Roach    public function alternateName(): ?string
510c1010edaSGreg Roach    {
511e364afe4SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
512a25f0a04SGreg Roach            $all_names = $this->getAllNames();
513cbc1590aSGreg Roach
514a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
515a25f0a04SGreg Roach        }
516b2ce94c6SRico Sonntag
517b2ce94c6SRico Sonntag        return null;
518a25f0a04SGreg Roach    }
519a25f0a04SGreg Roach
520a25f0a04SGreg Roach    /**
521a25f0a04SGreg Roach     * Format this object for display in a list
522a25f0a04SGreg Roach     *
523a25f0a04SGreg Roach     * @return string
524a25f0a04SGreg Roach     */
5258f53f488SRico Sonntag    public function formatList(): string
526c1010edaSGreg Roach    {
527b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
52839ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
529a25f0a04SGreg Roach        $html .= $this->formatListDetails();
530b165e17cSGreg Roach        $html .= '</a>';
531cbc1590aSGreg Roach
532a25f0a04SGreg Roach        return $html;
533a25f0a04SGreg Roach    }
534a25f0a04SGreg Roach
535a25f0a04SGreg Roach    /**
536a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
537a25f0a04SGreg Roach     * identifying characteristics of this record.
538a25f0a04SGreg Roach     *
539a25f0a04SGreg Roach     * @return string
540a25f0a04SGreg Roach     */
5418f53f488SRico Sonntag    public function formatListDetails(): string
542c1010edaSGreg Roach    {
543a25f0a04SGreg Roach        return '';
544a25f0a04SGreg Roach    }
545a25f0a04SGreg Roach
546a25f0a04SGreg Roach    /**
547a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
548a25f0a04SGreg Roach     *
5498d0ebef0SGreg Roach     * @param string[] $facts
550cbc1590aSGreg Roach     * @param int      $style
551a25f0a04SGreg Roach     *
552a25f0a04SGreg Roach     * @return string
553a25f0a04SGreg Roach     */
5548d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
555c1010edaSGreg Roach    {
55630158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
557a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
558e364afe4SGreg Roach            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
559d93f11b5SGreg Roach                $joiner = ' — ';
560d93f11b5SGreg Roach            } else {
561d93f11b5SGreg Roach                $joiner = '';
562d93f11b5SGreg Roach            }
563e364afe4SGreg Roach            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
564a25f0a04SGreg Roach                switch ($style) {
565a25f0a04SGreg Roach                    case 1:
5667b7d8067SGreg Roach                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
567a25f0a04SGreg Roach                    case 2:
5687b7d8067SGreg Roach                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
569a25f0a04SGreg Roach                }
570a25f0a04SGreg Roach            }
571a25f0a04SGreg Roach        }
572cbc1590aSGreg Roach
573a25f0a04SGreg Roach        return '';
574a25f0a04SGreg Roach    }
575a25f0a04SGreg Roach
576a25f0a04SGreg Roach    /**
577a25f0a04SGreg Roach     * Find individuals linked to this record.
578a25f0a04SGreg Roach     *
579a25f0a04SGreg Roach     * @param string $link
580a25f0a04SGreg Roach     *
581b5c8fd7eSGreg Roach     * @return Collection<Individual>
582a25f0a04SGreg Roach     */
583907c1109SGreg Roach    public function linkedIndividuals(string $link): Collection
584c1010edaSGreg Roach    {
585907c1109SGreg Roach        return DB::table('individuals')
5860b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
587907c1109SGreg Roach                $join
588907c1109SGreg Roach                    ->on('l_file', '=', 'i_file')
589907c1109SGreg Roach                    ->on('l_from', '=', 'i_id');
590ba1c12e8SGreg Roach            })
591ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
592ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
593ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
594907c1109SGreg Roach            ->select(['individuals.*'])
595907c1109SGreg Roach            ->get()
5966b9cb339SGreg Roach            ->map(Registry::individualFactory()->mapper($this->tree))
597907c1109SGreg Roach            ->filter(self::accessFilter());
598a25f0a04SGreg Roach    }
599a25f0a04SGreg Roach
600a25f0a04SGreg Roach    /**
601a25f0a04SGreg Roach     * Find families linked to this record.
602a25f0a04SGreg Roach     *
603a25f0a04SGreg Roach     * @param string $link
604a25f0a04SGreg Roach     *
605b5c8fd7eSGreg Roach     * @return Collection<Family>
606a25f0a04SGreg Roach     */
607907c1109SGreg Roach    public function linkedFamilies(string $link): Collection
608c1010edaSGreg Roach    {
609907c1109SGreg Roach        return DB::table('families')
6100b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
611907c1109SGreg Roach                $join
612907c1109SGreg Roach                    ->on('l_file', '=', 'f_file')
613907c1109SGreg Roach                    ->on('l_from', '=', 'f_id');
614ba1c12e8SGreg Roach            })
615ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
616ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
617ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
618907c1109SGreg Roach            ->select(['families.*'])
619907c1109SGreg Roach            ->get()
6206b9cb339SGreg Roach            ->map(Registry::familyFactory()->mapper($this->tree))
621907c1109SGreg Roach            ->filter(self::accessFilter());
622a25f0a04SGreg Roach    }
623a25f0a04SGreg Roach
624a25f0a04SGreg Roach    /**
625a25f0a04SGreg Roach     * Find sources linked to this record.
626a25f0a04SGreg Roach     *
627a25f0a04SGreg Roach     * @param string $link
628a25f0a04SGreg Roach     *
629b5c8fd7eSGreg Roach     * @return Collection<Source>
630a25f0a04SGreg Roach     */
631907c1109SGreg Roach    public function linkedSources(string $link): Collection
632c1010edaSGreg Roach    {
633907c1109SGreg Roach        return DB::table('sources')
6340b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
635907c1109SGreg Roach                $join
636907c1109SGreg Roach                    ->on('l_file', '=', 's_file')
637907c1109SGreg Roach                    ->on('l_from', '=', 's_id');
638ba1c12e8SGreg Roach            })
639ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
640ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
641ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
642907c1109SGreg Roach            ->select(['sources.*'])
643907c1109SGreg Roach            ->get()
6446b9cb339SGreg Roach            ->map(Registry::sourceFactory()->mapper($this->tree))
645907c1109SGreg Roach            ->filter(self::accessFilter());
646a25f0a04SGreg Roach    }
647a25f0a04SGreg Roach
648a25f0a04SGreg Roach    /**
649a25f0a04SGreg Roach     * Find media objects linked to this record.
650a25f0a04SGreg Roach     *
651a25f0a04SGreg Roach     * @param string $link
652a25f0a04SGreg Roach     *
653b5c8fd7eSGreg Roach     * @return Collection<Media>
654a25f0a04SGreg Roach     */
655907c1109SGreg Roach    public function linkedMedia(string $link): Collection
656c1010edaSGreg Roach    {
657907c1109SGreg Roach        return DB::table('media')
6580b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
659907c1109SGreg Roach                $join
660907c1109SGreg Roach                    ->on('l_file', '=', 'm_file')
661907c1109SGreg Roach                    ->on('l_from', '=', 'm_id');
662ba1c12e8SGreg Roach            })
663ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
664ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
665ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
666907c1109SGreg Roach            ->select(['media.*'])
667907c1109SGreg Roach            ->get()
6686b9cb339SGreg Roach            ->map(Registry::mediaFactory()->mapper($this->tree))
669907c1109SGreg Roach            ->filter(self::accessFilter());
670a25f0a04SGreg Roach    }
671a25f0a04SGreg Roach
672a25f0a04SGreg Roach    /**
673a25f0a04SGreg Roach     * Find notes linked to this record.
674a25f0a04SGreg Roach     *
675a25f0a04SGreg Roach     * @param string $link
676a25f0a04SGreg Roach     *
677b5c8fd7eSGreg Roach     * @return Collection<Note>
678a25f0a04SGreg Roach     */
679907c1109SGreg Roach    public function linkedNotes(string $link): Collection
680c1010edaSGreg Roach    {
681907c1109SGreg Roach        return DB::table('other')
6820b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
683907c1109SGreg Roach                $join
684907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
685907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
686ba1c12e8SGreg Roach            })
687ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
6887a8cbeebSGreg Roach            ->where('o_type', '=', Note::RECORD_TYPE)
689ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
690ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
691907c1109SGreg Roach            ->select(['other.*'])
692907c1109SGreg Roach            ->get()
6936b9cb339SGreg Roach            ->map(Registry::noteFactory()->mapper($this->tree))
694907c1109SGreg Roach            ->filter(self::accessFilter());
695a25f0a04SGreg Roach    }
696a25f0a04SGreg Roach
697a25f0a04SGreg Roach    /**
698a25f0a04SGreg Roach     * Find repositories linked to this record.
699a25f0a04SGreg Roach     *
700a25f0a04SGreg Roach     * @param string $link
701a25f0a04SGreg Roach     *
702b5c8fd7eSGreg Roach     * @return Collection<Repository>
703a25f0a04SGreg Roach     */
704907c1109SGreg Roach    public function linkedRepositories(string $link): Collection
705c1010edaSGreg Roach    {
706907c1109SGreg Roach        return DB::table('other')
7070b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
708907c1109SGreg Roach                $join
709907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
710907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
711ba1c12e8SGreg Roach            })
712ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
7137a8cbeebSGreg Roach            ->where('o_type', '=', Repository::RECORD_TYPE)
714ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
715ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
716907c1109SGreg Roach            ->select(['other.*'])
717907c1109SGreg Roach            ->get()
7186b9cb339SGreg Roach            ->map(Registry::repositoryFactory()->mapper($this->tree))
719907c1109SGreg Roach            ->filter(self::accessFilter());
720a25f0a04SGreg Roach    }
721a25f0a04SGreg Roach
722a25f0a04SGreg Roach    /**
72336254e3dSRichard Cissée     * Find locations linked to this record.
72436254e3dSRichard Cissée     *
72536254e3dSRichard Cissée     * @param string $link
72636254e3dSRichard Cissée     *
72736254e3dSRichard Cissée     * @return Collection<Location>
72836254e3dSRichard Cissée     */
72936254e3dSRichard Cissée    public function linkedLocations(string $link): Collection
73036254e3dSRichard Cissée    {
73136254e3dSRichard Cissée        return DB::table('other')
73236254e3dSRichard Cissée            ->join('link', static function (JoinClause $join): void {
73336254e3dSRichard Cissée                $join
73436254e3dSRichard Cissée                    ->on('l_file', '=', 'o_file')
73536254e3dSRichard Cissée                    ->on('l_from', '=', 'o_id');
73636254e3dSRichard Cissée            })
73736254e3dSRichard Cissée            ->where('o_file', '=', $this->tree->id())
7387a8cbeebSGreg Roach            ->where('o_type', '=', Location::RECORD_TYPE)
73936254e3dSRichard Cissée            ->where('l_type', '=', $link)
74036254e3dSRichard Cissée            ->where('l_to', '=', $this->xref)
74136254e3dSRichard Cissée            ->select(['other.*'])
74236254e3dSRichard Cissée            ->get()
7436b9cb339SGreg Roach            ->map(Registry::locationFactory()->mapper($this->tree))
74436254e3dSRichard Cissée            ->filter(self::accessFilter());
74536254e3dSRichard Cissée    }
74636254e3dSRichard Cissée
74736254e3dSRichard Cissée    /**
748a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
749a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
750a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
751a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
752a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
753a25f0a04SGreg Roach     *
7548d0ebef0SGreg Roach     * @param string[] $events
755a25f0a04SGreg Roach     *
756a25f0a04SGreg Roach     * @return Date[]
757a25f0a04SGreg Roach     */
7588d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
759c1010edaSGreg Roach    {
76013abd6f3SGreg Roach        $dates = [];
7611385b8caSGreg Roach        foreach ($this->facts($events, false, null, true) as $event) {
7622decada7SGreg Roach            if ($event->date()->isOK()) {
7632decada7SGreg Roach                $dates[] = $event->date();
764a25f0a04SGreg Roach            }
765a25f0a04SGreg Roach        }
766a25f0a04SGreg Roach
767a25f0a04SGreg Roach        return $dates;
768a25f0a04SGreg Roach    }
769a25f0a04SGreg Roach
770a25f0a04SGreg Roach    /**
771a25f0a04SGreg Roach     * Get all the places for a particular type of event
772a25f0a04SGreg Roach     *
7738d0ebef0SGreg Roach     * @param string[] $events
774a25f0a04SGreg Roach     *
7754080d558SGreg Roach     * @return Place[]
776a25f0a04SGreg Roach     */
7778d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
778c1010edaSGreg Roach    {
77913abd6f3SGreg Roach        $places = [];
7808d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
781138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
782a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
78316d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
784a25f0a04SGreg Roach                }
785a25f0a04SGreg Roach            }
786a25f0a04SGreg Roach        }
787a25f0a04SGreg Roach
788a25f0a04SGreg Roach        return $places;
789a25f0a04SGreg Roach    }
790a25f0a04SGreg Roach
791a25f0a04SGreg Roach    /**
792a25f0a04SGreg Roach     * The facts and events for this record.
793a25f0a04SGreg Roach     *
7948d0ebef0SGreg Roach     * @param string[] $filter
795cbc1590aSGreg Roach     * @param bool     $sort
796cbc1590aSGreg Roach     * @param int|null $access_level
797ce42304aSGreg Roach     * @param bool     $ignore_deleted
798a25f0a04SGreg Roach     *
799b5c8fd7eSGreg Roach     * @return Collection<Fact>
800a25f0a04SGreg Roach     */
801ce42304aSGreg Roach    public function facts(
802ce42304aSGreg Roach        array $filter = [],
803ce42304aSGreg Roach        bool $sort = false,
804ce42304aSGreg Roach        int $access_level = null,
805ce42304aSGreg Roach        bool $ignore_deleted = false
806ce42304aSGreg Roach    ): Collection {
807d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
8084b9ff166SGreg Roach
8098af3e5c1SGreg Roach        $facts = new Collection();
810ce42304aSGreg Roach        if ($this->canShow($access_level)) {
811a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
8127fe676e5SGreg Roach                if (($filter === [] || in_array($fact->getTag(), $filter, true)) && $fact->canShow($access_level)) {
8138af3e5c1SGreg Roach                    $facts->push($fact);
814a25f0a04SGreg Roach                }
815a25f0a04SGreg Roach            }
816a25f0a04SGreg Roach        }
817d17d7b9eSGreg Roach
818a25f0a04SGreg Roach        if ($sort) {
819580a4d11SGreg Roach            $facts = Fact::sortFacts($facts);
820a25f0a04SGreg Roach        }
821cbc1590aSGreg Roach
822ce42304aSGreg Roach        if ($ignore_deleted) {
823ce42304aSGreg Roach            $facts = $facts->filter(static function (Fact $fact): bool {
824ce42304aSGreg Roach                return !$fact->isPendingDeletion();
825ce42304aSGreg Roach            });
826ce42304aSGreg Roach        }
827ce42304aSGreg Roach
82839ca88baSGreg Roach        return new Collection($facts);
829a25f0a04SGreg Roach    }
830a25f0a04SGreg Roach
831a25f0a04SGreg Roach    /**
8324459dc9aSGreg Roach     * Get the last-change timestamp for this record
833a25f0a04SGreg Roach     *
8344459dc9aSGreg Roach     * @return Carbon
835a25f0a04SGreg Roach     */
8364459dc9aSGreg Roach    public function lastChangeTimestamp(): Carbon
837c1010edaSGreg Roach    {
8384459dc9aSGreg Roach        /** @var Fact|null $chan */
839820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
840a25f0a04SGreg Roach
8414459dc9aSGreg Roach        if ($chan instanceof Fact) {
842a25f0a04SGreg Roach            // The record does have a CHAN event
8432decada7SGreg Roach            $d = $chan->date()->minimumDate();
8444459dc9aSGreg Roach
845138ca96cSGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
8464459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
847e364afe4SGreg Roach            }
848e364afe4SGreg Roach
849e364afe4SGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
8504459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
851b2ce94c6SRico Sonntag            }
852b2ce94c6SRico Sonntag
8534459dc9aSGreg Roach            return Carbon::create($d->year(), $d->month(), $d->day());
854a25f0a04SGreg Roach        }
855b2ce94c6SRico Sonntag
856a25f0a04SGreg Roach        // The record does not have a CHAN event
8574459dc9aSGreg Roach        return Carbon::createFromTimestamp(0);
858a25f0a04SGreg Roach    }
859a25f0a04SGreg Roach
860a25f0a04SGreg Roach    /**
861a25f0a04SGreg Roach     * Get the last-change user for this record
862a25f0a04SGreg Roach     *
863a25f0a04SGreg Roach     * @return string
864a25f0a04SGreg Roach     */
865e364afe4SGreg Roach    public function lastChangeUser(): string
866c1010edaSGreg Roach    {
867820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
868a25f0a04SGreg Roach
869a25f0a04SGreg Roach        if ($chan === null) {
870a25f0a04SGreg Roach            return I18N::translate('Unknown');
871b2ce94c6SRico Sonntag        }
872b2ce94c6SRico Sonntag
8733425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
874baacc364SGreg Roach        if ($chan_user === '') {
875a25f0a04SGreg Roach            return I18N::translate('Unknown');
876b2ce94c6SRico Sonntag        }
877b2ce94c6SRico Sonntag
878a25f0a04SGreg Roach        return $chan_user;
879a25f0a04SGreg Roach    }
880a25f0a04SGreg Roach
881a25f0a04SGreg Roach    /**
882a25f0a04SGreg Roach     * Add a new fact to this record
883a25f0a04SGreg Roach     *
884a25f0a04SGreg Roach     * @param string $gedcom
885cbc1590aSGreg Roach     * @param bool   $update_chan
8867e96c925SGreg Roach     *
8877e96c925SGreg Roach     * @return void
888a25f0a04SGreg Roach     */
889e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
890c1010edaSGreg Roach    {
891fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
892a25f0a04SGreg Roach    }
893a25f0a04SGreg Roach
894a25f0a04SGreg Roach    /**
895a25f0a04SGreg Roach     * Delete a fact from this record
896a25f0a04SGreg Roach     *
897a25f0a04SGreg Roach     * @param string $fact_id
898cbc1590aSGreg Roach     * @param bool   $update_chan
8997e96c925SGreg Roach     *
9007e96c925SGreg Roach     * @return void
901a25f0a04SGreg Roach     */
902e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
903c1010edaSGreg Roach    {
904db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
905a25f0a04SGreg Roach    }
906a25f0a04SGreg Roach
907a25f0a04SGreg Roach    /**
908a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
909a25f0a04SGreg Roach     *
910a25f0a04SGreg Roach     * @param string $fact_id
911a25f0a04SGreg Roach     * @param string $gedcom
912cbc1590aSGreg Roach     * @param bool   $update_chan
913a25f0a04SGreg Roach     *
9147e96c925SGreg Roach     * @return void
9157e96c925SGreg Roach     * @throws Exception
916a25f0a04SGreg Roach     */
917e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
918c1010edaSGreg Roach    {
91971f696adSGreg Roach        // Not all record types allow a CHAN event.
92071f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
92171f696adSGreg Roach
922a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
923a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
924a25f0a04SGreg Roach        $gedcom = trim($gedcom);
925a25f0a04SGreg Roach
926a25f0a04SGreg Roach        if ($this->pending === '') {
9277e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
928a25f0a04SGreg Roach        }
9298d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
9307e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
931a25f0a04SGreg Roach        }
932a25f0a04SGreg Roach
933a25f0a04SGreg Roach        if ($this->pending) {
934a25f0a04SGreg Roach            $old_gedcom = $this->pending;
935a25f0a04SGreg Roach        } else {
936a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
937a25f0a04SGreg Roach        }
938a25f0a04SGreg Roach
939a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
94065e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
941a25f0a04SGreg Roach
942a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
94319aed3a1SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
944905ab80aSGreg Roach            if ($fact->id() === $fact_id) {
945db7bb364SGreg Roach                if ($gedcom !== '') {
946a25f0a04SGreg Roach                    $new_gedcom .= "\n" . $gedcom;
947a25f0a04SGreg Roach                }
948fc3ccce4SGreg Roach                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
9497fe676e5SGreg Roach            } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) {
950138ca96cSGreg Roach                $new_gedcom .= "\n" . $fact->gedcom();
951a25f0a04SGreg Roach            }
952a25f0a04SGreg Roach        }
953a25f0a04SGreg Roach
954a25f0a04SGreg Roach        // Adding a new fact
955fc3ccce4SGreg Roach        if ($fact_id === '') {
956a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
957a25f0a04SGreg Roach        }
958a25f0a04SGreg Roach
959dec352c1SGreg Roach        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
96019aed3a1SGreg Roach            $today = strtoupper(date('d M Y'));
96119aed3a1SGreg Roach            $now   = date('H:i:s');
96219aed3a1SGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
96319aed3a1SGreg Roach        }
96419aed3a1SGreg Roach
965e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
966a25f0a04SGreg Roach            // Save the changes
967d09b6323SGreg Roach            DB::table('change')->insert([
968d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
969d09b6323SGreg Roach                'xref'       => $this->xref,
970d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
971d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
972d09b6323SGreg Roach                'user_id'    => Auth::id(),
97313abd6f3SGreg Roach            ]);
974a25f0a04SGreg Roach
975a25f0a04SGreg Roach            $this->pending = $new_gedcom;
976a25f0a04SGreg Roach
9771fe542e9SGreg Roach            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
97822e73debSGreg Roach                app(PendingChangesService::class)->acceptRecord($this);
979a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
980a25f0a04SGreg Roach                $this->pending = null;
981a25f0a04SGreg Roach            }
982a25f0a04SGreg Roach        }
983a25f0a04SGreg Roach        $this->parseFacts();
984a25f0a04SGreg Roach    }
985a25f0a04SGreg Roach
986a25f0a04SGreg Roach    /**
987a25f0a04SGreg Roach     * Update this record
988a25f0a04SGreg Roach     *
989a25f0a04SGreg Roach     * @param string $gedcom
990cbc1590aSGreg Roach     * @param bool   $update_chan
9917e96c925SGreg Roach     *
9927e96c925SGreg Roach     * @return void
993a25f0a04SGreg Roach     */
994e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
995c1010edaSGreg Roach    {
99671f696adSGreg Roach        // Not all record types allow a CHAN event.
99771f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
99871f696adSGreg Roach
999a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1000a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1001a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1002a25f0a04SGreg Roach
1003a25f0a04SGreg Roach        // Update the CHAN record
1004a25f0a04SGreg Roach        if ($update_chan) {
1005a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
100653432476SGreg Roach            $today = strtoupper(date('d M Y'));
100753432476SGreg Roach            $now   = date('H:i:s');
100853432476SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
1009a25f0a04SGreg Roach        }
1010a25f0a04SGreg Roach
1011a25f0a04SGreg Roach        // Create a pending change
1012d09b6323SGreg Roach        DB::table('change')->insert([
1013d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1014d09b6323SGreg Roach            'xref'       => $this->xref,
1015d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1016d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1017d09b6323SGreg Roach            'user_id'    => Auth::id(),
101813abd6f3SGreg Roach        ]);
1019a25f0a04SGreg Roach
1020a25f0a04SGreg Roach        // Clear the cache
1021a25f0a04SGreg Roach        $this->pending = $gedcom;
1022a25f0a04SGreg Roach
1023a25f0a04SGreg Roach        // Accept this pending change
10241fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
102522e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1026a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1027a25f0a04SGreg Roach            $this->pending = null;
1028a25f0a04SGreg Roach        }
1029a25f0a04SGreg Roach
1030a25f0a04SGreg Roach        $this->parseFacts();
1031a25f0a04SGreg Roach
1032847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1033a25f0a04SGreg Roach    }
1034a25f0a04SGreg Roach
1035a25f0a04SGreg Roach    /**
1036a25f0a04SGreg Roach     * Delete this record
1037b874da82SGreg Roach     *
1038b874da82SGreg Roach     * @return void
1039a25f0a04SGreg Roach     */
1040e364afe4SGreg Roach    public function deleteRecord(): void
1041c1010edaSGreg Roach    {
1042a25f0a04SGreg Roach        // Create a pending change
10434c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1044d09b6323SGreg Roach            DB::table('change')->insert([
1045d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1046d09b6323SGreg Roach                'xref'       => $this->xref,
1047d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1048d09b6323SGreg Roach                'new_gedcom' => '',
1049d09b6323SGreg Roach                'user_id'    => Auth::id(),
105013abd6f3SGreg Roach            ]);
10514c0b5256SGreg Roach        }
1052a25f0a04SGreg Roach
10534c0b5256SGreg Roach        // Auto-accept this pending change
10541fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
105522e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1056a25f0a04SGreg Roach        }
1057a25f0a04SGreg Roach
1058847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1059a25f0a04SGreg Roach    }
1060a25f0a04SGreg Roach
1061a25f0a04SGreg Roach    /**
1062a25f0a04SGreg Roach     * Remove all links from this record to $xref
1063a25f0a04SGreg Roach     *
1064a25f0a04SGreg Roach     * @param string $xref
1065cbc1590aSGreg Roach     * @param bool   $update_chan
10667e96c925SGreg Roach     *
10677e96c925SGreg Roach     * @return void
1068a25f0a04SGreg Roach     */
1069e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
1070c1010edaSGreg Roach    {
1071a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1072a25f0a04SGreg Roach
107330158ae7SGreg Roach        foreach ($this->facts() as $fact) {
107484586c02SGreg Roach            if ($fact->value() === $value) {
1075905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
10768d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1077138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1078a25f0a04SGreg Roach                foreach ($matches as $match) {
1079a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1080a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1081a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1082a25f0a04SGreg Roach                }
1083905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1084a25f0a04SGreg Roach            }
1085a25f0a04SGreg Roach        }
1086a25f0a04SGreg Roach    }
1087bf4eb542SGreg Roach
1088bf4eb542SGreg Roach    /**
1089bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1090bf4eb542SGreg Roach     * also delete all links to it.
1091bf4eb542SGreg Roach     *
1092bf4eb542SGreg Roach     * @return GedcomRecord[]
1093bf4eb542SGreg Roach     */
1094bf4eb542SGreg Roach    public function linkingRecords(): array
1095bf4eb542SGreg Roach    {
1096b5961194SGreg Roach        $like = addcslashes($this->xref(), '\\%_');
1097b5961194SGreg Roach
1098bf4eb542SGreg Roach        $union = DB::table('change')
1099bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1100b5961194SGreg Roach            ->where('new_gedcom', 'LIKE', '%@' . $like . '@%')
1101b5961194SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $like . '@%')
110283242252SGreg Roach            ->whereIn('change_id', function (Builder $query): void {
110383242252SGreg Roach                $query->select(new Expression('MAX(change_id)'))
110483242252SGreg Roach                    ->from('change')
110583242252SGreg Roach                    ->where('gedcom_id', '=', $this->tree->id())
110683242252SGreg Roach                    ->where('status', '=', 'pending')
11077f5c2944SGreg Roach                    ->groupBy(['xref']);
110883242252SGreg Roach            })
1109bf4eb542SGreg Roach            ->select(['xref']);
1110bf4eb542SGreg Roach
1111bf4eb542SGreg Roach        $xrefs = DB::table('link')
1112bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1113bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
111447256fc5SGreg Roach            ->select(['l_from'])
1115bf4eb542SGreg Roach            ->union($union)
1116bf4eb542SGreg Roach            ->pluck('l_from');
1117bf4eb542SGreg Roach
1118bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
11196b9cb339SGreg Roach            $record = Registry::gedcomRecordFactory()->make($xref, $this->tree);
1120ffc0a61fSGreg Roach            assert($record instanceof GedcomRecord);
1121ffc0a61fSGreg Roach
1122ffc0a61fSGreg Roach            return $record;
1123bf4eb542SGreg Roach        })->all();
1124bf4eb542SGreg Roach    }
112522e73debSGreg Roach
112622e73debSGreg Roach    /**
112722e73debSGreg Roach     * Each object type may have its own special rules, and re-implement this function.
112822e73debSGreg Roach     *
112922e73debSGreg Roach     * @param int $access_level
113022e73debSGreg Roach     *
113122e73debSGreg Roach     * @return bool
113222e73debSGreg Roach     */
113322e73debSGreg Roach    protected function canShowByType(int $access_level): bool
113422e73debSGreg Roach    {
113522e73debSGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
113622e73debSGreg Roach
113722e73debSGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
113822e73debSGreg Roach            // Restriction found
113922e73debSGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
114022e73debSGreg Roach        }
114122e73debSGreg Roach
114222e73debSGreg Roach        // No restriction found - must be public:
114322e73debSGreg Roach        return true;
114422e73debSGreg Roach    }
114522e73debSGreg Roach
114622e73debSGreg Roach    /**
114722e73debSGreg Roach     * Generate a private version of this record
114822e73debSGreg Roach     *
114922e73debSGreg Roach     * @param int $access_level
115022e73debSGreg Roach     *
115122e73debSGreg Roach     * @return string
115222e73debSGreg Roach     */
115322e73debSGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
115422e73debSGreg Roach    {
1155228ede81SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
115622e73debSGreg Roach    }
115722e73debSGreg Roach
115822e73debSGreg Roach    /**
115922e73debSGreg Roach     * Convert a name record into sortable and full/display versions. This default
116022e73debSGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
116122e73debSGreg Roach     *
116222e73debSGreg Roach     * @param string $type
116322e73debSGreg Roach     * @param string $value
116422e73debSGreg Roach     * @param string $gedcom
116522e73debSGreg Roach     *
116622e73debSGreg Roach     * @return void
116722e73debSGreg Roach     */
116822e73debSGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
116922e73debSGreg Roach    {
117022e73debSGreg Roach        $this->getAllNames[] = [
117122e73debSGreg Roach            'type'   => $type,
1172*dbf91548SGreg Roach            'sort'   => preg_replace_callback('/(\d+)/', static function (array $matches): string {
117322e73debSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
117422e73debSGreg Roach            }, $value),
117522e73debSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
117622e73debSGreg Roach            // This is used for display
117722e73debSGreg Roach            'fullNN' => $value,
117822e73debSGreg Roach            // This goes into the database
117922e73debSGreg Roach        ];
118022e73debSGreg Roach    }
118122e73debSGreg Roach
118222e73debSGreg Roach    /**
118322e73debSGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
118422e73debSGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
118522e73debSGreg Roach     * Parameters: the level 1 fact containing the name.
118622e73debSGreg Roach     * Return value: an array of name structures, each containing
118722e73debSGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
118822e73debSGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
118922e73debSGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
119022e73debSGreg Roach     *
119122e73debSGreg Roach     * @param int              $level
119222e73debSGreg Roach     * @param string           $fact_type
1193d7634abbSGreg Roach     * @param Collection<Fact> $facts
119422e73debSGreg Roach     *
119522e73debSGreg Roach     * @return void
119622e73debSGreg Roach     */
119722e73debSGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
119822e73debSGreg Roach    {
119922e73debSGreg Roach        $sublevel    = $level + 1;
120022e73debSGreg Roach        $subsublevel = $sublevel + 1;
120122e73debSGreg Roach        foreach ($facts as $fact) {
120222e73debSGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
120322e73debSGreg Roach                foreach ($matches as $match) {
120422e73debSGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1205dec352c1SGreg Roach                    if ($match[1] === 'NAME' && str_contains($match[3], "\n2 TYPE married")) {
120622e73debSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
120722e73debSGreg Roach                    } else {
120822e73debSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
120922e73debSGreg Roach                    }
121022e73debSGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
121122e73debSGreg Roach                        foreach ($submatches as $submatch) {
121222e73debSGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
121322e73debSGreg Roach                        }
121422e73debSGreg Roach                    }
121522e73debSGreg Roach                }
121622e73debSGreg Roach            }
121722e73debSGreg Roach        }
121822e73debSGreg Roach    }
121922e73debSGreg Roach
122022e73debSGreg Roach    /**
122122e73debSGreg Roach     * Split the record into facts
122222e73debSGreg Roach     *
122322e73debSGreg Roach     * @return void
122422e73debSGreg Roach     */
122522e73debSGreg Roach    private function parseFacts(): void
122622e73debSGreg Roach    {
122722e73debSGreg Roach        // Split the record into facts
122822e73debSGreg Roach        if ($this->gedcom) {
1229d823340dSGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
123022e73debSGreg Roach            array_shift($gedcom_facts);
123122e73debSGreg Roach        } else {
123222e73debSGreg Roach            $gedcom_facts = [];
123322e73debSGreg Roach        }
123422e73debSGreg Roach        if ($this->pending) {
1235d823340dSGreg Roach            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
123622e73debSGreg Roach            array_shift($pending_facts);
123722e73debSGreg Roach        } else {
123822e73debSGreg Roach            $pending_facts = [];
123922e73debSGreg Roach        }
124022e73debSGreg Roach
124122e73debSGreg Roach        $this->facts = [];
124222e73debSGreg Roach
124322e73debSGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
124422e73debSGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
124522e73debSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
124622e73debSGreg Roach                $fact->setPendingDeletion();
124722e73debSGreg Roach            }
124822e73debSGreg Roach            $this->facts[] = $fact;
124922e73debSGreg Roach        }
125022e73debSGreg Roach        foreach ($pending_facts as $pending_fact) {
125122e73debSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
125222e73debSGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
125322e73debSGreg Roach                $fact->setPendingAddition();
125422e73debSGreg Roach                $this->facts[] = $fact;
125522e73debSGreg Roach            }
125622e73debSGreg Roach        }
125722e73debSGreg Roach    }
125822e73debSGreg Roach
125922e73debSGreg Roach    /**
126022e73debSGreg Roach     * Work out whether this record can be shown to a user with a given access level
126122e73debSGreg Roach     *
126222e73debSGreg Roach     * @param int $access_level
126322e73debSGreg Roach     *
126422e73debSGreg Roach     * @return bool
126522e73debSGreg Roach     */
126622e73debSGreg Roach    private function canShowRecord(int $access_level): bool
126722e73debSGreg Roach    {
126822e73debSGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
126922e73debSGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
127022e73debSGreg Roach            return true;
127122e73debSGreg Roach        }
127222e73debSGreg Roach
127322e73debSGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
12741fe542e9SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
127522e73debSGreg Roach            return true;
127622e73debSGreg Roach        }
127722e73debSGreg Roach
127822e73debSGreg Roach        // Does this record have a RESN?
1279dec352c1SGreg Roach        if (str_contains($this->gedcom, "\n1 RESN confidential")) {
128022e73debSGreg Roach            return Auth::PRIV_NONE >= $access_level;
128122e73debSGreg Roach        }
1282dec352c1SGreg Roach        if (str_contains($this->gedcom, "\n1 RESN privacy")) {
128322e73debSGreg Roach            return Auth::PRIV_USER >= $access_level;
128422e73debSGreg Roach        }
1285dec352c1SGreg Roach        if (str_contains($this->gedcom, "\n1 RESN none")) {
128622e73debSGreg Roach            return true;
128722e73debSGreg Roach        }
128822e73debSGreg Roach
128922e73debSGreg Roach        // Does this record have a default RESN?
129022e73debSGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
129122e73debSGreg Roach        if (isset($individual_privacy[$this->xref()])) {
129222e73debSGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
129322e73debSGreg Roach        }
129422e73debSGreg Roach
129522e73debSGreg Roach        // Privacy rules do not apply to admins
129622e73debSGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
129722e73debSGreg Roach            return true;
129822e73debSGreg Roach        }
129922e73debSGreg Roach
130022e73debSGreg Roach        // Different types of record have different privacy rules
130122e73debSGreg Roach        return $this->canShowByType($access_level);
130222e73debSGreg Roach    }
13038091bfd1SGreg Roach
13048091bfd1SGreg Roach    /**
13058091bfd1SGreg Roach     * Lock the database row, to prevent concurrent edits.
13068091bfd1SGreg Roach     */
13078091bfd1SGreg Roach    public function lock(): void
13088091bfd1SGreg Roach    {
13098091bfd1SGreg Roach        DB::table('other')
13108091bfd1SGreg Roach            ->where('o_file', '=', $this->tree->id())
13118091bfd1SGreg Roach            ->where('o_id', '=', $this->xref())
13128091bfd1SGreg Roach            ->lockForUpdate()
13138091bfd1SGreg Roach            ->get();
13148091bfd1SGreg Roach    }
1315c2ed51d1SGreg Roach
1316c2ed51d1SGreg Roach    /**
1317c2ed51d1SGreg Roach     * Add blank lines, to allow a user to add/edit new values.
1318c2ed51d1SGreg Roach     *
1319c2ed51d1SGreg Roach     * @return string
1320c2ed51d1SGreg Roach     */
1321c2ed51d1SGreg Roach    public function insertMissingSubtags(): string
1322c2ed51d1SGreg Roach    {
1323c2ed51d1SGreg Roach        $gedcom = $this->insertMissingLevels($this->tag(), $this->gedcom());
1324c2ed51d1SGreg Roach
1325c2ed51d1SGreg Roach        return preg_replace('/^0.*\n/', '', $gedcom);
1326c2ed51d1SGreg Roach    }
1327c2ed51d1SGreg Roach
1328c2ed51d1SGreg Roach    /**
1329c2ed51d1SGreg Roach     * @param string $tag
1330c2ed51d1SGreg Roach     * @param string $gedcom
1331c2ed51d1SGreg Roach     *
1332c2ed51d1SGreg Roach     * @return string
1333c2ed51d1SGreg Roach     */
1334b5a3d330SGreg Roach    public function insertMissingLevels(string $tag, string $gedcom): string
1335c2ed51d1SGreg Roach    {
1336c2ed51d1SGreg Roach        $next_level = substr_count($tag, ':') + 1;
1337c2ed51d1SGreg Roach        $factory    = Registry::elementFactory();
13383d2c98d1SGreg Roach        $subtags    = $factory->make($tag)->subtags();
1339c2ed51d1SGreg Roach
1340c2ed51d1SGreg Roach        // The first part is level N (includes CONT records).  The remainder are level N+1.
1341c2ed51d1SGreg Roach        $parts  = preg_split('/\n(?=' . $next_level . ')/', $gedcom);
1342c2ed51d1SGreg Roach        $return = array_shift($parts);
1343c2ed51d1SGreg Roach
1344c2ed51d1SGreg Roach        foreach ($subtags as $subtag => $occurrences) {
1345c2ed51d1SGreg Roach            [$min, $max] = explode(':', $occurrences);
1346c2ed51d1SGreg Roach            if ($max === 'M') {
1347c2ed51d1SGreg Roach                $max = PHP_INT_MAX;
1348c2ed51d1SGreg Roach            } else {
1349c2ed51d1SGreg Roach                $max = (int) $max;
1350c2ed51d1SGreg Roach            }
1351c2ed51d1SGreg Roach
1352c2ed51d1SGreg Roach            $count = 0;
1353c2ed51d1SGreg Roach
1354c2ed51d1SGreg Roach            // Add expected subtags in our preferred order.
1355c2ed51d1SGreg Roach            foreach ($parts as $n => $part) {
1356c2ed51d1SGreg Roach                if (str_starts_with($part, $next_level . ' ' . $subtag)) {
1357c2ed51d1SGreg Roach                    $return .= "\n" . $this->insertMissingLevels($tag . ':' . $subtag, $part);
1358c2ed51d1SGreg Roach                    $count++;
1359c2ed51d1SGreg Roach                    unset($parts[$n]);
1360c2ed51d1SGreg Roach                }
1361c2ed51d1SGreg Roach            }
1362c2ed51d1SGreg Roach
1363c2ed51d1SGreg Roach            // Allowed to have more of this subtag?
1364c2ed51d1SGreg Roach            if ($count < $max) {
1365c2ed51d1SGreg Roach                // Create a new one.
1366c2ed51d1SGreg Roach                $gedcom  = $next_level . ' ' . $subtag;
1367c2ed51d1SGreg Roach                $default = $factory->make($tag . ':' . $subtag)->default($this->tree);
1368c2ed51d1SGreg Roach                if ($default !== '') {
1369c2ed51d1SGreg Roach                    $gedcom .= ' ' . $default;
1370c2ed51d1SGreg Roach                }
1371c2ed51d1SGreg Roach                $return .= "\n" . $this->insertMissingLevels($tag . ':' . $subtag, $gedcom);
1372c2ed51d1SGreg Roach            }
1373c2ed51d1SGreg Roach        }
1374c2ed51d1SGreg Roach
1375c2ed51d1SGreg Roach        // Now add any unexpected/existing data.
1376c2ed51d1SGreg Roach        if ($parts !== []) {
1377c2ed51d1SGreg Roach            $return .= "\n" . implode("\n", $parts);
1378c2ed51d1SGreg Roach        }
1379c2ed51d1SGreg Roach
1380c2ed51d1SGreg Roach        return $return;
1381c2ed51d1SGreg Roach    }
1382a25f0a04SGreg Roach}
1383