xref: /webtrees/app/GedcomRecord.php (revision 665d37b17f677ba0664fb25a284ec06dba9185ef)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Closure;
23use Exception;
24use Fisharebest\Webtrees\Contracts\TimestampInterface;
25use Fisharebest\Webtrees\Contracts\UserInterface;
26use Fisharebest\Webtrees\Elements\RestrictionNotice;
27use Fisharebest\Webtrees\Http\RequestHandlers\GedcomRecordPage;
28use Fisharebest\Webtrees\Services\PendingChangesService;
29use Illuminate\Database\Capsule\Manager as DB;
30use Illuminate\Support\Collection;
31
32use function array_combine;
33use function array_keys;
34use function array_map;
35use function array_search;
36use function array_shift;
37use function count;
38use function date;
39use function e;
40use function explode;
41use function implode;
42use function in_array;
43use function md5;
44use function preg_match;
45use function preg_match_all;
46use function preg_replace;
47use function preg_replace_callback;
48use function preg_split;
49use function range;
50use function route;
51use function str_contains;
52use function str_ends_with;
53use function str_pad;
54use function str_starts_with;
55use function strtoupper;
56use function strtr;
57use function trim;
58use function view;
59
60use const PHP_INT_MAX;
61use const PREG_SET_ORDER;
62use const STR_PAD_LEFT;
63
64/**
65 * A GEDCOM object.
66 */
67class GedcomRecord
68{
69    public const RECORD_TYPE = 'UNKNOWN';
70
71    protected const ROUTE_NAME = GedcomRecordPage::class;
72
73    protected string $xref;
74
75    protected Tree $tree;
76
77    // GEDCOM data (before any pending edits)
78    protected string $gedcom;
79
80    // GEDCOM data (after any pending edits)
81    protected ?string $pending;
82
83    /** @var array<Fact> Facts extracted from $gedcom/$pending */
84    protected array $facts;
85
86    /** @var array<array<string>> All the names of this individual */
87    protected array $getAllNames = [];
88
89    /** @var int|null Cached result */
90    private ?int $getPrimaryName = null;
91
92    /** @var int|null Cached result */
93    private ?int $getSecondaryName = null;
94
95    /**
96     * Create a GedcomRecord object from raw GEDCOM data.
97     *
98     * @param string      $xref
99     * @param string      $gedcom  an empty string for new/pending records
100     * @param string|null $pending null for a record with no pending edits,
101     *                             empty string for records with pending deletions
102     * @param Tree        $tree
103     */
104    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
105    {
106        $this->xref    = $xref;
107        $this->gedcom  = $gedcom;
108        $this->pending = $pending;
109        $this->tree    = $tree;
110        $this->facts   = $this->parseFacts();
111    }
112
113    /**
114     * A closure which will filter out private records.
115     *
116     * @return Closure(GedcomRecord):bool
117     */
118    public static function accessFilter(): Closure
119    {
120        return static function (GedcomRecord $record): bool {
121            return $record->canShow();
122        };
123    }
124
125    /**
126     * A closure which will compare records by name.
127     *
128     * @return Closure(GedcomRecord,GedcomRecord):int
129     */
130    public static function nameComparator(): Closure
131    {
132        return static function (GedcomRecord $x, GedcomRecord $y): int {
133            if ($x->canShowName()) {
134                if ($y->canShowName()) {
135                    return I18N::comparator()($x->sortName(), $y->sortName());
136                }
137
138                return -1; // only $y is private
139            }
140
141            if ($y->canShowName()) {
142                return 1; // only $x is private
143            }
144
145            return 0; // both $x and $y private
146        };
147    }
148
149    /**
150     * A closure which will compare records by change time.
151     *
152     * @param int $direction +1 to sort ascending, -1 to sort descending
153     *
154     * @return Closure(GedcomRecord,GedcomRecord):int
155     */
156    public static function lastChangeComparator(int $direction = 1): Closure
157    {
158        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
159            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
160        };
161    }
162
163    /**
164     * Get the GEDCOM tag for this record.
165     *
166     * @return string
167     */
168    public function tag(): string
169    {
170        preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
171
172        return $match[1] ?? static::RECORD_TYPE;
173    }
174
175    /**
176     * Get the XREF for this record
177     *
178     * @return string
179     */
180    public function xref(): string
181    {
182        return $this->xref;
183    }
184
185    /**
186     * Get the tree to which this record belongs
187     *
188     * @return Tree
189     */
190    public function tree(): Tree
191    {
192        return $this->tree;
193    }
194
195    /**
196     * Application code should access data via Fact objects.
197     * This function exists to support old code.
198     *
199     * @return string
200     */
201    public function gedcom(): string
202    {
203        return $this->pending ?? $this->gedcom;
204    }
205
206    /**
207     * Does this record have a pending change?
208     *
209     * @return bool
210     */
211    public function isPendingAddition(): bool
212    {
213        return $this->pending !== null;
214    }
215
216    /**
217     * Does this record have a pending deletion?
218     *
219     * @return bool
220     */
221    public function isPendingDeletion(): bool
222    {
223        return $this->pending === '';
224    }
225
226    /**
227     * Generate a URL to this record.
228     *
229     * @return string
230     */
231    public function url(): string
232    {
233        return route(static::ROUTE_NAME, [
234            'xref' => $this->xref(),
235            'tree' => $this->tree->name(),
236            'slug' => Registry::slugFactory()->make($this),
237        ]);
238    }
239
240    /**
241     * Can the details of this record be shown?
242     *
243     * @param int|null $access_level
244     *
245     * @return bool
246     */
247    public function canShow(int $access_level = null): bool
248    {
249        $access_level ??= Auth::accessLevel($this->tree);
250
251        // We use this value to bypass privacy checks. For example,
252        // when downloading data or when calculating privacy itself.
253        if ($access_level === Auth::PRIV_HIDE) {
254            return true;
255        }
256
257        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
258
259        return Registry::cache()->array()->remember($cache_key, function () use ($access_level) {
260            return $this->canShowRecord($access_level);
261        });
262    }
263
264    /**
265     * Can the name of this record be shown?
266     *
267     * @param int|null $access_level
268     *
269     * @return bool
270     */
271    public function canShowName(int $access_level = null): bool
272    {
273        return $this->canShow($access_level);
274    }
275
276    /**
277     * Can we edit this record?
278     *
279     * @return bool
280     */
281    public function canEdit(): bool
282    {
283        if ($this->isPendingDeletion()) {
284            return false;
285        }
286
287        if (Auth::isManager($this->tree)) {
288            return true;
289        }
290
291        $fact   = $this->facts(['RESN'])->first();
292        $locked = $fact instanceof Fact && str_ends_with($fact->attribute('RESN'), RestrictionNotice::VALUE_LOCKED);
293
294        return Auth::isEditor($this->tree) && !$locked;
295    }
296
297    /**
298     * Remove private data from the raw gedcom record.
299     * Return both the visible and invisible data. We need the invisible data when editing.
300     *
301     * @param int $access_level
302     *
303     * @return string
304     */
305    public function privatizeGedcom(int $access_level): string
306    {
307        if ($access_level === Auth::PRIV_HIDE) {
308            // We may need the original record, for example when downloading a GEDCOM or clippings cart
309            return $this->gedcom;
310        }
311
312        if ($this->canShow($access_level)) {
313            // The record is not private, but the individual facts may be.
314
315            // Include the entire first line (for NOTE records)
316            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
317
318            // Check each of the facts for access
319            foreach ($this->facts([], false, $access_level) as $fact) {
320                $gedrec .= "\n" . $fact->gedcom();
321            }
322
323            return $gedrec;
324        }
325
326        // We cannot display the details, but we may be able to display
327        // limited data, such as links to other records.
328        return $this->createPrivateGedcomRecord($access_level);
329    }
330
331    /**
332     * Default for "other" object types
333     *
334     * @return void
335     */
336    public function extractNames(): void
337    {
338        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
339    }
340
341    /**
342     * Derived classes should redefine this function, otherwise the object will have no name
343     *
344     * @return array<int,array<string,string>>
345     */
346    public function getAllNames(): array
347    {
348        if ($this->getAllNames === []) {
349            if ($this->canShowName()) {
350                // Ask the record to extract its names
351                $this->extractNames();
352                // No name found? Use a fallback.
353                if ($this->getAllNames === []) {
354                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
355                }
356            } else {
357                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
358            }
359        }
360
361        return $this->getAllNames;
362    }
363
364    /**
365     * If this object has no name, what do we call it?
366     *
367     * @return string
368     */
369    public function getFallBackName(): string
370    {
371        return e($this->xref());
372    }
373
374    /**
375     * Which of the (possibly several) names of this record is the primary one.
376     *
377     * @return int
378     */
379    public function getPrimaryName(): int
380    {
381        static $language_script;
382
383        $language_script ??= I18N::locale()->script()->code();
384
385        if ($this->getPrimaryName === null) {
386            // Generally, the first name is the primary one....
387            $this->getPrimaryName = 0;
388            // ...except when the language/name use different character sets
389            foreach ($this->getAllNames() as $n => $name) {
390                if (I18N::textScript($name['sort']) === $language_script) {
391                    $this->getPrimaryName = $n;
392                    break;
393                }
394            }
395        }
396
397        return $this->getPrimaryName;
398    }
399
400    /**
401     * Which of the (possibly several) names of this record is the secondary one.
402     *
403     * @return int
404     */
405    public function getSecondaryName(): int
406    {
407        if ($this->getSecondaryName === null) {
408            // Generally, the primary and secondary names are the same
409            $this->getSecondaryName = $this->getPrimaryName();
410            // ....except when there are names with different character sets
411            $all_names = $this->getAllNames();
412            if (count($all_names) > 1) {
413                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
414                foreach ($all_names as $n => $name) {
415                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
416                        $this->getSecondaryName = $n;
417                        break;
418                    }
419                }
420            }
421        }
422
423        return $this->getSecondaryName;
424    }
425
426    /**
427     * Allow the choice of primary name to be overidden, e.g. in a search result
428     *
429     * @param int|null $n
430     *
431     * @return void
432     */
433    public function setPrimaryName(int $n = null): void
434    {
435        $this->getPrimaryName   = $n;
436        $this->getSecondaryName = null;
437    }
438
439    /**
440     * Allow native PHP functions such as array_unique() to work with objects
441     *
442     * @return string
443     */
444    public function __toString(): string
445    {
446        return $this->xref . '@' . $this->tree->id();
447    }
448
449    /**
450     * /**
451     * Get variants of the name
452     *
453     * @return string
454     */
455    public function fullName(): string
456    {
457        if ($this->canShowName()) {
458            $tmp = $this->getAllNames();
459
460            return $tmp[$this->getPrimaryName()]['full'];
461        }
462
463        return I18N::translate('Private');
464    }
465
466    /**
467     * Get a sortable version of the name. Do not display this!
468     *
469     * @return string
470     */
471    public function sortName(): string
472    {
473        // The sortable name is never displayed, no need to call canShowName()
474        $tmp = $this->getAllNames();
475
476        return $tmp[$this->getPrimaryName()]['sort'];
477    }
478
479    /**
480     * Get the full name in an alternative character set
481     *
482     * @return string|null
483     */
484    public function alternateName(): ?string
485    {
486        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
487            $all_names = $this->getAllNames();
488
489            return $all_names[$this->getSecondaryName()]['full'];
490        }
491
492        return null;
493    }
494
495    /**
496     * Format this object for display in a list
497     *
498     * @return string
499     */
500    public function formatList(): string
501    {
502        $html = '<a href="' . e($this->url()) . '">';
503        $html .= '<b>' . $this->fullName() . '</b>';
504        $html .= '</a>';
505        $html .= $this->formatListDetails();
506
507        return $html;
508    }
509
510    /**
511     * This function should be redefined in derived classes to show any major
512     * identifying characteristics of this record.
513     *
514     * @return string
515     */
516    public function formatListDetails(): string
517    {
518        return '';
519    }
520
521    /**
522     * Extract/format the first fact from a list of facts.
523     *
524     * @param array<string> $facts
525     * @param int           $style
526     *
527     * @return string
528     */
529    public function formatFirstMajorFact(array $facts, int $style): string
530    {
531        $fact = $this->facts($facts, true)->first();
532
533        if ($fact === null) {
534            return '';
535        }
536
537        // Only display if it has a date or place (or both)
538        $attributes = [];
539
540        if ($fact->date()->isOK()) {
541            $attributes[] = view('fact-date', ['cal_link' => 'false', 'fact' => $fact, 'record' => $fact->record(), 'time' => false]);
542        }
543
544        if ($fact->place()->gedcomName() !== '' && $style === 2) {
545            $attributes[] = $fact->place()->shortName();
546        }
547
548        if ($attributes === []) {
549            return '';
550        }
551
552        return '<div><em>' . I18N::translate('%1$s: %2$s', $fact->label(), implode(' — ', $attributes)) . '</em></div>';
553    }
554
555    /**
556     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
557     * This is used to display multiple events on the individual/family lists.
558     * Multiple events can exist because of uncertainty in dates, dates in different
559     * calendars, place-names in both latin and hebrew character sets, etc.
560     * It also allows us to combine dates/places from different events in the summaries.
561     *
562     * @param array<string> $events
563     *
564     * @return array<Date>
565     */
566    public function getAllEventDates(array $events): array
567    {
568        $dates = [];
569        foreach ($this->facts($events, false, null, true) as $event) {
570            if ($event->date()->isOK()) {
571                $dates[] = $event->date();
572            }
573        }
574
575        return $dates;
576    }
577
578    /**
579     * Get all the places for a particular type of event
580     *
581     * @param array<string> $events
582     *
583     * @return array<Place>
584     */
585    public function getAllEventPlaces(array $events): array
586    {
587        $places = [];
588        foreach ($this->facts($events) as $event) {
589            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
590                foreach ($ged_places[1] as $ged_place) {
591                    $places[] = new Place($ged_place, $this->tree);
592                }
593            }
594        }
595
596        return $places;
597    }
598
599    /**
600     * The facts and events for this record.
601     *
602     * @param array<string> $filter
603     * @param bool          $sort
604     * @param int|null      $access_level
605     * @param bool          $ignore_deleted
606     *
607     * @return Collection<int,Fact>
608     */
609    public function facts(
610        array $filter = [],
611        bool $sort = false,
612        int $access_level = null,
613        bool $ignore_deleted = false
614    ): Collection {
615        $access_level ??= Auth::accessLevel($this->tree);
616
617        // Convert BIRT into INDI:BIRT, etc.
618        $filter = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, $filter);
619
620        $facts = new Collection();
621        if ($this->canShow($access_level)) {
622            foreach ($this->facts as $fact) {
623                if (($filter === [] || in_array($fact->tag(), $filter, true)) && $fact->canShow($access_level)) {
624                    $facts->push($fact);
625                }
626            }
627        }
628
629        if ($sort) {
630            switch ($this->tag()) {
631                case Family::RECORD_TYPE:
632                case Individual::RECORD_TYPE:
633                    $facts = Fact::sortFacts($facts);
634                    break;
635
636                default:
637                    $subtags = Registry::elementFactory()->make($this->tag())->subtags();
638                    $subtags = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, array_keys($subtags));
639
640                    if ($subtags !== []) {
641                        // Renumber keys from 1.
642                        $subtags = array_combine(range(1, count($subtags)), $subtags);
643                    }
644
645
646                    $facts = $facts
647                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
648                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
649                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
650
651                            return $sort_x <=> $sort_y;
652                        });
653                    break;
654            }
655        }
656
657        if ($ignore_deleted) {
658            $facts = $facts->filter(static function (Fact $fact): bool {
659                return !$fact->isPendingDeletion();
660            });
661        }
662
663        return $facts;
664    }
665
666    /**
667     * @return array<string,string>
668     */
669    public function missingFacts(): array
670    {
671        $missing_facts = [];
672
673        foreach (Registry::elementFactory()->make($this->tag())->subtags() as $subtag => $repeat) {
674            [, $max] = explode(':', $repeat);
675            $max = $max === 'M' ? PHP_INT_MAX : (int) $max;
676
677            if ($this->facts([$subtag], false, null, true)->count() < $max) {
678                $missing_facts[$subtag] = $subtag;
679                $missing_facts[$subtag] = Registry::elementFactory()->make($this->tag() . ':' . $subtag)->label();
680            }
681        }
682
683        uasort($missing_facts, I18N::comparator());
684
685        if (!Auth::canUploadMedia($this->tree, Auth::user())) {
686            unset($missing_facts['OBJE']);
687        }
688
689        // We have special code for this.
690        unset($missing_facts['FILE']);
691
692        return $missing_facts;
693    }
694
695    /**
696     * Get the last-change timestamp for this record
697     *
698     * @return TimestampInterface
699     */
700    public function lastChangeTimestamp(): TimestampInterface
701    {
702        $chan = $this->facts(['CHAN'])->first();
703
704        if ($chan instanceof Fact) {
705            // The record has a CHAN event.
706            $date = $chan->date()->minimumDate();
707            $ymd = sprintf('%04d-%02d-%02d', $date->year(), $date->month(), $date->day());
708
709            if ($ymd !== '') {
710                // The CHAN event has a valid DATE.
711                if (preg_match('/\n3 TIME (([01]\d|2[0-3]):([0-5]\d):([0-5]\d))/', $chan->gedcom(), $match) === 1) {
712                    return Registry::timestampFactory()->fromString($ymd . $match[1], 'Y-m-d H:i:s');
713                }
714
715                if (preg_match('/\n3 TIME (([01]\d|2[0-3]):([0-5]\d))/', $chan->gedcom(), $match) === 1) {
716                    return Registry::timestampFactory()->fromString($ymd . $match[1], 'Y-m-d H:i');
717                }
718
719                return Registry::timestampFactory()->fromString($ymd, 'Y-m-d');
720            }
721        }
722
723        // The record does not have a CHAN event
724        return Registry::timestampFactory()->make(0);
725    }
726
727    /**
728     * Get the last-change user for this record
729     *
730     * @return string
731     */
732    public function lastChangeUser(): string
733    {
734        $chan = $this->facts(['CHAN'])->first();
735
736        if ($chan === null) {
737            return I18N::translate('Unknown');
738        }
739
740        $chan_user = $chan->attribute('_WT_USER');
741        if ($chan_user === '') {
742            return I18N::translate('Unknown');
743        }
744
745        return $chan_user;
746    }
747
748    /**
749     * Add a new fact to this record
750     *
751     * @param string $gedcom
752     * @param bool   $update_chan
753     *
754     * @return void
755     */
756    public function createFact(string $gedcom, bool $update_chan): void
757    {
758        $this->updateFact('', $gedcom, $update_chan);
759    }
760
761    /**
762     * Delete a fact from this record
763     *
764     * @param string $fact_id
765     * @param bool   $update_chan
766     *
767     * @return void
768     */
769    public function deleteFact(string $fact_id, bool $update_chan): void
770    {
771        $this->updateFact($fact_id, '', $update_chan);
772    }
773
774    /**
775     * Replace a fact with a new gedcom data.
776     *
777     * @param string $fact_id
778     * @param string $gedcom
779     * @param bool   $update_chan
780     *
781     * @return void
782     * @throws Exception
783     */
784    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
785    {
786        // Not all record types allow a CHAN event.
787        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
788
789        // MSDOS line endings will break things in horrible ways
790        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
791        $gedcom = trim($gedcom);
792
793        if ($this->pending === '') {
794            throw new Exception('Cannot edit a deleted record');
795        }
796        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
797            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
798        }
799
800        if ($this->pending) {
801            $old_gedcom = $this->pending;
802        } else {
803            $old_gedcom = $this->gedcom;
804        }
805
806        // First line of record may contain data - e.g. NOTE records.
807        [$new_gedcom] = explode("\n", $old_gedcom, 2);
808
809        // Replacing (or deleting) an existing fact
810        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
811            if ($fact->id() === $fact_id) {
812                if ($gedcom !== '') {
813                    $new_gedcom .= "\n" . $gedcom;
814                }
815                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
816            } elseif ($update_chan && str_ends_with($fact->tag(), ':CHAN')) {
817                $new_gedcom .= "\n" . $this->updateChange($fact->gedcom());
818            } else {
819                $new_gedcom .= "\n" . $fact->gedcom();
820            }
821        }
822
823        // Adding a new fact
824        if ($fact_id === '') {
825            $new_gedcom .= "\n" . $gedcom;
826        }
827
828        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
829            $new_gedcom .= $this->updateChange("\n1 CHAN");
830        }
831
832        if ($new_gedcom !== $old_gedcom) {
833            // Save the changes
834            DB::table('change')->insert([
835                'gedcom_id'  => $this->tree->id(),
836                'xref'       => $this->xref,
837                'old_gedcom' => $old_gedcom,
838                'new_gedcom' => $new_gedcom,
839                'status'     => 'pending',
840                'user_id'    => Auth::id(),
841            ]);
842
843            $this->pending = $new_gedcom;
844
845            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
846                $pending_changes_service = Registry::container()->get(PendingChangesService::class);
847
848                $pending_changes_service->acceptRecord($this);
849                $this->gedcom  = $new_gedcom;
850                $this->pending = null;
851            }
852        }
853
854        $this->facts = $this->parseFacts();
855    }
856
857    /**
858     * Update this record
859     *
860     * @param string $gedcom
861     * @param bool   $update_chan
862     *
863     * @return void
864     */
865    public function updateRecord(string $gedcom, bool $update_chan): void
866    {
867        // Not all record types allow a CHAN event.
868        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
869
870        // MSDOS line endings will break things in horrible ways
871        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
872        $gedcom = trim($gedcom);
873
874        // Update the CHAN record
875        if ($update_chan) {
876            if (preg_match('/\n1 CHAN(\n[2-9].*)*/', $gedcom, $match)) {
877                $gedcom = strtr($gedcom, [$match[0] => $this->updateChange($match[0])]);
878            } else {
879                $gedcom .= $this->updateChange("\n1 CHAN");
880            }
881        }
882
883        // Create a pending change
884        DB::table('change')->insert([
885            'gedcom_id'  => $this->tree->id(),
886            'xref'       => $this->xref,
887            'old_gedcom' => $this->gedcom(),
888            'new_gedcom' => $gedcom,
889            'status'     => 'pending',
890            'user_id'    => Auth::id(),
891        ]);
892
893        // Clear the cache
894        $this->pending = $gedcom;
895
896        // Accept this pending change
897        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
898            $pending_changes_service = Registry::container()->get(PendingChangesService::class);
899
900            $pending_changes_service->acceptRecord($this);
901            $this->gedcom  = $gedcom;
902            $this->pending = null;
903        }
904
905        $this->facts = $this->parseFacts();
906
907        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
908    }
909
910    /**
911     * Delete this record
912     *
913     * @return void
914     */
915    public function deleteRecord(): void
916    {
917        // Create a pending change
918        if (!$this->isPendingDeletion()) {
919            DB::table('change')->insert([
920                'gedcom_id'  => $this->tree->id(),
921                'xref'       => $this->xref,
922                'old_gedcom' => $this->gedcom(),
923                'new_gedcom' => '',
924                'status'     => 'pending',
925                'user_id'    => Auth::id(),
926            ]);
927        }
928
929        // Auto-accept this pending change
930        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
931            $pending_changes_service = Registry::container()->get(PendingChangesService::class);
932            $pending_changes_service->acceptRecord($this);
933        }
934
935        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
936    }
937
938    /**
939     * Remove all links from this record to $xref
940     *
941     * @param string $xref
942     * @param bool   $update_chan
943     *
944     * @return void
945     */
946    public function removeLinks(string $xref, bool $update_chan): void
947    {
948        $value = '@' . $xref . '@';
949
950        foreach ($this->facts() as $fact) {
951            if ($fact->value() === $value) {
952                $this->deleteFact($fact->id(), $update_chan);
953            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
954                $gedcom = $fact->gedcom();
955                foreach ($matches as $match) {
956                    $next_level  = 1 + (int) $match[1];
957                    $next_levels = '[' . $next_level . '-9]';
958                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
959                }
960                $this->updateFact($fact->id(), $gedcom, $update_chan);
961            }
962        }
963    }
964
965    /**
966     * Each object type may have its own special rules, and re-implement this function.
967     *
968     * @param int $access_level
969     *
970     * @return bool
971     */
972    protected function canShowByType(int $access_level): bool
973    {
974        $fact_privacy = $this->tree->getFactPrivacy();
975
976        if (isset($fact_privacy[static::RECORD_TYPE])) {
977            // Restriction found
978            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
979        }
980
981        // No restriction found - must be public:
982        return true;
983    }
984
985    /**
986     * Generate a private version of this record
987     *
988     * @param int $access_level
989     *
990     * @return string
991     */
992    protected function createPrivateGedcomRecord(int $access_level): string
993    {
994        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
995    }
996
997    /**
998     * Convert a name record into sortable and full/display versions. This default
999     * should be OK for simple record types. INDI/FAM records will need to redefine it.
1000     *
1001     * @param string $type
1002     * @param string $value
1003     * @param string $gedcom
1004     *
1005     * @return void
1006     */
1007    protected function addName(string $type, string $value, string $gedcom): void
1008    {
1009        $this->getAllNames[] = [
1010            'type'   => $type,
1011            'sort'   => preg_replace_callback('/(\d+)/', static function (array $matches): string {
1012                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
1013            }, $value),
1014            'full'   => '<bdi>' . e($value) . '</bdi>',
1015            // This is used for display
1016            'fullNN' => $value,
1017            // This goes into the database
1018        ];
1019    }
1020
1021    /**
1022     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
1023     * Records without a name (e.g. FAM) will need to redefine this function.
1024     * Parameters: the level 1 fact containing the name.
1025     * Return value: an array of name structures, each containing
1026     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
1027     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
1028     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
1029     *
1030     * @param int              $level
1031     * @param string           $fact_type
1032     * @param Collection<int,Fact> $facts
1033     *
1034     * @return void
1035     */
1036    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
1037    {
1038        $sublevel    = $level + 1;
1039        $subsublevel = $sublevel + 1;
1040        foreach ($facts as $fact) {
1041            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1042                foreach ($matches as $match) {
1043                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1044                    if ($match[1] === 'NAME' && str_contains(strtoupper($match[3]), "\n2 TYPE MARRIED")) {
1045                        $this->addName('_MARNM', $match[2], $fact->gedcom());
1046                    } else {
1047                        $this->addName($match[1], $match[2], $fact->gedcom());
1048                    }
1049                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
1050                        foreach ($submatches as $submatch) {
1051                            if ($submatch[1] !== '_RUFNAME') {
1052                                $this->addName($submatch[1], $submatch[2], $match[3]);
1053                            }
1054                        }
1055                    }
1056                }
1057            }
1058        }
1059    }
1060
1061    /**
1062     * Split the record into facts
1063     *
1064     * @return array<Fact>
1065     */
1066    private function parseFacts(): array
1067    {
1068        // Split the record into facts
1069        if ($this->gedcom) {
1070            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
1071            array_shift($gedcom_facts);
1072        } else {
1073            $gedcom_facts = [];
1074        }
1075        if ($this->pending) {
1076            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
1077            array_shift($pending_facts);
1078        } else {
1079            $pending_facts = [];
1080        }
1081
1082        $facts = [];
1083
1084        foreach ($gedcom_facts as $gedcom_fact) {
1085            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
1086            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
1087                $fact->setPendingDeletion();
1088            }
1089            $facts[] = $fact;
1090        }
1091        foreach ($pending_facts as $pending_fact) {
1092            if (!in_array($pending_fact, $gedcom_facts, true)) {
1093                $fact = new Fact($pending_fact, $this, md5($pending_fact));
1094                $fact->setPendingAddition();
1095                $facts[] = $fact;
1096            }
1097        }
1098
1099        return $facts;
1100    }
1101
1102    /**
1103     * Work out whether this record can be shown to a user with a given access level
1104     *
1105     * @param int $access_level
1106     *
1107     * @return bool
1108     */
1109    private function canShowRecord(int $access_level): bool
1110    {
1111        // This setting would better be called "$ENABLE_PRIVACY"
1112        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
1113            return true;
1114        }
1115
1116        // We should always be able to see our own record (unless an admin is applying download restrictions)
1117        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
1118            return true;
1119        }
1120
1121        // Does this record have a restriction notice?
1122        // Cannot use $this->>fact(), as that function calls this one.
1123        if (preg_match('/\n1 RESN (.+)/', $this->gedcom(), $match)) {
1124            $element     = new RestrictionNotice('');
1125            $restriction = $element->canonical($match[1]);
1126
1127            if (str_starts_with($restriction, RestrictionNotice::VALUE_CONFIDENTIAL)) {
1128                return Auth::PRIV_NONE >= $access_level;
1129            }
1130            if (str_starts_with($restriction, RestrictionNotice::VALUE_PRIVACY)) {
1131                return Auth::PRIV_USER >= $access_level;
1132            }
1133            if (str_starts_with($restriction, RestrictionNotice::VALUE_NONE)) {
1134                return true;
1135            }
1136        }
1137
1138        // Does this record have a default RESN?
1139        $individual_privacy = $this->tree->getIndividualPrivacy();
1140        if (isset($individual_privacy[$this->xref()])) {
1141            return $individual_privacy[$this->xref()] >= $access_level;
1142        }
1143
1144        // Privacy rules do not apply to admins
1145        if (Auth::PRIV_NONE >= $access_level) {
1146            return true;
1147        }
1148
1149        // Different types of record have different privacy rules
1150        return $this->canShowByType($access_level);
1151    }
1152
1153    /**
1154     * Lock the database row, to prevent concurrent edits.
1155     */
1156    public function lock(): void
1157    {
1158        DB::table('other')
1159            ->where('o_file', '=', $this->tree->id())
1160            ->where('o_id', '=', $this->xref())
1161            ->lockForUpdate()
1162            ->get();
1163    }
1164
1165    /**
1166     * Change records may contain notes and other fields.  Just update the date/time/author.
1167     *
1168     * @param string $gedcom
1169     *
1170     * @return string
1171     */
1172    private function updateChange(string $gedcom): string
1173    {
1174        $gedcom = preg_replace('/\n2 (DATE|_WT_USER).*(\n[3-9].*)*/', '', $gedcom);
1175        $today  = strtoupper(date('d M Y'));
1176        $now    = date('H:i:s');
1177        $author = Auth::user()->userName();
1178
1179        return $gedcom . "\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . $author;
1180    }
1181}
1182