xref: /webtrees/app/GedcomRecord.php (revision 1db2616a8ca2f8dc7655d066d9cc9530bad098ba)
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_replace;
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 string RECORD_TYPE = 'UNKNOWN';
70
71    protected const string 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|null $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|null $getPrimaryName = null;
91
92    /** @var int|null Cached result */
93    private int|null $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|null $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 fn (GedcomRecord $record): bool => $record->canShow();
121    }
122
123    /**
124     * A closure which will compare records by name.
125     *
126     * @return Closure(GedcomRecord,GedcomRecord):int
127     */
128    public static function nameComparator(): Closure
129    {
130        return static function (GedcomRecord $x, GedcomRecord $y): int {
131            if ($x->canShowName()) {
132                if ($y->canShowName()) {
133                    return I18N::comparator()($x->sortName(), $y->sortName());
134                }
135
136                return -1; // only $y is private
137            }
138
139            if ($y->canShowName()) {
140                return 1; // only $x is private
141            }
142
143            return 0; // both $x and $y private
144        };
145    }
146
147    /**
148     * A closure which will compare records by change time.
149     *
150     * @param int $direction +1 to sort ascending, -1 to sort descending
151     *
152     * @return Closure(GedcomRecord,GedcomRecord):int
153     */
154    public static function lastChangeComparator(int $direction = 1): Closure
155    {
156        return static fn (GedcomRecord $x, GedcomRecord $y): int => $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
157    }
158
159    /**
160     * Get the GEDCOM tag for this record.
161     *
162     * @return string
163     */
164    public function tag(): string
165    {
166        preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
167
168        return $match[1] ?? static::RECORD_TYPE;
169    }
170
171    /**
172     * Get the XREF for this record
173     *
174     * @return string
175     */
176    public function xref(): string
177    {
178        return $this->xref;
179    }
180
181    /**
182     * Get the tree to which this record belongs
183     *
184     * @return Tree
185     */
186    public function tree(): Tree
187    {
188        return $this->tree;
189    }
190
191    /**
192     * Application code should access data via Fact objects.
193     * This function exists to support old code.
194     *
195     * @return string
196     */
197    public function gedcom(): string
198    {
199        return $this->pending ?? $this->gedcom;
200    }
201
202    /**
203     * Does this record have a pending change?
204     *
205     * @return bool
206     */
207    public function isPendingAddition(): bool
208    {
209        return $this->pending !== null;
210    }
211
212    /**
213     * Does this record have a pending deletion?
214     *
215     * @return bool
216     */
217    public function isPendingDeletion(): bool
218    {
219        return $this->pending === '';
220    }
221
222    /**
223     * Generate a URL to this record.
224     *
225     * @return string
226     */
227    public function url(): string
228    {
229        return route(static::ROUTE_NAME, [
230            'xref' => $this->xref(),
231            'tree' => $this->tree->name(),
232            'slug' => Registry::slugFactory()->make($this),
233        ]);
234    }
235
236    /**
237     * Can the details of this record be shown?
238     *
239     * @param int|null $access_level
240     *
241     * @return bool
242     */
243    public function canShow(int|null $access_level = null): bool
244    {
245        $access_level ??= Auth::accessLevel($this->tree);
246
247        // We use this value to bypass privacy checks. For example,
248        // when downloading data or when calculating privacy itself.
249        if ($access_level === Auth::PRIV_HIDE) {
250            return true;
251        }
252
253        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
254
255        return Registry::cache()->array()->remember($cache_key, fn () => $this->canShowRecord($access_level));
256    }
257
258    /**
259     * Can the name of this record be shown?
260     *
261     * @param int|null $access_level
262     *
263     * @return bool
264     */
265    public function canShowName(int|null $access_level = null): bool
266    {
267        return $this->canShow($access_level);
268    }
269
270    /**
271     * Can we edit this record?
272     *
273     * @return bool
274     */
275    public function canEdit(): bool
276    {
277        if ($this->isPendingDeletion()) {
278            return false;
279        }
280
281        if (Auth::isManager($this->tree)) {
282            return true;
283        }
284
285        $fact   = $this->facts(['RESN'])->first();
286        $locked = $fact instanceof Fact && str_ends_with($fact->value(), RestrictionNotice::VALUE_LOCKED);
287
288        return Auth::isEditor($this->tree) && !$locked;
289    }
290
291    /**
292     * Remove private data from the raw gedcom record.
293     */
294    public function privatizeGedcom(int $access_level): string
295    {
296        if ($access_level === Auth::PRIV_HIDE) {
297            return $this->gedcom;
298        }
299
300        if (!$this->canShow($access_level)) {
301            return '';
302        }
303
304        // The record is not private, but parts of it may be.
305
306        // Include the entire first line (for NOTE records)
307        [$gedcom] = explode("\n", $this->gedcom . $this->pending, 2);
308
309        // Check each of the facts for access
310        foreach ($this->facts([], false, $access_level) as $fact) {
311            $gedcom .= "\n" . $fact->gedcom();
312        }
313
314        // Remove links to missing and private records
315        $pattern =  '/\n(\d) ' . Gedcom::REGEX_TAG . ' @(' . Gedcom::REGEX_XREF . ')@/';
316        preg_match_all($pattern, $gedcom, $matches, PREG_SET_ORDER);
317
318        foreach ($matches as $match) {
319            $xref = $match[2];
320            $record = Registry::gedcomRecordFactory()->make($xref, $this->tree);
321
322            if ($record === null || !$record->canShow($access_level)) {
323                $level   = $match[1];
324                $next    = 1 + (int) $level;
325                $pattern = '/\n' . $level . ' ' . Gedcom::REGEX_TAG . ' @' . $xref . '@(\n[' . $next . '-9].*)*/';
326                $gedcom  = preg_replace($pattern, '', $gedcom);
327            }
328        }
329
330        return $gedcom;
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 (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 overridden, e.g. in a search result
430     *
431     * @param int|null $n
432     *
433     * @return void
434     */
435    public function setPrimaryName(int|null $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|null
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|null $access_level = null,
615        bool $ignore_deleted = false
616    ): Collection {
617        $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                    $facts = $facts
648                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
649                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
650                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
651
652                            return $sort_x <=> $sort_y;
653                        });
654                    break;
655            }
656        }
657
658        if ($ignore_deleted) {
659            $facts = $facts->filter(static fn (Fact $fact): bool => !$fact->isPendingDeletion());
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 !== null && $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     * Convert a name record into sortable and full/display versions. This default
986     * should be OK for simple record types. INDI/FAM records will need to redefine it.
987     *
988     * @param string $type
989     * @param string $value
990     * @param string $gedcom
991     *
992     * @return void
993     */
994    protected function addName(string $type, string $value, string $gedcom): void
995    {
996        $this->getAllNames[] = [
997            'type'   => $type,
998            'sort'   => preg_replace_callback('/(\d+)/', static fn (array $matches): string => str_pad($matches[0], 10, '0', STR_PAD_LEFT), $value),
999            'full'   => '<bdi>' . e($value) . '</bdi>',
1000            // This is used for display
1001            'fullNN' => $value,
1002            // This goes into the database
1003        ];
1004    }
1005
1006    /**
1007     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
1008     * Records without a name (e.g. FAM) will need to redefine this function.
1009     * Parameters: the level 1 fact containing the name.
1010     * Return value: an array of name structures, each containing
1011     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
1012     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
1013     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
1014     *
1015     * @param int              $level
1016     * @param string           $fact_type
1017     * @param Collection<int,Fact> $facts
1018     *
1019     * @return void
1020     */
1021    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
1022    {
1023        $sublevel    = $level + 1;
1024        $subsublevel = $sublevel + 1;
1025        foreach ($facts as $fact) {
1026            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1027                foreach ($matches as $match) {
1028                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1029                    if ($match[1] === 'NAME' && str_contains(strtoupper($match[3]), "\n2 TYPE MARRIED")) {
1030                        $this->addName('_MARNM', $match[2], $fact->gedcom());
1031                    } else {
1032                        $this->addName($match[1], $match[2], $fact->gedcom());
1033                    }
1034                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
1035                        foreach ($submatches as $submatch) {
1036                            if ($submatch[1] !== '_RUFNAME') {
1037                                $this->addName($submatch[1], $submatch[2], $match[3]);
1038                            }
1039                        }
1040                    }
1041                }
1042            }
1043        }
1044    }
1045
1046    /**
1047     * Split the record into facts
1048     *
1049     * @return array<Fact>
1050     */
1051    private function parseFacts(): array
1052    {
1053        // Split the record into facts
1054        if ($this->gedcom !== '') {
1055            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
1056            array_shift($gedcom_facts);
1057        } else {
1058            $gedcom_facts = [];
1059        }
1060        if ($this->pending !== null && $this->pending !== '') {
1061            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
1062            array_shift($pending_facts);
1063        } else {
1064            $pending_facts = [];
1065        }
1066
1067        $facts = [];
1068
1069        foreach ($gedcom_facts as $gedcom_fact) {
1070            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
1071            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
1072                $fact->setPendingDeletion();
1073            }
1074            $facts[] = $fact;
1075        }
1076        foreach ($pending_facts as $pending_fact) {
1077            if (!in_array($pending_fact, $gedcom_facts, true)) {
1078                $fact = new Fact($pending_fact, $this, md5($pending_fact));
1079                $fact->setPendingAddition();
1080                $facts[] = $fact;
1081            }
1082        }
1083
1084        return $facts;
1085    }
1086
1087    /**
1088     * Work out whether this record can be shown to a user with a given access level
1089     *
1090     * @param int $access_level
1091     *
1092     * @return bool
1093     */
1094    private function canShowRecord(int $access_level): bool
1095    {
1096        // This setting would better be called "$ENABLE_PRIVACY"
1097        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
1098            return true;
1099        }
1100
1101        // We should always be able to see our own record (unless an admin is applying download restrictions)
1102        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
1103            return true;
1104        }
1105
1106        // Does this record have a restriction notice?
1107        // Cannot use $this->>fact(), as that function calls this one.
1108        if (preg_match('/\n1 RESN (.+)/', $this->gedcom(), $match)) {
1109            $element     = new RestrictionNotice('');
1110            $restriction = $element->canonical($match[1]);
1111
1112            if (str_starts_with($restriction, RestrictionNotice::VALUE_CONFIDENTIAL)) {
1113                return Auth::PRIV_NONE >= $access_level;
1114            }
1115            if (str_starts_with($restriction, RestrictionNotice::VALUE_PRIVACY)) {
1116                return Auth::PRIV_USER >= $access_level;
1117            }
1118            if (str_starts_with($restriction, RestrictionNotice::VALUE_NONE)) {
1119                return true;
1120            }
1121        }
1122
1123        // Does this record have a default RESN?
1124        $individual_privacy = $this->tree->getIndividualPrivacy();
1125        if (isset($individual_privacy[$this->xref()])) {
1126            return $individual_privacy[$this->xref()] >= $access_level;
1127        }
1128
1129        // Privacy rules do not apply to admins
1130        if (Auth::PRIV_NONE >= $access_level) {
1131            return true;
1132        }
1133
1134        // Different types of record have different privacy rules
1135        return $this->canShowByType($access_level);
1136    }
1137
1138    /**
1139     * Lock the database row, to prevent concurrent edits.
1140     */
1141    public function lock(): void
1142    {
1143        DB::table('other')
1144            ->where('o_file', '=', $this->tree->id())
1145            ->where('o_id', '=', $this->xref())
1146            ->lockForUpdate()
1147            ->get();
1148    }
1149
1150    /**
1151     * Change records may contain notes and other fields.  Just update the date/time/author.
1152     *
1153     * @param string $gedcom
1154     *
1155     * @return string
1156     */
1157    private function updateChange(string $gedcom): string
1158    {
1159        $gedcom = preg_replace('/\n2 (DATE|_WT_USER).*(\n[3-9].*)*/', '', $gedcom);
1160        $today  = strtoupper(date('d M Y'));
1161        $now    = date('H:i:s');
1162        $author = Auth::user()->userName();
1163
1164        return $gedcom . "\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . $author;
1165    }
1166}
1167