xref: /webtrees/app/GedcomRecord.php (revision c908635b89a84d0a06f38a4d07640639e838703f)
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\Http\RequestHandlers\GedcomRecordPage;
27use Fisharebest\Webtrees\Services\PendingChangesService;
28use Illuminate\Database\Capsule\Manager as DB;
29use Illuminate\Database\Query\Builder;
30use Illuminate\Database\Query\Expression;
31use Illuminate\Database\Query\JoinClause;
32use Illuminate\Support\Collection;
33
34use function addcslashes;
35use function app;
36use function array_combine;
37use function array_keys;
38use function array_map;
39use function array_search;
40use function array_shift;
41use function assert;
42use function count;
43use function date;
44use function e;
45use function explode;
46use function in_array;
47use function md5;
48use function preg_match;
49use function preg_match_all;
50use function preg_replace;
51use function preg_replace_callback;
52use function preg_split;
53use function range;
54use function route;
55use function str_contains;
56use function str_ends_with;
57use function str_pad;
58use function strtoupper;
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        return Auth::isEditor($this->tree) && !str_contains($this->gedcom, "\n1 RESN locked");
294    }
295
296    /**
297     * Remove private data from the raw gedcom record.
298     * Return both the visible and invisible data. We need the invisible data when editing.
299     *
300     * @param int $access_level
301     *
302     * @return string
303     */
304    public function privatizeGedcom(int $access_level): string
305    {
306        if ($access_level === Auth::PRIV_HIDE) {
307            // We may need the original record, for example when downloading a GEDCOM or clippings cart
308            return $this->gedcom;
309        }
310
311        if ($this->canShow($access_level)) {
312            // The record is not private, but the individual facts may be.
313
314            // Include the entire first line (for NOTE records)
315            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
316
317            // Check each of the facts for access
318            foreach ($this->facts([], false, $access_level) as $fact) {
319                $gedrec .= "\n" . $fact->gedcom();
320            }
321
322            return $gedrec;
323        }
324
325        // We cannot display the details, but we may be able to display
326        // limited data, such as links to other records.
327        return $this->createPrivateGedcomRecord($access_level);
328    }
329
330    /**
331     * Default for "other" object types
332     *
333     * @return void
334     */
335    public function extractNames(): void
336    {
337        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
338    }
339
340    /**
341     * Derived classes should redefine this function, otherwise the object will have no name
342     *
343     * @return array<int,array<string,string>>
344     */
345    public function getAllNames(): array
346    {
347        if ($this->getAllNames === []) {
348            if ($this->canShowName()) {
349                // Ask the record to extract its names
350                $this->extractNames();
351                // No name found? Use a fallback.
352                if ($this->getAllNames === []) {
353                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
354                }
355            } else {
356                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
357            }
358        }
359
360        return $this->getAllNames;
361    }
362
363    /**
364     * If this object has no name, what do we call it?
365     *
366     * @return string
367     */
368    public function getFallBackName(): string
369    {
370        return e($this->xref());
371    }
372
373    /**
374     * Which of the (possibly several) names of this record is the primary one.
375     *
376     * @return int
377     */
378    public function getPrimaryName(): int
379    {
380        static $language_script;
381
382        $language_script ??= I18N::locale()->script()->code();
383
384        if ($this->getPrimaryName === null) {
385            // Generally, the first name is the primary one....
386            $this->getPrimaryName = 0;
387            // ...except when the language/name use different character sets
388            foreach ($this->getAllNames() as $n => $name) {
389                if (I18N::textScript($name['sort']) === $language_script) {
390                    $this->getPrimaryName = $n;
391                    break;
392                }
393            }
394        }
395
396        return $this->getPrimaryName;
397    }
398
399    /**
400     * Which of the (possibly several) names of this record is the secondary one.
401     *
402     * @return int
403     */
404    public function getSecondaryName(): int
405    {
406        if ($this->getSecondaryName === null) {
407            // Generally, the primary and secondary names are the same
408            $this->getSecondaryName = $this->getPrimaryName();
409            // ....except when there are names with different character sets
410            $all_names = $this->getAllNames();
411            if (count($all_names) > 1) {
412                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
413                foreach ($all_names as $n => $name) {
414                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
415                        $this->getSecondaryName = $n;
416                        break;
417                    }
418                }
419            }
420        }
421
422        return $this->getSecondaryName;
423    }
424
425    /**
426     * Allow the choice of primary name to be overidden, e.g. in a search result
427     *
428     * @param int|null $n
429     *
430     * @return void
431     */
432    public function setPrimaryName(int $n = null): void
433    {
434        $this->getPrimaryName   = $n;
435        $this->getSecondaryName = null;
436    }
437
438    /**
439     * Allow native PHP functions such as array_unique() to work with objects
440     *
441     * @return string
442     */
443    public function __toString(): string
444    {
445        return $this->xref . '@' . $this->tree->id();
446    }
447
448    /**
449     * /**
450     * Get variants of the name
451     *
452     * @return string
453     */
454    public function fullName(): string
455    {
456        if ($this->canShowName()) {
457            $tmp = $this->getAllNames();
458
459            return $tmp[$this->getPrimaryName()]['full'];
460        }
461
462        return I18N::translate('Private');
463    }
464
465    /**
466     * Get a sortable version of the name. Do not display this!
467     *
468     * @return string
469     */
470    public function sortName(): string
471    {
472        // The sortable name is never displayed, no need to call canShowName()
473        $tmp = $this->getAllNames();
474
475        return $tmp[$this->getPrimaryName()]['sort'];
476    }
477
478    /**
479     * Get the full name in an alternative character set
480     *
481     * @return string|null
482     */
483    public function alternateName(): ?string
484    {
485        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
486            $all_names = $this->getAllNames();
487
488            return $all_names[$this->getSecondaryName()]['full'];
489        }
490
491        return null;
492    }
493
494    /**
495     * Format this object for display in a list
496     *
497     * @return string
498     */
499    public function formatList(): string
500    {
501        $html = '<a href="' . e($this->url()) . '" class="list_item">';
502        $html .= '<b>' . $this->fullName() . '</b>';
503        $html .= $this->formatListDetails();
504        $html .= '</a>';
505
506        return $html;
507    }
508
509    /**
510     * This function should be redefined in derived classes to show any major
511     * identifying characteristics of this record.
512     *
513     * @return string
514     */
515    public function formatListDetails(): string
516    {
517        return '';
518    }
519
520    /**
521     * Extract/format the first fact from a list of facts.
522     *
523     * @param array<string> $facts
524     * @param int           $style
525     *
526     * @return string
527     */
528    public function formatFirstMajorFact(array $facts, int $style): string
529    {
530        foreach ($this->facts($facts, true) as $event) {
531            // Only display if it has a date or place (or both)
532            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
533                $joiner = ' — ';
534            } else {
535                $joiner = '';
536            }
537            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
538                switch ($style) {
539                    case 1:
540                        return '<br><em>' . $event->label() . ' ' . view('fact-date', ['cal_link' => 'false', 'fact' => $event, 'record' => $event->record(), 'time' => false]) . '</em>';
541                    case 2:
542                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . view('fact-date', ['cal_link' => 'false', 'fact' => $event, 'record' => $event->record(), 'time' => false]) . $joiner . $event->place()->shortName() . '</dd></dl>';
543                }
544            }
545        }
546
547        return '';
548    }
549
550    /**
551     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
552     * This is used to display multiple events on the individual/family lists.
553     * Multiple events can exist because of uncertainty in dates, dates in different
554     * calendars, place-names in both latin and hebrew character sets, etc.
555     * It also allows us to combine dates/places from different events in the summaries.
556     *
557     * @param array<string> $events
558     *
559     * @return array<Date>
560     */
561    public function getAllEventDates(array $events): array
562    {
563        $dates = [];
564        foreach ($this->facts($events, false, null, true) as $event) {
565            if ($event->date()->isOK()) {
566                $dates[] = $event->date();
567            }
568        }
569
570        return $dates;
571    }
572
573    /**
574     * Get all the places for a particular type of event
575     *
576     * @param array<string> $events
577     *
578     * @return array<Place>
579     */
580    public function getAllEventPlaces(array $events): array
581    {
582        $places = [];
583        foreach ($this->facts($events) as $event) {
584            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
585                foreach ($ged_places[1] as $ged_place) {
586                    $places[] = new Place($ged_place, $this->tree);
587                }
588            }
589        }
590
591        return $places;
592    }
593
594    /**
595     * The facts and events for this record.
596     *
597     * @param array<string> $filter
598     * @param bool          $sort
599     * @param int|null      $access_level
600     * @param bool          $ignore_deleted
601     *
602     * @return Collection<int,Fact>
603     */
604    public function facts(
605        array $filter = [],
606        bool $sort = false,
607        int $access_level = null,
608        bool $ignore_deleted = false
609    ): Collection {
610        $access_level = $access_level ?? Auth::accessLevel($this->tree);
611
612        // Convert BIRT into INDI:BIRT, etc.
613        $filter = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, $filter);
614
615        $facts = new Collection();
616        if ($this->canShow($access_level)) {
617            foreach ($this->facts as $fact) {
618                if (($filter === [] || in_array($fact->tag(), $filter, true)) && $fact->canShow($access_level)) {
619                    $facts->push($fact);
620                }
621            }
622        }
623
624        if ($sort) {
625            switch ($this->tag()) {
626                case Family::RECORD_TYPE:
627                case Individual::RECORD_TYPE:
628                    $facts = Fact::sortFacts($facts);
629                    break;
630
631                default:
632                    $subtags = Registry::elementFactory()->make($this->tag())->subtags();
633                    $subtags = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, array_keys($subtags));
634                    $subtags = array_combine(range(1, count($subtags)), $subtags);
635
636                    $facts = $facts
637                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
638                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
639                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
640
641                            return $sort_x <=> $sort_y;
642                        });
643                    break;
644            }
645        }
646
647        if ($ignore_deleted) {
648            $facts = $facts->filter(static function (Fact $fact): bool {
649                return !$fact->isPendingDeletion();
650            });
651        }
652
653        return $facts;
654    }
655
656    /**
657     * @return array<string,string>
658     */
659    public function missingFacts(): array
660    {
661        $missing_facts = [];
662
663        foreach (Registry::elementFactory()->make($this->tag())->subtags() as $subtag => $repeat) {
664            [, $max] = explode(':', $repeat);
665            $max = $max === 'M' ? PHP_INT_MAX : (int) $max;
666
667            if ($this->facts([$subtag], false, null, true)->count() < $max) {
668                $missing_facts[$subtag] = $subtag;
669                $missing_facts[$subtag] = Registry::elementFactory()->make($this->tag() . ':' . $subtag)->label();
670            }
671        }
672
673        uasort($missing_facts, I18N::comparator());
674
675        if (!Auth::canUploadMedia($this->tree, Auth::user())) {
676            unset($missing_facts['OBJE']);
677        }
678
679        // We have special code for this.
680        unset($missing_facts['FILE']);
681
682        return $missing_facts;
683    }
684
685    /**
686     * Get the last-change timestamp for this record
687     *
688     * @return TimestampInterface
689     */
690    public function lastChangeTimestamp(): TimestampInterface
691    {
692        /** @var Fact|null $chan */
693        $chan = $this->facts(['CHAN'])->first();
694
695        if ($chan instanceof Fact) {
696            // The record does have a CHAN event
697            $d = $chan->date()->minimumDate()->format('%Y-%m-%d');
698
699            if (preg_match('/\n3 TIME( (\d\d):(\d\d):(\d\d))/', $chan->gedcom(), $match)) {
700                return Registry::timestampFactory()->fromString($d . $match[1], 'Y-m-d H:i:s');
701            }
702
703            if (preg_match('/\n3 TIME ((\d\d):(\d\d))/', $chan->gedcom(), $match)) {
704                return Registry::timestampFactory()->fromString($d . $match[1], 'Y-m-d H:i');
705            }
706
707            return Registry::timestampFactory()->fromString($d, 'Y-m-d');
708        }
709
710        // The record does not have a CHAN event
711        return Registry::timestampFactory()->make(0);
712    }
713
714    /**
715     * Get the last-change user for this record
716     *
717     * @return string
718     */
719    public function lastChangeUser(): string
720    {
721        $chan = $this->facts(['CHAN'])->first();
722
723        if ($chan === null) {
724            return I18N::translate('Unknown');
725        }
726
727        $chan_user = $chan->attribute('_WT_USER');
728        if ($chan_user === '') {
729            return I18N::translate('Unknown');
730        }
731
732        return $chan_user;
733    }
734
735    /**
736     * Add a new fact to this record
737     *
738     * @param string $gedcom
739     * @param bool   $update_chan
740     *
741     * @return void
742     */
743    public function createFact(string $gedcom, bool $update_chan): void
744    {
745        $this->updateFact('', $gedcom, $update_chan);
746    }
747
748    /**
749     * Delete a fact from this record
750     *
751     * @param string $fact_id
752     * @param bool   $update_chan
753     *
754     * @return void
755     */
756    public function deleteFact(string $fact_id, bool $update_chan): void
757    {
758        $this->updateFact($fact_id, '', $update_chan);
759    }
760
761    /**
762     * Replace a fact with a new gedcom data.
763     *
764     * @param string $fact_id
765     * @param string $gedcom
766     * @param bool   $update_chan
767     *
768     * @return void
769     * @throws Exception
770     */
771    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
772    {
773        // Not all record types allow a CHAN event.
774        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
775
776        // MSDOS line endings will break things in horrible ways
777        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
778        $gedcom = trim($gedcom);
779
780        if ($this->pending === '') {
781            throw new Exception('Cannot edit a deleted record');
782        }
783        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
784            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
785        }
786
787        if ($this->pending) {
788            $old_gedcom = $this->pending;
789        } else {
790            $old_gedcom = $this->gedcom;
791        }
792
793        // First line of record may contain data - e.g. NOTE records.
794        [$new_gedcom] = explode("\n", $old_gedcom, 2);
795
796        // Replacing (or deleting) an existing fact
797        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
798            if ($fact->id() === $fact_id) {
799                if ($gedcom !== '') {
800                    $new_gedcom .= "\n" . $gedcom;
801                }
802                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
803            } elseif (!str_ends_with($fact->tag(), ':CHAN') || !$update_chan) {
804                $new_gedcom .= "\n" . $fact->gedcom();
805            }
806        }
807
808        // Adding a new fact
809        if ($fact_id === '') {
810            $new_gedcom .= "\n" . $gedcom;
811        }
812
813        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
814            $today = strtoupper(date('d M Y'));
815            $now   = date('H:i:s');
816            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
817        }
818
819        if ($new_gedcom !== $old_gedcom) {
820            // Save the changes
821            DB::table('change')->insert([
822                'gedcom_id'  => $this->tree->id(),
823                'xref'       => $this->xref,
824                'old_gedcom' => $old_gedcom,
825                'new_gedcom' => $new_gedcom,
826                'user_id'    => Auth::id(),
827            ]);
828
829            $this->pending = $new_gedcom;
830
831            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
832                $pending_changes_service = app(PendingChangesService::class);
833                assert($pending_changes_service instanceof PendingChangesService);
834
835                $pending_changes_service->acceptRecord($this);
836                $this->gedcom  = $new_gedcom;
837                $this->pending = null;
838            }
839        }
840
841        $this->facts = $this->parseFacts();
842    }
843
844    /**
845     * Update this record
846     *
847     * @param string $gedcom
848     * @param bool   $update_chan
849     *
850     * @return void
851     */
852    public function updateRecord(string $gedcom, bool $update_chan): void
853    {
854        // Not all record types allow a CHAN event.
855        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
856
857        // MSDOS line endings will break things in horrible ways
858        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
859        $gedcom = trim($gedcom);
860
861        // Update the CHAN record
862        if ($update_chan) {
863            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
864            $today = strtoupper(date('d M Y'));
865            $now   = date('H:i:s');
866            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
867        }
868
869        // Create a pending change
870        DB::table('change')->insert([
871            'gedcom_id'  => $this->tree->id(),
872            'xref'       => $this->xref,
873            'old_gedcom' => $this->gedcom(),
874            'new_gedcom' => $gedcom,
875            'user_id'    => Auth::id(),
876        ]);
877
878        // Clear the cache
879        $this->pending = $gedcom;
880
881        // Accept this pending change
882        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
883            $pending_changes_service = app(PendingChangesService::class);
884            assert($pending_changes_service instanceof PendingChangesService);
885
886            $pending_changes_service->acceptRecord($this);
887            $this->gedcom  = $gedcom;
888            $this->pending = null;
889        }
890
891        $this->facts = $this->parseFacts();
892
893        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
894    }
895
896    /**
897     * Delete this record
898     *
899     * @return void
900     */
901    public function deleteRecord(): void
902    {
903        // Create a pending change
904        if (!$this->isPendingDeletion()) {
905            DB::table('change')->insert([
906                'gedcom_id'  => $this->tree->id(),
907                'xref'       => $this->xref,
908                'old_gedcom' => $this->gedcom(),
909                'new_gedcom' => '',
910                'user_id'    => Auth::id(),
911            ]);
912        }
913
914        // Auto-accept this pending change
915        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
916            $pending_changes_service = app(PendingChangesService::class);
917            assert($pending_changes_service instanceof PendingChangesService);
918
919            $pending_changes_service->acceptRecord($this);
920        }
921
922        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
923    }
924
925    /**
926     * Remove all links from this record to $xref
927     *
928     * @param string $xref
929     * @param bool   $update_chan
930     *
931     * @return void
932     */
933    public function removeLinks(string $xref, bool $update_chan): void
934    {
935        $value = '@' . $xref . '@';
936
937        foreach ($this->facts() as $fact) {
938            if ($fact->value() === $value) {
939                $this->deleteFact($fact->id(), $update_chan);
940            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
941                $gedcom = $fact->gedcom();
942                foreach ($matches as $match) {
943                    $next_level  = $match[1] + 1;
944                    $next_levels = '[' . $next_level . '-9]';
945                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
946                }
947                $this->updateFact($fact->id(), $gedcom, $update_chan);
948            }
949        }
950    }
951
952    /**
953     * Each object type may have its own special rules, and re-implement this function.
954     *
955     * @param int $access_level
956     *
957     * @return bool
958     */
959    protected function canShowByType(int $access_level): bool
960    {
961        $fact_privacy = $this->tree->getFactPrivacy();
962
963        if (isset($fact_privacy[static::RECORD_TYPE])) {
964            // Restriction found
965            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
966        }
967
968        // No restriction found - must be public:
969        return true;
970    }
971
972    /**
973     * Generate a private version of this record
974     *
975     * @param int $access_level
976     *
977     * @return string
978     */
979    protected function createPrivateGedcomRecord(int $access_level): string
980    {
981        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
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 function (array $matches): string {
999                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
1000            }, $value),
1001            'full'   => '<bdi>' . e($value) . '</bdi>',
1002            // This is used for display
1003            'fullNN' => $value,
1004            // This goes into the database
1005        ];
1006    }
1007
1008    /**
1009     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
1010     * Records without a name (e.g. FAM) will need to redefine this function.
1011     * Parameters: the level 1 fact containing the name.
1012     * Return value: an array of name structures, each containing
1013     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
1014     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
1015     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
1016     *
1017     * @param int              $level
1018     * @param string           $fact_type
1019     * @param Collection<int,Fact> $facts
1020     *
1021     * @return void
1022     */
1023    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
1024    {
1025        $sublevel    = $level + 1;
1026        $subsublevel = $sublevel + 1;
1027        foreach ($facts as $fact) {
1028            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1029                foreach ($matches as $match) {
1030                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1031                    if ($match[1] === 'NAME' && str_contains($match[3], "\n2 TYPE married")) {
1032                        $this->addName('_MARNM', $match[2], $fact->gedcom());
1033                    } else {
1034                        $this->addName($match[1], $match[2], $fact->gedcom());
1035                    }
1036                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
1037                        foreach ($submatches as $submatch) {
1038                            $this->addName($submatch[1], $submatch[2], $match[3]);
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) {
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 RESN?
1107        if (str_contains($this->gedcom, "\n1 RESN confidential")) {
1108            return Auth::PRIV_NONE >= $access_level;
1109        }
1110        if (str_contains($this->gedcom, "\n1 RESN privacy")) {
1111            return Auth::PRIV_USER >= $access_level;
1112        }
1113        if (str_contains($this->gedcom, "\n1 RESN none")) {
1114            return true;
1115        }
1116
1117        // Does this record have a default RESN?
1118        $individual_privacy = $this->tree->getIndividualPrivacy();
1119        if (isset($individual_privacy[$this->xref()])) {
1120            return $individual_privacy[$this->xref()] >= $access_level;
1121        }
1122
1123        // Privacy rules do not apply to admins
1124        if (Auth::PRIV_NONE >= $access_level) {
1125            return true;
1126        }
1127
1128        // Different types of record have different privacy rules
1129        return $this->canShowByType($access_level);
1130    }
1131
1132    /**
1133     * Lock the database row, to prevent concurrent edits.
1134     */
1135    public function lock(): void
1136    {
1137        DB::table('other')
1138            ->where('o_file', '=', $this->tree->id())
1139            ->where('o_id', '=', $this->xref())
1140            ->lockForUpdate()
1141            ->get();
1142    }
1143}
1144