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