xref: /webtrees/app/GedcomRecord.php (revision f9e38ab10cf9c38408ac1038c5fad82fea00955d)
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;
33
34use function addcslashes;
35use function app;
36use function array_shift;
37use function assert;
38use function count;
39use function date;
40use function e;
41use function explode;
42use function implode;
43use function in_array;
44use function max;
45use function md5;
46use function preg_match;
47use function preg_match_all;
48use function preg_replace;
49use function preg_replace_callback;
50use function preg_split;
51use function route;
52use function str_contains;
53use function str_pad;
54use function str_starts_with;
55use function strtoupper;
56use function substr_count;
57use function trim;
58
59use const PHP_INT_MAX;
60use const PREG_SET_ORDER;
61use const STR_PAD_LEFT;
62
63/**
64 * A GEDCOM object.
65 */
66class GedcomRecord
67{
68    public const RECORD_TYPE = 'UNKNOWN';
69
70    protected const ROUTE_NAME = GedcomRecordPage::class;
71
72    /** @var string The record identifier */
73    protected $xref;
74
75    /** @var Tree  The family tree to which this record belongs */
76    protected $tree;
77
78    /** @var string  GEDCOM data (before any pending edits) */
79    protected $gedcom;
80
81    /** @var string|null  GEDCOM data (after any pending edits) */
82    protected $pending;
83
84    /** @var Fact[] facts extracted from $gedcom/$pending */
85    protected $facts;
86
87    /** @var string[][] All the names of this individual */
88    protected $getAllNames;
89
90    /** @var int|null Cached result */
91    protected $getPrimaryName;
92    /** @var int|null Cached result */
93    protected $getSecondaryName;
94
95    /**
96     * Create a GedcomRecord object from raw GEDCOM data.
97     *
98     * @param string      $xref
99     * @param string      $gedcom  an empty string for new/pending records
100     * @param string|null $pending null for a record with no pending edits,
101     *                             empty string for records with pending deletions
102     * @param Tree        $tree
103     */
104    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
105    {
106        $this->xref    = $xref;
107        $this->gedcom  = $gedcom;
108        $this->pending = $pending;
109        $this->tree    = $tree;
110
111        $this->parseFacts();
112    }
113
114    /**
115     * A closure which will filter out private records.
116     *
117     * @return Closure
118     */
119    public static function accessFilter(): Closure
120    {
121        return static function (GedcomRecord $record): bool {
122            return $record->canShow();
123        };
124    }
125
126    /**
127     * A closure which will compare records by name.
128     *
129     * @return Closure
130     */
131    public static function nameComparator(): Closure
132    {
133        return static function (GedcomRecord $x, GedcomRecord $y): int {
134            if ($x->canShowName()) {
135                if ($y->canShowName()) {
136                    return I18N::comparator()($x->sortName(), $y->sortName());
137                }
138
139                return -1; // only $y is private
140            }
141
142            if ($y->canShowName()) {
143                return 1; // only $x is private
144            }
145
146            return 0; // both $x and $y private
147        };
148    }
149
150    /**
151     * A closure which will compare records by change time.
152     *
153     * @param int $direction +1 to sort ascending, -1 to sort descending
154     *
155     * @return Closure
156     */
157    public static function lastChangeComparator(int $direction = 1): Closure
158    {
159        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
160            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
161        };
162    }
163
164    /**
165     * Get the GEDCOM tag for this record.
166     *
167     * @return string
168     */
169    public function tag(): string
170    {
171        preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
172
173        return $match[1] ?? static::RECORD_TYPE;
174    }
175
176    /**
177     * Get the XREF for this record
178     *
179     * @return string
180     */
181    public function xref(): string
182    {
183        return $this->xref;
184    }
185
186    /**
187     * Get the tree to which this record belongs
188     *
189     * @return Tree
190     */
191    public function tree(): Tree
192    {
193        return $this->tree;
194    }
195
196    /**
197     * Application code should access data via Fact objects.
198     * This function exists to support old code.
199     *
200     * @return string
201     */
202    public function gedcom(): string
203    {
204        return $this->pending ?? $this->gedcom;
205    }
206
207    /**
208     * Does this record have a pending change?
209     *
210     * @return bool
211     */
212    public function isPendingAddition(): bool
213    {
214        return $this->pending !== null;
215    }
216
217    /**
218     * Does this record have a pending deletion?
219     *
220     * @return bool
221     */
222    public function isPendingDeletion(): bool
223    {
224        return $this->pending === '';
225    }
226
227    /**
228     * Generate a URL to this record.
229     *
230     * @return string
231     */
232    public function url(): string
233    {
234        return route(static::ROUTE_NAME, [
235            'xref' => $this->xref(),
236            'tree' => $this->tree->name(),
237            'slug' => Registry::slugFactory()->make($this),
238        ]);
239    }
240
241    /**
242     * Can the details of this record be shown?
243     *
244     * @param int|null $access_level
245     *
246     * @return bool
247     */
248    public function canShow(int $access_level = null): bool
249    {
250        $access_level = $access_level ?? Auth::accessLevel($this->tree);
251
252        // We use this value to bypass privacy checks. For example,
253        // when downloading data or when calculating privacy itself.
254        if ($access_level === Auth::PRIV_HIDE) {
255            return true;
256        }
257
258        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
259
260        return Registry::cache()->array()->remember($cache_key, function () use ($access_level) {
261            return $this->canShowRecord($access_level);
262        });
263    }
264
265    /**
266     * Can the name of this record be shown?
267     *
268     * @param int|null $access_level
269     *
270     * @return bool
271     */
272    public function canShowName(int $access_level = null): bool
273    {
274        return $this->canShow($access_level);
275    }
276
277    /**
278     * Can we edit this record?
279     *
280     * @return bool
281     */
282    public function canEdit(): bool
283    {
284        if ($this->isPendingDeletion()) {
285            return false;
286        }
287
288        if (Auth::isManager($this->tree)) {
289            return true;
290        }
291
292        return Auth::isEditor($this->tree) && !str_contains($this->gedcom, "\n1 RESN locked");
293    }
294
295    /**
296     * Remove private data from the raw gedcom record.
297     * Return both the visible and invisible data. We need the invisible data when editing.
298     *
299     * @param int $access_level
300     *
301     * @return string
302     */
303    public function privatizeGedcom(int $access_level): string
304    {
305        if ($access_level === Auth::PRIV_HIDE) {
306            // We may need the original record, for example when downloading a GEDCOM or clippings cart
307            return $this->gedcom;
308        }
309
310        if ($this->canShow($access_level)) {
311            // The record is not private, but the individual facts may be.
312
313            // Include the entire first line (for NOTE records)
314            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
315
316            // Check each of the facts for access
317            foreach ($this->facts([], false, $access_level) as $fact) {
318                $gedrec .= "\n" . $fact->gedcom();
319            }
320
321            return $gedrec;
322        }
323
324        // We cannot display the details, but we may be able to display
325        // limited data, such as links to other records.
326        return $this->createPrivateGedcomRecord($access_level);
327    }
328
329    /**
330     * Default for "other" object types
331     *
332     * @return void
333     */
334    public function extractNames(): void
335    {
336        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
337    }
338
339    /**
340     * Derived classes should redefine this function, otherwise the object will have no name
341     *
342     * @return array<int,array<string,string>>
343     */
344    public function getAllNames(): array
345    {
346        if ($this->getAllNames === null) {
347            $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 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() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
541                    case 2:
542                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</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<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<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<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<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<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<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<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 string[] $events
729     *
730     * @return 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 string[] $events
748     *
749     * @return 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 string[] $filter
769     * @param bool     $sort
770     * @param int|null $access_level
771     * @param bool     $ignore_deleted
772     *
773     * @return Collection<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        $facts = new Collection();
784        if ($this->canShow($access_level)) {
785            foreach ($this->facts as $fact) {
786                if (($filter === [] || in_array($fact->getTag(), $filter, true)) && $fact->canShow($access_level)) {
787                    $facts->push($fact);
788                }
789            }
790        }
791
792        if ($sort) {
793            $facts = Fact::sortFacts($facts);
794        }
795
796        if ($ignore_deleted) {
797            $facts = $facts->filter(static function (Fact $fact): bool {
798                return !$fact->isPendingDeletion();
799            });
800        }
801
802        return new Collection($facts);
803    }
804
805    /**
806     * Get the last-change timestamp for this record
807     *
808     * @return Carbon
809     */
810    public function lastChangeTimestamp(): Carbon
811    {
812        /** @var Fact|null $chan */
813        $chan = $this->facts(['CHAN'])->first();
814
815        if ($chan instanceof Fact) {
816            // The record does have a CHAN event
817            $d = $chan->date()->minimumDate();
818
819            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
820                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
821            }
822
823            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
824                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
825            }
826
827            return Carbon::create($d->year(), $d->month(), $d->day());
828        }
829
830        // The record does not have a CHAN event
831        return Carbon::createFromTimestamp(0);
832    }
833
834    /**
835     * Get the last-change user for this record
836     *
837     * @return string
838     */
839    public function lastChangeUser(): string
840    {
841        $chan = $this->facts(['CHAN'])->first();
842
843        if ($chan === null) {
844            return I18N::translate('Unknown');
845        }
846
847        $chan_user = $chan->attribute('_WT_USER');
848        if ($chan_user === '') {
849            return I18N::translate('Unknown');
850        }
851
852        return $chan_user;
853    }
854
855    /**
856     * Add a new fact to this record
857     *
858     * @param string $gedcom
859     * @param bool   $update_chan
860     *
861     * @return void
862     */
863    public function createFact(string $gedcom, bool $update_chan): void
864    {
865        $this->updateFact('', $gedcom, $update_chan);
866    }
867
868    /**
869     * Delete a fact from this record
870     *
871     * @param string $fact_id
872     * @param bool   $update_chan
873     *
874     * @return void
875     */
876    public function deleteFact(string $fact_id, bool $update_chan): void
877    {
878        $this->updateFact($fact_id, '', $update_chan);
879    }
880
881    /**
882     * Replace a fact with a new gedcom data.
883     *
884     * @param string $fact_id
885     * @param string $gedcom
886     * @param bool   $update_chan
887     *
888     * @return void
889     * @throws Exception
890     */
891    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
892    {
893        // Not all record types allow a CHAN event.
894        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
895
896        // MSDOS line endings will break things in horrible ways
897        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
898        $gedcom = trim($gedcom);
899
900        if ($this->pending === '') {
901            throw new Exception('Cannot edit a deleted record');
902        }
903        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
904            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
905        }
906
907        if ($this->pending) {
908            $old_gedcom = $this->pending;
909        } else {
910            $old_gedcom = $this->gedcom;
911        }
912
913        // First line of record may contain data - e.g. NOTE records.
914        [$new_gedcom] = explode("\n", $old_gedcom, 2);
915
916        // Replacing (or deleting) an existing fact
917        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
918            if ($fact->id() === $fact_id) {
919                if ($gedcom !== '') {
920                    $new_gedcom .= "\n" . $gedcom;
921                }
922                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
923            } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) {
924                $new_gedcom .= "\n" . $fact->gedcom();
925            }
926        }
927
928        // Adding a new fact
929        if ($fact_id === '') {
930            $new_gedcom .= "\n" . $gedcom;
931        }
932
933        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
934            $today = strtoupper(date('d M Y'));
935            $now   = date('H:i:s');
936            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
937        }
938
939        if ($new_gedcom !== $old_gedcom) {
940            // Save the changes
941            DB::table('change')->insert([
942                'gedcom_id'  => $this->tree->id(),
943                'xref'       => $this->xref,
944                'old_gedcom' => $old_gedcom,
945                'new_gedcom' => $new_gedcom,
946                'user_id'    => Auth::id(),
947            ]);
948
949            $this->pending = $new_gedcom;
950
951            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
952                app(PendingChangesService::class)->acceptRecord($this);
953                $this->gedcom  = $new_gedcom;
954                $this->pending = null;
955            }
956        }
957        $this->parseFacts();
958    }
959
960    /**
961     * Update this record
962     *
963     * @param string $gedcom
964     * @param bool   $update_chan
965     *
966     * @return void
967     */
968    public function updateRecord(string $gedcom, bool $update_chan): void
969    {
970        // Not all record types allow a CHAN event.
971        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
972
973        // MSDOS line endings will break things in horrible ways
974        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
975        $gedcom = trim($gedcom);
976
977        // Update the CHAN record
978        if ($update_chan) {
979            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
980            $today = strtoupper(date('d M Y'));
981            $now   = date('H:i:s');
982            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
983        }
984
985        // Create a pending change
986        DB::table('change')->insert([
987            'gedcom_id'  => $this->tree->id(),
988            'xref'       => $this->xref,
989            'old_gedcom' => $this->gedcom(),
990            'new_gedcom' => $gedcom,
991            'user_id'    => Auth::id(),
992        ]);
993
994        // Clear the cache
995        $this->pending = $gedcom;
996
997        // Accept this pending change
998        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
999            app(PendingChangesService::class)->acceptRecord($this);
1000            $this->gedcom  = $gedcom;
1001            $this->pending = null;
1002        }
1003
1004        $this->parseFacts();
1005
1006        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1007    }
1008
1009    /**
1010     * Delete this record
1011     *
1012     * @return void
1013     */
1014    public function deleteRecord(): void
1015    {
1016        // Create a pending change
1017        if (!$this->isPendingDeletion()) {
1018            DB::table('change')->insert([
1019                'gedcom_id'  => $this->tree->id(),
1020                'xref'       => $this->xref,
1021                'old_gedcom' => $this->gedcom(),
1022                'new_gedcom' => '',
1023                'user_id'    => Auth::id(),
1024            ]);
1025        }
1026
1027        // Auto-accept this pending change
1028        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1029            app(PendingChangesService::class)->acceptRecord($this);
1030        }
1031
1032        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1033    }
1034
1035    /**
1036     * Remove all links from this record to $xref
1037     *
1038     * @param string $xref
1039     * @param bool   $update_chan
1040     *
1041     * @return void
1042     */
1043    public function removeLinks(string $xref, bool $update_chan): void
1044    {
1045        $value = '@' . $xref . '@';
1046
1047        foreach ($this->facts() as $fact) {
1048            if ($fact->value() === $value) {
1049                $this->deleteFact($fact->id(), $update_chan);
1050            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1051                $gedcom = $fact->gedcom();
1052                foreach ($matches as $match) {
1053                    $next_level  = $match[1] + 1;
1054                    $next_levels = '[' . $next_level . '-9]';
1055                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1056                }
1057                $this->updateFact($fact->id(), $gedcom, $update_chan);
1058            }
1059        }
1060    }
1061
1062    /**
1063     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1064     * also delete all links to it.
1065     *
1066     * @return GedcomRecord[]
1067     */
1068    public function linkingRecords(): array
1069    {
1070        $like = addcslashes($this->xref(), '\\%_');
1071
1072        $union = DB::table('change')
1073            ->where('gedcom_id', '=', $this->tree()->id())
1074            ->where('new_gedcom', 'LIKE', '%@' . $like . '@%')
1075            ->where('new_gedcom', 'NOT LIKE', '0 @' . $like . '@%')
1076            ->whereIn('change_id', function (Builder $query): void {
1077                $query->select(new Expression('MAX(change_id)'))
1078                    ->from('change')
1079                    ->where('gedcom_id', '=', $this->tree->id())
1080                    ->where('status', '=', 'pending')
1081                    ->groupBy(['xref']);
1082            })
1083            ->select(['xref']);
1084
1085        $xrefs = DB::table('link')
1086            ->where('l_file', '=', $this->tree()->id())
1087            ->where('l_to', '=', $this->xref())
1088            ->select(['l_from'])
1089            ->union($union)
1090            ->pluck('l_from');
1091
1092        return $xrefs->map(function (string $xref): GedcomRecord {
1093            $record = Registry::gedcomRecordFactory()->make($xref, $this->tree);
1094            assert($record instanceof GedcomRecord);
1095
1096            return $record;
1097        })->all();
1098    }
1099
1100    /**
1101     * Each object type may have its own special rules, and re-implement this function.
1102     *
1103     * @param int $access_level
1104     *
1105     * @return bool
1106     */
1107    protected function canShowByType(int $access_level): bool
1108    {
1109        $fact_privacy = $this->tree->getFactPrivacy();
1110
1111        if (isset($fact_privacy[static::RECORD_TYPE])) {
1112            // Restriction found
1113            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
1114        }
1115
1116        // No restriction found - must be public:
1117        return true;
1118    }
1119
1120    /**
1121     * Generate a private version of this record
1122     *
1123     * @param int $access_level
1124     *
1125     * @return string
1126     */
1127    protected function createPrivateGedcomRecord(int $access_level): string
1128    {
1129        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
1130    }
1131
1132    /**
1133     * Convert a name record into sortable and full/display versions. This default
1134     * should be OK for simple record types. INDI/FAM records will need to redefine it.
1135     *
1136     * @param string $type
1137     * @param string $value
1138     * @param string $gedcom
1139     *
1140     * @return void
1141     */
1142    protected function addName(string $type, string $value, string $gedcom): void
1143    {
1144        $this->getAllNames[] = [
1145            'type'   => $type,
1146            'sort'   => preg_replace_callback('/(\d+)/', static function (array $matches): string {
1147                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
1148            }, $value),
1149            'full'   => '<span dir="auto">' . e($value) . '</span>',
1150            // This is used for display
1151            'fullNN' => $value,
1152            // This goes into the database
1153        ];
1154    }
1155
1156    /**
1157     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
1158     * Records without a name (e.g. FAM) will need to redefine this function.
1159     * Parameters: the level 1 fact containing the name.
1160     * Return value: an array of name structures, each containing
1161     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
1162     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
1163     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
1164     *
1165     * @param int              $level
1166     * @param string           $fact_type
1167     * @param Collection<Fact> $facts
1168     *
1169     * @return void
1170     */
1171    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
1172    {
1173        $sublevel    = $level + 1;
1174        $subsublevel = $sublevel + 1;
1175        foreach ($facts as $fact) {
1176            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1177                foreach ($matches as $match) {
1178                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1179                    if ($match[1] === 'NAME' && str_contains($match[3], "\n2 TYPE married")) {
1180                        $this->addName('_MARNM', $match[2], $fact->gedcom());
1181                    } else {
1182                        $this->addName($match[1], $match[2], $fact->gedcom());
1183                    }
1184                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
1185                        foreach ($submatches as $submatch) {
1186                            $this->addName($submatch[1], $submatch[2], $match[3]);
1187                        }
1188                    }
1189                }
1190            }
1191        }
1192    }
1193
1194    /**
1195     * Split the record into facts
1196     *
1197     * @return void
1198     */
1199    private function parseFacts(): void
1200    {
1201        // Split the record into facts
1202        if ($this->gedcom) {
1203            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
1204            array_shift($gedcom_facts);
1205        } else {
1206            $gedcom_facts = [];
1207        }
1208        if ($this->pending) {
1209            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
1210            array_shift($pending_facts);
1211        } else {
1212            $pending_facts = [];
1213        }
1214
1215        $this->facts = [];
1216
1217        foreach ($gedcom_facts as $gedcom_fact) {
1218            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
1219            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
1220                $fact->setPendingDeletion();
1221            }
1222            $this->facts[] = $fact;
1223        }
1224        foreach ($pending_facts as $pending_fact) {
1225            if (!in_array($pending_fact, $gedcom_facts, true)) {
1226                $fact = new Fact($pending_fact, $this, md5($pending_fact));
1227                $fact->setPendingAddition();
1228                $this->facts[] = $fact;
1229            }
1230        }
1231    }
1232
1233    /**
1234     * Work out whether this record can be shown to a user with a given access level
1235     *
1236     * @param int $access_level
1237     *
1238     * @return bool
1239     */
1240    private function canShowRecord(int $access_level): bool
1241    {
1242        // This setting would better be called "$ENABLE_PRIVACY"
1243        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
1244            return true;
1245        }
1246
1247        // We should always be able to see our own record (unless an admin is applying download restrictions)
1248        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
1249            return true;
1250        }
1251
1252        // Does this record have a RESN?
1253        if (str_contains($this->gedcom, "\n1 RESN confidential")) {
1254            return Auth::PRIV_NONE >= $access_level;
1255        }
1256        if (str_contains($this->gedcom, "\n1 RESN privacy")) {
1257            return Auth::PRIV_USER >= $access_level;
1258        }
1259        if (str_contains($this->gedcom, "\n1 RESN none")) {
1260            return true;
1261        }
1262
1263        // Does this record have a default RESN?
1264        $individual_privacy = $this->tree->getIndividualPrivacy();
1265        if (isset($individual_privacy[$this->xref()])) {
1266            return $individual_privacy[$this->xref()] >= $access_level;
1267        }
1268
1269        // Privacy rules do not apply to admins
1270        if (Auth::PRIV_NONE >= $access_level) {
1271            return true;
1272        }
1273
1274        // Different types of record have different privacy rules
1275        return $this->canShowByType($access_level);
1276    }
1277
1278    /**
1279     * Lock the database row, to prevent concurrent edits.
1280     */
1281    public function lock(): void
1282    {
1283        DB::table('other')
1284            ->where('o_file', '=', $this->tree->id())
1285            ->where('o_id', '=', $this->xref())
1286            ->lockForUpdate()
1287            ->get();
1288    }
1289
1290    /**
1291     * Add blank lines, to allow a user to add/edit new values.
1292     *
1293     * @return string
1294     */
1295    public function insertMissingSubtags(): string
1296    {
1297        $gedcom = $this->insertMissingLevels($this->tag(), $this->gedcom());
1298
1299        // NOTE records have data at level 0.  Move it to 1 CONC.
1300        if (static::RECORD_TYPE === 'NOTE') {
1301            return preg_replace('/^0 @[^@]+@ NOTE/', '1 CONC', $gedcom);
1302        }
1303
1304        return preg_replace('/^0.*\n/', '', $gedcom);
1305    }
1306
1307    /**
1308     * @param string $tag
1309     * @param string $gedcom
1310     *
1311     * @return string
1312     */
1313    public function insertMissingLevels(string $tag, string $gedcom): string
1314    {
1315        $next_level = substr_count($tag, ':') + 1;
1316        $factory    = Registry::elementFactory();
1317        $subtags    = $factory->make($tag)->subtags();
1318
1319        // Merge CONT records onto their parent line.
1320        $gedcom = strtr($gedcom, [
1321            "\n" . $next_level . ' CONT ' => "\r",
1322            "\n" . $next_level . ' CONT' => "\r",
1323        ]);
1324
1325        // The first part is level N.  The remainder are level N+1.
1326        $parts  = preg_split('/\n(?=' . $next_level . ')/', $gedcom);
1327        $return = array_shift($parts);
1328
1329        foreach ($subtags as $subtag => $occurrences) {
1330            [$min, $max] = explode(':', $occurrences);
1331
1332            $min = (int) $min;
1333
1334            if ($max === 'M') {
1335                $max = PHP_INT_MAX;
1336            } else {
1337                $max = (int) $max;
1338            }
1339
1340            $count = 0;
1341
1342            // Add expected subtags in our preferred order.
1343            foreach ($parts as $n => $part) {
1344                if (str_starts_with($part, $next_level . ' ' . $subtag)) {
1345                    $return .= "\n" . $this->insertMissingLevels($tag . ':' . $subtag, $part);
1346                    $count++;
1347                    unset($parts[$n]);
1348                }
1349            }
1350
1351            // Allowed to have more of this subtag?
1352            if ($count < $max) {
1353                // Create a new one.
1354                $gedcom  = $next_level . ' ' . $subtag;
1355                $default = $factory->make($tag . ':' . $subtag)->default($this->tree);
1356                if ($default !== '') {
1357                    $gedcom .= ' ' . $default;
1358                }
1359
1360                $number_to_add = max(1, $min - $count);
1361                $gedcom_to_add = "\n" . $this->insertMissingLevels($tag . ':' . $subtag, $gedcom);
1362
1363                $return .= \str_repeat($gedcom_to_add, $number_to_add);
1364            }
1365        }
1366
1367        // Now add any unexpected/existing data.
1368        if ($parts !== []) {
1369            $return .= "\n" . implode("\n", $parts);
1370        }
1371
1372        return $return;
1373    }
1374}
1375