xref: /webtrees/app/GedcomRecord.php (revision 2c6f1bd538f46b93645991518398bb087011cb42)
1a25f0a04SGreg Roach<?php
23976b470SGreg Roach
3a25f0a04SGreg Roach/**
4a25f0a04SGreg Roach * webtrees: online genealogy
5d11be702SGreg Roach * Copyright (C) 2023 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;
2939ca88baSGreg Roachuse Illuminate\Support\Collection;
30a25f0a04SGreg Roach
310f5fd22fSGreg Roachuse function array_combine;
320f5fd22fSGreg Roachuse function array_keys;
330f5fd22fSGreg Roachuse function array_map;
340f5fd22fSGreg Roachuse function array_search;
35f7440925SGreg Roachuse function array_shift;
36f7440925SGreg Roachuse function count;
37f7440925SGreg Roachuse function date;
38f7440925SGreg Roachuse function e;
39f7440925SGreg Roachuse function explode;
40a79e52aaSGreg Roachuse function implode;
41f7440925SGreg Roachuse function in_array;
42f7440925SGreg Roachuse function md5;
43f7440925SGreg Roachuse function preg_match;
44f7440925SGreg Roachuse function preg_match_all;
45f7440925SGreg Roachuse function preg_replace;
46f7440925SGreg Roachuse function preg_replace_callback;
47f7440925SGreg Roachuse function preg_split;
480f5fd22fSGreg Roachuse function range;
49f7440925SGreg Roachuse function route;
50dec352c1SGreg Roachuse function str_contains;
51d0889c63SGreg Roachuse function str_ends_with;
52f7440925SGreg Roachuse function str_pad;
5355105892SGreg Roachuse function str_starts_with;
54f7440925SGreg Roachuse function strtoupper;
5572f8afdbSGreg Roachuse function strtr;
56f7440925SGreg Roachuse function trim;
57b315f3e1SGreg Roachuse function view;
58b315f3e1SGreg Roach
59c2ed51d1SGreg Roachuse const PHP_INT_MAX;
60f7440925SGreg Roachuse const PREG_SET_ORDER;
61f7440925SGreg Roachuse const STR_PAD_LEFT;
6222e73debSGreg Roach
63a25f0a04SGreg Roach/**
6476692c8bSGreg Roach * A GEDCOM object.
65a25f0a04SGreg Roach */
66c1010edaSGreg Roachclass GedcomRecord
67c1010edaSGreg Roach{
6816d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
6916d6367aSGreg Roach
705818a371SGreg Roach    protected const ROUTE_NAME = GedcomRecordPage::class;
715818a371SGreg Roach
729599771eSGreg Roach    protected string $xref;
73bb03c9f0SGreg Roach
749599771eSGreg Roach    protected Tree $tree;
75bb03c9f0SGreg Roach
769599771eSGreg Roach    // GEDCOM data (before any pending edits)
779599771eSGreg Roach    protected string $gedcom;
78bb03c9f0SGreg Roach
799599771eSGreg Roach    // GEDCOM data (after any pending edits)
809599771eSGreg Roach    protected ?string $pending;
81bb03c9f0SGreg Roach
829599771eSGreg Roach    /** @var array<Fact> Facts extracted from $gedcom/$pending */
839599771eSGreg Roach    protected array $facts;
84bb03c9f0SGreg Roach
8509482a55SGreg Roach    /** @var array<array<string>> All the names of this individual */
869599771eSGreg Roach    protected array $getAllNames = [];
87bb03c9f0SGreg Roach
8822e73debSGreg Roach    /** @var int|null Cached result */
899599771eSGreg Roach    private ?int $getPrimaryName = null;
90c4943cffSGreg Roach
9122e73debSGreg Roach    /** @var int|null Cached result */
929599771eSGreg Roach    private ?int $getSecondaryName = null;
93a25f0a04SGreg Roach
94a25f0a04SGreg Roach    /**
95a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
96a25f0a04SGreg Roach     *
97a25f0a04SGreg Roach     * @param string      $xref
98a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
99a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
100a25f0a04SGreg Roach     *                             empty string for records with pending deletions
10124ec66ceSGreg Roach     * @param Tree        $tree
102a25f0a04SGreg Roach     */
103e364afe4SGreg Roach    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
104c1010edaSGreg Roach    {
105a25f0a04SGreg Roach        $this->xref    = $xref;
106a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
107a25f0a04SGreg Roach        $this->pending = $pending;
10824ec66ceSGreg Roach        $this->tree    = $tree;
1099599771eSGreg Roach        $this->facts   = $this->parseFacts();
110a25f0a04SGreg Roach    }
111a25f0a04SGreg Roach
112a25f0a04SGreg Roach    /**
113886b77daSGreg Roach     * A closure which will filter out private records.
114886b77daSGreg Roach     *
115c6921a17SGreg Roach     * @return Closure(GedcomRecord):bool
116886b77daSGreg Roach     */
1174146fabcSGreg Roach    public static function accessFilter(): Closure
118886b77daSGreg Roach    {
1196c2179e2SGreg Roach        return static function (GedcomRecord $record): bool {
120886b77daSGreg Roach            return $record->canShow();
121886b77daSGreg Roach        };
122886b77daSGreg Roach    }
123886b77daSGreg Roach
124886b77daSGreg Roach    /**
125c156e8f5SGreg Roach     * A closure which will compare records by name.
126c156e8f5SGreg Roach     *
127c6921a17SGreg Roach     * @return Closure(GedcomRecord,GedcomRecord):int
128c156e8f5SGreg Roach     */
129c156e8f5SGreg Roach    public static function nameComparator(): Closure
130c156e8f5SGreg Roach    {
1316c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y): int {
132c156e8f5SGreg Roach            if ($x->canShowName()) {
133c156e8f5SGreg Roach                if ($y->canShowName()) {
13437646143SGreg Roach                    return I18N::comparator()($x->sortName(), $y->sortName());
135c156e8f5SGreg Roach                }
136c156e8f5SGreg Roach
137c156e8f5SGreg Roach                return -1; // only $y is private
138c156e8f5SGreg Roach            }
139c156e8f5SGreg Roach
140c156e8f5SGreg Roach            if ($y->canShowName()) {
141c156e8f5SGreg Roach                return 1; // only $x is private
142c156e8f5SGreg Roach            }
143c156e8f5SGreg Roach
144c156e8f5SGreg Roach            return 0; // both $x and $y private
145c156e8f5SGreg Roach        };
146c156e8f5SGreg Roach    }
147c156e8f5SGreg Roach
148c156e8f5SGreg Roach    /**
149c156e8f5SGreg Roach     * A closure which will compare records by change time.
150c156e8f5SGreg Roach     *
151c156e8f5SGreg Roach     * @param int $direction +1 to sort ascending, -1 to sort descending
152c156e8f5SGreg Roach     *
153c6921a17SGreg Roach     * @return Closure(GedcomRecord,GedcomRecord):int
154c156e8f5SGreg Roach     */
155c156e8f5SGreg Roach    public static function lastChangeComparator(int $direction = 1): Closure
156c156e8f5SGreg Roach    {
1576c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
1584459dc9aSGreg Roach            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
159c156e8f5SGreg Roach        };
160c156e8f5SGreg Roach    }
161c156e8f5SGreg Roach
162c156e8f5SGreg Roach    /**
16302467d32SGreg Roach     * Get the GEDCOM tag for this record.
16402467d32SGreg Roach     *
16502467d32SGreg Roach     * @return string
16602467d32SGreg Roach     */
16702467d32SGreg Roach    public function tag(): string
16802467d32SGreg Roach    {
16902467d32SGreg Roach        preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
17002467d32SGreg Roach
17102467d32SGreg Roach        return $match[1] ?? static::RECORD_TYPE;
17202467d32SGreg Roach    }
17302467d32SGreg Roach
17402467d32SGreg Roach    /**
175a25f0a04SGreg Roach     * Get the XREF for this record
176a25f0a04SGreg Roach     *
177a25f0a04SGreg Roach     * @return string
178a25f0a04SGreg Roach     */
179c0935879SGreg Roach    public function xref(): string
180c1010edaSGreg Roach    {
181a25f0a04SGreg Roach        return $this->xref;
182a25f0a04SGreg Roach    }
183a25f0a04SGreg Roach
184a25f0a04SGreg Roach    /**
185000959d9SGreg Roach     * Get the tree to which this record belongs
186000959d9SGreg Roach     *
187000959d9SGreg Roach     * @return Tree
188000959d9SGreg Roach     */
189f4afa648SGreg Roach    public function tree(): Tree
190c1010edaSGreg Roach    {
191518bbdc1SGreg Roach        return $this->tree;
192000959d9SGreg Roach    }
193000959d9SGreg Roach
194000959d9SGreg Roach    /**
195a25f0a04SGreg Roach     * Application code should access data via Fact objects.
196a25f0a04SGreg Roach     * This function exists to support old code.
197a25f0a04SGreg Roach     *
198a25f0a04SGreg Roach     * @return string
199a25f0a04SGreg Roach     */
200e364afe4SGreg Roach    public function gedcom(): string
201c1010edaSGreg Roach    {
202b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
203a25f0a04SGreg Roach    }
204a25f0a04SGreg Roach
205a25f0a04SGreg Roach    /**
206a25f0a04SGreg Roach     * Does this record have a pending change?
207a25f0a04SGreg Roach     *
208cbc1590aSGreg Roach     * @return bool
209a25f0a04SGreg Roach     */
2108f53f488SRico Sonntag    public function isPendingAddition(): bool
211c1010edaSGreg Roach    {
212a25f0a04SGreg Roach        return $this->pending !== null;
213a25f0a04SGreg Roach    }
214a25f0a04SGreg Roach
215a25f0a04SGreg Roach    /**
216a25f0a04SGreg Roach     * Does this record have a pending deletion?
217a25f0a04SGreg Roach     *
218cbc1590aSGreg Roach     * @return bool
219a25f0a04SGreg Roach     */
2208f53f488SRico Sonntag    public function isPendingDeletion(): bool
221c1010edaSGreg Roach    {
222a25f0a04SGreg Roach        return $this->pending === '';
223a25f0a04SGreg Roach    }
224a25f0a04SGreg Roach
225a25f0a04SGreg Roach    /**
226225e381fSGreg Roach     * Generate a URL to this record.
227a25f0a04SGreg Roach     *
228a25f0a04SGreg Roach     * @return string
229a25f0a04SGreg Roach     */
2308f53f488SRico Sonntag    public function url(): string
231c1010edaSGreg Roach    {
232225e381fSGreg Roach        return route(static::ROUTE_NAME, [
233c0935879SGreg Roach            'xref' => $this->xref(),
234ee4364daSGreg Roach            'tree' => $this->tree->name(),
235194b0938SGreg Roach            'slug' => Registry::slugFactory()->make($this),
236225e381fSGreg Roach        ]);
237a25f0a04SGreg Roach    }
238a25f0a04SGreg Roach
239a25f0a04SGreg Roach    /**
240a25f0a04SGreg Roach     * Can the details of this record be shown?
241a25f0a04SGreg Roach     *
242cbc1590aSGreg Roach     * @param int|null $access_level
243a25f0a04SGreg Roach     *
244cbc1590aSGreg Roach     * @return bool
245a25f0a04SGreg Roach     */
246*2c6f1bd5SGreg Roach    public function canShow(int|null $access_level = null): bool
247c1010edaSGreg Roach    {
2483529c469SGreg Roach        $access_level ??= Auth::accessLevel($this->tree);
2494b9ff166SGreg Roach
250a25f0a04SGreg Roach        // We use this value to bypass privacy checks. For example,
251a25f0a04SGreg Roach        // when downloading data or when calculating privacy itself.
252f0b9c048SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
253a25f0a04SGreg Roach            return true;
254a25f0a04SGreg Roach        }
255f0b9c048SGreg Roach
2567476e8a5SGreg Roach        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
257f0b9c048SGreg Roach
2586b9cb339SGreg Roach        return Registry::cache()->array()->remember($cache_key, function () use ($access_level) {
259f0b9c048SGreg Roach            return $this->canShowRecord($access_level);
260f0b9c048SGreg Roach        });
261a25f0a04SGreg Roach    }
262a25f0a04SGreg Roach
263a25f0a04SGreg Roach    /**
264a25f0a04SGreg Roach     * Can the name of this record be shown?
265a25f0a04SGreg Roach     *
266cbc1590aSGreg Roach     * @param int|null $access_level
267a25f0a04SGreg Roach     *
268cbc1590aSGreg Roach     * @return bool
269a25f0a04SGreg Roach     */
270*2c6f1bd5SGreg Roach    public function canShowName(int|null $access_level = null): bool
271c1010edaSGreg Roach    {
272a25f0a04SGreg Roach        return $this->canShow($access_level);
273a25f0a04SGreg Roach    }
274a25f0a04SGreg Roach
275a25f0a04SGreg Roach    /**
276a25f0a04SGreg Roach     * Can we edit this record?
277a25f0a04SGreg Roach     *
278cbc1590aSGreg Roach     * @return bool
279a25f0a04SGreg Roach     */
2808f53f488SRico Sonntag    public function canEdit(): bool
281c1010edaSGreg Roach    {
2821450f098SGreg Roach        if ($this->isPendingDeletion()) {
2831450f098SGreg Roach            return false;
2841450f098SGreg Roach        }
2851450f098SGreg Roach
2861450f098SGreg Roach        if (Auth::isManager($this->tree)) {
2871450f098SGreg Roach            return true;
2881450f098SGreg Roach        }
2891450f098SGreg Roach
29055105892SGreg Roach        $fact   = $this->facts(['RESN'])->first();
29155105892SGreg Roach        $locked = $fact instanceof Fact && str_ends_with($fact->attribute('RESN'), RestrictionNotice::VALUE_LOCKED);
29255105892SGreg Roach
29355105892SGreg Roach        return Auth::isEditor($this->tree) && !$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) {
3899d15b78eSGreg 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    /**
426a2c8afeaSAlejandro Criado-Pérez     * Allow the choice of primary name to be overridden, e.g. in a search result
427a25f0a04SGreg Roach     *
42876f666f4SGreg Roach     * @param int|null $n
4297e96c925SGreg Roach     *
4307e96c925SGreg Roach     * @return void
431a25f0a04SGreg Roach     */
432*2c6f1bd5SGreg Roach    public function setPrimaryName(int|null $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    {
501a79e52aaSGreg Roach        $html = '<a href="' . e($this->url()) . '">';
50239ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
503b165e17cSGreg Roach        $html .= '</a>';
504a79e52aaSGreg Roach        $html .= $this->formatListDetails();
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    {
530a79e52aaSGreg Roach        $fact = $this->facts($facts, true)->first();
531a79e52aaSGreg Roach
532a79e52aaSGreg Roach        if ($fact === null) {
533a79e52aaSGreg Roach            return '';
534a25f0a04SGreg Roach        }
535cbc1590aSGreg Roach
536a79e52aaSGreg Roach        // Only display if it has a date or place (or both)
537a79e52aaSGreg Roach        $attributes = [];
538a79e52aaSGreg Roach
539a79e52aaSGreg Roach        if ($fact->date()->isOK()) {
540a79e52aaSGreg Roach            $attributes[] = view('fact-date', ['cal_link' => 'false', 'fact' => $fact, 'record' => $fact->record(), 'time' => false]);
541a79e52aaSGreg Roach        }
542a79e52aaSGreg Roach
543a79e52aaSGreg Roach        if ($fact->place()->gedcomName() !== '' && $style === 2) {
544a79e52aaSGreg Roach            $attributes[] = $fact->place()->shortName();
545a79e52aaSGreg Roach        }
546a79e52aaSGreg Roach
547a79e52aaSGreg Roach        if ($attributes === []) {
548a25f0a04SGreg Roach            return '';
549a25f0a04SGreg Roach        }
550a25f0a04SGreg Roach
551a79e52aaSGreg Roach        return '<div><em>' . I18N::translate('%1$s: %2$s', $fact->label(), implode(' — ', $attributes)) . '</em></div>';
552a79e52aaSGreg Roach    }
553a79e52aaSGreg Roach
554a25f0a04SGreg Roach    /**
555a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
556a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
557a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
558a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
559a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
560a25f0a04SGreg Roach     *
56109482a55SGreg Roach     * @param array<string> $events
562a25f0a04SGreg Roach     *
56309482a55SGreg Roach     * @return array<Date>
564a25f0a04SGreg Roach     */
5658d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
566c1010edaSGreg Roach    {
56713abd6f3SGreg Roach        $dates = [];
5681385b8caSGreg Roach        foreach ($this->facts($events, false, null, true) as $event) {
5692decada7SGreg Roach            if ($event->date()->isOK()) {
5702decada7SGreg Roach                $dates[] = $event->date();
571a25f0a04SGreg Roach            }
572a25f0a04SGreg Roach        }
573a25f0a04SGreg Roach
574a25f0a04SGreg Roach        return $dates;
575a25f0a04SGreg Roach    }
576a25f0a04SGreg Roach
577a25f0a04SGreg Roach    /**
578a25f0a04SGreg Roach     * Get all the places for a particular type of event
579a25f0a04SGreg Roach     *
58009482a55SGreg Roach     * @param array<string> $events
581a25f0a04SGreg Roach     *
58209482a55SGreg Roach     * @return array<Place>
583a25f0a04SGreg Roach     */
5848d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
585c1010edaSGreg Roach    {
58613abd6f3SGreg Roach        $places = [];
5878d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
588138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
589a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
59016d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
591a25f0a04SGreg Roach                }
592a25f0a04SGreg Roach            }
593a25f0a04SGreg Roach        }
594a25f0a04SGreg Roach
595a25f0a04SGreg Roach        return $places;
596a25f0a04SGreg Roach    }
597a25f0a04SGreg Roach
598a25f0a04SGreg Roach    /**
599a25f0a04SGreg Roach     * The facts and events for this record.
600a25f0a04SGreg Roach     *
60109482a55SGreg Roach     * @param array<string> $filter
602cbc1590aSGreg Roach     * @param bool          $sort
603cbc1590aSGreg Roach     * @param int|null      $access_level
604ce42304aSGreg Roach     * @param bool          $ignore_deleted
605a25f0a04SGreg Roach     *
60636779af1SGreg Roach     * @return Collection<int,Fact>
607a25f0a04SGreg Roach     */
608ce42304aSGreg Roach    public function facts(
609ce42304aSGreg Roach        array $filter = [],
610ce42304aSGreg Roach        bool $sort = false,
611*2c6f1bd5SGreg Roach        int|null $access_level = null,
612ce42304aSGreg Roach        bool $ignore_deleted = false
613ce42304aSGreg Roach    ): Collection {
6143529c469SGreg Roach        $access_level ??= Auth::accessLevel($this->tree);
6154b9ff166SGreg Roach
616d0889c63SGreg Roach        // Convert BIRT into INDI:BIRT, etc.
617d0889c63SGreg Roach        $filter = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, $filter);
618d0889c63SGreg Roach
6198af3e5c1SGreg Roach        $facts = new Collection();
620ce42304aSGreg Roach        if ($this->canShow($access_level)) {
621a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
622d0889c63SGreg Roach                if (($filter === [] || in_array($fact->tag(), $filter, true)) && $fact->canShow($access_level)) {
6238af3e5c1SGreg Roach                    $facts->push($fact);
624a25f0a04SGreg Roach                }
625a25f0a04SGreg Roach            }
626a25f0a04SGreg Roach        }
627d17d7b9eSGreg Roach
628a25f0a04SGreg Roach        if ($sort) {
6290f5fd22fSGreg Roach            switch ($this->tag()) {
6300f5fd22fSGreg Roach                case Family::RECORD_TYPE:
6310f5fd22fSGreg Roach                case Individual::RECORD_TYPE:
632580a4d11SGreg Roach                    $facts = Fact::sortFacts($facts);
6330f5fd22fSGreg Roach                    break;
6340f5fd22fSGreg Roach
6350f5fd22fSGreg Roach                default:
6360f5fd22fSGreg Roach                    $subtags = Registry::elementFactory()->make($this->tag())->subtags();
6370f5fd22fSGreg Roach                    $subtags = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, array_keys($subtags));
6381259996fSGreg Roach
6391259996fSGreg Roach                    if ($subtags !== []) {
6401259996fSGreg Roach                        // Renumber keys from 1.
6410f5fd22fSGreg Roach                        $subtags = array_combine(range(1, count($subtags)), $subtags);
6421259996fSGreg Roach                    }
6431259996fSGreg Roach
6440f5fd22fSGreg Roach
6450f5fd22fSGreg Roach                    $facts = $facts
6460f5fd22fSGreg Roach                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
6470f5fd22fSGreg Roach                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
6480f5fd22fSGreg Roach                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
6490f5fd22fSGreg Roach
6500f5fd22fSGreg Roach                            return $sort_x <=> $sort_y;
6510f5fd22fSGreg Roach                        });
6520f5fd22fSGreg Roach                    break;
6530f5fd22fSGreg Roach            }
654a25f0a04SGreg Roach        }
655cbc1590aSGreg Roach
656ce42304aSGreg Roach        if ($ignore_deleted) {
657ce42304aSGreg Roach            $facts = $facts->filter(static function (Fact $fact): bool {
658ce42304aSGreg Roach                return !$fact->isPendingDeletion();
659ce42304aSGreg Roach            });
660ce42304aSGreg Roach        }
661ce42304aSGreg Roach
6625fef3bfaSGreg Roach        return $facts;
663a25f0a04SGreg Roach    }
664a25f0a04SGreg Roach
665a25f0a04SGreg Roach    /**
6660f5fd22fSGreg Roach     * @return array<string,string>
6670f5fd22fSGreg Roach     */
6680f5fd22fSGreg Roach    public function missingFacts(): array
6690f5fd22fSGreg Roach    {
6700f5fd22fSGreg Roach        $missing_facts = [];
6710f5fd22fSGreg Roach
6720f5fd22fSGreg Roach        foreach (Registry::elementFactory()->make($this->tag())->subtags() as $subtag => $repeat) {
6730f5fd22fSGreg Roach            [, $max] = explode(':', $repeat);
6740f5fd22fSGreg Roach            $max = $max === 'M' ? PHP_INT_MAX : (int) $max;
6750f5fd22fSGreg Roach
67698f93f3aSGreg Roach            if ($this->facts([$subtag], false, null, true)->count() < $max) {
6770f5fd22fSGreg Roach                $missing_facts[$subtag] = $subtag;
6780f5fd22fSGreg Roach                $missing_facts[$subtag] = Registry::elementFactory()->make($this->tag() . ':' . $subtag)->label();
6790f5fd22fSGreg Roach            }
6800f5fd22fSGreg Roach        }
6810f5fd22fSGreg Roach
6820f5fd22fSGreg Roach        uasort($missing_facts, I18N::comparator());
6830f5fd22fSGreg Roach
6845416d6ddSGreg Roach        if (!Auth::canUploadMedia($this->tree, Auth::user())) {
6850f5fd22fSGreg Roach            unset($missing_facts['OBJE']);
6860f5fd22fSGreg Roach        }
6870f5fd22fSGreg Roach
6880f5fd22fSGreg Roach        // We have special code for this.
6890f5fd22fSGreg Roach        unset($missing_facts['FILE']);
6900f5fd22fSGreg Roach
6910f5fd22fSGreg Roach        return $missing_facts;
6920f5fd22fSGreg Roach    }
6930f5fd22fSGreg Roach
6940f5fd22fSGreg Roach    /**
6954459dc9aSGreg Roach     * Get the last-change timestamp for this record
696a25f0a04SGreg Roach     *
69776d39c55SGreg Roach     * @return TimestampInterface
698a25f0a04SGreg Roach     */
69976d39c55SGreg Roach    public function lastChangeTimestamp(): TimestampInterface
700c1010edaSGreg Roach    {
701820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
702a25f0a04SGreg Roach
7034459dc9aSGreg Roach        if ($chan instanceof Fact) {
70403f2cc61SGreg Roach            // The record has a CHAN event.
70586c727c1SGreg Roach            $date = $chan->date()->minimumDate();
70686c727c1SGreg Roach            $ymd = sprintf('%04d-%02d-%02d', $date->year(), $date->month(), $date->day());
7074459dc9aSGreg Roach
70886c727c1SGreg Roach            if ($ymd !== '') {
70903f2cc61SGreg Roach                // The CHAN event has a valid DATE.
71086c727c1SGreg Roach                if (preg_match('/\n3 TIME (([01]\d|2[0-3]):([0-5]\d):([0-5]\d))/', $chan->gedcom(), $match) === 1) {
71186c727c1SGreg Roach                    return Registry::timestampFactory()->fromString($ymd . $match[1], 'Y-m-d H:i:s');
712e364afe4SGreg Roach                }
713e364afe4SGreg Roach
71486c727c1SGreg Roach                if (preg_match('/\n3 TIME (([01]\d|2[0-3]):([0-5]\d))/', $chan->gedcom(), $match) === 1) {
71586c727c1SGreg Roach                    return Registry::timestampFactory()->fromString($ymd . $match[1], 'Y-m-d H:i');
716b2ce94c6SRico Sonntag                }
717b2ce94c6SRico Sonntag
71886c727c1SGreg Roach                return Registry::timestampFactory()->fromString($ymd, 'Y-m-d');
719a25f0a04SGreg Roach            }
72003f2cc61SGreg Roach        }
721b2ce94c6SRico Sonntag
722a25f0a04SGreg Roach        // The record does not have a CHAN event
723d97083feSGreg Roach        return Registry::timestampFactory()->make(0);
724a25f0a04SGreg Roach    }
725a25f0a04SGreg Roach
726a25f0a04SGreg Roach    /**
727a25f0a04SGreg Roach     * Get the last-change user for this record
728a25f0a04SGreg Roach     *
729a25f0a04SGreg Roach     * @return string
730a25f0a04SGreg Roach     */
731e364afe4SGreg Roach    public function lastChangeUser(): string
732c1010edaSGreg Roach    {
733820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
734a25f0a04SGreg Roach
735a25f0a04SGreg Roach        if ($chan === null) {
736a25f0a04SGreg Roach            return I18N::translate('Unknown');
737b2ce94c6SRico Sonntag        }
738b2ce94c6SRico Sonntag
7393425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
740baacc364SGreg Roach        if ($chan_user === '') {
741a25f0a04SGreg Roach            return I18N::translate('Unknown');
742b2ce94c6SRico Sonntag        }
743b2ce94c6SRico Sonntag
744a25f0a04SGreg Roach        return $chan_user;
745a25f0a04SGreg Roach    }
746a25f0a04SGreg Roach
747a25f0a04SGreg Roach    /**
748a25f0a04SGreg Roach     * Add a new fact to this record
749a25f0a04SGreg Roach     *
750a25f0a04SGreg Roach     * @param string $gedcom
751cbc1590aSGreg Roach     * @param bool   $update_chan
7527e96c925SGreg Roach     *
7537e96c925SGreg Roach     * @return void
754a25f0a04SGreg Roach     */
755e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
756c1010edaSGreg Roach    {
757fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
758a25f0a04SGreg Roach    }
759a25f0a04SGreg Roach
760a25f0a04SGreg Roach    /**
761a25f0a04SGreg Roach     * Delete a fact from this record
762a25f0a04SGreg Roach     *
763a25f0a04SGreg Roach     * @param string $fact_id
764cbc1590aSGreg Roach     * @param bool   $update_chan
7657e96c925SGreg Roach     *
7667e96c925SGreg Roach     * @return void
767a25f0a04SGreg Roach     */
768e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
769c1010edaSGreg Roach    {
770db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
771a25f0a04SGreg Roach    }
772a25f0a04SGreg Roach
773a25f0a04SGreg Roach    /**
774a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
775a25f0a04SGreg Roach     *
776a25f0a04SGreg Roach     * @param string $fact_id
777a25f0a04SGreg Roach     * @param string $gedcom
778cbc1590aSGreg Roach     * @param bool   $update_chan
779a25f0a04SGreg Roach     *
7807e96c925SGreg Roach     * @return void
7817e96c925SGreg Roach     * @throws Exception
782a25f0a04SGreg Roach     */
783e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
784c1010edaSGreg Roach    {
78571f696adSGreg Roach        // Not all record types allow a CHAN event.
78671f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
78771f696adSGreg Roach
788a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
789a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
790a25f0a04SGreg Roach        $gedcom = trim($gedcom);
791a25f0a04SGreg Roach
792a25f0a04SGreg Roach        if ($this->pending === '') {
7937e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
794a25f0a04SGreg Roach        }
7958d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
7967e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
797a25f0a04SGreg Roach        }
798a25f0a04SGreg Roach
799b6ec1ccfSGreg Roach        if ($this->pending !== null && $this->pending !== '') {
800a25f0a04SGreg Roach            $old_gedcom = $this->pending;
801a25f0a04SGreg Roach        } else {
802a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
803a25f0a04SGreg Roach        }
804a25f0a04SGreg Roach
805a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
80665e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
807a25f0a04SGreg Roach
808a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
80919aed3a1SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
810905ab80aSGreg Roach            if ($fact->id() === $fact_id) {
811db7bb364SGreg Roach                if ($gedcom !== '') {
812a25f0a04SGreg Roach                    $new_gedcom .= "\n" . $gedcom;
813a25f0a04SGreg Roach                }
814fc3ccce4SGreg Roach                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
81572f8afdbSGreg Roach            } elseif ($update_chan && str_ends_with($fact->tag(), ':CHAN')) {
81672f8afdbSGreg Roach                $new_gedcom .= "\n" . $this->updateChange($fact->gedcom());
81772f8afdbSGreg Roach            } else {
818138ca96cSGreg Roach                $new_gedcom .= "\n" . $fact->gedcom();
819a25f0a04SGreg Roach            }
820a25f0a04SGreg Roach        }
821a25f0a04SGreg Roach
822a25f0a04SGreg Roach        // Adding a new fact
823fc3ccce4SGreg Roach        if ($fact_id === '') {
824a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
825a25f0a04SGreg Roach        }
826a25f0a04SGreg Roach
827dec352c1SGreg Roach        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
82872f8afdbSGreg Roach            $new_gedcom .= $this->updateChange("\n1 CHAN");
82919aed3a1SGreg Roach        }
83019aed3a1SGreg Roach
831e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
832a25f0a04SGreg Roach            // Save the changes
833d09b6323SGreg Roach            DB::table('change')->insert([
834d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
835d09b6323SGreg Roach                'xref'       => $this->xref,
836d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
837d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
8385ae3edd9SGreg Roach                'status'     => 'pending',
839d09b6323SGreg Roach                'user_id'    => Auth::id(),
84013abd6f3SGreg Roach            ]);
841a25f0a04SGreg Roach
842a25f0a04SGreg Roach            $this->pending = $new_gedcom;
843a25f0a04SGreg Roach
8441fe542e9SGreg Roach            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
845d35568b4SGreg Roach                $pending_changes_service = Registry::container()->get(PendingChangesService::class);
846b55cbc6bSGreg Roach
847b55cbc6bSGreg Roach                $pending_changes_service->acceptRecord($this);
848a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
849a25f0a04SGreg Roach                $this->pending = null;
850a25f0a04SGreg Roach            }
851a25f0a04SGreg Roach        }
8529599771eSGreg Roach
8539599771eSGreg Roach        $this->facts = $this->parseFacts();
854a25f0a04SGreg Roach    }
855a25f0a04SGreg Roach
856a25f0a04SGreg Roach    /**
857a25f0a04SGreg Roach     * Update this record
858a25f0a04SGreg Roach     *
859a25f0a04SGreg Roach     * @param string $gedcom
860cbc1590aSGreg Roach     * @param bool   $update_chan
8617e96c925SGreg Roach     *
8627e96c925SGreg Roach     * @return void
863a25f0a04SGreg Roach     */
864e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
865c1010edaSGreg Roach    {
86671f696adSGreg Roach        // Not all record types allow a CHAN event.
86771f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
86871f696adSGreg Roach
869a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
870a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
871a25f0a04SGreg Roach        $gedcom = trim($gedcom);
872a25f0a04SGreg Roach
873a25f0a04SGreg Roach        // Update the CHAN record
874a25f0a04SGreg Roach        if ($update_chan) {
87572f8afdbSGreg Roach            if (preg_match('/\n1 CHAN(\n[2-9].*)*/', $gedcom, $match)) {
87672f8afdbSGreg Roach                $gedcom = strtr($gedcom, [$match[0] => $this->updateChange($match[0])]);
87772f8afdbSGreg Roach            } else {
87872f8afdbSGreg Roach                $gedcom .= $this->updateChange("\n1 CHAN");
87972f8afdbSGreg Roach            }
880a25f0a04SGreg Roach        }
881a25f0a04SGreg Roach
882a25f0a04SGreg Roach        // Create a pending change
883d09b6323SGreg Roach        DB::table('change')->insert([
884d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
885d09b6323SGreg Roach            'xref'       => $this->xref,
886d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
887d09b6323SGreg Roach            'new_gedcom' => $gedcom,
888665d37b1SGreg Roach            'status'     => 'pending',
889d09b6323SGreg Roach            'user_id'    => Auth::id(),
89013abd6f3SGreg Roach        ]);
891a25f0a04SGreg Roach
892a25f0a04SGreg Roach        // Clear the cache
893a25f0a04SGreg Roach        $this->pending = $gedcom;
894a25f0a04SGreg Roach
895a25f0a04SGreg Roach        // Accept this pending change
8961fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
897d35568b4SGreg Roach            $pending_changes_service = Registry::container()->get(PendingChangesService::class);
898b55cbc6bSGreg Roach
899b55cbc6bSGreg Roach            $pending_changes_service->acceptRecord($this);
900a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
901a25f0a04SGreg Roach            $this->pending = null;
902a25f0a04SGreg Roach        }
903a25f0a04SGreg Roach
9049599771eSGreg Roach        $this->facts = $this->parseFacts();
905a25f0a04SGreg Roach
906847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
907a25f0a04SGreg Roach    }
908a25f0a04SGreg Roach
909a25f0a04SGreg Roach    /**
910a25f0a04SGreg Roach     * Delete this record
911b874da82SGreg Roach     *
912b874da82SGreg Roach     * @return void
913a25f0a04SGreg Roach     */
914e364afe4SGreg Roach    public function deleteRecord(): void
915c1010edaSGreg Roach    {
916a25f0a04SGreg Roach        // Create a pending change
9174c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
918d09b6323SGreg Roach            DB::table('change')->insert([
919d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
920d09b6323SGreg Roach                'xref'       => $this->xref,
921d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
922d09b6323SGreg Roach                'new_gedcom' => '',
923665d37b1SGreg Roach                'status'     => 'pending',
924d09b6323SGreg Roach                'user_id'    => Auth::id(),
92513abd6f3SGreg Roach            ]);
9264c0b5256SGreg Roach        }
927a25f0a04SGreg Roach
9284c0b5256SGreg Roach        // Auto-accept this pending change
9291fe542e9SGreg Roach        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
930d35568b4SGreg Roach            $pending_changes_service = Registry::container()->get(PendingChangesService::class);
931b55cbc6bSGreg Roach            $pending_changes_service->acceptRecord($this);
932a25f0a04SGreg Roach        }
933a25f0a04SGreg Roach
934847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
935a25f0a04SGreg Roach    }
936a25f0a04SGreg Roach
937a25f0a04SGreg Roach    /**
938a25f0a04SGreg Roach     * Remove all links from this record to $xref
939a25f0a04SGreg Roach     *
940a25f0a04SGreg Roach     * @param string $xref
941cbc1590aSGreg Roach     * @param bool   $update_chan
9427e96c925SGreg Roach     *
9437e96c925SGreg Roach     * @return void
944a25f0a04SGreg Roach     */
945e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
946c1010edaSGreg Roach    {
947a25f0a04SGreg Roach        $value = '@' . $xref . '@';
948a25f0a04SGreg Roach
94930158ae7SGreg Roach        foreach ($this->facts() as $fact) {
95084586c02SGreg Roach            if ($fact->value() === $value) {
951905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
9528d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
953138ca96cSGreg Roach                $gedcom = $fact->gedcom();
954a25f0a04SGreg Roach                foreach ($matches as $match) {
955ef475b14SGreg Roach                    $next_level  = 1 + (int) $match[1];
956a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
957a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
958a25f0a04SGreg Roach                }
959905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
960a25f0a04SGreg Roach            }
961a25f0a04SGreg Roach        }
962a25f0a04SGreg Roach    }
963bf4eb542SGreg Roach
964bf4eb542SGreg Roach    /**
96522e73debSGreg Roach     * Each object type may have its own special rules, and re-implement this function.
96622e73debSGreg Roach     *
96722e73debSGreg Roach     * @param int $access_level
96822e73debSGreg Roach     *
96922e73debSGreg Roach     * @return bool
97022e73debSGreg Roach     */
97122e73debSGreg Roach    protected function canShowByType(int $access_level): bool
97222e73debSGreg Roach    {
97322e73debSGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
97422e73debSGreg Roach
97522e73debSGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
97622e73debSGreg Roach            // Restriction found
97722e73debSGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
97822e73debSGreg Roach        }
97922e73debSGreg Roach
98022e73debSGreg Roach        // No restriction found - must be public:
98122e73debSGreg Roach        return true;
98222e73debSGreg Roach    }
98322e73debSGreg Roach
98422e73debSGreg Roach    /**
98522e73debSGreg Roach     * Generate a private version of this record
98622e73debSGreg Roach     *
98722e73debSGreg Roach     * @param int $access_level
98822e73debSGreg Roach     *
98922e73debSGreg Roach     * @return string
99022e73debSGreg Roach     */
99122e73debSGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
99222e73debSGreg Roach    {
993228ede81SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
99422e73debSGreg Roach    }
99522e73debSGreg Roach
99622e73debSGreg Roach    /**
99722e73debSGreg Roach     * Convert a name record into sortable and full/display versions. This default
99822e73debSGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
99922e73debSGreg Roach     *
100022e73debSGreg Roach     * @param string $type
100122e73debSGreg Roach     * @param string $value
100222e73debSGreg Roach     * @param string $gedcom
100322e73debSGreg Roach     *
100422e73debSGreg Roach     * @return void
100522e73debSGreg Roach     */
100622e73debSGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
100722e73debSGreg Roach    {
100822e73debSGreg Roach        $this->getAllNames[] = [
100922e73debSGreg Roach            'type'   => $type,
1010dbf91548SGreg Roach            'sort'   => preg_replace_callback('/(\d+)/', static function (array $matches): string {
101122e73debSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
101222e73debSGreg Roach            }, $value),
1013315eb316SGreg Roach            'full'   => '<bdi>' . e($value) . '</bdi>',
101422e73debSGreg Roach            // This is used for display
101522e73debSGreg Roach            'fullNN' => $value,
101622e73debSGreg Roach            // This goes into the database
101722e73debSGreg Roach        ];
101822e73debSGreg Roach    }
101922e73debSGreg Roach
102022e73debSGreg Roach    /**
102122e73debSGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
102222e73debSGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
102322e73debSGreg Roach     * Parameters: the level 1 fact containing the name.
102422e73debSGreg Roach     * Return value: an array of name structures, each containing
102522e73debSGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
102622e73debSGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
102722e73debSGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
102822e73debSGreg Roach     *
102922e73debSGreg Roach     * @param int              $level
103022e73debSGreg Roach     * @param string           $fact_type
103136779af1SGreg Roach     * @param Collection<int,Fact> $facts
103222e73debSGreg Roach     *
103322e73debSGreg Roach     * @return void
103422e73debSGreg Roach     */
103522e73debSGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
103622e73debSGreg Roach    {
103722e73debSGreg Roach        $sublevel    = $level + 1;
103822e73debSGreg Roach        $subsublevel = $sublevel + 1;
103922e73debSGreg Roach        foreach ($facts as $fact) {
1040c8ff5fdcSGreg Roach            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
104122e73debSGreg Roach                foreach ($matches as $match) {
104222e73debSGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1043cc9d82dcSGreg Roach                    if ($match[1] === 'NAME' && str_contains(strtoupper($match[3]), "\n2 TYPE MARRIED")) {
104422e73debSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
104522e73debSGreg Roach                    } else {
104622e73debSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
104722e73debSGreg Roach                    }
1048c8ff5fdcSGreg Roach                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
104922e73debSGreg Roach                        foreach ($submatches as $submatch) {
10502d21e9c2SGreg Roach                            if ($submatch[1] !== '_RUFNAME') {
105122e73debSGreg Roach                                $this->addName($submatch[1], $submatch[2], $match[3]);
105222e73debSGreg Roach                            }
105322e73debSGreg Roach                        }
105422e73debSGreg Roach                    }
105522e73debSGreg Roach                }
105622e73debSGreg Roach            }
105722e73debSGreg Roach        }
10582d21e9c2SGreg Roach    }
105922e73debSGreg Roach
106022e73debSGreg Roach    /**
106122e73debSGreg Roach     * Split the record into facts
106222e73debSGreg Roach     *
10639599771eSGreg Roach     * @return array<Fact>
106422e73debSGreg Roach     */
10659599771eSGreg Roach    private function parseFacts(): array
106622e73debSGreg Roach    {
106722e73debSGreg Roach        // Split the record into facts
1068b6ec1ccfSGreg Roach        if ($this->gedcom !== '') {
1069d823340dSGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
107022e73debSGreg Roach            array_shift($gedcom_facts);
107122e73debSGreg Roach        } else {
107222e73debSGreg Roach            $gedcom_facts = [];
107322e73debSGreg Roach        }
1074b6ec1ccfSGreg Roach        if ($this->pending !== null && $this->pending !== '') {
1075d823340dSGreg Roach            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
107622e73debSGreg Roach            array_shift($pending_facts);
107722e73debSGreg Roach        } else {
107822e73debSGreg Roach            $pending_facts = [];
107922e73debSGreg Roach        }
108022e73debSGreg Roach
10819599771eSGreg Roach        $facts = [];
108222e73debSGreg Roach
108322e73debSGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
108422e73debSGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
108522e73debSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
108622e73debSGreg Roach                $fact->setPendingDeletion();
108722e73debSGreg Roach            }
10889599771eSGreg Roach            $facts[] = $fact;
108922e73debSGreg Roach        }
109022e73debSGreg Roach        foreach ($pending_facts as $pending_fact) {
109122e73debSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
109222e73debSGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
109322e73debSGreg Roach                $fact->setPendingAddition();
10949599771eSGreg Roach                $facts[] = $fact;
109522e73debSGreg Roach            }
109622e73debSGreg Roach        }
10979599771eSGreg Roach
10989599771eSGreg Roach        return $facts;
109922e73debSGreg Roach    }
110022e73debSGreg Roach
110122e73debSGreg Roach    /**
110222e73debSGreg Roach     * Work out whether this record can be shown to a user with a given access level
110322e73debSGreg Roach     *
110422e73debSGreg Roach     * @param int $access_level
110522e73debSGreg Roach     *
110622e73debSGreg Roach     * @return bool
110722e73debSGreg Roach     */
110822e73debSGreg Roach    private function canShowRecord(int $access_level): bool
110922e73debSGreg Roach    {
111022e73debSGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
111122e73debSGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
111222e73debSGreg Roach            return true;
111322e73debSGreg Roach        }
111422e73debSGreg Roach
111522e73debSGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
11161fe542e9SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
111722e73debSGreg Roach            return true;
111822e73debSGreg Roach        }
111922e73debSGreg Roach
112055105892SGreg Roach        // Does this record have a restriction notice?
1121da7adf56SGreg Roach        // Cannot use $this->>fact(), as that function calls this one.
112255105892SGreg Roach        if (preg_match('/\n1 RESN (.+)/', $this->gedcom(), $match)) {
112355105892SGreg Roach            $element     = new RestrictionNotice('');
112455105892SGreg Roach            $restriction = $element->canonical($match[1]);
112555105892SGreg Roach
112655105892SGreg Roach            if (str_starts_with($restriction, RestrictionNotice::VALUE_CONFIDENTIAL)) {
112722e73debSGreg Roach                return Auth::PRIV_NONE >= $access_level;
112822e73debSGreg Roach            }
112955105892SGreg Roach            if (str_starts_with($restriction, RestrictionNotice::VALUE_PRIVACY)) {
113022e73debSGreg Roach                return Auth::PRIV_USER >= $access_level;
113122e73debSGreg Roach            }
113255105892SGreg Roach            if (str_starts_with($restriction, RestrictionNotice::VALUE_NONE)) {
113322e73debSGreg Roach                return true;
113422e73debSGreg Roach            }
113555105892SGreg Roach        }
113622e73debSGreg Roach
113722e73debSGreg Roach        // Does this record have a default RESN?
113822e73debSGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
113922e73debSGreg Roach        if (isset($individual_privacy[$this->xref()])) {
114022e73debSGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
114122e73debSGreg Roach        }
114222e73debSGreg Roach
114322e73debSGreg Roach        // Privacy rules do not apply to admins
114422e73debSGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
114522e73debSGreg Roach            return true;
114622e73debSGreg Roach        }
114722e73debSGreg Roach
114822e73debSGreg Roach        // Different types of record have different privacy rules
114922e73debSGreg Roach        return $this->canShowByType($access_level);
115022e73debSGreg Roach    }
11518091bfd1SGreg Roach
11528091bfd1SGreg Roach    /**
11538091bfd1SGreg Roach     * Lock the database row, to prevent concurrent edits.
11548091bfd1SGreg Roach     */
11558091bfd1SGreg Roach    public function lock(): void
11568091bfd1SGreg Roach    {
11578091bfd1SGreg Roach        DB::table('other')
11588091bfd1SGreg Roach            ->where('o_file', '=', $this->tree->id())
11598091bfd1SGreg Roach            ->where('o_id', '=', $this->xref())
11608091bfd1SGreg Roach            ->lockForUpdate()
11618091bfd1SGreg Roach            ->get();
11628091bfd1SGreg Roach    }
116372f8afdbSGreg Roach
116472f8afdbSGreg Roach    /**
116572f8afdbSGreg Roach     * Change records may contain notes and other fields.  Just update the date/time/author.
116672f8afdbSGreg Roach     *
116772f8afdbSGreg Roach     * @param string $gedcom
116872f8afdbSGreg Roach     *
116972f8afdbSGreg Roach     * @return string
117072f8afdbSGreg Roach     */
11715cba5dc7SGreg Roach    private function updateChange(string $gedcom): string
11725cba5dc7SGreg Roach    {
117372f8afdbSGreg Roach        $gedcom = preg_replace('/\n2 (DATE|_WT_USER).*(\n[3-9].*)*/', '', $gedcom);
117472f8afdbSGreg Roach        $today  = strtoupper(date('d M Y'));
117572f8afdbSGreg Roach        $now    = date('H:i:s');
117672f8afdbSGreg Roach        $author = Auth::user()->userName();
117772f8afdbSGreg Roach
117872f8afdbSGreg Roach        return $gedcom . "\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . $author;
117972f8afdbSGreg Roach    }
1180a25f0a04SGreg Roach}
1181