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