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