xref: /webtrees/app/GedcomRecord.php (revision b55cbc6b43247e8b2ad14af6f6d24dc6747195ff)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 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     * Find individuals linked to this record.
552     *
553     * @param string $link
554     *
555     * @return Collection<int,Individual>
556     */
557    public function linkedIndividuals(string $link): Collection
558    {
559        return DB::table('individuals')
560            ->join('link', static function (JoinClause $join): void {
561                $join
562                    ->on('l_file', '=', 'i_file')
563                    ->on('l_from', '=', 'i_id');
564            })
565            ->where('i_file', '=', $this->tree->id())
566            ->where('l_type', '=', $link)
567            ->where('l_to', '=', $this->xref)
568            ->select(['individuals.*'])
569            ->get()
570            ->map(Registry::individualFactory()->mapper($this->tree))
571            ->filter(self::accessFilter());
572    }
573
574    /**
575     * Find families linked to this record.
576     *
577     * @param string $link
578     *
579     * @return Collection<int,Family>
580     */
581    public function linkedFamilies(string $link): Collection
582    {
583        return DB::table('families')
584            ->join('link', static function (JoinClause $join): void {
585                $join
586                    ->on('l_file', '=', 'f_file')
587                    ->on('l_from', '=', 'f_id');
588            })
589            ->where('f_file', '=', $this->tree->id())
590            ->where('l_type', '=', $link)
591            ->where('l_to', '=', $this->xref)
592            ->select(['families.*'])
593            ->get()
594            ->map(Registry::familyFactory()->mapper($this->tree))
595            ->filter(self::accessFilter());
596    }
597
598    /**
599     * Find sources linked to this record.
600     *
601     * @param string $link
602     *
603     * @return Collection<int,Source>
604     */
605    public function linkedSources(string $link): Collection
606    {
607        return DB::table('sources')
608            ->join('link', static function (JoinClause $join): void {
609                $join
610                    ->on('l_file', '=', 's_file')
611                    ->on('l_from', '=', 's_id');
612            })
613            ->where('s_file', '=', $this->tree->id())
614            ->where('l_type', '=', $link)
615            ->where('l_to', '=', $this->xref)
616            ->select(['sources.*'])
617            ->get()
618            ->map(Registry::sourceFactory()->mapper($this->tree))
619            ->filter(self::accessFilter());
620    }
621
622    /**
623     * Find media objects linked to this record.
624     *
625     * @param string $link
626     *
627     * @return Collection<int,Media>
628     */
629    public function linkedMedia(string $link): Collection
630    {
631        return DB::table('media')
632            ->join('link', static function (JoinClause $join): void {
633                $join
634                    ->on('l_file', '=', 'm_file')
635                    ->on('l_from', '=', 'm_id');
636            })
637            ->where('m_file', '=', $this->tree->id())
638            ->where('l_type', '=', $link)
639            ->where('l_to', '=', $this->xref)
640            ->select(['media.*'])
641            ->get()
642            ->map(Registry::mediaFactory()->mapper($this->tree))
643            ->filter(self::accessFilter());
644    }
645
646    /**
647     * Find notes linked to this record.
648     *
649     * @param string $link
650     *
651     * @return Collection<int,Note>
652     */
653    public function linkedNotes(string $link): Collection
654    {
655        return DB::table('other')
656            ->join('link', static function (JoinClause $join): void {
657                $join
658                    ->on('l_file', '=', 'o_file')
659                    ->on('l_from', '=', 'o_id');
660            })
661            ->where('o_file', '=', $this->tree->id())
662            ->where('o_type', '=', Note::RECORD_TYPE)
663            ->where('l_type', '=', $link)
664            ->where('l_to', '=', $this->xref)
665            ->select(['other.*'])
666            ->get()
667            ->map(Registry::noteFactory()->mapper($this->tree))
668            ->filter(self::accessFilter());
669    }
670
671    /**
672     * Find repositories linked to this record.
673     *
674     * @param string $link
675     *
676     * @return Collection<int,Repository>
677     */
678    public function linkedRepositories(string $link): Collection
679    {
680        return DB::table('other')
681            ->join('link', static function (JoinClause $join): void {
682                $join
683                    ->on('l_file', '=', 'o_file')
684                    ->on('l_from', '=', 'o_id');
685            })
686            ->where('o_file', '=', $this->tree->id())
687            ->where('o_type', '=', Repository::RECORD_TYPE)
688            ->where('l_type', '=', $link)
689            ->where('l_to', '=', $this->xref)
690            ->select(['other.*'])
691            ->get()
692            ->map(Registry::repositoryFactory()->mapper($this->tree))
693            ->filter(self::accessFilter());
694    }
695
696    /**
697     * Find locations linked to this record.
698     *
699     * @param string $link
700     *
701     * @return Collection<int,Location>
702     */
703    public function linkedLocations(string $link): Collection
704    {
705        return DB::table('other')
706            ->join('link', static function (JoinClause $join): void {
707                $join
708                    ->on('l_file', '=', 'o_file')
709                    ->on('l_from', '=', 'o_id');
710            })
711            ->where('o_file', '=', $this->tree->id())
712            ->where('o_type', '=', Location::RECORD_TYPE)
713            ->where('l_type', '=', $link)
714            ->where('l_to', '=', $this->xref)
715            ->select(['other.*'])
716            ->get()
717            ->map(Registry::locationFactory()->mapper($this->tree))
718            ->filter(self::accessFilter());
719    }
720
721    /**
722     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
723     * This is used to display multiple events on the individual/family lists.
724     * Multiple events can exist because of uncertainty in dates, dates in different
725     * calendars, place-names in both latin and hebrew character sets, etc.
726     * It also allows us to combine dates/places from different events in the summaries.
727     *
728     * @param array<string> $events
729     *
730     * @return array<Date>
731     */
732    public function getAllEventDates(array $events): array
733    {
734        $dates = [];
735        foreach ($this->facts($events, false, null, true) as $event) {
736            if ($event->date()->isOK()) {
737                $dates[] = $event->date();
738            }
739        }
740
741        return $dates;
742    }
743
744    /**
745     * Get all the places for a particular type of event
746     *
747     * @param array<string> $events
748     *
749     * @return array<Place>
750     */
751    public function getAllEventPlaces(array $events): array
752    {
753        $places = [];
754        foreach ($this->facts($events) as $event) {
755            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
756                foreach ($ged_places[1] as $ged_place) {
757                    $places[] = new Place($ged_place, $this->tree);
758                }
759            }
760        }
761
762        return $places;
763    }
764
765    /**
766     * The facts and events for this record.
767     *
768     * @param array<string> $filter
769     * @param bool          $sort
770     * @param int|null      $access_level
771     * @param bool          $ignore_deleted
772     *
773     * @return Collection<int,Fact>
774     */
775    public function facts(
776        array $filter = [],
777        bool $sort = false,
778        int $access_level = null,
779        bool $ignore_deleted = false
780    ): Collection {
781        $access_level = $access_level ?? Auth::accessLevel($this->tree);
782
783        // Convert BIRT into INDI:BIRT, etc.
784        $filter = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, $filter);
785
786        $facts = new Collection();
787        if ($this->canShow($access_level)) {
788            foreach ($this->facts as $fact) {
789                if (($filter === [] || in_array($fact->tag(), $filter, true)) && $fact->canShow($access_level)) {
790                    $facts->push($fact);
791                }
792            }
793        }
794
795        if ($sort) {
796            switch ($this->tag()) {
797                case Family::RECORD_TYPE:
798                case Individual::RECORD_TYPE:
799                    $facts = Fact::sortFacts($facts);
800                    break;
801
802                default:
803                    $subtags = Registry::elementFactory()->make($this->tag())->subtags();
804                    $subtags = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, array_keys($subtags));
805                    $subtags = array_combine(range(1, count($subtags)), $subtags);
806
807                    $facts = $facts
808                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
809                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
810                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
811
812                            return $sort_x <=> $sort_y;
813                        });
814                    break;
815            }
816        }
817
818        if ($ignore_deleted) {
819            $facts = $facts->filter(static function (Fact $fact): bool {
820                return !$fact->isPendingDeletion();
821            });
822        }
823
824        return $facts;
825    }
826
827    /**
828     * @return array<string,string>
829     */
830    public function missingFacts(): array
831    {
832        $missing_facts = [];
833
834        foreach (Registry::elementFactory()->make($this->tag())->subtags() as $subtag => $repeat) {
835            [, $max] = explode(':', $repeat);
836            $max = $max === 'M' ? PHP_INT_MAX : (int) $max;
837
838            if ($this->facts([$subtag], false, null, true)->count() < $max) {
839                $missing_facts[$subtag] = $subtag;
840                $missing_facts[$subtag] = Registry::elementFactory()->make($this->tag() . ':' . $subtag)->label();
841            }
842        }
843
844        uasort($missing_facts, I18N::comparator());
845
846        if (!Auth::canUploadMedia($this->tree, Auth::user())) {
847            unset($missing_facts['OBJE']);
848        }
849
850        // We have special code for this.
851        unset($missing_facts['FILE']);
852
853        return $missing_facts;
854    }
855
856    /**
857     * Get the last-change timestamp for this record
858     *
859     * @return TimestampInterface
860     */
861    public function lastChangeTimestamp(): TimestampInterface
862    {
863        /** @var Fact|null $chan */
864        $chan = $this->facts(['CHAN'])->first();
865
866        if ($chan instanceof Fact) {
867            // The record does have a CHAN event
868            $d = $chan->date()->minimumDate()->format('%Y-%m-%d');
869
870            if (preg_match('/\n3 TIME( (\d\d):(\d\d):(\d\d))/', $chan->gedcom(), $match)) {
871                return Registry::timestampFactory()->fromString($d . $match[1], 'Y-m-d H:i:s');
872            }
873
874            if (preg_match('/\n3 TIME ((\d\d):(\d\d))/', $chan->gedcom(), $match)) {
875                return Registry::timestampFactory()->fromString($d . $match[1], 'Y-m-d H:i');
876            }
877
878            return Registry::timestampFactory()->fromString($d, 'Y-m-d');
879        }
880
881        // The record does not have a CHAN event
882        return Registry::timestampFactory()->make(0);
883    }
884
885    /**
886     * Get the last-change user for this record
887     *
888     * @return string
889     */
890    public function lastChangeUser(): string
891    {
892        $chan = $this->facts(['CHAN'])->first();
893
894        if ($chan === null) {
895            return I18N::translate('Unknown');
896        }
897
898        $chan_user = $chan->attribute('_WT_USER');
899        if ($chan_user === '') {
900            return I18N::translate('Unknown');
901        }
902
903        return $chan_user;
904    }
905
906    /**
907     * Add a new fact to this record
908     *
909     * @param string $gedcom
910     * @param bool   $update_chan
911     *
912     * @return void
913     */
914    public function createFact(string $gedcom, bool $update_chan): void
915    {
916        $this->updateFact('', $gedcom, $update_chan);
917    }
918
919    /**
920     * Delete a fact from this record
921     *
922     * @param string $fact_id
923     * @param bool   $update_chan
924     *
925     * @return void
926     */
927    public function deleteFact(string $fact_id, bool $update_chan): void
928    {
929        $this->updateFact($fact_id, '', $update_chan);
930    }
931
932    /**
933     * Replace a fact with a new gedcom data.
934     *
935     * @param string $fact_id
936     * @param string $gedcom
937     * @param bool   $update_chan
938     *
939     * @return void
940     * @throws Exception
941     */
942    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
943    {
944        // Not all record types allow a CHAN event.
945        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
946
947        // MSDOS line endings will break things in horrible ways
948        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
949        $gedcom = trim($gedcom);
950
951        if ($this->pending === '') {
952            throw new Exception('Cannot edit a deleted record');
953        }
954        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
955            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
956        }
957
958        if ($this->pending) {
959            $old_gedcom = $this->pending;
960        } else {
961            $old_gedcom = $this->gedcom;
962        }
963
964        // First line of record may contain data - e.g. NOTE records.
965        [$new_gedcom] = explode("\n", $old_gedcom, 2);
966
967        // Replacing (or deleting) an existing fact
968        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
969            if ($fact->id() === $fact_id) {
970                if ($gedcom !== '') {
971                    $new_gedcom .= "\n" . $gedcom;
972                }
973                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
974            } elseif (!str_ends_with($fact->tag(), ':CHAN') || !$update_chan) {
975                $new_gedcom .= "\n" . $fact->gedcom();
976            }
977        }
978
979        // Adding a new fact
980        if ($fact_id === '') {
981            $new_gedcom .= "\n" . $gedcom;
982        }
983
984        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
985            $today = strtoupper(date('d M Y'));
986            $now   = date('H:i:s');
987            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
988        }
989
990        if ($new_gedcom !== $old_gedcom) {
991            // Save the changes
992            DB::table('change')->insert([
993                'gedcom_id'  => $this->tree->id(),
994                'xref'       => $this->xref,
995                'old_gedcom' => $old_gedcom,
996                'new_gedcom' => $new_gedcom,
997                'user_id'    => Auth::id(),
998            ]);
999
1000            $this->pending = $new_gedcom;
1001
1002            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1003                $pending_changes_service = app(PendingChangesService::class);
1004                assert($pending_changes_service instanceof PendingChangesService);
1005
1006                $pending_changes_service->acceptRecord($this);
1007                $this->gedcom  = $new_gedcom;
1008                $this->pending = null;
1009            }
1010        }
1011
1012        $this->facts = $this->parseFacts();
1013    }
1014
1015    /**
1016     * Update this record
1017     *
1018     * @param string $gedcom
1019     * @param bool   $update_chan
1020     *
1021     * @return void
1022     */
1023    public function updateRecord(string $gedcom, bool $update_chan): void
1024    {
1025        // Not all record types allow a CHAN event.
1026        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
1027
1028        // MSDOS line endings will break things in horrible ways
1029        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1030        $gedcom = trim($gedcom);
1031
1032        // Update the CHAN record
1033        if ($update_chan) {
1034            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1035            $today = strtoupper(date('d M Y'));
1036            $now   = date('H:i:s');
1037            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
1038        }
1039
1040        // Create a pending change
1041        DB::table('change')->insert([
1042            'gedcom_id'  => $this->tree->id(),
1043            'xref'       => $this->xref,
1044            'old_gedcom' => $this->gedcom(),
1045            'new_gedcom' => $gedcom,
1046            'user_id'    => Auth::id(),
1047        ]);
1048
1049        // Clear the cache
1050        $this->pending = $gedcom;
1051
1052        // Accept this pending change
1053        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1054            $pending_changes_service = app(PendingChangesService::class);
1055            assert($pending_changes_service instanceof PendingChangesService);
1056
1057            $pending_changes_service->acceptRecord($this);
1058            $this->gedcom  = $gedcom;
1059            $this->pending = null;
1060        }
1061
1062        $this->facts = $this->parseFacts();
1063
1064        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1065    }
1066
1067    /**
1068     * Delete this record
1069     *
1070     * @return void
1071     */
1072    public function deleteRecord(): void
1073    {
1074        // Create a pending change
1075        if (!$this->isPendingDeletion()) {
1076            DB::table('change')->insert([
1077                'gedcom_id'  => $this->tree->id(),
1078                'xref'       => $this->xref,
1079                'old_gedcom' => $this->gedcom(),
1080                'new_gedcom' => '',
1081                'user_id'    => Auth::id(),
1082            ]);
1083        }
1084
1085        // Auto-accept this pending change
1086        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1087            $pending_changes_service = app(PendingChangesService::class);
1088            assert($pending_changes_service instanceof PendingChangesService);
1089
1090            $pending_changes_service->acceptRecord($this);
1091        }
1092
1093        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1094    }
1095
1096    /**
1097     * Remove all links from this record to $xref
1098     *
1099     * @param string $xref
1100     * @param bool   $update_chan
1101     *
1102     * @return void
1103     */
1104    public function removeLinks(string $xref, bool $update_chan): void
1105    {
1106        $value = '@' . $xref . '@';
1107
1108        foreach ($this->facts() as $fact) {
1109            if ($fact->value() === $value) {
1110                $this->deleteFact($fact->id(), $update_chan);
1111            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1112                $gedcom = $fact->gedcom();
1113                foreach ($matches as $match) {
1114                    $next_level  = $match[1] + 1;
1115                    $next_levels = '[' . $next_level . '-9]';
1116                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1117                }
1118                $this->updateFact($fact->id(), $gedcom, $update_chan);
1119            }
1120        }
1121    }
1122
1123    /**
1124     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1125     * also delete all links to it.
1126     *
1127     * @return array<GedcomRecord>
1128     */
1129    public function linkingRecords(): array
1130    {
1131        $like = addcslashes($this->xref(), '\\%_');
1132
1133        $union = DB::table('change')
1134            ->where('gedcom_id', '=', $this->tree()->id())
1135            ->where('new_gedcom', 'LIKE', '%@' . $like . '@%')
1136            ->where('new_gedcom', 'NOT LIKE', '0 @' . $like . '@%')
1137            ->whereIn('change_id', function (Builder $query): void {
1138                $query->select(new Expression('MAX(change_id)'))
1139                    ->from('change')
1140                    ->where('gedcom_id', '=', $this->tree->id())
1141                    ->where('status', '=', 'pending')
1142                    ->groupBy(['xref']);
1143            })
1144            ->select(['xref']);
1145
1146        $xrefs = DB::table('link')
1147            ->where('l_file', '=', $this->tree()->id())
1148            ->where('l_to', '=', $this->xref())
1149            ->select(['l_from'])
1150            ->union($union)
1151            ->pluck('l_from');
1152
1153        return $xrefs->map(function (string $xref): GedcomRecord {
1154            $record = Registry::gedcomRecordFactory()->make($xref, $this->tree);
1155            assert($record instanceof GedcomRecord);
1156
1157            return $record;
1158        })->all();
1159    }
1160
1161    /**
1162     * Each object type may have its own special rules, and re-implement this function.
1163     *
1164     * @param int $access_level
1165     *
1166     * @return bool
1167     */
1168    protected function canShowByType(int $access_level): bool
1169    {
1170        $fact_privacy = $this->tree->getFactPrivacy();
1171
1172        if (isset($fact_privacy[static::RECORD_TYPE])) {
1173            // Restriction found
1174            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
1175        }
1176
1177        // No restriction found - must be public:
1178        return true;
1179    }
1180
1181    /**
1182     * Generate a private version of this record
1183     *
1184     * @param int $access_level
1185     *
1186     * @return string
1187     */
1188    protected function createPrivateGedcomRecord(int $access_level): string
1189    {
1190        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
1191    }
1192
1193    /**
1194     * Convert a name record into sortable and full/display versions. This default
1195     * should be OK for simple record types. INDI/FAM records will need to redefine it.
1196     *
1197     * @param string $type
1198     * @param string $value
1199     * @param string $gedcom
1200     *
1201     * @return void
1202     */
1203    protected function addName(string $type, string $value, string $gedcom): void
1204    {
1205        $this->getAllNames[] = [
1206            'type'   => $type,
1207            'sort'   => preg_replace_callback('/(\d+)/', static function (array $matches): string {
1208                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
1209            }, $value),
1210            'full'   => '<bdi>' . e($value) . '</bdi>',
1211            // This is used for display
1212            'fullNN' => $value,
1213            // This goes into the database
1214        ];
1215    }
1216
1217    /**
1218     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
1219     * Records without a name (e.g. FAM) will need to redefine this function.
1220     * Parameters: the level 1 fact containing the name.
1221     * Return value: an array of name structures, each containing
1222     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
1223     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
1224     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
1225     *
1226     * @param int              $level
1227     * @param string           $fact_type
1228     * @param Collection<int,Fact> $facts
1229     *
1230     * @return void
1231     */
1232    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
1233    {
1234        $sublevel    = $level + 1;
1235        $subsublevel = $sublevel + 1;
1236        foreach ($facts as $fact) {
1237            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1238                foreach ($matches as $match) {
1239                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1240                    if ($match[1] === 'NAME' && str_contains($match[3], "\n2 TYPE married")) {
1241                        $this->addName('_MARNM', $match[2], $fact->gedcom());
1242                    } else {
1243                        $this->addName($match[1], $match[2], $fact->gedcom());
1244                    }
1245                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
1246                        foreach ($submatches as $submatch) {
1247                            $this->addName($submatch[1], $submatch[2], $match[3]);
1248                        }
1249                    }
1250                }
1251            }
1252        }
1253    }
1254
1255    /**
1256     * Split the record into facts
1257     *
1258     * @return array<Fact>
1259     */
1260    private function parseFacts(): array
1261    {
1262        // Split the record into facts
1263        if ($this->gedcom) {
1264            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
1265            array_shift($gedcom_facts);
1266        } else {
1267            $gedcom_facts = [];
1268        }
1269        if ($this->pending) {
1270            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
1271            array_shift($pending_facts);
1272        } else {
1273            $pending_facts = [];
1274        }
1275
1276        $facts = [];
1277
1278        foreach ($gedcom_facts as $gedcom_fact) {
1279            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
1280            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
1281                $fact->setPendingDeletion();
1282            }
1283            $facts[] = $fact;
1284        }
1285        foreach ($pending_facts as $pending_fact) {
1286            if (!in_array($pending_fact, $gedcom_facts, true)) {
1287                $fact = new Fact($pending_fact, $this, md5($pending_fact));
1288                $fact->setPendingAddition();
1289                $facts[] = $fact;
1290            }
1291        }
1292
1293        return $facts;
1294    }
1295
1296    /**
1297     * Work out whether this record can be shown to a user with a given access level
1298     *
1299     * @param int $access_level
1300     *
1301     * @return bool
1302     */
1303    private function canShowRecord(int $access_level): bool
1304    {
1305        // This setting would better be called "$ENABLE_PRIVACY"
1306        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
1307            return true;
1308        }
1309
1310        // We should always be able to see our own record (unless an admin is applying download restrictions)
1311        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
1312            return true;
1313        }
1314
1315        // Does this record have a RESN?
1316        if (str_contains($this->gedcom, "\n1 RESN confidential")) {
1317            return Auth::PRIV_NONE >= $access_level;
1318        }
1319        if (str_contains($this->gedcom, "\n1 RESN privacy")) {
1320            return Auth::PRIV_USER >= $access_level;
1321        }
1322        if (str_contains($this->gedcom, "\n1 RESN none")) {
1323            return true;
1324        }
1325
1326        // Does this record have a default RESN?
1327        $individual_privacy = $this->tree->getIndividualPrivacy();
1328        if (isset($individual_privacy[$this->xref()])) {
1329            return $individual_privacy[$this->xref()] >= $access_level;
1330        }
1331
1332        // Privacy rules do not apply to admins
1333        if (Auth::PRIV_NONE >= $access_level) {
1334            return true;
1335        }
1336
1337        // Different types of record have different privacy rules
1338        return $this->canShowByType($access_level);
1339    }
1340
1341    /**
1342     * Lock the database row, to prevent concurrent edits.
1343     */
1344    public function lock(): void
1345    {
1346        DB::table('other')
1347            ->where('o_file', '=', $this->tree->id())
1348            ->where('o_id', '=', $this->xref())
1349            ->lockForUpdate()
1350            ->get();
1351    }
1352}
1353