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