xref: /webtrees/app/GedcomRecord.php (revision 5cba5dc792ef837a515f82eb2790ffd88c2aa791)
1a25f0a04SGreg Roach<?php
23976b470SGreg Roach
3a25f0a04SGreg Roach/**
4a25f0a04SGreg Roach * webtrees: online genealogy
55bfc6897SGreg Roach * Copyright (C) 2022 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;
2476d39c55SGreg Roachuse Fisharebest\Webtrees\Contracts\TimestampInterface;
251fe542e9SGreg Roachuse Fisharebest\Webtrees\Contracts\UserInterface;
2655105892SGreg Roachuse Fisharebest\Webtrees\Elements\RestrictionNotice;
275818a371SGreg Roachuse Fisharebest\Webtrees\Http\RequestHandlers\GedcomRecordPage;
2822e73debSGreg Roachuse Fisharebest\Webtrees\Services\PendingChangesService;
29bf4eb542SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
3039ca88baSGreg Roachuse Illuminate\Support\Collection;
31a25f0a04SGreg Roach
3222e73debSGreg Roachuse function app;
330f5fd22fSGreg Roachuse function array_combine;
340f5fd22fSGreg Roachuse function array_keys;
350f5fd22fSGreg Roachuse function array_map;
360f5fd22fSGreg Roachuse function array_search;
37f7440925SGreg Roachuse function array_shift;
38f7440925SGreg Roachuse function assert;
39f7440925SGreg Roachuse function count;
40f7440925SGreg Roachuse function date;
41f7440925SGreg Roachuse function e;
42f7440925SGreg Roachuse function explode;
43a79e52aaSGreg Roachuse function implode;
44f7440925SGreg Roachuse function in_array;
45f7440925SGreg Roachuse function md5;
46f7440925SGreg Roachuse function preg_match;
47f7440925SGreg Roachuse function preg_match_all;
48f7440925SGreg Roachuse function preg_replace;
49f7440925SGreg Roachuse function preg_replace_callback;
50f7440925SGreg Roachuse function preg_split;
510f5fd22fSGreg Roachuse function range;
52f7440925SGreg Roachuse function route;
53dec352c1SGreg Roachuse function str_contains;
54d0889c63SGreg Roachuse function str_ends_with;
55f7440925SGreg Roachuse function str_pad;
5655105892SGreg Roachuse function str_starts_with;
57f7440925SGreg Roachuse function strtoupper;
5872f8afdbSGreg Roachuse function strtr;
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
29355105892SGreg Roach        $fact   = $this->facts(['RESN'])->first();
29455105892SGreg Roach        $locked = $fact instanceof Fact && str_ends_with($fact->attribute('RESN'), RestrictionNotice::VALUE_LOCKED);
29555105892SGreg Roach
29655105892SGreg Roach        return Auth::isEditor($this->tree) && !$locked;
297a25f0a04SGreg Roach    }
298a25f0a04SGreg Roach
299a25f0a04SGreg Roach    /**
300a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
301a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
302a25f0a04SGreg Roach     *
303cbc1590aSGreg Roach     * @param int $access_level
304a25f0a04SGreg Roach     *
305a25f0a04SGreg Roach     * @return string
306a25f0a04SGreg Roach     */
307e364afe4SGreg Roach    public function privatizeGedcom(int $access_level): string
308c1010edaSGreg Roach    {
309e364afe4SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
310a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
311a25f0a04SGreg Roach            return $this->gedcom;
312b2ce94c6SRico Sonntag        }
313b2ce94c6SRico Sonntag
314b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
315a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
316a25f0a04SGreg Roach
317a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
318dc141db3SGreg Roach            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
319a25f0a04SGreg Roach
320a25f0a04SGreg Roach            // Check each of the facts for access
3218d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
322138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
323a25f0a04SGreg Roach            }
324cbc1590aSGreg Roach
325a25f0a04SGreg Roach            return $gedrec;
326b2ce94c6SRico Sonntag        }
327b2ce94c6SRico Sonntag
328a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
329a25f0a04SGreg Roach        // limited data, such as links to other records.
330a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
331a25f0a04SGreg Roach    }
332a25f0a04SGreg Roach
333a25f0a04SGreg Roach    /**
334a25f0a04SGreg Roach     * Default for "other" object types
335c7ff4153SGreg Roach     *
336c7ff4153SGreg Roach     * @return void
337a25f0a04SGreg Roach     */
338e364afe4SGreg Roach    public function extractNames(): void
339c1010edaSGreg Roach    {
34076f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
341a25f0a04SGreg Roach    }
342a25f0a04SGreg Roach
343a25f0a04SGreg Roach    /**
344a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
345a25f0a04SGreg Roach     *
346870ec5a3SGreg Roach     * @return array<int,array<string,string>>
347a25f0a04SGreg Roach     */
3488f53f488SRico Sonntag    public function getAllNames(): array
349c1010edaSGreg Roach    {
3509599771eSGreg Roach        if ($this->getAllNames === []) {
351a25f0a04SGreg Roach            if ($this->canShowName()) {
352a25f0a04SGreg Roach                // Ask the record to extract its names
353a25f0a04SGreg Roach                $this->extractNames();
354a25f0a04SGreg Roach                // No name found? Use a fallback.
355ec124fd2SGreg Roach                if ($this->getAllNames === []) {
356db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
357a25f0a04SGreg Roach                }
358a25f0a04SGreg Roach            } else {
359db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
360a25f0a04SGreg Roach            }
361a25f0a04SGreg Roach        }
362cbc1590aSGreg Roach
363bdb3725aSGreg Roach        return $this->getAllNames;
364a25f0a04SGreg Roach    }
365a25f0a04SGreg Roach
366a25f0a04SGreg Roach    /**
367a25f0a04SGreg Roach     * If this object has no name, what do we call it?
368a25f0a04SGreg Roach     *
369a25f0a04SGreg Roach     * @return string
370a25f0a04SGreg Roach     */
3718f53f488SRico Sonntag    public function getFallBackName(): string
372c1010edaSGreg Roach    {
373c0935879SGreg Roach        return e($this->xref());
374a25f0a04SGreg Roach    }
375a25f0a04SGreg Roach
376a25f0a04SGreg Roach    /**
377a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
378a25f0a04SGreg Roach     *
379cbc1590aSGreg Roach     * @return int
380a25f0a04SGreg Roach     */
3818f53f488SRico Sonntag    public function getPrimaryName(): int
382c1010edaSGreg Roach    {
383a25f0a04SGreg Roach        static $language_script;
384a25f0a04SGreg Roach
385448d466cSGreg Roach        $language_script ??= I18N::locale()->script()->code();
386a25f0a04SGreg Roach
387bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
388a25f0a04SGreg Roach            // Generally, the first name is the primary one....
389bdb3725aSGreg Roach            $this->getPrimaryName = 0;
390a25f0a04SGreg Roach            // ...except when the language/name use different character sets
391a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
39269546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
393bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
394a25f0a04SGreg Roach                    break;
395a25f0a04SGreg Roach                }
396a25f0a04SGreg Roach            }
397a25f0a04SGreg Roach        }
398a25f0a04SGreg Roach
399bdb3725aSGreg Roach        return $this->getPrimaryName;
400a25f0a04SGreg Roach    }
401a25f0a04SGreg Roach
402a25f0a04SGreg Roach    /**
403a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
404a25f0a04SGreg Roach     *
405cbc1590aSGreg Roach     * @return int
406a25f0a04SGreg Roach     */
4078f53f488SRico Sonntag    public function getSecondaryName(): int
408c1010edaSGreg Roach    {
4098f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
410a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
411bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
412a25f0a04SGreg Roach            // ....except when there are names with different character sets
413a25f0a04SGreg Roach            $all_names = $this->getAllNames();
414a25f0a04SGreg Roach            if (count($all_names) > 1) {
415a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
416a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
417e364afe4SGreg Roach                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
418bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
419a25f0a04SGreg Roach                        break;
420a25f0a04SGreg Roach                    }
421a25f0a04SGreg Roach                }
422a25f0a04SGreg Roach            }
423a25f0a04SGreg Roach        }
424cbc1590aSGreg Roach
425bdb3725aSGreg Roach        return $this->getSecondaryName;
426a25f0a04SGreg Roach    }
427a25f0a04SGreg Roach
428a25f0a04SGreg Roach    /**
429a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
430a25f0a04SGreg Roach     *
43176f666f4SGreg Roach     * @param int|null $n
4327e96c925SGreg Roach     *
4337e96c925SGreg Roach     * @return void
434a25f0a04SGreg Roach     */
435e364afe4SGreg Roach    public function setPrimaryName(int $n = null): void
436c1010edaSGreg Roach    {
437bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
438bdb3725aSGreg Roach        $this->getSecondaryName = null;
439a25f0a04SGreg Roach    }
440a25f0a04SGreg Roach
441a25f0a04SGreg Roach    /**
442a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
443a25f0a04SGreg Roach     *
444a25f0a04SGreg Roach     * @return string
445a25f0a04SGreg Roach     */
44624f2a3afSGreg Roach    public function __toString(): string
447c1010edaSGreg Roach    {
44872cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
449a25f0a04SGreg Roach    }
450a25f0a04SGreg Roach
451a25f0a04SGreg Roach    /**
452c156e8f5SGreg Roach     * /**
453a25f0a04SGreg Roach     * Get variants of the name
454a25f0a04SGreg Roach     *
455a25f0a04SGreg Roach     * @return string
456a25f0a04SGreg Roach     */
457e364afe4SGreg Roach    public function fullName(): string
458c1010edaSGreg Roach    {
459a25f0a04SGreg Roach        if ($this->canShowName()) {
460a25f0a04SGreg Roach            $tmp = $this->getAllNames();
461cbc1590aSGreg Roach
462a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
463a25f0a04SGreg Roach        }
464b2ce94c6SRico Sonntag
465b2ce94c6SRico Sonntag        return I18N::translate('Private');
466a25f0a04SGreg Roach    }
467a25f0a04SGreg Roach
468a25f0a04SGreg Roach    /**
469a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
470a25f0a04SGreg Roach     *
471a25f0a04SGreg Roach     * @return string
472a25f0a04SGreg Roach     */
47339ca88baSGreg Roach    public function sortName(): string
474c1010edaSGreg Roach    {
475a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
476a25f0a04SGreg Roach        $tmp = $this->getAllNames();
477cbc1590aSGreg Roach
478a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
479a25f0a04SGreg Roach    }
480a25f0a04SGreg Roach
481a25f0a04SGreg Roach    /**
482a25f0a04SGreg Roach     * Get the full name in an alternative character set
483a25f0a04SGreg Roach     *
484e364afe4SGreg Roach     * @return string|null
485a25f0a04SGreg Roach     */
486e364afe4SGreg Roach    public function alternateName(): ?string
487c1010edaSGreg Roach    {
488e364afe4SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
489a25f0a04SGreg Roach            $all_names = $this->getAllNames();
490cbc1590aSGreg Roach
491a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
492a25f0a04SGreg Roach        }
493b2ce94c6SRico Sonntag
494b2ce94c6SRico Sonntag        return null;
495a25f0a04SGreg Roach    }
496a25f0a04SGreg Roach
497a25f0a04SGreg Roach    /**
498a25f0a04SGreg Roach     * Format this object for display in a list
499a25f0a04SGreg Roach     *
500a25f0a04SGreg Roach     * @return string
501a25f0a04SGreg Roach     */
5028f53f488SRico Sonntag    public function formatList(): string
503c1010edaSGreg Roach    {
504a79e52aaSGreg Roach        $html = '<a href="' . e($this->url()) . '">';
50539ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
506b165e17cSGreg Roach        $html .= '</a>';
507a79e52aaSGreg Roach        $html .= $this->formatListDetails();
508cbc1590aSGreg Roach
509a25f0a04SGreg Roach        return $html;
510a25f0a04SGreg Roach    }
511a25f0a04SGreg Roach
512a25f0a04SGreg Roach    /**
513a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
514a25f0a04SGreg Roach     * identifying characteristics of this record.
515a25f0a04SGreg Roach     *
516a25f0a04SGreg Roach     * @return string
517a25f0a04SGreg Roach     */
5188f53f488SRico Sonntag    public function formatListDetails(): string
519c1010edaSGreg Roach    {
520a25f0a04SGreg Roach        return '';
521a25f0a04SGreg Roach    }
522a25f0a04SGreg Roach
523a25f0a04SGreg Roach    /**
524a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
525a25f0a04SGreg Roach     *
52609482a55SGreg Roach     * @param array<string> $facts
527cbc1590aSGreg Roach     * @param int           $style
528a25f0a04SGreg Roach     *
529a25f0a04SGreg Roach     * @return string
530a25f0a04SGreg Roach     */
5318d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
532c1010edaSGreg Roach    {
533a79e52aaSGreg Roach        $fact = $this->facts($facts, true)->first();
534a79e52aaSGreg Roach
535a79e52aaSGreg Roach        if ($fact === null) {
536a79e52aaSGreg Roach            return '';
537a25f0a04SGreg Roach        }
538cbc1590aSGreg Roach
539a79e52aaSGreg Roach        // Only display if it has a date or place (or both)
540a79e52aaSGreg Roach        $attributes = [];
541a79e52aaSGreg Roach
542a79e52aaSGreg Roach        if ($fact->date()->isOK()) {
543a79e52aaSGreg Roach            $attributes[] = view('fact-date', ['cal_link' => 'false', 'fact' => $fact, 'record' => $fact->record(), 'time' => false]);
544a79e52aaSGreg Roach        }
545a79e52aaSGreg Roach
546a79e52aaSGreg Roach        if ($fact->place()->gedcomName() !== '' && $style === 2) {
547a79e52aaSGreg Roach            $attributes[] = $fact->place()->shortName();
548a79e52aaSGreg Roach        }
549a79e52aaSGreg Roach
550a79e52aaSGreg Roach        if ($attributes === []) {
551a25f0a04SGreg Roach            return '';
552a25f0a04SGreg Roach        }
553a25f0a04SGreg Roach
554a79e52aaSGreg Roach        return '<div><em>' . I18N::translate('%1$s: %2$s', $fact->label(), implode(' — ', $attributes)) . '</em></div>';
555a79e52aaSGreg Roach    }
556a79e52aaSGreg Roach
557a25f0a04SGreg Roach    /**
558a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
559a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
560a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
561a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
562a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
563a25f0a04SGreg Roach     *
56409482a55SGreg Roach     * @param array<string> $events
565a25f0a04SGreg Roach     *
56609482a55SGreg Roach     * @return array<Date>
567a25f0a04SGreg Roach     */
5688d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
569c1010edaSGreg Roach    {
57013abd6f3SGreg Roach        $dates = [];
5711385b8caSGreg Roach        foreach ($this->facts($events, false, null, true) as $event) {
5722decada7SGreg Roach            if ($event->date()->isOK()) {
5732decada7SGreg Roach                $dates[] = $event->date();
574a25f0a04SGreg Roach            }
575a25f0a04SGreg Roach        }
576a25f0a04SGreg Roach
577a25f0a04SGreg Roach        return $dates;
578a25f0a04SGreg Roach    }
579a25f0a04SGreg Roach
580a25f0a04SGreg Roach    /**
581a25f0a04SGreg Roach     * Get all the places for a particular type of event
582a25f0a04SGreg Roach     *
58309482a55SGreg Roach     * @param array<string> $events
584a25f0a04SGreg Roach     *
58509482a55SGreg Roach     * @return array<Place>
586a25f0a04SGreg Roach     */
5878d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
588c1010edaSGreg Roach    {
58913abd6f3SGreg Roach        $places = [];
5908d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
591138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
592a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
59316d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
594a25f0a04SGreg Roach                }
595a25f0a04SGreg Roach            }
596a25f0a04SGreg Roach        }
597a25f0a04SGreg Roach
598a25f0a04SGreg Roach        return $places;
599a25f0a04SGreg Roach    }
600a25f0a04SGreg Roach
601a25f0a04SGreg Roach    /**
602a25f0a04SGreg Roach     * The facts and events for this record.
603a25f0a04SGreg Roach     *
60409482a55SGreg Roach     * @param array<string> $filter
605cbc1590aSGreg Roach     * @param bool          $sort
606cbc1590aSGreg Roach     * @param int|null      $access_level
607ce42304aSGreg Roach     * @param bool          $ignore_deleted
608a25f0a04SGreg Roach     *
60936779af1SGreg Roach     * @return Collection<int,Fact>
610a25f0a04SGreg Roach     */
611ce42304aSGreg Roach    public function facts(
612ce42304aSGreg Roach        array $filter = [],
613ce42304aSGreg Roach        bool $sort = false,
614ce42304aSGreg Roach        int $access_level = null,
615ce42304aSGreg Roach        bool $ignore_deleted = false
616ce42304aSGreg Roach    ): Collection {
617d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
6184b9ff166SGreg Roach
619d0889c63SGreg Roach        // Convert BIRT into INDI:BIRT, etc.
620d0889c63SGreg Roach        $filter = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, $filter);
621d0889c63SGreg Roach
6228af3e5c1SGreg Roach        $facts = new Collection();
623ce42304aSGreg Roach        if ($this->canShow($access_level)) {
624a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
625d0889c63SGreg Roach                if (($filter === [] || in_array($fact->tag(), $filter, true)) && $fact->canShow($access_level)) {
6268af3e5c1SGreg Roach                    $facts->push($fact);
627a25f0a04SGreg Roach                }
628a25f0a04SGreg Roach            }
629a25f0a04SGreg Roach        }
630d17d7b9eSGreg Roach
631a25f0a04SGreg Roach        if ($sort) {
6320f5fd22fSGreg Roach            switch ($this->tag()) {
6330f5fd22fSGreg Roach                case Family::RECORD_TYPE:
6340f5fd22fSGreg Roach                case Individual::RECORD_TYPE:
635580a4d11SGreg Roach                    $facts = Fact::sortFacts($facts);
6360f5fd22fSGreg Roach                    break;
6370f5fd22fSGreg Roach
6380f5fd22fSGreg Roach                default:
6390f5fd22fSGreg Roach                    $subtags = Registry::elementFactory()->make($this->tag())->subtags();
6400f5fd22fSGreg Roach                    $subtags = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, array_keys($subtags));
6411259996fSGreg Roach
6421259996fSGreg Roach                    if ($subtags !== []) {
6431259996fSGreg Roach                        // Renumber keys from 1.
6440f5fd22fSGreg Roach                        $subtags = array_combine(range(1, count($subtags)), $subtags);
6451259996fSGreg Roach                    }
6461259996fSGreg Roach
6470f5fd22fSGreg Roach
6480f5fd22fSGreg Roach                    $facts = $facts
6490f5fd22fSGreg Roach                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
6500f5fd22fSGreg Roach                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
6510f5fd22fSGreg Roach                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
6520f5fd22fSGreg Roach
6530f5fd22fSGreg Roach                            return $sort_x <=> $sort_y;
6540f5fd22fSGreg Roach                        });
6550f5fd22fSGreg Roach                    break;
6560f5fd22fSGreg Roach            }
657a25f0a04SGreg Roach        }
658cbc1590aSGreg Roach
659ce42304aSGreg Roach        if ($ignore_deleted) {
660ce42304aSGreg Roach            $facts = $facts->filter(static function (Fact $fact): bool {
661ce42304aSGreg Roach                return !$fact->isPendingDeletion();
662ce42304aSGreg Roach            });
663ce42304aSGreg Roach        }
664ce42304aSGreg Roach
6655fef3bfaSGreg Roach        return $facts;
666a25f0a04SGreg Roach    }
667a25f0a04SGreg Roach
668a25f0a04SGreg Roach    /**
6690f5fd22fSGreg Roach     * @return array<string,string>
6700f5fd22fSGreg Roach     */
6710f5fd22fSGreg Roach    public function missingFacts(): array
6720f5fd22fSGreg Roach    {
6730f5fd22fSGreg Roach        $missing_facts = [];
6740f5fd22fSGreg Roach
6750f5fd22fSGreg Roach        foreach (Registry::elementFactory()->make($this->tag())->subtags() as $subtag => $repeat) {
6760f5fd22fSGreg Roach            [, $max] = explode(':', $repeat);
6770f5fd22fSGreg Roach            $max = $max === 'M' ? PHP_INT_MAX : (int) $max;
6780f5fd22fSGreg Roach
67998f93f3aSGreg Roach            if ($this->facts([$subtag], false, null, true)->count() < $max) {
6800f5fd22fSGreg Roach                $missing_facts[$subtag] = $subtag;
6810f5fd22fSGreg Roach                $missing_facts[$subtag] = Registry::elementFactory()->make($this->tag() . ':' . $subtag)->label();
6820f5fd22fSGreg Roach            }
6830f5fd22fSGreg Roach        }
6840f5fd22fSGreg Roach
6850f5fd22fSGreg Roach        uasort($missing_facts, I18N::comparator());
6860f5fd22fSGreg Roach
6875416d6ddSGreg Roach        if (!Auth::canUploadMedia($this->tree, Auth::user())) {
6880f5fd22fSGreg Roach            unset($missing_facts['OBJE']);
6890f5fd22fSGreg Roach        }
6900f5fd22fSGreg Roach
6910f5fd22fSGreg Roach        // We have special code for this.
6920f5fd22fSGreg Roach        unset($missing_facts['FILE']);
6930f5fd22fSGreg Roach
6940f5fd22fSGreg Roach        return $missing_facts;
6950f5fd22fSGreg Roach    }
6960f5fd22fSGreg Roach
6970f5fd22fSGreg Roach    /**
6984459dc9aSGreg Roach     * Get the last-change timestamp for this record
699a25f0a04SGreg Roach     *
70076d39c55SGreg Roach     * @return TimestampInterface
701a25f0a04SGreg Roach     */
70276d39c55SGreg Roach    public function lastChangeTimestamp(): TimestampInterface
703c1010edaSGreg Roach    {
704820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
705a25f0a04SGreg Roach
7064459dc9aSGreg Roach        if ($chan instanceof Fact) {
70703f2cc61SGreg Roach            // The record has a CHAN event.
70886c727c1SGreg Roach            $date = $chan->date()->minimumDate();
70986c727c1SGreg Roach            $ymd = sprintf('%04d-%02d-%02d', $date->year(), $date->month(), $date->day());
7104459dc9aSGreg Roach
71186c727c1SGreg Roach            if ($ymd !== '') {
71203f2cc61SGreg Roach                // The CHAN event has a valid DATE.
71386c727c1SGreg Roach                if (preg_match('/\n3 TIME (([01]\d|2[0-3]):([0-5]\d):([0-5]\d))/', $chan->gedcom(), $match) === 1) {
71486c727c1SGreg Roach                    return Registry::timestampFactory()->fromString($ymd . $match[1], 'Y-m-d H:i:s');
715e364afe4SGreg Roach                }
716e364afe4SGreg Roach
71786c727c1SGreg Roach                if (preg_match('/\n3 TIME (([01]\d|2[0-3]):([0-5]\d))/', $chan->gedcom(), $match) === 1) {
71886c727c1SGreg Roach                    return Registry::timestampFactory()->fromString($ymd . $match[1], 'Y-m-d H:i');
719b2ce94c6SRico Sonntag                }
720b2ce94c6SRico Sonntag
72186c727c1SGreg Roach                return Registry::timestampFactory()->fromString($ymd, 'Y-m-d');
722a25f0a04SGreg Roach            }
72303f2cc61SGreg Roach        }
724b2ce94c6SRico Sonntag
725a25f0a04SGreg Roach        // The record does not have a CHAN event
726d97083feSGreg Roach        return Registry::timestampFactory()->make(0);
727a25f0a04SGreg Roach    }
728a25f0a04SGreg Roach
729a25f0a04SGreg Roach    /**
730a25f0a04SGreg Roach     * Get the last-change user for this record
731a25f0a04SGreg Roach     *
732a25f0a04SGreg Roach     * @return string
733a25f0a04SGreg Roach     */
734e364afe4SGreg Roach    public function lastChangeUser(): string
735c1010edaSGreg Roach    {
736820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
737a25f0a04SGreg Roach
738a25f0a04SGreg Roach        if ($chan === null) {
739a25f0a04SGreg Roach            return I18N::translate('Unknown');
740b2ce94c6SRico Sonntag        }
741b2ce94c6SRico Sonntag
7423425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
743baacc364SGreg Roach        if ($chan_user === '') {
744a25f0a04SGreg Roach            return I18N::translate('Unknown');
745b2ce94c6SRico Sonntag        }
746b2ce94c6SRico Sonntag
747a25f0a04SGreg Roach        return $chan_user;
748a25f0a04SGreg Roach    }
749a25f0a04SGreg Roach
750a25f0a04SGreg Roach    /**
751a25f0a04SGreg Roach     * Add a new fact to this record
752a25f0a04SGreg Roach     *
753a25f0a04SGreg Roach     * @param string $gedcom
754cbc1590aSGreg Roach     * @param bool   $update_chan
7557e96c925SGreg Roach     *
7567e96c925SGreg Roach     * @return void
757a25f0a04SGreg Roach     */
758e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
759c1010edaSGreg Roach    {
760fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
761a25f0a04SGreg Roach    }
762a25f0a04SGreg Roach
763a25f0a04SGreg Roach    /**
764a25f0a04SGreg Roach     * Delete a fact from this record
765a25f0a04SGreg Roach     *
766a25f0a04SGreg Roach     * @param string $fact_id
767cbc1590aSGreg Roach     * @param bool   $update_chan
7687e96c925SGreg Roach     *
7697e96c925SGreg Roach     * @return void
770a25f0a04SGreg Roach     */
771e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
772c1010edaSGreg Roach    {
773db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
774a25f0a04SGreg Roach    }
775a25f0a04SGreg Roach
776a25f0a04SGreg Roach    /**
777a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
778a25f0a04SGreg Roach     *
779a25f0a04SGreg Roach     * @param string $fact_id
780a25f0a04SGreg Roach     * @param string $gedcom
781cbc1590aSGreg Roach     * @param bool   $update_chan
782a25f0a04SGreg Roach     *
7837e96c925SGreg Roach     * @return void
7847e96c925SGreg Roach     * @throws Exception
785a25f0a04SGreg Roach     */
786e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
787c1010edaSGreg Roach    {
78871f696adSGreg Roach        // Not all record types allow a CHAN event.
78971f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
79071f696adSGreg Roach
791a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
792a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
793a25f0a04SGreg Roach        $gedcom = trim($gedcom);
794a25f0a04SGreg Roach
795a25f0a04SGreg Roach        if ($this->pending === '') {
7967e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
797a25f0a04SGreg Roach        }
7988d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
7997e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
800a25f0a04SGreg Roach        }
801a25f0a04SGreg Roach
802a25f0a04SGreg Roach        if ($this->pending) {
803a25f0a04SGreg Roach            $old_gedcom = $this->pending;
804a25f0a04SGreg Roach        } else {
805a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
806a25f0a04SGreg Roach        }
807a25f0a04SGreg Roach
808a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
80965e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
810a25f0a04SGreg Roach
811a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
81219aed3a1SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
813905ab80aSGreg Roach            if ($fact->id() === $fact_id) {
814db7bb364SGreg Roach                if ($gedcom !== '') {
815a25f0a04SGreg Roach                    $new_gedcom .= "\n" . $gedcom;
816a25f0a04SGreg Roach                }
817fc3ccce4SGreg Roach                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
81872f8afdbSGreg Roach            } elseif ($update_chan && str_ends_with($fact->tag(), ':CHAN')) {
81972f8afdbSGreg Roach                $new_gedcom .= "\n" . $this->updateChange($fact->gedcom());
82072f8afdbSGreg Roach            } else {
821138ca96cSGreg Roach                $new_gedcom .= "\n" . $fact->gedcom();
822a25f0a04SGreg Roach            }
823a25f0a04SGreg Roach        }
824a25f0a04SGreg Roach
825a25f0a04SGreg Roach        // Adding a new fact
826fc3ccce4SGreg Roach        if ($fact_id === '') {
827a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
828a25f0a04SGreg Roach        }
829a25f0a04SGreg Roach
830dec352c1SGreg Roach        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
83172f8afdbSGreg Roach            $new_gedcom .= $this->updateChange("\n1 CHAN");
83219aed3a1SGreg Roach        }
83319aed3a1SGreg Roach
834e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
835a25f0a04SGreg Roach            // Save the changes
836d09b6323SGreg Roach            DB::table('change')->insert([
837d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
838d09b6323SGreg Roach                'xref'       => $this->xref,
839d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
840d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
841d09b6323SGreg Roach                'user_id'    => Auth::id(),
84213abd6f3SGreg Roach            ]);
843a25f0a04SGreg Roach
844a25f0a04SGreg Roach            $this->pending = $new_gedcom;
845a25f0a04SGreg Roach
8461fe542e9SGreg Roach            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
847b55cbc6bSGreg Roach                $pending_changes_service = app(PendingChangesService::class);
848b55cbc6bSGreg Roach                assert($pending_changes_service instanceof PendingChangesService);
849b55cbc6bSGreg Roach
850b55cbc6bSGreg Roach                $pending_changes_service->acceptRecord($this);
851a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
852a25f0a04SGreg Roach                $this->pending = null;
853a25f0a04SGreg Roach            }
854a25f0a04SGreg Roach        }
8559599771eSGreg Roach
8569599771eSGreg Roach        $this->facts = $this->parseFacts();
857a25f0a04SGreg Roach    }
858a25f0a04SGreg Roach
859a25f0a04SGreg Roach    /**
860a25f0a04SGreg Roach     * Update this record
861a25f0a04SGreg Roach     *
862a25f0a04SGreg Roach     * @param string $gedcom
863cbc1590aSGreg Roach     * @param bool   $update_chan
8647e96c925SGreg Roach     *
8657e96c925SGreg Roach     * @return void
866a25f0a04SGreg Roach     */
867e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
868c1010edaSGreg Roach    {
86971f696adSGreg Roach        // Not all record types allow a CHAN event.
87071f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
87171f696adSGreg Roach
872a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
873a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
874a25f0a04SGreg Roach        $gedcom = trim($gedcom);
875a25f0a04SGreg Roach
876a25f0a04SGreg Roach        // Update the CHAN record
877a25f0a04SGreg Roach        if ($update_chan) {
87872f8afdbSGreg Roach            if (preg_match('/\n1 CHAN(\n[2-9].*)*/', $gedcom, $match)) {
87972f8afdbSGreg Roach                $gedcom = strtr($gedcom, [$match[0] => $this->updateChange($match[0])]);
88072f8afdbSGreg Roach            } else {
88172f8afdbSGreg Roach                $gedcom .= $this->updateChange("\n1 CHAN");
88272f8afdbSGreg Roach            }
883a25f0a04SGreg Roach        }
884a25f0a04SGreg Roach
885a25f0a04SGreg Roach        // Create a pending change
886d09b6323SGreg Roach        DB::table('change')->insert([
887d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
888d09b6323SGreg Roach            'xref'       => $this->xref,
889d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
890d09b6323SGreg Roach            'new_gedcom' => $gedcom,
891d09b6323SGreg Roach            'user_id'    => Auth::id(),
89213abd6f3SGreg Roach        ]);
893a25f0a04SGreg Roach
894a25f0a04SGreg Roach        // Clear the cache
895a25f0a04SGreg Roach        $this->pending = $gedcom;
896a25f0a04SGreg Roach
897a25f0a04SGreg Roach        // Accept this pending change
8981fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
899b55cbc6bSGreg Roach            $pending_changes_service = app(PendingChangesService::class);
900b55cbc6bSGreg Roach            assert($pending_changes_service instanceof PendingChangesService);
901b55cbc6bSGreg Roach
902b55cbc6bSGreg Roach            $pending_changes_service->acceptRecord($this);
903a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
904a25f0a04SGreg Roach            $this->pending = null;
905a25f0a04SGreg Roach        }
906a25f0a04SGreg Roach
9079599771eSGreg Roach        $this->facts = $this->parseFacts();
908a25f0a04SGreg Roach
909847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
910a25f0a04SGreg Roach    }
911a25f0a04SGreg Roach
912a25f0a04SGreg Roach    /**
913a25f0a04SGreg Roach     * Delete this record
914b874da82SGreg Roach     *
915b874da82SGreg Roach     * @return void
916a25f0a04SGreg Roach     */
917e364afe4SGreg Roach    public function deleteRecord(): void
918c1010edaSGreg Roach    {
919a25f0a04SGreg Roach        // Create a pending change
9204c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
921d09b6323SGreg Roach            DB::table('change')->insert([
922d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
923d09b6323SGreg Roach                'xref'       => $this->xref,
924d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
925d09b6323SGreg Roach                'new_gedcom' => '',
926d09b6323SGreg Roach                'user_id'    => Auth::id(),
92713abd6f3SGreg Roach            ]);
9284c0b5256SGreg Roach        }
929a25f0a04SGreg Roach
9304c0b5256SGreg Roach        // Auto-accept this pending change
9311fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
932b55cbc6bSGreg Roach            $pending_changes_service = app(PendingChangesService::class);
933b55cbc6bSGreg Roach            assert($pending_changes_service instanceof PendingChangesService);
934b55cbc6bSGreg Roach
935b55cbc6bSGreg Roach            $pending_changes_service->acceptRecord($this);
936a25f0a04SGreg Roach        }
937a25f0a04SGreg Roach
938847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
939a25f0a04SGreg Roach    }
940a25f0a04SGreg Roach
941a25f0a04SGreg Roach    /**
942a25f0a04SGreg Roach     * Remove all links from this record to $xref
943a25f0a04SGreg Roach     *
944a25f0a04SGreg Roach     * @param string $xref
945cbc1590aSGreg Roach     * @param bool   $update_chan
9467e96c925SGreg Roach     *
9477e96c925SGreg Roach     * @return void
948a25f0a04SGreg Roach     */
949e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
950c1010edaSGreg Roach    {
951a25f0a04SGreg Roach        $value = '@' . $xref . '@';
952a25f0a04SGreg Roach
95330158ae7SGreg Roach        foreach ($this->facts() as $fact) {
95484586c02SGreg Roach            if ($fact->value() === $value) {
955905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
9568d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
957138ca96cSGreg Roach                $gedcom = $fact->gedcom();
958a25f0a04SGreg Roach                foreach ($matches as $match) {
959a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
960a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
961a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
962a25f0a04SGreg Roach                }
963905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
964a25f0a04SGreg Roach            }
965a25f0a04SGreg Roach        }
966a25f0a04SGreg Roach    }
967bf4eb542SGreg Roach
968bf4eb542SGreg Roach    /**
96922e73debSGreg Roach     * Each object type may have its own special rules, and re-implement this function.
97022e73debSGreg Roach     *
97122e73debSGreg Roach     * @param int $access_level
97222e73debSGreg Roach     *
97322e73debSGreg Roach     * @return bool
97422e73debSGreg Roach     */
97522e73debSGreg Roach    protected function canShowByType(int $access_level): bool
97622e73debSGreg Roach    {
97722e73debSGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
97822e73debSGreg Roach
97922e73debSGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
98022e73debSGreg Roach            // Restriction found
98122e73debSGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
98222e73debSGreg Roach        }
98322e73debSGreg Roach
98422e73debSGreg Roach        // No restriction found - must be public:
98522e73debSGreg Roach        return true;
98622e73debSGreg Roach    }
98722e73debSGreg Roach
98822e73debSGreg Roach    /**
98922e73debSGreg Roach     * Generate a private version of this record
99022e73debSGreg Roach     *
99122e73debSGreg Roach     * @param int $access_level
99222e73debSGreg Roach     *
99322e73debSGreg Roach     * @return string
99422e73debSGreg Roach     */
99522e73debSGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
99622e73debSGreg Roach    {
997228ede81SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
99822e73debSGreg Roach    }
99922e73debSGreg Roach
100022e73debSGreg Roach    /**
100122e73debSGreg Roach     * Convert a name record into sortable and full/display versions. This default
100222e73debSGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
100322e73debSGreg Roach     *
100422e73debSGreg Roach     * @param string $type
100522e73debSGreg Roach     * @param string $value
100622e73debSGreg Roach     * @param string $gedcom
100722e73debSGreg Roach     *
100822e73debSGreg Roach     * @return void
100922e73debSGreg Roach     */
101022e73debSGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
101122e73debSGreg Roach    {
101222e73debSGreg Roach        $this->getAllNames[] = [
101322e73debSGreg Roach            'type'   => $type,
1014dbf91548SGreg Roach            'sort'   => preg_replace_callback('/(\d+)/', static function (array $matches): string {
101522e73debSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
101622e73debSGreg Roach            }, $value),
1017315eb316SGreg Roach            'full'   => '<bdi>' . e($value) . '</bdi>',
101822e73debSGreg Roach            // This is used for display
101922e73debSGreg Roach            'fullNN' => $value,
102022e73debSGreg Roach            // This goes into the database
102122e73debSGreg Roach        ];
102222e73debSGreg Roach    }
102322e73debSGreg Roach
102422e73debSGreg Roach    /**
102522e73debSGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
102622e73debSGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
102722e73debSGreg Roach     * Parameters: the level 1 fact containing the name.
102822e73debSGreg Roach     * Return value: an array of name structures, each containing
102922e73debSGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
103022e73debSGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
103122e73debSGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
103222e73debSGreg Roach     *
103322e73debSGreg Roach     * @param int              $level
103422e73debSGreg Roach     * @param string           $fact_type
103536779af1SGreg Roach     * @param Collection<int,Fact> $facts
103622e73debSGreg Roach     *
103722e73debSGreg Roach     * @return void
103822e73debSGreg Roach     */
103922e73debSGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
104022e73debSGreg Roach    {
104122e73debSGreg Roach        $sublevel    = $level + 1;
104222e73debSGreg Roach        $subsublevel = $sublevel + 1;
104322e73debSGreg Roach        foreach ($facts as $fact) {
1044c8ff5fdcSGreg Roach            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
104522e73debSGreg Roach                foreach ($matches as $match) {
104622e73debSGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1047cc9d82dcSGreg Roach                    if ($match[1] === 'NAME' && str_contains(strtoupper($match[3]), "\n2 TYPE MARRIED")) {
104822e73debSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
104922e73debSGreg Roach                    } else {
105022e73debSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
105122e73debSGreg Roach                    }
1052c8ff5fdcSGreg Roach                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
105322e73debSGreg Roach                        foreach ($submatches as $submatch) {
10542d21e9c2SGreg Roach                            if ($submatch[1] !== '_RUFNAME') {
105522e73debSGreg Roach                                $this->addName($submatch[1], $submatch[2], $match[3]);
105622e73debSGreg Roach                            }
105722e73debSGreg Roach                        }
105822e73debSGreg Roach                    }
105922e73debSGreg Roach                }
106022e73debSGreg Roach            }
106122e73debSGreg Roach        }
10622d21e9c2SGreg Roach    }
106322e73debSGreg Roach
106422e73debSGreg Roach    /**
106522e73debSGreg Roach     * Split the record into facts
106622e73debSGreg Roach     *
10679599771eSGreg Roach     * @return array<Fact>
106822e73debSGreg Roach     */
10699599771eSGreg Roach    private function parseFacts(): array
107022e73debSGreg Roach    {
107122e73debSGreg Roach        // Split the record into facts
107222e73debSGreg Roach        if ($this->gedcom) {
1073d823340dSGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
107422e73debSGreg Roach            array_shift($gedcom_facts);
107522e73debSGreg Roach        } else {
107622e73debSGreg Roach            $gedcom_facts = [];
107722e73debSGreg Roach        }
107822e73debSGreg Roach        if ($this->pending) {
1079d823340dSGreg Roach            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
108022e73debSGreg Roach            array_shift($pending_facts);
108122e73debSGreg Roach        } else {
108222e73debSGreg Roach            $pending_facts = [];
108322e73debSGreg Roach        }
108422e73debSGreg Roach
10859599771eSGreg Roach        $facts = [];
108622e73debSGreg Roach
108722e73debSGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
108822e73debSGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
108922e73debSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
109022e73debSGreg Roach                $fact->setPendingDeletion();
109122e73debSGreg Roach            }
10929599771eSGreg Roach            $facts[] = $fact;
109322e73debSGreg Roach        }
109422e73debSGreg Roach        foreach ($pending_facts as $pending_fact) {
109522e73debSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
109622e73debSGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
109722e73debSGreg Roach                $fact->setPendingAddition();
10989599771eSGreg Roach                $facts[] = $fact;
109922e73debSGreg Roach            }
110022e73debSGreg Roach        }
11019599771eSGreg Roach
11029599771eSGreg Roach        return $facts;
110322e73debSGreg Roach    }
110422e73debSGreg Roach
110522e73debSGreg Roach    /**
110622e73debSGreg Roach     * Work out whether this record can be shown to a user with a given access level
110722e73debSGreg Roach     *
110822e73debSGreg Roach     * @param int $access_level
110922e73debSGreg Roach     *
111022e73debSGreg Roach     * @return bool
111122e73debSGreg Roach     */
111222e73debSGreg Roach    private function canShowRecord(int $access_level): bool
111322e73debSGreg Roach    {
111422e73debSGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
111522e73debSGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
111622e73debSGreg Roach            return true;
111722e73debSGreg Roach        }
111822e73debSGreg Roach
111922e73debSGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
11201fe542e9SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
112122e73debSGreg Roach            return true;
112222e73debSGreg Roach        }
112322e73debSGreg Roach
112455105892SGreg Roach        // Does this record have a restriction notice?
1125da7adf56SGreg Roach        // Cannot use $this->>fact(), as that function calls this one.
112655105892SGreg Roach        if (preg_match('/\n1 RESN (.+)/', $this->gedcom(), $match)) {
112755105892SGreg Roach            $element     = new RestrictionNotice('');
112855105892SGreg Roach            $restriction = $element->canonical($match[1]);
112955105892SGreg Roach
113055105892SGreg Roach            if (str_starts_with($restriction, RestrictionNotice::VALUE_CONFIDENTIAL)) {
113122e73debSGreg Roach                return Auth::PRIV_NONE >= $access_level;
113222e73debSGreg Roach            }
113355105892SGreg Roach            if (str_starts_with($restriction, RestrictionNotice::VALUE_PRIVACY)) {
113422e73debSGreg Roach                return Auth::PRIV_USER >= $access_level;
113522e73debSGreg Roach            }
113655105892SGreg Roach            if (str_starts_with($restriction, RestrictionNotice::VALUE_NONE)) {
113722e73debSGreg Roach                return true;
113822e73debSGreg Roach            }
113955105892SGreg Roach        }
114022e73debSGreg Roach
114122e73debSGreg Roach        // Does this record have a default RESN?
114222e73debSGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
114322e73debSGreg Roach        if (isset($individual_privacy[$this->xref()])) {
114422e73debSGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
114522e73debSGreg Roach        }
114622e73debSGreg Roach
114722e73debSGreg Roach        // Privacy rules do not apply to admins
114822e73debSGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
114922e73debSGreg Roach            return true;
115022e73debSGreg Roach        }
115122e73debSGreg Roach
115222e73debSGreg Roach        // Different types of record have different privacy rules
115322e73debSGreg Roach        return $this->canShowByType($access_level);
115422e73debSGreg Roach    }
11558091bfd1SGreg Roach
11568091bfd1SGreg Roach    /**
11578091bfd1SGreg Roach     * Lock the database row, to prevent concurrent edits.
11588091bfd1SGreg Roach     */
11598091bfd1SGreg Roach    public function lock(): void
11608091bfd1SGreg Roach    {
11618091bfd1SGreg Roach        DB::table('other')
11628091bfd1SGreg Roach            ->where('o_file', '=', $this->tree->id())
11638091bfd1SGreg Roach            ->where('o_id', '=', $this->xref())
11648091bfd1SGreg Roach            ->lockForUpdate()
11658091bfd1SGreg Roach            ->get();
11668091bfd1SGreg Roach    }
116772f8afdbSGreg Roach
116872f8afdbSGreg Roach    /**
116972f8afdbSGreg Roach     * Change records may contain notes and other fields.  Just update the date/time/author.
117072f8afdbSGreg Roach     *
117172f8afdbSGreg Roach     * @param string $gedcom
117272f8afdbSGreg Roach     *
117372f8afdbSGreg Roach     * @return string
117472f8afdbSGreg Roach     */
1175*5cba5dc7SGreg Roach    private function updateChange(string $gedcom): string
1176*5cba5dc7SGreg Roach    {
117772f8afdbSGreg Roach        $gedcom = preg_replace('/\n2 (DATE|_WT_USER).*(\n[3-9].*)*/', '', $gedcom);
117872f8afdbSGreg Roach        $today  = strtoupper(date('d M Y'));
117972f8afdbSGreg Roach        $now    = date('H:i:s');
118072f8afdbSGreg Roach        $author = Auth::user()->userName();
118172f8afdbSGreg Roach
118272f8afdbSGreg Roach        return $gedcom . "\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . $author;
118372f8afdbSGreg Roach    }
1184a25f0a04SGreg Roach}
1185