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\UserInterface;
25use Fisharebest\Webtrees\Functions\FunctionsPrint;
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;
33use Throwable;
34use Transliterator;
35
36use function addcslashes;
37use function app;
38use function array_shift;
39use function assert;
40use function count;
41use function date;
42use function e;
43use function explode;
44use function implode;
45use function in_array;
46use function md5;
47use function preg_match;
48use function preg_match_all;
49use function preg_replace;
50use function preg_replace_callback;
51use function preg_split;
52use function route;
53use function str_contains;
54use function str_pad;
55use function str_starts_with;
56use function strip_tags;
57use function strtoupper;
58use function substr_count;
59use function trim;
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    /** @var string The record identifier */
75    protected $xref;
76
77    /** @var Tree  The family tree to which this record belongs */
78    protected $tree;
79
80    /** @var string  GEDCOM data (before any pending edits) */
81    protected $gedcom;
82
83    /** @var string|null  GEDCOM data (after any pending edits) */
84    protected $pending;
85
86    /** @var Fact[] facts extracted from $gedcom/$pending */
87    protected $facts;
88
89    /** @var string[][] All the names of this individual */
90    protected $getAllNames;
91
92    /** @var int|null Cached result */
93    protected $getPrimaryName;
94    /** @var int|null Cached result */
95    protected $getSecondaryName;
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
113        $this->parseFacts();
114    }
115
116    /**
117     * A closure which will create a record from a database row.
118     *
119     * @deprecated since 2.0.4.  Will be removed in 2.1.0 - Use Registry::gedcomRecordFactory()
120     *
121     * @param Tree $tree
122     *
123     * @return Closure
124     */
125    public static function rowMapper(Tree $tree): Closure
126    {
127        return Registry::gedcomRecordFactory()->mapper($tree);
128    }
129
130    /**
131     * A closure which will filter out private records.
132     *
133     * @return Closure
134     */
135    public static function accessFilter(): Closure
136    {
137        return static function (GedcomRecord $record): bool {
138            return $record->canShow();
139        };
140    }
141
142    /**
143     * A closure which will compare records by name.
144     *
145     * @return Closure
146     */
147    public static function nameComparator(): Closure
148    {
149        return static function (GedcomRecord $x, GedcomRecord $y): int {
150            if ($x->canShowName()) {
151                if ($y->canShowName()) {
152                    return I18N::strcasecmp($x->sortName(), $y->sortName());
153                }
154
155                return -1; // only $y is private
156            }
157
158            if ($y->canShowName()) {
159                return 1; // only $x is private
160            }
161
162            return 0; // both $x and $y private
163        };
164    }
165
166    /**
167     * A closure which will compare records by change time.
168     *
169     * @param int $direction +1 to sort ascending, -1 to sort descending
170     *
171     * @return Closure
172     */
173    public static function lastChangeComparator(int $direction = 1): Closure
174    {
175        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
176            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
177        };
178    }
179
180    /**
181     * Get an instance of a GedcomRecord object. For single records,
182     * we just receive the XREF. For bulk records (such as lists
183     * and search results) we can receive the GEDCOM data as well.
184     *
185     * @deprecated since 2.0.4.  Will be removed in 2.1.0 - Use Registry::gedcomRecordFactory()
186     *
187     * @param string      $xref
188     * @param Tree        $tree
189     * @param string|null $gedcom
190     *
191     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|Submitter|null
192     */
193    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
194    {
195        return Registry::gedcomRecordFactory()->make($xref, $tree, $gedcom);
196    }
197
198    /**
199     * Get the GEDCOM tag for this record.
200     *
201     * @return string
202     */
203    public function tag(): string
204    {
205        preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
206
207        return $match[1] ?? static::RECORD_TYPE;
208    }
209
210    /**
211     * Get the XREF for this record
212     *
213     * @return string
214     */
215    public function xref(): string
216    {
217        return $this->xref;
218    }
219
220    /**
221     * Get the tree to which this record belongs
222     *
223     * @return Tree
224     */
225    public function tree(): Tree
226    {
227        return $this->tree;
228    }
229
230    /**
231     * Application code should access data via Fact objects.
232     * This function exists to support old code.
233     *
234     * @return string
235     */
236    public function gedcom(): string
237    {
238        return $this->pending ?? $this->gedcom;
239    }
240
241    /**
242     * Does this record have a pending change?
243     *
244     * @return bool
245     */
246    public function isPendingAddition(): bool
247    {
248        return $this->pending !== null;
249    }
250
251    /**
252     * Does this record have a pending deletion?
253     *
254     * @return bool
255     */
256    public function isPendingDeletion(): bool
257    {
258        return $this->pending === '';
259    }
260
261    /**
262     * Generate a "slug" to use in pretty URLs.
263     *
264     * @return string
265     *
266     * @deprecated since 2.0.18.  Use the slug factory directly.
267     */
268    public function slug(): string
269    {
270        return Registry::slugFactory()->make($this);
271    }
272
273    /**
274     * Generate a URL to this record.
275     *
276     * @return string
277     */
278    public function url(): string
279    {
280        return route(static::ROUTE_NAME, [
281            'xref' => $this->xref(),
282            'tree' => $this->tree->name(),
283            'slug' => Registry::slugFactory()->make($this),
284        ]);
285    }
286
287    /**
288     * Can the details of this record be shown?
289     *
290     * @param int|null $access_level
291     *
292     * @return bool
293     */
294    public function canShow(int $access_level = null): bool
295    {
296        $access_level = $access_level ?? Auth::accessLevel($this->tree);
297
298        // We use this value to bypass privacy checks. For example,
299        // when downloading data or when calculating privacy itself.
300        if ($access_level === Auth::PRIV_HIDE) {
301            return true;
302        }
303
304        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
305
306        return Registry::cache()->array()->remember($cache_key, function () use ($access_level) {
307            return $this->canShowRecord($access_level);
308        });
309    }
310
311    /**
312     * Can the name of this record be shown?
313     *
314     * @param int|null $access_level
315     *
316     * @return bool
317     */
318    public function canShowName(int $access_level = null): bool
319    {
320        return $this->canShow($access_level);
321    }
322
323    /**
324     * Can we edit this record?
325     *
326     * @return bool
327     */
328    public function canEdit(): bool
329    {
330        if ($this->isPendingDeletion()) {
331            return false;
332        }
333
334        if (Auth::isManager($this->tree)) {
335            return true;
336        }
337
338        return Auth::isEditor($this->tree) && !str_contains($this->gedcom, "\n1 RESN locked");
339    }
340
341    /**
342     * Remove private data from the raw gedcom record.
343     * Return both the visible and invisible data. We need the invisible data when editing.
344     *
345     * @param int $access_level
346     *
347     * @return string
348     */
349    public function privatizeGedcom(int $access_level): string
350    {
351        if ($access_level === Auth::PRIV_HIDE) {
352            // We may need the original record, for example when downloading a GEDCOM or clippings cart
353            return $this->gedcom;
354        }
355
356        if ($this->canShow($access_level)) {
357            // The record is not private, but the individual facts may be.
358
359            // Include the entire first line (for NOTE records)
360            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
361
362            // Check each of the facts for access
363            foreach ($this->facts([], false, $access_level) as $fact) {
364                $gedrec .= "\n" . $fact->gedcom();
365            }
366
367            return $gedrec;
368        }
369
370        // We cannot display the details, but we may be able to display
371        // limited data, such as links to other records.
372        return $this->createPrivateGedcomRecord($access_level);
373    }
374
375    /**
376     * Default for "other" object types
377     *
378     * @return void
379     */
380    public function extractNames(): void
381    {
382        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
383    }
384
385    /**
386     * Derived classes should redefine this function, otherwise the object will have no name
387     *
388     * @return array<array<string>>
389     */
390    public function getAllNames(): array
391    {
392        if ($this->getAllNames === null) {
393            $this->getAllNames = [];
394            if ($this->canShowName()) {
395                // Ask the record to extract its names
396                $this->extractNames();
397                // No name found? Use a fallback.
398                if ($this->getAllNames === []) {
399                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
400                }
401            } else {
402                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
403            }
404        }
405
406        return $this->getAllNames;
407    }
408
409    /**
410     * If this object has no name, what do we call it?
411     *
412     * @return string
413     */
414    public function getFallBackName(): string
415    {
416        return e($this->xref());
417    }
418
419    /**
420     * Which of the (possibly several) names of this record is the primary one.
421     *
422     * @return int
423     */
424    public function getPrimaryName(): int
425    {
426        static $language_script;
427
428        if ($language_script === null) {
429            $language_script = $language_script ?? I18N::locale()->script()->code();
430        }
431
432        if ($this->getPrimaryName === null) {
433            // Generally, the first name is the primary one....
434            $this->getPrimaryName = 0;
435            // ...except when the language/name use different character sets
436            foreach ($this->getAllNames() as $n => $name) {
437                if (I18N::textScript($name['sort']) === $language_script) {
438                    $this->getPrimaryName = $n;
439                    break;
440                }
441            }
442        }
443
444        return $this->getPrimaryName;
445    }
446
447    /**
448     * Which of the (possibly several) names of this record is the secondary one.
449     *
450     * @return int
451     */
452    public function getSecondaryName(): int
453    {
454        if ($this->getSecondaryName === null) {
455            // Generally, the primary and secondary names are the same
456            $this->getSecondaryName = $this->getPrimaryName();
457            // ....except when there are names with different character sets
458            $all_names = $this->getAllNames();
459            if (count($all_names) > 1) {
460                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
461                foreach ($all_names as $n => $name) {
462                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
463                        $this->getSecondaryName = $n;
464                        break;
465                    }
466                }
467            }
468        }
469
470        return $this->getSecondaryName;
471    }
472
473    /**
474     * Allow the choice of primary name to be overidden, e.g. in a search result
475     *
476     * @param int|null $n
477     *
478     * @return void
479     */
480    public function setPrimaryName(int $n = null): void
481    {
482        $this->getPrimaryName   = $n;
483        $this->getSecondaryName = null;
484    }
485
486    /**
487     * Allow native PHP functions such as array_unique() to work with objects
488     *
489     * @return string
490     */
491    public function __toString(): string
492    {
493        return $this->xref . '@' . $this->tree->id();
494    }
495
496    /**
497     * /**
498     * Get variants of the name
499     *
500     * @return string
501     */
502    public function fullName(): string
503    {
504        if ($this->canShowName()) {
505            $tmp = $this->getAllNames();
506
507            return $tmp[$this->getPrimaryName()]['full'];
508        }
509
510        return I18N::translate('Private');
511    }
512
513    /**
514     * Get a sortable version of the name. Do not display this!
515     *
516     * @return string
517     */
518    public function sortName(): string
519    {
520        // The sortable name is never displayed, no need to call canShowName()
521        $tmp = $this->getAllNames();
522
523        return $tmp[$this->getPrimaryName()]['sort'];
524    }
525
526    /**
527     * Get the full name in an alternative character set
528     *
529     * @return string|null
530     */
531    public function alternateName(): ?string
532    {
533        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
534            $all_names = $this->getAllNames();
535
536            return $all_names[$this->getSecondaryName()]['full'];
537        }
538
539        return null;
540    }
541
542    /**
543     * Format this object for display in a list
544     *
545     * @return string
546     */
547    public function formatList(): string
548    {
549        $html = '<a href="' . e($this->url()) . '" class="list_item">';
550        $html .= '<b>' . $this->fullName() . '</b>';
551        $html .= $this->formatListDetails();
552        $html .= '</a>';
553
554        return $html;
555    }
556
557    /**
558     * This function should be redefined in derived classes to show any major
559     * identifying characteristics of this record.
560     *
561     * @return string
562     */
563    public function formatListDetails(): string
564    {
565        return '';
566    }
567
568    /**
569     * Extract/format the first fact from a list of facts.
570     *
571     * @param string[] $facts
572     * @param int      $style
573     *
574     * @return string
575     */
576    public function formatFirstMajorFact(array $facts, int $style): string
577    {
578        foreach ($this->facts($facts, true) as $event) {
579            // Only display if it has a date or place (or both)
580            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
581                $joiner = ' — ';
582            } else {
583                $joiner = '';
584            }
585            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
586                switch ($style) {
587                    case 1:
588                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
589                    case 2:
590                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
591                }
592            }
593        }
594
595        return '';
596    }
597
598    /**
599     * Find individuals linked to this record.
600     *
601     * @param string $link
602     *
603     * @return Collection<Individual>
604     */
605    public function linkedIndividuals(string $link): Collection
606    {
607        return DB::table('individuals')
608            ->join('link', static function (JoinClause $join): void {
609                $join
610                    ->on('l_file', '=', 'i_file')
611                    ->on('l_from', '=', 'i_id');
612            })
613            ->where('i_file', '=', $this->tree->id())
614            ->where('l_type', '=', $link)
615            ->where('l_to', '=', $this->xref)
616            ->select(['individuals.*'])
617            ->get()
618            ->map(Registry::individualFactory()->mapper($this->tree))
619            ->filter(self::accessFilter());
620    }
621
622    /**
623     * Find families linked to this record.
624     *
625     * @param string $link
626     *
627     * @return Collection<Family>
628     */
629    public function linkedFamilies(string $link): Collection
630    {
631        return DB::table('families')
632            ->join('link', static function (JoinClause $join): void {
633                $join
634                    ->on('l_file', '=', 'f_file')
635                    ->on('l_from', '=', 'f_id');
636            })
637            ->where('f_file', '=', $this->tree->id())
638            ->where('l_type', '=', $link)
639            ->where('l_to', '=', $this->xref)
640            ->select(['families.*'])
641            ->get()
642            ->map(Registry::familyFactory()->mapper($this->tree))
643            ->filter(self::accessFilter());
644    }
645
646    /**
647     * Find sources linked to this record.
648     *
649     * @param string $link
650     *
651     * @return Collection<Source>
652     */
653    public function linkedSources(string $link): Collection
654    {
655        return DB::table('sources')
656            ->join('link', static function (JoinClause $join): void {
657                $join
658                    ->on('l_file', '=', 's_file')
659                    ->on('l_from', '=', 's_id');
660            })
661            ->where('s_file', '=', $this->tree->id())
662            ->where('l_type', '=', $link)
663            ->where('l_to', '=', $this->xref)
664            ->select(['sources.*'])
665            ->get()
666            ->map(Registry::sourceFactory()->mapper($this->tree))
667            ->filter(self::accessFilter());
668    }
669
670    /**
671     * Find media objects linked to this record.
672     *
673     * @param string $link
674     *
675     * @return Collection<Media>
676     */
677    public function linkedMedia(string $link): Collection
678    {
679        return DB::table('media')
680            ->join('link', static function (JoinClause $join): void {
681                $join
682                    ->on('l_file', '=', 'm_file')
683                    ->on('l_from', '=', 'm_id');
684            })
685            ->where('m_file', '=', $this->tree->id())
686            ->where('l_type', '=', $link)
687            ->where('l_to', '=', $this->xref)
688            ->select(['media.*'])
689            ->get()
690            ->map(Registry::mediaFactory()->mapper($this->tree))
691            ->filter(self::accessFilter());
692    }
693
694    /**
695     * Find notes linked to this record.
696     *
697     * @param string $link
698     *
699     * @return Collection<Note>
700     */
701    public function linkedNotes(string $link): Collection
702    {
703        return DB::table('other')
704            ->join('link', static function (JoinClause $join): void {
705                $join
706                    ->on('l_file', '=', 'o_file')
707                    ->on('l_from', '=', 'o_id');
708            })
709            ->where('o_file', '=', $this->tree->id())
710            ->where('o_type', '=', Note::RECORD_TYPE)
711            ->where('l_type', '=', $link)
712            ->where('l_to', '=', $this->xref)
713            ->select(['other.*'])
714            ->get()
715            ->map(Registry::noteFactory()->mapper($this->tree))
716            ->filter(self::accessFilter());
717    }
718
719    /**
720     * Find repositories linked to this record.
721     *
722     * @param string $link
723     *
724     * @return Collection<Repository>
725     */
726    public function linkedRepositories(string $link): Collection
727    {
728        return DB::table('other')
729            ->join('link', static function (JoinClause $join): void {
730                $join
731                    ->on('l_file', '=', 'o_file')
732                    ->on('l_from', '=', 'o_id');
733            })
734            ->where('o_file', '=', $this->tree->id())
735            ->where('o_type', '=', Repository::RECORD_TYPE)
736            ->where('l_type', '=', $link)
737            ->where('l_to', '=', $this->xref)
738            ->select(['other.*'])
739            ->get()
740            ->map(Registry::repositoryFactory()->mapper($this->tree))
741            ->filter(self::accessFilter());
742    }
743
744    /**
745     * Find locations linked to this record.
746     *
747     * @param string $link
748     *
749     * @return Collection<Location>
750     */
751    public function linkedLocations(string $link): Collection
752    {
753        return DB::table('other')
754            ->join('link', static function (JoinClause $join): void {
755                $join
756                    ->on('l_file', '=', 'o_file')
757                    ->on('l_from', '=', 'o_id');
758            })
759            ->where('o_file', '=', $this->tree->id())
760            ->where('o_type', '=', Location::RECORD_TYPE)
761            ->where('l_type', '=', $link)
762            ->where('l_to', '=', $this->xref)
763            ->select(['other.*'])
764            ->get()
765            ->map(Registry::locationFactory()->mapper($this->tree))
766            ->filter(self::accessFilter());
767    }
768
769    /**
770     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
771     * This is used to display multiple events on the individual/family lists.
772     * Multiple events can exist because of uncertainty in dates, dates in different
773     * calendars, place-names in both latin and hebrew character sets, etc.
774     * It also allows us to combine dates/places from different events in the summaries.
775     *
776     * @param string[] $events
777     *
778     * @return Date[]
779     */
780    public function getAllEventDates(array $events): array
781    {
782        $dates = [];
783        foreach ($this->facts($events, false, null, true) as $event) {
784            if ($event->date()->isOK()) {
785                $dates[] = $event->date();
786            }
787        }
788
789        return $dates;
790    }
791
792    /**
793     * Get all the places for a particular type of event
794     *
795     * @param string[] $events
796     *
797     * @return Place[]
798     */
799    public function getAllEventPlaces(array $events): array
800    {
801        $places = [];
802        foreach ($this->facts($events) as $event) {
803            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
804                foreach ($ged_places[1] as $ged_place) {
805                    $places[] = new Place($ged_place, $this->tree);
806                }
807            }
808        }
809
810        return $places;
811    }
812
813    /**
814     * The facts and events for this record.
815     *
816     * @param string[] $filter
817     * @param bool     $sort
818     * @param int|null $access_level
819     * @param bool     $ignore_deleted
820     *
821     * @return Collection<Fact>
822     */
823    public function facts(
824        array $filter = [],
825        bool $sort = false,
826        int $access_level = null,
827        bool $ignore_deleted = false
828    ): Collection {
829        $access_level = $access_level ?? Auth::accessLevel($this->tree);
830
831        $facts = new Collection();
832        if ($this->canShow($access_level)) {
833            foreach ($this->facts as $fact) {
834                if (($filter === [] || in_array($fact->getTag(), $filter, true)) && $fact->canShow($access_level)) {
835                    $facts->push($fact);
836                }
837            }
838        }
839
840        if ($sort) {
841            $facts = Fact::sortFacts($facts);
842        }
843
844        if ($ignore_deleted) {
845            $facts = $facts->filter(static function (Fact $fact): bool {
846                return !$fact->isPendingDeletion();
847            });
848        }
849
850        return new Collection($facts);
851    }
852
853    /**
854     * Get the last-change timestamp for this record
855     *
856     * @return Carbon
857     */
858    public function lastChangeTimestamp(): Carbon
859    {
860        /** @var Fact|null $chan */
861        $chan = $this->facts(['CHAN'])->first();
862
863        if ($chan instanceof Fact) {
864            // The record does have a CHAN event
865            $d = $chan->date()->minimumDate();
866
867            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
868                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
869            }
870
871            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
872                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
873            }
874
875            return Carbon::create($d->year(), $d->month(), $d->day());
876        }
877
878        // The record does not have a CHAN event
879        return Carbon::createFromTimestamp(0);
880    }
881
882    /**
883     * Get the last-change user for this record
884     *
885     * @return string
886     */
887    public function lastChangeUser(): string
888    {
889        $chan = $this->facts(['CHAN'])->first();
890
891        if ($chan === null) {
892            return I18N::translate('Unknown');
893        }
894
895        $chan_user = $chan->attribute('_WT_USER');
896        if ($chan_user === '') {
897            return I18N::translate('Unknown');
898        }
899
900        return $chan_user;
901    }
902
903    /**
904     * Add a new fact to this record
905     *
906     * @param string $gedcom
907     * @param bool   $update_chan
908     *
909     * @return void
910     */
911    public function createFact(string $gedcom, bool $update_chan): void
912    {
913        $this->updateFact('', $gedcom, $update_chan);
914    }
915
916    /**
917     * Delete a fact from this record
918     *
919     * @param string $fact_id
920     * @param bool   $update_chan
921     *
922     * @return void
923     */
924    public function deleteFact(string $fact_id, bool $update_chan): void
925    {
926        $this->updateFact($fact_id, '', $update_chan);
927    }
928
929    /**
930     * Replace a fact with a new gedcom data.
931     *
932     * @param string $fact_id
933     * @param string $gedcom
934     * @param bool   $update_chan
935     *
936     * @return void
937     * @throws Exception
938     */
939    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
940    {
941        // Not all record types allow a CHAN event.
942        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
943
944        // MSDOS line endings will break things in horrible ways
945        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
946        $gedcom = trim($gedcom);
947
948        if ($this->pending === '') {
949            throw new Exception('Cannot edit a deleted record');
950        }
951        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
952            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
953        }
954
955        if ($this->pending) {
956            $old_gedcom = $this->pending;
957        } else {
958            $old_gedcom = $this->gedcom;
959        }
960
961        // First line of record may contain data - e.g. NOTE records.
962        [$new_gedcom] = explode("\n", $old_gedcom, 2);
963
964        // Replacing (or deleting) an existing fact
965        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
966            if ($fact->id() === $fact_id) {
967                if ($gedcom !== '') {
968                    $new_gedcom .= "\n" . $gedcom;
969                }
970                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
971            } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) {
972                $new_gedcom .= "\n" . $fact->gedcom();
973            }
974        }
975
976        // Adding a new fact
977        if ($fact_id === '') {
978            $new_gedcom .= "\n" . $gedcom;
979        }
980
981        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
982            $today = strtoupper(date('d M Y'));
983            $now   = date('H:i:s');
984            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
985        }
986
987        if ($new_gedcom !== $old_gedcom) {
988            // Save the changes
989            DB::table('change')->insert([
990                'gedcom_id'  => $this->tree->id(),
991                'xref'       => $this->xref,
992                'old_gedcom' => $old_gedcom,
993                'new_gedcom' => $new_gedcom,
994                'user_id'    => Auth::id(),
995            ]);
996
997            $this->pending = $new_gedcom;
998
999            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1000                app(PendingChangesService::class)->acceptRecord($this);
1001                $this->gedcom  = $new_gedcom;
1002                $this->pending = null;
1003            }
1004        }
1005        $this->parseFacts();
1006    }
1007
1008    /**
1009     * Update this record
1010     *
1011     * @param string $gedcom
1012     * @param bool   $update_chan
1013     *
1014     * @return void
1015     */
1016    public function updateRecord(string $gedcom, bool $update_chan): void
1017    {
1018        // Not all record types allow a CHAN event.
1019        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
1020
1021        // MSDOS line endings will break things in horrible ways
1022        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1023        $gedcom = trim($gedcom);
1024
1025        // Update the CHAN record
1026        if ($update_chan) {
1027            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1028            $today = strtoupper(date('d M Y'));
1029            $now   = date('H:i:s');
1030            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
1031        }
1032
1033        // Create a pending change
1034        DB::table('change')->insert([
1035            'gedcom_id'  => $this->tree->id(),
1036            'xref'       => $this->xref,
1037            'old_gedcom' => $this->gedcom(),
1038            'new_gedcom' => $gedcom,
1039            'user_id'    => Auth::id(),
1040        ]);
1041
1042        // Clear the cache
1043        $this->pending = $gedcom;
1044
1045        // Accept this pending change
1046        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1047            app(PendingChangesService::class)->acceptRecord($this);
1048            $this->gedcom  = $gedcom;
1049            $this->pending = null;
1050        }
1051
1052        $this->parseFacts();
1053
1054        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1055    }
1056
1057    /**
1058     * Delete this record
1059     *
1060     * @return void
1061     */
1062    public function deleteRecord(): void
1063    {
1064        // Create a pending change
1065        if (!$this->isPendingDeletion()) {
1066            DB::table('change')->insert([
1067                'gedcom_id'  => $this->tree->id(),
1068                'xref'       => $this->xref,
1069                'old_gedcom' => $this->gedcom(),
1070                'new_gedcom' => '',
1071                'user_id'    => Auth::id(),
1072            ]);
1073        }
1074
1075        // Auto-accept this pending change
1076        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1077            app(PendingChangesService::class)->acceptRecord($this);
1078        }
1079
1080        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1081    }
1082
1083    /**
1084     * Remove all links from this record to $xref
1085     *
1086     * @param string $xref
1087     * @param bool   $update_chan
1088     *
1089     * @return void
1090     */
1091    public function removeLinks(string $xref, bool $update_chan): void
1092    {
1093        $value = '@' . $xref . '@';
1094
1095        foreach ($this->facts() as $fact) {
1096            if ($fact->value() === $value) {
1097                $this->deleteFact($fact->id(), $update_chan);
1098            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1099                $gedcom = $fact->gedcom();
1100                foreach ($matches as $match) {
1101                    $next_level  = $match[1] + 1;
1102                    $next_levels = '[' . $next_level . '-9]';
1103                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1104                }
1105                $this->updateFact($fact->id(), $gedcom, $update_chan);
1106            }
1107        }
1108    }
1109
1110    /**
1111     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1112     * also delete all links to it.
1113     *
1114     * @return GedcomRecord[]
1115     */
1116    public function linkingRecords(): array
1117    {
1118        $like = addcslashes($this->xref(), '\\%_');
1119
1120        $union = DB::table('change')
1121            ->where('gedcom_id', '=', $this->tree()->id())
1122            ->where('new_gedcom', 'LIKE', '%@' . $like . '@%')
1123            ->where('new_gedcom', 'NOT LIKE', '0 @' . $like . '@%')
1124            ->whereIn('change_id', function (Builder $query): void {
1125                $query->select(new Expression('MAX(change_id)'))
1126                    ->from('change')
1127                    ->where('gedcom_id', '=', $this->tree->id())
1128                    ->where('status', '=', 'pending')
1129                    ->groupBy(['xref']);
1130            })
1131            ->select(['xref']);
1132
1133        $xrefs = DB::table('link')
1134            ->where('l_file', '=', $this->tree()->id())
1135            ->where('l_to', '=', $this->xref())
1136            ->select(['l_from'])
1137            ->union($union)
1138            ->pluck('l_from');
1139
1140        return $xrefs->map(function (string $xref): GedcomRecord {
1141            $record = Registry::gedcomRecordFactory()->make($xref, $this->tree);
1142            assert($record instanceof GedcomRecord);
1143
1144            return $record;
1145        })->all();
1146    }
1147
1148    /**
1149     * Each object type may have its own special rules, and re-implement this function.
1150     *
1151     * @param int $access_level
1152     *
1153     * @return bool
1154     */
1155    protected function canShowByType(int $access_level): bool
1156    {
1157        $fact_privacy = $this->tree->getFactPrivacy();
1158
1159        if (isset($fact_privacy[static::RECORD_TYPE])) {
1160            // Restriction found
1161            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
1162        }
1163
1164        // No restriction found - must be public:
1165        return true;
1166    }
1167
1168    /**
1169     * Generate a private version of this record
1170     *
1171     * @param int $access_level
1172     *
1173     * @return string
1174     */
1175    protected function createPrivateGedcomRecord(int $access_level): string
1176    {
1177        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
1178    }
1179
1180    /**
1181     * Convert a name record into sortable and full/display versions. This default
1182     * should be OK for simple record types. INDI/FAM records will need to redefine it.
1183     *
1184     * @param string $type
1185     * @param string $value
1186     * @param string $gedcom
1187     *
1188     * @return void
1189     */
1190    protected function addName(string $type, string $value, string $gedcom): void
1191    {
1192        $this->getAllNames[] = [
1193            'type'   => $type,
1194            'sort'   => preg_replace_callback('/([0-9]+)/', static function (array $matches): string {
1195                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
1196            }, $value),
1197            'full'   => '<span dir="auto">' . e($value) . '</span>',
1198            // This is used for display
1199            'fullNN' => $value,
1200            // This goes into the database
1201        ];
1202    }
1203
1204    /**
1205     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
1206     * Records without a name (e.g. FAM) will need to redefine this function.
1207     * Parameters: the level 1 fact containing the name.
1208     * Return value: an array of name structures, each containing
1209     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
1210     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
1211     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
1212     *
1213     * @param int              $level
1214     * @param string           $fact_type
1215     * @param Collection<Fact> $facts
1216     *
1217     * @return void
1218     */
1219    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
1220    {
1221        $sublevel    = $level + 1;
1222        $subsublevel = $sublevel + 1;
1223        foreach ($facts as $fact) {
1224            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1225                foreach ($matches as $match) {
1226                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1227                    if ($match[1] === 'NAME' && str_contains($match[3], "\n2 TYPE married")) {
1228                        $this->addName('_MARNM', $match[2], $fact->gedcom());
1229                    } else {
1230                        $this->addName($match[1], $match[2], $fact->gedcom());
1231                    }
1232                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
1233                        foreach ($submatches as $submatch) {
1234                            $this->addName($submatch[1], $submatch[2], $match[3]);
1235                        }
1236                    }
1237                }
1238            }
1239        }
1240    }
1241
1242    /**
1243     * Split the record into facts
1244     *
1245     * @return void
1246     */
1247    private function parseFacts(): void
1248    {
1249        // Split the record into facts
1250        if ($this->gedcom) {
1251            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
1252            array_shift($gedcom_facts);
1253        } else {
1254            $gedcom_facts = [];
1255        }
1256        if ($this->pending) {
1257            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
1258            array_shift($pending_facts);
1259        } else {
1260            $pending_facts = [];
1261        }
1262
1263        $this->facts = [];
1264
1265        foreach ($gedcom_facts as $gedcom_fact) {
1266            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
1267            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
1268                $fact->setPendingDeletion();
1269            }
1270            $this->facts[] = $fact;
1271        }
1272        foreach ($pending_facts as $pending_fact) {
1273            if (!in_array($pending_fact, $gedcom_facts, true)) {
1274                $fact = new Fact($pending_fact, $this, md5($pending_fact));
1275                $fact->setPendingAddition();
1276                $this->facts[] = $fact;
1277            }
1278        }
1279    }
1280
1281    /**
1282     * Work out whether this record can be shown to a user with a given access level
1283     *
1284     * @param int $access_level
1285     *
1286     * @return bool
1287     */
1288    private function canShowRecord(int $access_level): bool
1289    {
1290        // This setting would better be called "$ENABLE_PRIVACY"
1291        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
1292            return true;
1293        }
1294
1295        // We should always be able to see our own record (unless an admin is applying download restrictions)
1296        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
1297            return true;
1298        }
1299
1300        // Does this record have a RESN?
1301        if (str_contains($this->gedcom, "\n1 RESN confidential")) {
1302            return Auth::PRIV_NONE >= $access_level;
1303        }
1304        if (str_contains($this->gedcom, "\n1 RESN privacy")) {
1305            return Auth::PRIV_USER >= $access_level;
1306        }
1307        if (str_contains($this->gedcom, "\n1 RESN none")) {
1308            return true;
1309        }
1310
1311        // Does this record have a default RESN?
1312        $individual_privacy = $this->tree->getIndividualPrivacy();
1313        if (isset($individual_privacy[$this->xref()])) {
1314            return $individual_privacy[$this->xref()] >= $access_level;
1315        }
1316
1317        // Privacy rules do not apply to admins
1318        if (Auth::PRIV_NONE >= $access_level) {
1319            return true;
1320        }
1321
1322        // Different types of record have different privacy rules
1323        return $this->canShowByType($access_level);
1324    }
1325
1326    /**
1327     * Lock the database row, to prevent concurrent edits.
1328     */
1329    public function lock(): void
1330    {
1331        DB::table('other')
1332            ->where('o_file', '=', $this->tree->id())
1333            ->where('o_id', '=', $this->xref())
1334            ->lockForUpdate()
1335            ->get();
1336    }
1337
1338    /**
1339     * Add blank lines, to allow a user to add/edit new values.
1340     *
1341     * @return string
1342     */
1343    public function insertMissingSubtags(): string
1344    {
1345        $gedcom = $this->insertMissingLevels($this->tag(), $this->gedcom());
1346
1347        return preg_replace('/^0.*\n/', '', $gedcom);
1348    }
1349
1350    /**
1351     * @param string $tag
1352     * @param string $gedcom
1353     *
1354     * @return string
1355     */
1356    protected function insertMissingLevels(string $tag, string $gedcom): string
1357    {
1358        $next_level = substr_count($tag, ':') + 1;
1359        $factory    = Registry::elementFactory();
1360        $subtags    = $factory->make($tag)->subtags();
1361
1362        // The first part is level N (includes CONT records).  The remainder are level N+1.
1363        $parts  = preg_split('/\n(?=' . $next_level . ')/', $gedcom);
1364        $return = array_shift($parts);
1365
1366        foreach ($subtags as $subtag => $occurrences) {
1367            [$min, $max] = explode(':', $occurrences);
1368            if ($max === 'M') {
1369                $max = PHP_INT_MAX;
1370            } else {
1371                $max = (int) $max;
1372            }
1373
1374            $count = 0;
1375
1376            // Add expected subtags in our preferred order.
1377            foreach ($parts as $n => $part) {
1378                if (str_starts_with($part, $next_level . ' ' . $subtag)) {
1379                    $return .= "\n" . $this->insertMissingLevels($tag . ':' . $subtag, $part);
1380                    $count++;
1381                    unset($parts[$n]);
1382                }
1383            }
1384
1385            // Allowed to have more of this subtag?
1386            if ($count < $max) {
1387                // Create a new one.
1388                $gedcom  = $next_level . ' ' . $subtag;
1389                $default = $factory->make($tag . ':' . $subtag)->default($this->tree);
1390                if ($default !== '') {
1391                    $gedcom .= ' ' . $default;
1392                }
1393                $return .= "\n" . $this->insertMissingLevels($tag . ':' . $subtag, $gedcom);
1394            }
1395        }
1396
1397        // Now add any unexpected/existing data.
1398        if ($parts !== []) {
1399            $return .= "\n" . implode("\n", $parts);
1400        }
1401
1402        return $return;
1403    }
1404}
1405