xref: /webtrees/app/GedcomRecord.php (revision 76d39c55735cfa9ad0972b0dd530e96b051f9ebe)
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;
24*76d39c55SGreg Roachuse Fisharebest\Webtrees\Contracts\TimestampInterface;
251fe542e9SGreg Roachuse Fisharebest\Webtrees\Contracts\UserInterface;
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;
33a25f0a04SGreg Roach
34b5961194SGreg Roachuse function addcslashes;
3522e73debSGreg Roachuse function app;
360f5fd22fSGreg Roachuse function array_combine;
370f5fd22fSGreg Roachuse function array_keys;
380f5fd22fSGreg Roachuse function array_map;
390f5fd22fSGreg Roachuse function array_search;
40f7440925SGreg Roachuse function array_shift;
41f7440925SGreg Roachuse function assert;
42f7440925SGreg Roachuse function count;
43f7440925SGreg Roachuse function date;
44f7440925SGreg Roachuse function e;
45f7440925SGreg Roachuse function explode;
46f7440925SGreg Roachuse function in_array;
47f7440925SGreg Roachuse function md5;
48f7440925SGreg Roachuse function preg_match;
49f7440925SGreg Roachuse function preg_match_all;
50f7440925SGreg Roachuse function preg_replace;
51f7440925SGreg Roachuse function preg_replace_callback;
52f7440925SGreg Roachuse function preg_split;
530f5fd22fSGreg Roachuse function range;
54f7440925SGreg Roachuse function route;
55dec352c1SGreg Roachuse function str_contains;
56d0889c63SGreg Roachuse function str_ends_with;
57f7440925SGreg Roachuse function str_pad;
58f7440925SGreg Roachuse function strtoupper;
59f7440925SGreg Roachuse function trim;
60b315f3e1SGreg Roachuse function view;
61b315f3e1SGreg Roach
62c2ed51d1SGreg Roachuse const PHP_INT_MAX;
63f7440925SGreg Roachuse const PREG_SET_ORDER;
64f7440925SGreg Roachuse const STR_PAD_LEFT;
6522e73debSGreg Roach
66a25f0a04SGreg Roach/**
6776692c8bSGreg Roach * A GEDCOM object.
68a25f0a04SGreg Roach */
69c1010edaSGreg Roachclass GedcomRecord
70c1010edaSGreg Roach{
7116d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
7216d6367aSGreg Roach
735818a371SGreg Roach    protected const ROUTE_NAME = GedcomRecordPage::class;
745818a371SGreg Roach
759599771eSGreg Roach    protected string $xref;
76bb03c9f0SGreg Roach
779599771eSGreg Roach    protected Tree $tree;
78bb03c9f0SGreg Roach
799599771eSGreg Roach    // GEDCOM data (before any pending edits)
809599771eSGreg Roach    protected string $gedcom;
81bb03c9f0SGreg Roach
829599771eSGreg Roach    // GEDCOM data (after any pending edits)
839599771eSGreg Roach    protected ?string $pending;
84bb03c9f0SGreg Roach
859599771eSGreg Roach    /** @var array<Fact> Facts extracted from $gedcom/$pending */
869599771eSGreg Roach    protected array $facts;
87bb03c9f0SGreg Roach
8809482a55SGreg Roach    /** @var array<array<string>> All the names of this individual */
899599771eSGreg Roach    protected array $getAllNames = [];
90bb03c9f0SGreg Roach
9122e73debSGreg Roach    /** @var int|null Cached result */
929599771eSGreg Roach    private ?int $getPrimaryName = null;
93c4943cffSGreg Roach
9422e73debSGreg Roach    /** @var int|null Cached result */
959599771eSGreg Roach    private ?int $getSecondaryName = null;
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;
1129599771eSGreg Roach        $this->facts   = $this->parseFacts();
113a25f0a04SGreg Roach    }
114a25f0a04SGreg Roach
115a25f0a04SGreg Roach    /**
116886b77daSGreg Roach     * A closure which will filter out private records.
117886b77daSGreg Roach     *
118886b77daSGreg Roach     * @return Closure
119886b77daSGreg Roach     */
1204146fabcSGreg Roach    public static function accessFilter(): Closure
121886b77daSGreg Roach    {
1226c2179e2SGreg Roach        return static function (GedcomRecord $record): bool {
123886b77daSGreg Roach            return $record->canShow();
124886b77daSGreg Roach        };
125886b77daSGreg Roach    }
126886b77daSGreg Roach
127886b77daSGreg Roach    /**
128c156e8f5SGreg Roach     * A closure which will compare records by name.
129c156e8f5SGreg Roach     *
130c156e8f5SGreg Roach     * @return Closure
131c156e8f5SGreg Roach     */
132c156e8f5SGreg Roach    public static function nameComparator(): Closure
133c156e8f5SGreg Roach    {
1346c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y): int {
135c156e8f5SGreg Roach            if ($x->canShowName()) {
136c156e8f5SGreg Roach                if ($y->canShowName()) {
13737646143SGreg Roach                    return I18N::comparator()($x->sortName(), $y->sortName());
138c156e8f5SGreg Roach                }
139c156e8f5SGreg Roach
140c156e8f5SGreg Roach                return -1; // only $y is private
141c156e8f5SGreg Roach            }
142c156e8f5SGreg Roach
143c156e8f5SGreg Roach            if ($y->canShowName()) {
144c156e8f5SGreg Roach                return 1; // only $x is private
145c156e8f5SGreg Roach            }
146c156e8f5SGreg Roach
147c156e8f5SGreg Roach            return 0; // both $x and $y private
148c156e8f5SGreg Roach        };
149c156e8f5SGreg Roach    }
150c156e8f5SGreg Roach
151c156e8f5SGreg Roach    /**
152c156e8f5SGreg Roach     * A closure which will compare records by change time.
153c156e8f5SGreg Roach     *
154c156e8f5SGreg Roach     * @param int $direction +1 to sort ascending, -1 to sort descending
155c156e8f5SGreg Roach     *
156c156e8f5SGreg Roach     * @return Closure
157c156e8f5SGreg Roach     */
158c156e8f5SGreg Roach    public static function lastChangeComparator(int $direction = 1): Closure
159c156e8f5SGreg Roach    {
1606c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
1614459dc9aSGreg Roach            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
162c156e8f5SGreg Roach        };
163c156e8f5SGreg Roach    }
164c156e8f5SGreg Roach
165c156e8f5SGreg Roach    /**
16602467d32SGreg Roach     * Get the GEDCOM tag for this record.
16702467d32SGreg Roach     *
16802467d32SGreg Roach     * @return string
16902467d32SGreg Roach     */
17002467d32SGreg Roach    public function tag(): string
17102467d32SGreg Roach    {
17202467d32SGreg Roach        preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
17302467d32SGreg Roach
17402467d32SGreg Roach        return $match[1] ?? static::RECORD_TYPE;
17502467d32SGreg Roach    }
17602467d32SGreg Roach
17702467d32SGreg Roach    /**
178a25f0a04SGreg Roach     * Get the XREF for this record
179a25f0a04SGreg Roach     *
180a25f0a04SGreg Roach     * @return string
181a25f0a04SGreg Roach     */
182c0935879SGreg Roach    public function xref(): string
183c1010edaSGreg Roach    {
184a25f0a04SGreg Roach        return $this->xref;
185a25f0a04SGreg Roach    }
186a25f0a04SGreg Roach
187a25f0a04SGreg Roach    /**
188000959d9SGreg Roach     * Get the tree to which this record belongs
189000959d9SGreg Roach     *
190000959d9SGreg Roach     * @return Tree
191000959d9SGreg Roach     */
192f4afa648SGreg Roach    public function tree(): Tree
193c1010edaSGreg Roach    {
194518bbdc1SGreg Roach        return $this->tree;
195000959d9SGreg Roach    }
196000959d9SGreg Roach
197000959d9SGreg Roach    /**
198a25f0a04SGreg Roach     * Application code should access data via Fact objects.
199a25f0a04SGreg Roach     * This function exists to support old code.
200a25f0a04SGreg Roach     *
201a25f0a04SGreg Roach     * @return string
202a25f0a04SGreg Roach     */
203e364afe4SGreg Roach    public function gedcom(): string
204c1010edaSGreg Roach    {
205b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
206a25f0a04SGreg Roach    }
207a25f0a04SGreg Roach
208a25f0a04SGreg Roach    /**
209a25f0a04SGreg Roach     * Does this record have a pending change?
210a25f0a04SGreg Roach     *
211cbc1590aSGreg Roach     * @return bool
212a25f0a04SGreg Roach     */
2138f53f488SRico Sonntag    public function isPendingAddition(): bool
214c1010edaSGreg Roach    {
215a25f0a04SGreg Roach        return $this->pending !== null;
216a25f0a04SGreg Roach    }
217a25f0a04SGreg Roach
218a25f0a04SGreg Roach    /**
219a25f0a04SGreg Roach     * Does this record have a pending deletion?
220a25f0a04SGreg Roach     *
221cbc1590aSGreg Roach     * @return bool
222a25f0a04SGreg Roach     */
2238f53f488SRico Sonntag    public function isPendingDeletion(): bool
224c1010edaSGreg Roach    {
225a25f0a04SGreg Roach        return $this->pending === '';
226a25f0a04SGreg Roach    }
227a25f0a04SGreg Roach
228a25f0a04SGreg Roach    /**
229225e381fSGreg Roach     * Generate a URL to this record.
230a25f0a04SGreg Roach     *
231a25f0a04SGreg Roach     * @return string
232a25f0a04SGreg Roach     */
2338f53f488SRico Sonntag    public function url(): string
234c1010edaSGreg Roach    {
235225e381fSGreg Roach        return route(static::ROUTE_NAME, [
236c0935879SGreg Roach            'xref' => $this->xref(),
237ee4364daSGreg Roach            'tree' => $this->tree->name(),
238194b0938SGreg Roach            'slug' => Registry::slugFactory()->make($this),
239225e381fSGreg Roach        ]);
240a25f0a04SGreg Roach    }
241a25f0a04SGreg Roach
242a25f0a04SGreg Roach    /**
243a25f0a04SGreg Roach     * Can the details of this record be shown?
244a25f0a04SGreg Roach     *
245cbc1590aSGreg Roach     * @param int|null $access_level
246a25f0a04SGreg Roach     *
247cbc1590aSGreg Roach     * @return bool
248a25f0a04SGreg Roach     */
24935584196SGreg Roach    public function canShow(int $access_level = null): bool
250c1010edaSGreg Roach    {
251f0b9c048SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
2524b9ff166SGreg Roach
253a25f0a04SGreg Roach        // We use this value to bypass privacy checks. For example,
254a25f0a04SGreg Roach        // when downloading data or when calculating privacy itself.
255f0b9c048SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
256a25f0a04SGreg Roach            return true;
257a25f0a04SGreg Roach        }
258f0b9c048SGreg Roach
2597476e8a5SGreg Roach        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
260f0b9c048SGreg Roach
2616b9cb339SGreg Roach        return Registry::cache()->array()->remember($cache_key, function () use ($access_level) {
262f0b9c048SGreg Roach            return $this->canShowRecord($access_level);
263f0b9c048SGreg Roach        });
264a25f0a04SGreg Roach    }
265a25f0a04SGreg Roach
266a25f0a04SGreg Roach    /**
267a25f0a04SGreg Roach     * Can the name of this record be shown?
268a25f0a04SGreg Roach     *
269cbc1590aSGreg Roach     * @param int|null $access_level
270a25f0a04SGreg Roach     *
271cbc1590aSGreg Roach     * @return bool
272a25f0a04SGreg Roach     */
27376f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
274c1010edaSGreg Roach    {
275a25f0a04SGreg Roach        return $this->canShow($access_level);
276a25f0a04SGreg Roach    }
277a25f0a04SGreg Roach
278a25f0a04SGreg Roach    /**
279a25f0a04SGreg Roach     * Can we edit this record?
280a25f0a04SGreg Roach     *
281cbc1590aSGreg Roach     * @return bool
282a25f0a04SGreg Roach     */
2838f53f488SRico Sonntag    public function canEdit(): bool
284c1010edaSGreg Roach    {
2851450f098SGreg Roach        if ($this->isPendingDeletion()) {
2861450f098SGreg Roach            return false;
2871450f098SGreg Roach        }
2881450f098SGreg Roach
2891450f098SGreg Roach        if (Auth::isManager($this->tree)) {
2901450f098SGreg Roach            return true;
2911450f098SGreg Roach        }
2921450f098SGreg Roach
293dec352c1SGreg Roach        return Auth::isEditor($this->tree) && !str_contains($this->gedcom, "\n1 RESN locked");
294a25f0a04SGreg Roach    }
295a25f0a04SGreg Roach
296a25f0a04SGreg Roach    /**
297a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
298a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
299a25f0a04SGreg Roach     *
300cbc1590aSGreg Roach     * @param int $access_level
301a25f0a04SGreg Roach     *
302a25f0a04SGreg Roach     * @return string
303a25f0a04SGreg Roach     */
304e364afe4SGreg Roach    public function privatizeGedcom(int $access_level): string
305c1010edaSGreg Roach    {
306e364afe4SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
307a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
308a25f0a04SGreg Roach            return $this->gedcom;
309b2ce94c6SRico Sonntag        }
310b2ce94c6SRico Sonntag
311b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
312a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
313a25f0a04SGreg Roach
314a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
315dc141db3SGreg Roach            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
316a25f0a04SGreg Roach
317a25f0a04SGreg Roach            // Check each of the facts for access
3188d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
319138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
320a25f0a04SGreg Roach            }
321cbc1590aSGreg Roach
322a25f0a04SGreg Roach            return $gedrec;
323b2ce94c6SRico Sonntag        }
324b2ce94c6SRico Sonntag
325a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
326a25f0a04SGreg Roach        // limited data, such as links to other records.
327a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
328a25f0a04SGreg Roach    }
329a25f0a04SGreg Roach
330a25f0a04SGreg Roach    /**
331a25f0a04SGreg Roach     * Default for "other" object types
332c7ff4153SGreg Roach     *
333c7ff4153SGreg Roach     * @return void
334a25f0a04SGreg Roach     */
335e364afe4SGreg Roach    public function extractNames(): void
336c1010edaSGreg Roach    {
33776f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
338a25f0a04SGreg Roach    }
339a25f0a04SGreg Roach
340a25f0a04SGreg Roach    /**
341a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
342a25f0a04SGreg Roach     *
343870ec5a3SGreg Roach     * @return array<int,array<string,string>>
344a25f0a04SGreg Roach     */
3458f53f488SRico Sonntag    public function getAllNames(): array
346c1010edaSGreg Roach    {
3479599771eSGreg Roach        if ($this->getAllNames === []) {
348a25f0a04SGreg Roach            if ($this->canShowName()) {
349a25f0a04SGreg Roach                // Ask the record to extract its names
350a25f0a04SGreg Roach                $this->extractNames();
351a25f0a04SGreg Roach                // No name found? Use a fallback.
352ec124fd2SGreg Roach                if ($this->getAllNames === []) {
353db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
354a25f0a04SGreg Roach                }
355a25f0a04SGreg Roach            } else {
356db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
357a25f0a04SGreg Roach            }
358a25f0a04SGreg Roach        }
359cbc1590aSGreg Roach
360bdb3725aSGreg Roach        return $this->getAllNames;
361a25f0a04SGreg Roach    }
362a25f0a04SGreg Roach
363a25f0a04SGreg Roach    /**
364a25f0a04SGreg Roach     * If this object has no name, what do we call it?
365a25f0a04SGreg Roach     *
366a25f0a04SGreg Roach     * @return string
367a25f0a04SGreg Roach     */
3688f53f488SRico Sonntag    public function getFallBackName(): string
369c1010edaSGreg Roach    {
370c0935879SGreg Roach        return e($this->xref());
371a25f0a04SGreg Roach    }
372a25f0a04SGreg Roach
373a25f0a04SGreg Roach    /**
374a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
375a25f0a04SGreg Roach     *
376cbc1590aSGreg Roach     * @return int
377a25f0a04SGreg Roach     */
3788f53f488SRico Sonntag    public function getPrimaryName(): int
379c1010edaSGreg Roach    {
380a25f0a04SGreg Roach        static $language_script;
381a25f0a04SGreg Roach
382448d466cSGreg Roach        $language_script ??= I18N::locale()->script()->code();
383a25f0a04SGreg Roach
384bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
385a25f0a04SGreg Roach            // Generally, the first name is the primary one....
386bdb3725aSGreg Roach            $this->getPrimaryName = 0;
387a25f0a04SGreg Roach            // ...except when the language/name use different character sets
388a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
38969546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
390bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
391a25f0a04SGreg Roach                    break;
392a25f0a04SGreg Roach                }
393a25f0a04SGreg Roach            }
394a25f0a04SGreg Roach        }
395a25f0a04SGreg Roach
396bdb3725aSGreg Roach        return $this->getPrimaryName;
397a25f0a04SGreg Roach    }
398a25f0a04SGreg Roach
399a25f0a04SGreg Roach    /**
400a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
401a25f0a04SGreg Roach     *
402cbc1590aSGreg Roach     * @return int
403a25f0a04SGreg Roach     */
4048f53f488SRico Sonntag    public function getSecondaryName(): int
405c1010edaSGreg Roach    {
4068f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
407a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
408bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
409a25f0a04SGreg Roach            // ....except when there are names with different character sets
410a25f0a04SGreg Roach            $all_names = $this->getAllNames();
411a25f0a04SGreg Roach            if (count($all_names) > 1) {
412a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
413a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
414e364afe4SGreg Roach                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
415bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
416a25f0a04SGreg Roach                        break;
417a25f0a04SGreg Roach                    }
418a25f0a04SGreg Roach                }
419a25f0a04SGreg Roach            }
420a25f0a04SGreg Roach        }
421cbc1590aSGreg Roach
422bdb3725aSGreg Roach        return $this->getSecondaryName;
423a25f0a04SGreg Roach    }
424a25f0a04SGreg Roach
425a25f0a04SGreg Roach    /**
426a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
427a25f0a04SGreg Roach     *
42876f666f4SGreg Roach     * @param int|null $n
4297e96c925SGreg Roach     *
4307e96c925SGreg Roach     * @return void
431a25f0a04SGreg Roach     */
432e364afe4SGreg Roach    public function setPrimaryName(int $n = null): void
433c1010edaSGreg Roach    {
434bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
435bdb3725aSGreg Roach        $this->getSecondaryName = null;
436a25f0a04SGreg Roach    }
437a25f0a04SGreg Roach
438a25f0a04SGreg Roach    /**
439a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
440a25f0a04SGreg Roach     *
441a25f0a04SGreg Roach     * @return string
442a25f0a04SGreg Roach     */
44324f2a3afSGreg Roach    public function __toString(): string
444c1010edaSGreg Roach    {
44572cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
446a25f0a04SGreg Roach    }
447a25f0a04SGreg Roach
448a25f0a04SGreg Roach    /**
449c156e8f5SGreg Roach     * /**
450a25f0a04SGreg Roach     * Get variants of the name
451a25f0a04SGreg Roach     *
452a25f0a04SGreg Roach     * @return string
453a25f0a04SGreg Roach     */
454e364afe4SGreg Roach    public function fullName(): string
455c1010edaSGreg Roach    {
456a25f0a04SGreg Roach        if ($this->canShowName()) {
457a25f0a04SGreg Roach            $tmp = $this->getAllNames();
458cbc1590aSGreg Roach
459a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
460a25f0a04SGreg Roach        }
461b2ce94c6SRico Sonntag
462b2ce94c6SRico Sonntag        return I18N::translate('Private');
463a25f0a04SGreg Roach    }
464a25f0a04SGreg Roach
465a25f0a04SGreg Roach    /**
466a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
467a25f0a04SGreg Roach     *
468a25f0a04SGreg Roach     * @return string
469a25f0a04SGreg Roach     */
47039ca88baSGreg Roach    public function sortName(): string
471c1010edaSGreg Roach    {
472a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
473a25f0a04SGreg Roach        $tmp = $this->getAllNames();
474cbc1590aSGreg Roach
475a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
476a25f0a04SGreg Roach    }
477a25f0a04SGreg Roach
478a25f0a04SGreg Roach    /**
479a25f0a04SGreg Roach     * Get the full name in an alternative character set
480a25f0a04SGreg Roach     *
481e364afe4SGreg Roach     * @return string|null
482a25f0a04SGreg Roach     */
483e364afe4SGreg Roach    public function alternateName(): ?string
484c1010edaSGreg Roach    {
485e364afe4SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
486a25f0a04SGreg Roach            $all_names = $this->getAllNames();
487cbc1590aSGreg Roach
488a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
489a25f0a04SGreg Roach        }
490b2ce94c6SRico Sonntag
491b2ce94c6SRico Sonntag        return null;
492a25f0a04SGreg Roach    }
493a25f0a04SGreg Roach
494a25f0a04SGreg Roach    /**
495a25f0a04SGreg Roach     * Format this object for display in a list
496a25f0a04SGreg Roach     *
497a25f0a04SGreg Roach     * @return string
498a25f0a04SGreg Roach     */
4998f53f488SRico Sonntag    public function formatList(): string
500c1010edaSGreg Roach    {
501b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
50239ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
503a25f0a04SGreg Roach        $html .= $this->formatListDetails();
504b165e17cSGreg Roach        $html .= '</a>';
505cbc1590aSGreg Roach
506a25f0a04SGreg Roach        return $html;
507a25f0a04SGreg Roach    }
508a25f0a04SGreg Roach
509a25f0a04SGreg Roach    /**
510a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
511a25f0a04SGreg Roach     * identifying characteristics of this record.
512a25f0a04SGreg Roach     *
513a25f0a04SGreg Roach     * @return string
514a25f0a04SGreg Roach     */
5158f53f488SRico Sonntag    public function formatListDetails(): string
516c1010edaSGreg Roach    {
517a25f0a04SGreg Roach        return '';
518a25f0a04SGreg Roach    }
519a25f0a04SGreg Roach
520a25f0a04SGreg Roach    /**
521a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
522a25f0a04SGreg Roach     *
52309482a55SGreg Roach     * @param array<string> $facts
524cbc1590aSGreg Roach     * @param int           $style
525a25f0a04SGreg Roach     *
526a25f0a04SGreg Roach     * @return string
527a25f0a04SGreg Roach     */
5288d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
529c1010edaSGreg Roach    {
53030158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
531a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
532e364afe4SGreg Roach            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
533d93f11b5SGreg Roach                $joiner = ' — ';
534d93f11b5SGreg Roach            } else {
535d93f11b5SGreg Roach                $joiner = '';
536d93f11b5SGreg Roach            }
537e364afe4SGreg Roach            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
538a25f0a04SGreg Roach                switch ($style) {
539a25f0a04SGreg Roach                    case 1:
540b315f3e1SGreg Roach                        return '<br><em>' . $event->label() . ' ' . view('fact-date', ['cal_link' => 'false', 'fact' => $event, 'record' => $event->record(), 'time' => false]) . '</em>';
541a25f0a04SGreg Roach                    case 2:
542b315f3e1SGreg 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>';
543a25f0a04SGreg Roach                }
544a25f0a04SGreg Roach            }
545a25f0a04SGreg Roach        }
546cbc1590aSGreg Roach
547a25f0a04SGreg Roach        return '';
548a25f0a04SGreg Roach    }
549a25f0a04SGreg Roach
550a25f0a04SGreg Roach    /**
551a25f0a04SGreg Roach     * Find individuals linked to this record.
552a25f0a04SGreg Roach     *
553a25f0a04SGreg Roach     * @param string $link
554a25f0a04SGreg Roach     *
55536779af1SGreg Roach     * @return Collection<int,Individual>
556a25f0a04SGreg Roach     */
557907c1109SGreg Roach    public function linkedIndividuals(string $link): Collection
558c1010edaSGreg Roach    {
559907c1109SGreg Roach        return DB::table('individuals')
5600b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
561907c1109SGreg Roach                $join
562907c1109SGreg Roach                    ->on('l_file', '=', 'i_file')
563907c1109SGreg Roach                    ->on('l_from', '=', 'i_id');
564ba1c12e8SGreg Roach            })
565ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
566ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
567ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
568907c1109SGreg Roach            ->select(['individuals.*'])
569907c1109SGreg Roach            ->get()
5706b9cb339SGreg Roach            ->map(Registry::individualFactory()->mapper($this->tree))
571907c1109SGreg Roach            ->filter(self::accessFilter());
572a25f0a04SGreg Roach    }
573a25f0a04SGreg Roach
574a25f0a04SGreg Roach    /**
575a25f0a04SGreg Roach     * Find families linked to this record.
576a25f0a04SGreg Roach     *
577a25f0a04SGreg Roach     * @param string $link
578a25f0a04SGreg Roach     *
57936779af1SGreg Roach     * @return Collection<int,Family>
580a25f0a04SGreg Roach     */
581907c1109SGreg Roach    public function linkedFamilies(string $link): Collection
582c1010edaSGreg Roach    {
583907c1109SGreg Roach        return DB::table('families')
5840b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
585907c1109SGreg Roach                $join
586907c1109SGreg Roach                    ->on('l_file', '=', 'f_file')
587907c1109SGreg Roach                    ->on('l_from', '=', 'f_id');
588ba1c12e8SGreg Roach            })
589ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
590ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
591ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
592907c1109SGreg Roach            ->select(['families.*'])
593907c1109SGreg Roach            ->get()
5946b9cb339SGreg Roach            ->map(Registry::familyFactory()->mapper($this->tree))
595907c1109SGreg Roach            ->filter(self::accessFilter());
596a25f0a04SGreg Roach    }
597a25f0a04SGreg Roach
598a25f0a04SGreg Roach    /**
599a25f0a04SGreg Roach     * Find sources linked to this record.
600a25f0a04SGreg Roach     *
601a25f0a04SGreg Roach     * @param string $link
602a25f0a04SGreg Roach     *
60336779af1SGreg Roach     * @return Collection<int,Source>
604a25f0a04SGreg Roach     */
605907c1109SGreg Roach    public function linkedSources(string $link): Collection
606c1010edaSGreg Roach    {
607907c1109SGreg Roach        return DB::table('sources')
6080b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
609907c1109SGreg Roach                $join
610907c1109SGreg Roach                    ->on('l_file', '=', 's_file')
611907c1109SGreg Roach                    ->on('l_from', '=', 's_id');
612ba1c12e8SGreg Roach            })
613ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
614ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
615ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
616907c1109SGreg Roach            ->select(['sources.*'])
617907c1109SGreg Roach            ->get()
6186b9cb339SGreg Roach            ->map(Registry::sourceFactory()->mapper($this->tree))
619907c1109SGreg Roach            ->filter(self::accessFilter());
620a25f0a04SGreg Roach    }
621a25f0a04SGreg Roach
622a25f0a04SGreg Roach    /**
623a25f0a04SGreg Roach     * Find media objects linked to this record.
624a25f0a04SGreg Roach     *
625a25f0a04SGreg Roach     * @param string $link
626a25f0a04SGreg Roach     *
62736779af1SGreg Roach     * @return Collection<int,Media>
628a25f0a04SGreg Roach     */
629907c1109SGreg Roach    public function linkedMedia(string $link): Collection
630c1010edaSGreg Roach    {
631907c1109SGreg Roach        return DB::table('media')
6320b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
633907c1109SGreg Roach                $join
634907c1109SGreg Roach                    ->on('l_file', '=', 'm_file')
635907c1109SGreg Roach                    ->on('l_from', '=', 'm_id');
636ba1c12e8SGreg Roach            })
637ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
638ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
639ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
640907c1109SGreg Roach            ->select(['media.*'])
641907c1109SGreg Roach            ->get()
6426b9cb339SGreg Roach            ->map(Registry::mediaFactory()->mapper($this->tree))
643907c1109SGreg Roach            ->filter(self::accessFilter());
644a25f0a04SGreg Roach    }
645a25f0a04SGreg Roach
646a25f0a04SGreg Roach    /**
647a25f0a04SGreg Roach     * Find notes linked to this record.
648a25f0a04SGreg Roach     *
649a25f0a04SGreg Roach     * @param string $link
650a25f0a04SGreg Roach     *
65136779af1SGreg Roach     * @return Collection<int,Note>
652a25f0a04SGreg Roach     */
653907c1109SGreg Roach    public function linkedNotes(string $link): Collection
654c1010edaSGreg Roach    {
655907c1109SGreg Roach        return DB::table('other')
6560b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
657907c1109SGreg Roach                $join
658907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
659907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
660ba1c12e8SGreg Roach            })
661ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
6627a8cbeebSGreg Roach            ->where('o_type', '=', Note::RECORD_TYPE)
663ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
664ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
665907c1109SGreg Roach            ->select(['other.*'])
666907c1109SGreg Roach            ->get()
6676b9cb339SGreg Roach            ->map(Registry::noteFactory()->mapper($this->tree))
668907c1109SGreg Roach            ->filter(self::accessFilter());
669a25f0a04SGreg Roach    }
670a25f0a04SGreg Roach
671a25f0a04SGreg Roach    /**
672a25f0a04SGreg Roach     * Find repositories linked to this record.
673a25f0a04SGreg Roach     *
674a25f0a04SGreg Roach     * @param string $link
675a25f0a04SGreg Roach     *
67636779af1SGreg Roach     * @return Collection<int,Repository>
677a25f0a04SGreg Roach     */
678907c1109SGreg Roach    public function linkedRepositories(string $link): Collection
679c1010edaSGreg Roach    {
680907c1109SGreg Roach        return DB::table('other')
6810b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
682907c1109SGreg Roach                $join
683907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
684907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
685ba1c12e8SGreg Roach            })
686ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
6877a8cbeebSGreg Roach            ->where('o_type', '=', Repository::RECORD_TYPE)
688ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
689ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
690907c1109SGreg Roach            ->select(['other.*'])
691907c1109SGreg Roach            ->get()
6926b9cb339SGreg Roach            ->map(Registry::repositoryFactory()->mapper($this->tree))
693907c1109SGreg Roach            ->filter(self::accessFilter());
694a25f0a04SGreg Roach    }
695a25f0a04SGreg Roach
696a25f0a04SGreg Roach    /**
69736254e3dSRichard Cissée     * Find locations linked to this record.
69836254e3dSRichard Cissée     *
69936254e3dSRichard Cissée     * @param string $link
70036254e3dSRichard Cissée     *
70136779af1SGreg Roach     * @return Collection<int,Location>
70236254e3dSRichard Cissée     */
70336254e3dSRichard Cissée    public function linkedLocations(string $link): Collection
70436254e3dSRichard Cissée    {
70536254e3dSRichard Cissée        return DB::table('other')
70636254e3dSRichard Cissée            ->join('link', static function (JoinClause $join): void {
70736254e3dSRichard Cissée                $join
70836254e3dSRichard Cissée                    ->on('l_file', '=', 'o_file')
70936254e3dSRichard Cissée                    ->on('l_from', '=', 'o_id');
71036254e3dSRichard Cissée            })
71136254e3dSRichard Cissée            ->where('o_file', '=', $this->tree->id())
7127a8cbeebSGreg Roach            ->where('o_type', '=', Location::RECORD_TYPE)
71336254e3dSRichard Cissée            ->where('l_type', '=', $link)
71436254e3dSRichard Cissée            ->where('l_to', '=', $this->xref)
71536254e3dSRichard Cissée            ->select(['other.*'])
71636254e3dSRichard Cissée            ->get()
7176b9cb339SGreg Roach            ->map(Registry::locationFactory()->mapper($this->tree))
71836254e3dSRichard Cissée            ->filter(self::accessFilter());
71936254e3dSRichard Cissée    }
72036254e3dSRichard Cissée
72136254e3dSRichard Cissée    /**
722a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
723a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
724a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
725a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
726a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
727a25f0a04SGreg Roach     *
72809482a55SGreg Roach     * @param array<string> $events
729a25f0a04SGreg Roach     *
73009482a55SGreg Roach     * @return array<Date>
731a25f0a04SGreg Roach     */
7328d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
733c1010edaSGreg Roach    {
73413abd6f3SGreg Roach        $dates = [];
7351385b8caSGreg Roach        foreach ($this->facts($events, false, null, true) as $event) {
7362decada7SGreg Roach            if ($event->date()->isOK()) {
7372decada7SGreg Roach                $dates[] = $event->date();
738a25f0a04SGreg Roach            }
739a25f0a04SGreg Roach        }
740a25f0a04SGreg Roach
741a25f0a04SGreg Roach        return $dates;
742a25f0a04SGreg Roach    }
743a25f0a04SGreg Roach
744a25f0a04SGreg Roach    /**
745a25f0a04SGreg Roach     * Get all the places for a particular type of event
746a25f0a04SGreg Roach     *
74709482a55SGreg Roach     * @param array<string> $events
748a25f0a04SGreg Roach     *
74909482a55SGreg Roach     * @return array<Place>
750a25f0a04SGreg Roach     */
7518d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
752c1010edaSGreg Roach    {
75313abd6f3SGreg Roach        $places = [];
7548d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
755138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
756a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
75716d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
758a25f0a04SGreg Roach                }
759a25f0a04SGreg Roach            }
760a25f0a04SGreg Roach        }
761a25f0a04SGreg Roach
762a25f0a04SGreg Roach        return $places;
763a25f0a04SGreg Roach    }
764a25f0a04SGreg Roach
765a25f0a04SGreg Roach    /**
766a25f0a04SGreg Roach     * The facts and events for this record.
767a25f0a04SGreg Roach     *
76809482a55SGreg Roach     * @param array<string> $filter
769cbc1590aSGreg Roach     * @param bool          $sort
770cbc1590aSGreg Roach     * @param int|null      $access_level
771ce42304aSGreg Roach     * @param bool          $ignore_deleted
772a25f0a04SGreg Roach     *
77336779af1SGreg Roach     * @return Collection<int,Fact>
774a25f0a04SGreg Roach     */
775ce42304aSGreg Roach    public function facts(
776ce42304aSGreg Roach        array $filter = [],
777ce42304aSGreg Roach        bool $sort = false,
778ce42304aSGreg Roach        int $access_level = null,
779ce42304aSGreg Roach        bool $ignore_deleted = false
780ce42304aSGreg Roach    ): Collection {
781d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
7824b9ff166SGreg Roach
783d0889c63SGreg Roach        // Convert BIRT into INDI:BIRT, etc.
784d0889c63SGreg Roach        $filter = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, $filter);
785d0889c63SGreg Roach
7868af3e5c1SGreg Roach        $facts = new Collection();
787ce42304aSGreg Roach        if ($this->canShow($access_level)) {
788a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
789d0889c63SGreg Roach                if (($filter === [] || in_array($fact->tag(), $filter, true)) && $fact->canShow($access_level)) {
7908af3e5c1SGreg Roach                    $facts->push($fact);
791a25f0a04SGreg Roach                }
792a25f0a04SGreg Roach            }
793a25f0a04SGreg Roach        }
794d17d7b9eSGreg Roach
795a25f0a04SGreg Roach        if ($sort) {
7960f5fd22fSGreg Roach            switch ($this->tag()) {
7970f5fd22fSGreg Roach                case Family::RECORD_TYPE:
7980f5fd22fSGreg Roach                case Individual::RECORD_TYPE:
799580a4d11SGreg Roach                    $facts = Fact::sortFacts($facts);
8000f5fd22fSGreg Roach                    break;
8010f5fd22fSGreg Roach
8020f5fd22fSGreg Roach                default:
8030f5fd22fSGreg Roach                    $subtags = Registry::elementFactory()->make($this->tag())->subtags();
8040f5fd22fSGreg Roach                    $subtags = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, array_keys($subtags));
8050f5fd22fSGreg Roach                    $subtags = array_combine(range(1, count($subtags)), $subtags);
8060f5fd22fSGreg Roach
8070f5fd22fSGreg Roach                    $facts = $facts
8080f5fd22fSGreg Roach                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
8090f5fd22fSGreg Roach                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
8100f5fd22fSGreg Roach                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
8110f5fd22fSGreg Roach
8120f5fd22fSGreg Roach                            return $sort_x <=> $sort_y;
8130f5fd22fSGreg Roach                        });
8140f5fd22fSGreg Roach                    break;
8150f5fd22fSGreg Roach            }
816a25f0a04SGreg Roach        }
817cbc1590aSGreg Roach
818ce42304aSGreg Roach        if ($ignore_deleted) {
819ce42304aSGreg Roach            $facts = $facts->filter(static function (Fact $fact): bool {
820ce42304aSGreg Roach                return !$fact->isPendingDeletion();
821ce42304aSGreg Roach            });
822ce42304aSGreg Roach        }
823ce42304aSGreg Roach
8245fef3bfaSGreg Roach        return $facts;
825a25f0a04SGreg Roach    }
826a25f0a04SGreg Roach
827a25f0a04SGreg Roach    /**
8280f5fd22fSGreg Roach     * @return array<string,string>
8290f5fd22fSGreg Roach     */
8300f5fd22fSGreg Roach    public function missingFacts(): array
8310f5fd22fSGreg Roach    {
8320f5fd22fSGreg Roach        $missing_facts = [];
8330f5fd22fSGreg Roach
8340f5fd22fSGreg Roach        foreach (Registry::elementFactory()->make($this->tag())->subtags() as $subtag => $repeat) {
8350f5fd22fSGreg Roach            [, $max] = explode(':', $repeat);
8360f5fd22fSGreg Roach            $max = $max === 'M' ? PHP_INT_MAX : (int) $max;
8370f5fd22fSGreg Roach
83898f93f3aSGreg Roach            if ($this->facts([$subtag], false, null, true)->count() < $max) {
8390f5fd22fSGreg Roach                $missing_facts[$subtag] = $subtag;
8400f5fd22fSGreg Roach                $missing_facts[$subtag] = Registry::elementFactory()->make($this->tag() . ':' . $subtag)->label();
8410f5fd22fSGreg Roach            }
8420f5fd22fSGreg Roach        }
8430f5fd22fSGreg Roach
8440f5fd22fSGreg Roach        uasort($missing_facts, I18N::comparator());
8450f5fd22fSGreg Roach
8465416d6ddSGreg Roach        if (!Auth::canUploadMedia($this->tree, Auth::user())) {
8470f5fd22fSGreg Roach            unset($missing_facts['OBJE']);
8480f5fd22fSGreg Roach        }
8490f5fd22fSGreg Roach
8500f5fd22fSGreg Roach        // We have special code for this.
8510f5fd22fSGreg Roach        unset($missing_facts['FILE']);
8520f5fd22fSGreg Roach
8530f5fd22fSGreg Roach        return $missing_facts;
8540f5fd22fSGreg Roach    }
8550f5fd22fSGreg Roach
8560f5fd22fSGreg Roach    /**
8574459dc9aSGreg Roach     * Get the last-change timestamp for this record
858a25f0a04SGreg Roach     *
859*76d39c55SGreg Roach     * @return TimestampInterface
860a25f0a04SGreg Roach     */
861*76d39c55SGreg Roach    public function lastChangeTimestamp(): TimestampInterface
862c1010edaSGreg Roach    {
8634459dc9aSGreg Roach        /** @var Fact|null $chan */
864820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
865a25f0a04SGreg Roach
8664459dc9aSGreg Roach        if ($chan instanceof Fact) {
867a25f0a04SGreg Roach            // The record does have a CHAN event
868d97083feSGreg Roach            $d = $chan->date()->minimumDate()->format('%Y-%m-%d');
8694459dc9aSGreg Roach
870d97083feSGreg Roach            if (preg_match('/\n3 TIME( (\d\d):(\d\d):(\d\d))/', $chan->gedcom(), $match)) {
871d97083feSGreg Roach                return Registry::timestampFactory()->fromString($d . $match[1], 'Y-m-d H:i:s');
872e364afe4SGreg Roach            }
873e364afe4SGreg Roach
874d97083feSGreg Roach            if (preg_match('/\n3 TIME ((\d\d):(\d\d))/', $chan->gedcom(), $match)) {
875d97083feSGreg Roach                return Registry::timestampFactory()->fromString($d . $match[1], 'Y-m-d H:i');
876b2ce94c6SRico Sonntag            }
877b2ce94c6SRico Sonntag
878d97083feSGreg Roach            return Registry::timestampFactory()->fromString($d, 'Y-m-d');
879a25f0a04SGreg Roach        }
880b2ce94c6SRico Sonntag
881a25f0a04SGreg Roach        // The record does not have a CHAN event
882d97083feSGreg Roach        return Registry::timestampFactory()->make(0);
883a25f0a04SGreg Roach    }
884a25f0a04SGreg Roach
885a25f0a04SGreg Roach    /**
886a25f0a04SGreg Roach     * Get the last-change user for this record
887a25f0a04SGreg Roach     *
888a25f0a04SGreg Roach     * @return string
889a25f0a04SGreg Roach     */
890e364afe4SGreg Roach    public function lastChangeUser(): string
891c1010edaSGreg Roach    {
892820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
893a25f0a04SGreg Roach
894a25f0a04SGreg Roach        if ($chan === null) {
895a25f0a04SGreg Roach            return I18N::translate('Unknown');
896b2ce94c6SRico Sonntag        }
897b2ce94c6SRico Sonntag
8983425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
899baacc364SGreg Roach        if ($chan_user === '') {
900a25f0a04SGreg Roach            return I18N::translate('Unknown');
901b2ce94c6SRico Sonntag        }
902b2ce94c6SRico Sonntag
903a25f0a04SGreg Roach        return $chan_user;
904a25f0a04SGreg Roach    }
905a25f0a04SGreg Roach
906a25f0a04SGreg Roach    /**
907a25f0a04SGreg Roach     * Add a new fact to this record
908a25f0a04SGreg Roach     *
909a25f0a04SGreg Roach     * @param string $gedcom
910cbc1590aSGreg Roach     * @param bool   $update_chan
9117e96c925SGreg Roach     *
9127e96c925SGreg Roach     * @return void
913a25f0a04SGreg Roach     */
914e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
915c1010edaSGreg Roach    {
916fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
917a25f0a04SGreg Roach    }
918a25f0a04SGreg Roach
919a25f0a04SGreg Roach    /**
920a25f0a04SGreg Roach     * Delete a fact from this record
921a25f0a04SGreg Roach     *
922a25f0a04SGreg Roach     * @param string $fact_id
923cbc1590aSGreg Roach     * @param bool   $update_chan
9247e96c925SGreg Roach     *
9257e96c925SGreg Roach     * @return void
926a25f0a04SGreg Roach     */
927e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
928c1010edaSGreg Roach    {
929db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
930a25f0a04SGreg Roach    }
931a25f0a04SGreg Roach
932a25f0a04SGreg Roach    /**
933a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
934a25f0a04SGreg Roach     *
935a25f0a04SGreg Roach     * @param string $fact_id
936a25f0a04SGreg Roach     * @param string $gedcom
937cbc1590aSGreg Roach     * @param bool   $update_chan
938a25f0a04SGreg Roach     *
9397e96c925SGreg Roach     * @return void
9407e96c925SGreg Roach     * @throws Exception
941a25f0a04SGreg Roach     */
942e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
943c1010edaSGreg Roach    {
94471f696adSGreg Roach        // Not all record types allow a CHAN event.
94571f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
94671f696adSGreg Roach
947a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
948a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
949a25f0a04SGreg Roach        $gedcom = trim($gedcom);
950a25f0a04SGreg Roach
951a25f0a04SGreg Roach        if ($this->pending === '') {
9527e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
953a25f0a04SGreg Roach        }
9548d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
9557e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
956a25f0a04SGreg Roach        }
957a25f0a04SGreg Roach
958a25f0a04SGreg Roach        if ($this->pending) {
959a25f0a04SGreg Roach            $old_gedcom = $this->pending;
960a25f0a04SGreg Roach        } else {
961a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
962a25f0a04SGreg Roach        }
963a25f0a04SGreg Roach
964a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
96565e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
966a25f0a04SGreg Roach
967a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
96819aed3a1SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
969905ab80aSGreg Roach            if ($fact->id() === $fact_id) {
970db7bb364SGreg Roach                if ($gedcom !== '') {
971a25f0a04SGreg Roach                    $new_gedcom .= "\n" . $gedcom;
972a25f0a04SGreg Roach                }
973fc3ccce4SGreg Roach                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
974d0889c63SGreg Roach            } elseif (!str_ends_with($fact->tag(), ':CHAN') || !$update_chan) {
975138ca96cSGreg Roach                $new_gedcom .= "\n" . $fact->gedcom();
976a25f0a04SGreg Roach            }
977a25f0a04SGreg Roach        }
978a25f0a04SGreg Roach
979a25f0a04SGreg Roach        // Adding a new fact
980fc3ccce4SGreg Roach        if ($fact_id === '') {
981a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
982a25f0a04SGreg Roach        }
983a25f0a04SGreg Roach
984dec352c1SGreg Roach        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
98519aed3a1SGreg Roach            $today = strtoupper(date('d M Y'));
98619aed3a1SGreg Roach            $now   = date('H:i:s');
98719aed3a1SGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
98819aed3a1SGreg Roach        }
98919aed3a1SGreg Roach
990e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
991a25f0a04SGreg Roach            // Save the changes
992d09b6323SGreg Roach            DB::table('change')->insert([
993d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
994d09b6323SGreg Roach                'xref'       => $this->xref,
995d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
996d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
997d09b6323SGreg Roach                'user_id'    => Auth::id(),
99813abd6f3SGreg Roach            ]);
999a25f0a04SGreg Roach
1000a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1001a25f0a04SGreg Roach
10021fe542e9SGreg Roach            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
100322e73debSGreg Roach                app(PendingChangesService::class)->acceptRecord($this);
1004a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1005a25f0a04SGreg Roach                $this->pending = null;
1006a25f0a04SGreg Roach            }
1007a25f0a04SGreg Roach        }
10089599771eSGreg Roach
10099599771eSGreg Roach        $this->facts = $this->parseFacts();
1010a25f0a04SGreg Roach    }
1011a25f0a04SGreg Roach
1012a25f0a04SGreg Roach    /**
1013a25f0a04SGreg Roach     * Update this record
1014a25f0a04SGreg Roach     *
1015a25f0a04SGreg Roach     * @param string $gedcom
1016cbc1590aSGreg Roach     * @param bool   $update_chan
10177e96c925SGreg Roach     *
10187e96c925SGreg Roach     * @return void
1019a25f0a04SGreg Roach     */
1020e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
1021c1010edaSGreg Roach    {
102271f696adSGreg Roach        // Not all record types allow a CHAN event.
102371f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
102471f696adSGreg Roach
1025a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1026a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1027a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1028a25f0a04SGreg Roach
1029a25f0a04SGreg Roach        // Update the CHAN record
1030a25f0a04SGreg Roach        if ($update_chan) {
1031a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
103253432476SGreg Roach            $today = strtoupper(date('d M Y'));
103353432476SGreg Roach            $now   = date('H:i:s');
103453432476SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
1035a25f0a04SGreg Roach        }
1036a25f0a04SGreg Roach
1037a25f0a04SGreg Roach        // Create a pending change
1038d09b6323SGreg Roach        DB::table('change')->insert([
1039d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1040d09b6323SGreg Roach            'xref'       => $this->xref,
1041d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1042d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1043d09b6323SGreg Roach            'user_id'    => Auth::id(),
104413abd6f3SGreg Roach        ]);
1045a25f0a04SGreg Roach
1046a25f0a04SGreg Roach        // Clear the cache
1047a25f0a04SGreg Roach        $this->pending = $gedcom;
1048a25f0a04SGreg Roach
1049a25f0a04SGreg Roach        // Accept this pending change
10501fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
105122e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1052a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1053a25f0a04SGreg Roach            $this->pending = null;
1054a25f0a04SGreg Roach        }
1055a25f0a04SGreg Roach
10569599771eSGreg Roach        $this->facts = $this->parseFacts();
1057a25f0a04SGreg Roach
1058847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1059a25f0a04SGreg Roach    }
1060a25f0a04SGreg Roach
1061a25f0a04SGreg Roach    /**
1062a25f0a04SGreg Roach     * Delete this record
1063b874da82SGreg Roach     *
1064b874da82SGreg Roach     * @return void
1065a25f0a04SGreg Roach     */
1066e364afe4SGreg Roach    public function deleteRecord(): void
1067c1010edaSGreg Roach    {
1068a25f0a04SGreg Roach        // Create a pending change
10694c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1070d09b6323SGreg Roach            DB::table('change')->insert([
1071d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1072d09b6323SGreg Roach                'xref'       => $this->xref,
1073d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1074d09b6323SGreg Roach                'new_gedcom' => '',
1075d09b6323SGreg Roach                'user_id'    => Auth::id(),
107613abd6f3SGreg Roach            ]);
10774c0b5256SGreg Roach        }
1078a25f0a04SGreg Roach
10794c0b5256SGreg Roach        // Auto-accept this pending change
10801fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
108122e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1082a25f0a04SGreg Roach        }
1083a25f0a04SGreg Roach
1084847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1085a25f0a04SGreg Roach    }
1086a25f0a04SGreg Roach
1087a25f0a04SGreg Roach    /**
1088a25f0a04SGreg Roach     * Remove all links from this record to $xref
1089a25f0a04SGreg Roach     *
1090a25f0a04SGreg Roach     * @param string $xref
1091cbc1590aSGreg Roach     * @param bool   $update_chan
10927e96c925SGreg Roach     *
10937e96c925SGreg Roach     * @return void
1094a25f0a04SGreg Roach     */
1095e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
1096c1010edaSGreg Roach    {
1097a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1098a25f0a04SGreg Roach
109930158ae7SGreg Roach        foreach ($this->facts() as $fact) {
110084586c02SGreg Roach            if ($fact->value() === $value) {
1101905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
11028d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1103138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1104a25f0a04SGreg Roach                foreach ($matches as $match) {
1105a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1106a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1107a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1108a25f0a04SGreg Roach                }
1109905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1110a25f0a04SGreg Roach            }
1111a25f0a04SGreg Roach        }
1112a25f0a04SGreg Roach    }
1113bf4eb542SGreg Roach
1114bf4eb542SGreg Roach    /**
1115bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1116bf4eb542SGreg Roach     * also delete all links to it.
1117bf4eb542SGreg Roach     *
111809482a55SGreg Roach     * @return array<GedcomRecord>
1119bf4eb542SGreg Roach     */
1120bf4eb542SGreg Roach    public function linkingRecords(): array
1121bf4eb542SGreg Roach    {
1122b5961194SGreg Roach        $like = addcslashes($this->xref(), '\\%_');
1123b5961194SGreg Roach
1124bf4eb542SGreg Roach        $union = DB::table('change')
1125bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1126b5961194SGreg Roach            ->where('new_gedcom', 'LIKE', '%@' . $like . '@%')
1127b5961194SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $like . '@%')
112883242252SGreg Roach            ->whereIn('change_id', function (Builder $query): void {
112983242252SGreg Roach                $query->select(new Expression('MAX(change_id)'))
113083242252SGreg Roach                    ->from('change')
113183242252SGreg Roach                    ->where('gedcom_id', '=', $this->tree->id())
113283242252SGreg Roach                    ->where('status', '=', 'pending')
11337f5c2944SGreg Roach                    ->groupBy(['xref']);
113483242252SGreg Roach            })
1135bf4eb542SGreg Roach            ->select(['xref']);
1136bf4eb542SGreg Roach
1137bf4eb542SGreg Roach        $xrefs = DB::table('link')
1138bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1139bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
114047256fc5SGreg Roach            ->select(['l_from'])
1141bf4eb542SGreg Roach            ->union($union)
1142bf4eb542SGreg Roach            ->pluck('l_from');
1143bf4eb542SGreg Roach
1144bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
11456b9cb339SGreg Roach            $record = Registry::gedcomRecordFactory()->make($xref, $this->tree);
1146ffc0a61fSGreg Roach            assert($record instanceof GedcomRecord);
1147ffc0a61fSGreg Roach
1148ffc0a61fSGreg Roach            return $record;
1149bf4eb542SGreg Roach        })->all();
1150bf4eb542SGreg Roach    }
115122e73debSGreg Roach
115222e73debSGreg Roach    /**
115322e73debSGreg Roach     * Each object type may have its own special rules, and re-implement this function.
115422e73debSGreg Roach     *
115522e73debSGreg Roach     * @param int $access_level
115622e73debSGreg Roach     *
115722e73debSGreg Roach     * @return bool
115822e73debSGreg Roach     */
115922e73debSGreg Roach    protected function canShowByType(int $access_level): bool
116022e73debSGreg Roach    {
116122e73debSGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
116222e73debSGreg Roach
116322e73debSGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
116422e73debSGreg Roach            // Restriction found
116522e73debSGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
116622e73debSGreg Roach        }
116722e73debSGreg Roach
116822e73debSGreg Roach        // No restriction found - must be public:
116922e73debSGreg Roach        return true;
117022e73debSGreg Roach    }
117122e73debSGreg Roach
117222e73debSGreg Roach    /**
117322e73debSGreg Roach     * Generate a private version of this record
117422e73debSGreg Roach     *
117522e73debSGreg Roach     * @param int $access_level
117622e73debSGreg Roach     *
117722e73debSGreg Roach     * @return string
117822e73debSGreg Roach     */
117922e73debSGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
118022e73debSGreg Roach    {
1181228ede81SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
118222e73debSGreg Roach    }
118322e73debSGreg Roach
118422e73debSGreg Roach    /**
118522e73debSGreg Roach     * Convert a name record into sortable and full/display versions. This default
118622e73debSGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
118722e73debSGreg Roach     *
118822e73debSGreg Roach     * @param string $type
118922e73debSGreg Roach     * @param string $value
119022e73debSGreg Roach     * @param string $gedcom
119122e73debSGreg Roach     *
119222e73debSGreg Roach     * @return void
119322e73debSGreg Roach     */
119422e73debSGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
119522e73debSGreg Roach    {
119622e73debSGreg Roach        $this->getAllNames[] = [
119722e73debSGreg Roach            'type'   => $type,
1198dbf91548SGreg Roach            'sort'   => preg_replace_callback('/(\d+)/', static function (array $matches): string {
119922e73debSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
120022e73debSGreg Roach            }, $value),
1201315eb316SGreg Roach            'full'   => '<bdi>' . e($value) . '</bdi>',
120222e73debSGreg Roach            // This is used for display
120322e73debSGreg Roach            'fullNN' => $value,
120422e73debSGreg Roach            // This goes into the database
120522e73debSGreg Roach        ];
120622e73debSGreg Roach    }
120722e73debSGreg Roach
120822e73debSGreg Roach    /**
120922e73debSGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
121022e73debSGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
121122e73debSGreg Roach     * Parameters: the level 1 fact containing the name.
121222e73debSGreg Roach     * Return value: an array of name structures, each containing
121322e73debSGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
121422e73debSGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
121522e73debSGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
121622e73debSGreg Roach     *
121722e73debSGreg Roach     * @param int              $level
121822e73debSGreg Roach     * @param string           $fact_type
121936779af1SGreg Roach     * @param Collection<int,Fact> $facts
122022e73debSGreg Roach     *
122122e73debSGreg Roach     * @return void
122222e73debSGreg Roach     */
122322e73debSGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
122422e73debSGreg Roach    {
122522e73debSGreg Roach        $sublevel    = $level + 1;
122622e73debSGreg Roach        $subsublevel = $sublevel + 1;
122722e73debSGreg Roach        foreach ($facts as $fact) {
1228c8ff5fdcSGreg Roach            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
122922e73debSGreg Roach                foreach ($matches as $match) {
123022e73debSGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1231dec352c1SGreg Roach                    if ($match[1] === 'NAME' && str_contains($match[3], "\n2 TYPE married")) {
123222e73debSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
123322e73debSGreg Roach                    } else {
123422e73debSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
123522e73debSGreg Roach                    }
1236c8ff5fdcSGreg Roach                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
123722e73debSGreg Roach                        foreach ($submatches as $submatch) {
123822e73debSGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
123922e73debSGreg Roach                        }
124022e73debSGreg Roach                    }
124122e73debSGreg Roach                }
124222e73debSGreg Roach            }
124322e73debSGreg Roach        }
124422e73debSGreg Roach    }
124522e73debSGreg Roach
124622e73debSGreg Roach    /**
124722e73debSGreg Roach     * Split the record into facts
124822e73debSGreg Roach     *
12499599771eSGreg Roach     * @return array<Fact>
125022e73debSGreg Roach     */
12519599771eSGreg Roach    private function parseFacts(): array
125222e73debSGreg Roach    {
125322e73debSGreg Roach        // Split the record into facts
125422e73debSGreg Roach        if ($this->gedcom) {
1255d823340dSGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
125622e73debSGreg Roach            array_shift($gedcom_facts);
125722e73debSGreg Roach        } else {
125822e73debSGreg Roach            $gedcom_facts = [];
125922e73debSGreg Roach        }
126022e73debSGreg Roach        if ($this->pending) {
1261d823340dSGreg Roach            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
126222e73debSGreg Roach            array_shift($pending_facts);
126322e73debSGreg Roach        } else {
126422e73debSGreg Roach            $pending_facts = [];
126522e73debSGreg Roach        }
126622e73debSGreg Roach
12679599771eSGreg Roach        $facts = [];
126822e73debSGreg Roach
126922e73debSGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
127022e73debSGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
127122e73debSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
127222e73debSGreg Roach                $fact->setPendingDeletion();
127322e73debSGreg Roach            }
12749599771eSGreg Roach            $facts[] = $fact;
127522e73debSGreg Roach        }
127622e73debSGreg Roach        foreach ($pending_facts as $pending_fact) {
127722e73debSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
127822e73debSGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
127922e73debSGreg Roach                $fact->setPendingAddition();
12809599771eSGreg Roach                $facts[] = $fact;
128122e73debSGreg Roach            }
128222e73debSGreg Roach        }
12839599771eSGreg Roach
12849599771eSGreg Roach        return $facts;
128522e73debSGreg Roach    }
128622e73debSGreg Roach
128722e73debSGreg Roach    /**
128822e73debSGreg Roach     * Work out whether this record can be shown to a user with a given access level
128922e73debSGreg Roach     *
129022e73debSGreg Roach     * @param int $access_level
129122e73debSGreg Roach     *
129222e73debSGreg Roach     * @return bool
129322e73debSGreg Roach     */
129422e73debSGreg Roach    private function canShowRecord(int $access_level): bool
129522e73debSGreg Roach    {
129622e73debSGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
129722e73debSGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
129822e73debSGreg Roach            return true;
129922e73debSGreg Roach        }
130022e73debSGreg Roach
130122e73debSGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
13021fe542e9SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
130322e73debSGreg Roach            return true;
130422e73debSGreg Roach        }
130522e73debSGreg Roach
130622e73debSGreg Roach        // Does this record have a RESN?
1307dec352c1SGreg Roach        if (str_contains($this->gedcom, "\n1 RESN confidential")) {
130822e73debSGreg Roach            return Auth::PRIV_NONE >= $access_level;
130922e73debSGreg Roach        }
1310dec352c1SGreg Roach        if (str_contains($this->gedcom, "\n1 RESN privacy")) {
131122e73debSGreg Roach            return Auth::PRIV_USER >= $access_level;
131222e73debSGreg Roach        }
1313dec352c1SGreg Roach        if (str_contains($this->gedcom, "\n1 RESN none")) {
131422e73debSGreg Roach            return true;
131522e73debSGreg Roach        }
131622e73debSGreg Roach
131722e73debSGreg Roach        // Does this record have a default RESN?
131822e73debSGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
131922e73debSGreg Roach        if (isset($individual_privacy[$this->xref()])) {
132022e73debSGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
132122e73debSGreg Roach        }
132222e73debSGreg Roach
132322e73debSGreg Roach        // Privacy rules do not apply to admins
132422e73debSGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
132522e73debSGreg Roach            return true;
132622e73debSGreg Roach        }
132722e73debSGreg Roach
132822e73debSGreg Roach        // Different types of record have different privacy rules
132922e73debSGreg Roach        return $this->canShowByType($access_level);
133022e73debSGreg Roach    }
13318091bfd1SGreg Roach
13328091bfd1SGreg Roach    /**
13338091bfd1SGreg Roach     * Lock the database row, to prevent concurrent edits.
13348091bfd1SGreg Roach     */
13358091bfd1SGreg Roach    public function lock(): void
13368091bfd1SGreg Roach    {
13378091bfd1SGreg Roach        DB::table('other')
13388091bfd1SGreg Roach            ->where('o_file', '=', $this->tree->id())
13398091bfd1SGreg Roach            ->where('o_id', '=', $this->xref())
13408091bfd1SGreg Roach            ->lockForUpdate()
13418091bfd1SGreg Roach            ->get();
13428091bfd1SGreg Roach    }
1343a25f0a04SGreg Roach}
1344