xref: /webtrees/app/GedcomRecord.php (revision 2c685d76b4ab2ea8f166ab8a2e4112fa1ba8de5d)
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\Http\RequestHandlers\GedcomRecordPage;
26use Fisharebest\Webtrees\Services\PendingChangesService;
27use Illuminate\Database\Capsule\Manager as DB;
28use Illuminate\Database\Query\Builder;
29use Illuminate\Database\Query\Expression;
30use Illuminate\Database\Query\JoinClause;
31use Illuminate\Support\Collection;
32
33use function addcslashes;
34use function app;
35use function array_combine;
36use function array_keys;
37use function array_map;
38use function array_search;
39use function array_shift;
40use function assert;
41use function count;
42use function date;
43use function e;
44use function explode;
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 range;
53use function route;
54use function str_contains;
55use function str_ends_with;
56use function str_pad;
57use function strtoupper;
58use function trim;
59use function view;
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    protected string $xref;
75
76    protected Tree $tree;
77
78    // GEDCOM data (before any pending edits)
79    protected string $gedcom;
80
81    // GEDCOM data (after any pending edits)
82    protected ?string $pending;
83
84    /** @var array<Fact> Facts extracted from $gedcom/$pending */
85    protected array $facts;
86
87    /** @var array<array<string>> All the names of this individual */
88    protected array $getAllNames = [];
89
90    /** @var int|null Cached result */
91    private ?int $getPrimaryName = null;
92
93    /** @var int|null Cached result */
94    private ?int $getSecondaryName = null;
95
96    /**
97     * Create a GedcomRecord object from raw GEDCOM data.
98     *
99     * @param string      $xref
100     * @param string      $gedcom  an empty string for new/pending records
101     * @param string|null $pending null for a record with no pending edits,
102     *                             empty string for records with pending deletions
103     * @param Tree        $tree
104     */
105    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
106    {
107        $this->xref    = $xref;
108        $this->gedcom  = $gedcom;
109        $this->pending = $pending;
110        $this->tree    = $tree;
111        $this->facts   = $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 === []) {
347            if ($this->canShowName()) {
348                // Ask the record to extract its names
349                $this->extractNames();
350                // No name found? Use a fallback.
351                if ($this->getAllNames === []) {
352                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
353                }
354            } else {
355                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
356            }
357        }
358
359        return $this->getAllNames;
360    }
361
362    /**
363     * If this object has no name, what do we call it?
364     *
365     * @return string
366     */
367    public function getFallBackName(): string
368    {
369        return e($this->xref());
370    }
371
372    /**
373     * Which of the (possibly several) names of this record is the primary one.
374     *
375     * @return int
376     */
377    public function getPrimaryName(): int
378    {
379        static $language_script;
380
381        $language_script ??= I18N::locale()->script()->code();
382
383        if ($this->getPrimaryName === null) {
384            // Generally, the first name is the primary one....
385            $this->getPrimaryName = 0;
386            // ...except when the language/name use different character sets
387            foreach ($this->getAllNames() as $n => $name) {
388                if (I18N::textScript($name['sort']) === $language_script) {
389                    $this->getPrimaryName = $n;
390                    break;
391                }
392            }
393        }
394
395        return $this->getPrimaryName;
396    }
397
398    /**
399     * Which of the (possibly several) names of this record is the secondary one.
400     *
401     * @return int
402     */
403    public function getSecondaryName(): int
404    {
405        if ($this->getSecondaryName === null) {
406            // Generally, the primary and secondary names are the same
407            $this->getSecondaryName = $this->getPrimaryName();
408            // ....except when there are names with different character sets
409            $all_names = $this->getAllNames();
410            if (count($all_names) > 1) {
411                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
412                foreach ($all_names as $n => $name) {
413                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
414                        $this->getSecondaryName = $n;
415                        break;
416                    }
417                }
418            }
419        }
420
421        return $this->getSecondaryName;
422    }
423
424    /**
425     * Allow the choice of primary name to be overidden, e.g. in a search result
426     *
427     * @param int|null $n
428     *
429     * @return void
430     */
431    public function setPrimaryName(int $n = null): void
432    {
433        $this->getPrimaryName   = $n;
434        $this->getSecondaryName = null;
435    }
436
437    /**
438     * Allow native PHP functions such as array_unique() to work with objects
439     *
440     * @return string
441     */
442    public function __toString(): string
443    {
444        return $this->xref . '@' . $this->tree->id();
445    }
446
447    /**
448     * /**
449     * Get variants of the name
450     *
451     * @return string
452     */
453    public function fullName(): string
454    {
455        if ($this->canShowName()) {
456            $tmp = $this->getAllNames();
457
458            return $tmp[$this->getPrimaryName()]['full'];
459        }
460
461        return I18N::translate('Private');
462    }
463
464    /**
465     * Get a sortable version of the name. Do not display this!
466     *
467     * @return string
468     */
469    public function sortName(): string
470    {
471        // The sortable name is never displayed, no need to call canShowName()
472        $tmp = $this->getAllNames();
473
474        return $tmp[$this->getPrimaryName()]['sort'];
475    }
476
477    /**
478     * Get the full name in an alternative character set
479     *
480     * @return string|null
481     */
482    public function alternateName(): ?string
483    {
484        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
485            $all_names = $this->getAllNames();
486
487            return $all_names[$this->getSecondaryName()]['full'];
488        }
489
490        return null;
491    }
492
493    /**
494     * Format this object for display in a list
495     *
496     * @return string
497     */
498    public function formatList(): string
499    {
500        $html = '<a href="' . e($this->url()) . '" class="list_item">';
501        $html .= '<b>' . $this->fullName() . '</b>';
502        $html .= $this->formatListDetails();
503        $html .= '</a>';
504
505        return $html;
506    }
507
508    /**
509     * This function should be redefined in derived classes to show any major
510     * identifying characteristics of this record.
511     *
512     * @return string
513     */
514    public function formatListDetails(): string
515    {
516        return '';
517    }
518
519    /**
520     * Extract/format the first fact from a list of facts.
521     *
522     * @param array<string> $facts
523     * @param int           $style
524     *
525     * @return string
526     */
527    public function formatFirstMajorFact(array $facts, int $style): string
528    {
529        foreach ($this->facts($facts, true) as $event) {
530            // Only display if it has a date or place (or both)
531            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
532                $joiner = ' — ';
533            } else {
534                $joiner = '';
535            }
536            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
537                switch ($style) {
538                    case 1:
539                        return '<br><em>' . $event->label() . ' ' . view('fact-date', ['cal_link' => 'false', 'fact' => $event, 'record' => $event->record(), 'time' => false]) . '</em>';
540                    case 2:
541                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . view('fact-date', ['cal_link' => 'false', 'fact' => $event, 'record' => $event->record(), 'time' => false]) . $joiner . $event->place()->shortName() . '</dd></dl>';
542                }
543            }
544        }
545
546        return '';
547    }
548
549    /**
550     * Find individuals linked to this record.
551     *
552     * @param string $link
553     *
554     * @return Collection<int,Individual>
555     */
556    public function linkedIndividuals(string $link): Collection
557    {
558        return DB::table('individuals')
559            ->join('link', static function (JoinClause $join): void {
560                $join
561                    ->on('l_file', '=', 'i_file')
562                    ->on('l_from', '=', 'i_id');
563            })
564            ->where('i_file', '=', $this->tree->id())
565            ->where('l_type', '=', $link)
566            ->where('l_to', '=', $this->xref)
567            ->select(['individuals.*'])
568            ->get()
569            ->map(Registry::individualFactory()->mapper($this->tree))
570            ->filter(self::accessFilter());
571    }
572
573    /**
574     * Find families linked to this record.
575     *
576     * @param string $link
577     *
578     * @return Collection<int,Family>
579     */
580    public function linkedFamilies(string $link): Collection
581    {
582        return DB::table('families')
583            ->join('link', static function (JoinClause $join): void {
584                $join
585                    ->on('l_file', '=', 'f_file')
586                    ->on('l_from', '=', 'f_id');
587            })
588            ->where('f_file', '=', $this->tree->id())
589            ->where('l_type', '=', $link)
590            ->where('l_to', '=', $this->xref)
591            ->select(['families.*'])
592            ->get()
593            ->map(Registry::familyFactory()->mapper($this->tree))
594            ->filter(self::accessFilter());
595    }
596
597    /**
598     * Find sources linked to this record.
599     *
600     * @param string $link
601     *
602     * @return Collection<int,Source>
603     */
604    public function linkedSources(string $link): Collection
605    {
606        return DB::table('sources')
607            ->join('link', static function (JoinClause $join): void {
608                $join
609                    ->on('l_file', '=', 's_file')
610                    ->on('l_from', '=', 's_id');
611            })
612            ->where('s_file', '=', $this->tree->id())
613            ->where('l_type', '=', $link)
614            ->where('l_to', '=', $this->xref)
615            ->select(['sources.*'])
616            ->get()
617            ->map(Registry::sourceFactory()->mapper($this->tree))
618            ->filter(self::accessFilter());
619    }
620
621    /**
622     * Find media objects linked to this record.
623     *
624     * @param string $link
625     *
626     * @return Collection<int,Media>
627     */
628    public function linkedMedia(string $link): Collection
629    {
630        return DB::table('media')
631            ->join('link', static function (JoinClause $join): void {
632                $join
633                    ->on('l_file', '=', 'm_file')
634                    ->on('l_from', '=', 'm_id');
635            })
636            ->where('m_file', '=', $this->tree->id())
637            ->where('l_type', '=', $link)
638            ->where('l_to', '=', $this->xref)
639            ->select(['media.*'])
640            ->get()
641            ->map(Registry::mediaFactory()->mapper($this->tree))
642            ->filter(self::accessFilter());
643    }
644
645    /**
646     * Find notes linked to this record.
647     *
648     * @param string $link
649     *
650     * @return Collection<int,Note>
651     */
652    public function linkedNotes(string $link): Collection
653    {
654        return DB::table('other')
655            ->join('link', static function (JoinClause $join): void {
656                $join
657                    ->on('l_file', '=', 'o_file')
658                    ->on('l_from', '=', 'o_id');
659            })
660            ->where('o_file', '=', $this->tree->id())
661            ->where('o_type', '=', Note::RECORD_TYPE)
662            ->where('l_type', '=', $link)
663            ->where('l_to', '=', $this->xref)
664            ->select(['other.*'])
665            ->get()
666            ->map(Registry::noteFactory()->mapper($this->tree))
667            ->filter(self::accessFilter());
668    }
669
670    /**
671     * Find repositories linked to this record.
672     *
673     * @param string $link
674     *
675     * @return Collection<int,Repository>
676     */
677    public function linkedRepositories(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', '=', Repository::RECORD_TYPE)
687            ->where('l_type', '=', $link)
688            ->where('l_to', '=', $this->xref)
689            ->select(['other.*'])
690            ->get()
691            ->map(Registry::repositoryFactory()->mapper($this->tree))
692            ->filter(self::accessFilter());
693    }
694
695    /**
696     * Find locations linked to this record.
697     *
698     * @param string $link
699     *
700     * @return Collection<int,Location>
701     */
702    public function linkedLocations(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', '=', Location::RECORD_TYPE)
712            ->where('l_type', '=', $link)
713            ->where('l_to', '=', $this->xref)
714            ->select(['other.*'])
715            ->get()
716            ->map(Registry::locationFactory()->mapper($this->tree))
717            ->filter(self::accessFilter());
718    }
719
720    /**
721     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
722     * This is used to display multiple events on the individual/family lists.
723     * Multiple events can exist because of uncertainty in dates, dates in different
724     * calendars, place-names in both latin and hebrew character sets, etc.
725     * It also allows us to combine dates/places from different events in the summaries.
726     *
727     * @param array<string> $events
728     *
729     * @return array<Date>
730     */
731    public function getAllEventDates(array $events): array
732    {
733        $dates = [];
734        foreach ($this->facts($events, false, null, true) as $event) {
735            if ($event->date()->isOK()) {
736                $dates[] = $event->date();
737            }
738        }
739
740        return $dates;
741    }
742
743    /**
744     * Get all the places for a particular type of event
745     *
746     * @param array<string> $events
747     *
748     * @return array<Place>
749     */
750    public function getAllEventPlaces(array $events): array
751    {
752        $places = [];
753        foreach ($this->facts($events) as $event) {
754            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
755                foreach ($ged_places[1] as $ged_place) {
756                    $places[] = new Place($ged_place, $this->tree);
757                }
758            }
759        }
760
761        return $places;
762    }
763
764    /**
765     * The facts and events for this record.
766     *
767     * @param array<string> $filter
768     * @param bool          $sort
769     * @param int|null      $access_level
770     * @param bool          $ignore_deleted
771     *
772     * @return Collection<int,Fact>
773     */
774    public function facts(
775        array $filter = [],
776        bool $sort = false,
777        int $access_level = null,
778        bool $ignore_deleted = false
779    ): Collection {
780        $access_level = $access_level ?? Auth::accessLevel($this->tree);
781
782        // Convert BIRT into INDI:BIRT, etc.
783        $filter = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, $filter);
784
785        $facts = new Collection();
786        if ($this->canShow($access_level)) {
787            foreach ($this->facts as $fact) {
788                if (($filter === [] || in_array($fact->tag(), $filter, true)) && $fact->canShow($access_level)) {
789                    $facts->push($fact);
790                }
791            }
792        }
793
794        if ($sort) {
795            switch ($this->tag()) {
796                case Family::RECORD_TYPE:
797                case Individual::RECORD_TYPE:
798                    $facts = Fact::sortFacts($facts);
799                    break;
800
801                default:
802                    $subtags = Registry::elementFactory()->make($this->tag())->subtags();
803                    $subtags = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, array_keys($subtags));
804                    $subtags = array_combine(range(1, count($subtags)), $subtags);
805
806                    $facts = $facts
807                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
808                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
809                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
810
811                            return $sort_x <=> $sort_y;
812                        });
813                    break;
814            }
815        }
816
817        if ($ignore_deleted) {
818            $facts = $facts->filter(static function (Fact $fact): bool {
819                return !$fact->isPendingDeletion();
820            });
821        }
822
823        return $facts;
824    }
825
826    /**
827     * @return array<string,string>
828     */
829    public function missingFacts(): array
830    {
831        $missing_facts = [];
832
833        foreach (Registry::elementFactory()->make($this->tag())->subtags() as $subtag => $repeat) {
834            [, $max] = explode(':', $repeat);
835            $max = $max === 'M' ? PHP_INT_MAX : (int) $max;
836
837            if ($this->facts([$subtag], false, null, true)->count() < $max) {
838                $missing_facts[$subtag] = $subtag;
839                $missing_facts[$subtag] = Registry::elementFactory()->make($this->tag() . ':' . $subtag)->label();
840            }
841        }
842
843        uasort($missing_facts, I18N::comparator());
844
845        if (!Auth::canUploadMedia($this->tree, Auth::user())) {
846            unset($missing_facts['OBJE']);
847        }
848
849        // We have special code for this.
850        unset($missing_facts['FILE']);
851
852        return $missing_facts;
853    }
854
855    /**
856     * Get the last-change timestamp for this record
857     *
858     * @return Timestamp
859     */
860    public function lastChangeTimestamp(): Timestamp
861    {
862        /** @var Fact|null $chan */
863        $chan = $this->facts(['CHAN'])->first();
864
865        if ($chan instanceof Fact) {
866            // The record does have a CHAN event
867            $d = $chan->date()->minimumDate()->format('%Y-%m-%d');
868
869            if (preg_match('/\n3 TIME( (\d\d):(\d\d):(\d\d))/', $chan->gedcom(), $match)) {
870                return Registry::timestampFactory()->fromString($d . $match[1], 'Y-m-d H:i:s');
871            }
872
873            if (preg_match('/\n3 TIME ((\d\d):(\d\d))/', $chan->gedcom(), $match)) {
874                return Registry::timestampFactory()->fromString($d . $match[1], 'Y-m-d H:i');
875            }
876
877            return Registry::timestampFactory()->fromString($d, 'Y-m-d');
878        }
879
880        // The record does not have a CHAN event
881        return Registry::timestampFactory()->make(0);
882    }
883
884    /**
885     * Get the last-change user for this record
886     *
887     * @return string
888     */
889    public function lastChangeUser(): string
890    {
891        $chan = $this->facts(['CHAN'])->first();
892
893        if ($chan === null) {
894            return I18N::translate('Unknown');
895        }
896
897        $chan_user = $chan->attribute('_WT_USER');
898        if ($chan_user === '') {
899            return I18N::translate('Unknown');
900        }
901
902        return $chan_user;
903    }
904
905    /**
906     * Add a new fact to this record
907     *
908     * @param string $gedcom
909     * @param bool   $update_chan
910     *
911     * @return void
912     */
913    public function createFact(string $gedcom, bool $update_chan): void
914    {
915        $this->updateFact('', $gedcom, $update_chan);
916    }
917
918    /**
919     * Delete a fact from this record
920     *
921     * @param string $fact_id
922     * @param bool   $update_chan
923     *
924     * @return void
925     */
926    public function deleteFact(string $fact_id, bool $update_chan): void
927    {
928        $this->updateFact($fact_id, '', $update_chan);
929    }
930
931    /**
932     * Replace a fact with a new gedcom data.
933     *
934     * @param string $fact_id
935     * @param string $gedcom
936     * @param bool   $update_chan
937     *
938     * @return void
939     * @throws Exception
940     */
941    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
942    {
943        // Not all record types allow a CHAN event.
944        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
945
946        // MSDOS line endings will break things in horrible ways
947        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
948        $gedcom = trim($gedcom);
949
950        if ($this->pending === '') {
951            throw new Exception('Cannot edit a deleted record');
952        }
953        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
954            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
955        }
956
957        if ($this->pending) {
958            $old_gedcom = $this->pending;
959        } else {
960            $old_gedcom = $this->gedcom;
961        }
962
963        // First line of record may contain data - e.g. NOTE records.
964        [$new_gedcom] = explode("\n", $old_gedcom, 2);
965
966        // Replacing (or deleting) an existing fact
967        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
968            if ($fact->id() === $fact_id) {
969                if ($gedcom !== '') {
970                    $new_gedcom .= "\n" . $gedcom;
971                }
972                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
973            } elseif (!str_ends_with($fact->tag(), ':CHAN') || !$update_chan) {
974                $new_gedcom .= "\n" . $fact->gedcom();
975            }
976        }
977
978        // Adding a new fact
979        if ($fact_id === '') {
980            $new_gedcom .= "\n" . $gedcom;
981        }
982
983        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
984            $today = strtoupper(date('d M Y'));
985            $now   = date('H:i:s');
986            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
987        }
988
989        if ($new_gedcom !== $old_gedcom) {
990            // Save the changes
991            DB::table('change')->insert([
992                'gedcom_id'  => $this->tree->id(),
993                'xref'       => $this->xref,
994                'old_gedcom' => $old_gedcom,
995                'new_gedcom' => $new_gedcom,
996                'user_id'    => Auth::id(),
997            ]);
998
999            $this->pending = $new_gedcom;
1000
1001            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1002                app(PendingChangesService::class)->acceptRecord($this);
1003                $this->gedcom  = $new_gedcom;
1004                $this->pending = null;
1005            }
1006        }
1007
1008        $this->facts = $this->parseFacts();
1009    }
1010
1011    /**
1012     * Update this record
1013     *
1014     * @param string $gedcom
1015     * @param bool   $update_chan
1016     *
1017     * @return void
1018     */
1019    public function updateRecord(string $gedcom, bool $update_chan): void
1020    {
1021        // Not all record types allow a CHAN event.
1022        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
1023
1024        // MSDOS line endings will break things in horrible ways
1025        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1026        $gedcom = trim($gedcom);
1027
1028        // Update the CHAN record
1029        if ($update_chan) {
1030            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1031            $today = strtoupper(date('d M Y'));
1032            $now   = date('H:i:s');
1033            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
1034        }
1035
1036        // Create a pending change
1037        DB::table('change')->insert([
1038            'gedcom_id'  => $this->tree->id(),
1039            'xref'       => $this->xref,
1040            'old_gedcom' => $this->gedcom(),
1041            'new_gedcom' => $gedcom,
1042            'user_id'    => Auth::id(),
1043        ]);
1044
1045        // Clear the cache
1046        $this->pending = $gedcom;
1047
1048        // Accept this pending change
1049        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1050            app(PendingChangesService::class)->acceptRecord($this);
1051            $this->gedcom  = $gedcom;
1052            $this->pending = null;
1053        }
1054
1055        $this->facts = $this->parseFacts();
1056
1057        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1058    }
1059
1060    /**
1061     * Delete this record
1062     *
1063     * @return void
1064     */
1065    public function deleteRecord(): void
1066    {
1067        // Create a pending change
1068        if (!$this->isPendingDeletion()) {
1069            DB::table('change')->insert([
1070                'gedcom_id'  => $this->tree->id(),
1071                'xref'       => $this->xref,
1072                'old_gedcom' => $this->gedcom(),
1073                'new_gedcom' => '',
1074                'user_id'    => Auth::id(),
1075            ]);
1076        }
1077
1078        // Auto-accept this pending change
1079        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
1080            app(PendingChangesService::class)->acceptRecord($this);
1081        }
1082
1083        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1084    }
1085
1086    /**
1087     * Remove all links from this record to $xref
1088     *
1089     * @param string $xref
1090     * @param bool   $update_chan
1091     *
1092     * @return void
1093     */
1094    public function removeLinks(string $xref, bool $update_chan): void
1095    {
1096        $value = '@' . $xref . '@';
1097
1098        foreach ($this->facts() as $fact) {
1099            if ($fact->value() === $value) {
1100                $this->deleteFact($fact->id(), $update_chan);
1101            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1102                $gedcom = $fact->gedcom();
1103                foreach ($matches as $match) {
1104                    $next_level  = $match[1] + 1;
1105                    $next_levels = '[' . $next_level . '-9]';
1106                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1107                }
1108                $this->updateFact($fact->id(), $gedcom, $update_chan);
1109            }
1110        }
1111    }
1112
1113    /**
1114     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1115     * also delete all links to it.
1116     *
1117     * @return array<GedcomRecord>
1118     */
1119    public function linkingRecords(): array
1120    {
1121        $like = addcslashes($this->xref(), '\\%_');
1122
1123        $union = DB::table('change')
1124            ->where('gedcom_id', '=', $this->tree()->id())
1125            ->where('new_gedcom', 'LIKE', '%@' . $like . '@%')
1126            ->where('new_gedcom', 'NOT LIKE', '0 @' . $like . '@%')
1127            ->whereIn('change_id', function (Builder $query): void {
1128                $query->select(new Expression('MAX(change_id)'))
1129                    ->from('change')
1130                    ->where('gedcom_id', '=', $this->tree->id())
1131                    ->where('status', '=', 'pending')
1132                    ->groupBy(['xref']);
1133            })
1134            ->select(['xref']);
1135
1136        $xrefs = DB::table('link')
1137            ->where('l_file', '=', $this->tree()->id())
1138            ->where('l_to', '=', $this->xref())
1139            ->select(['l_from'])
1140            ->union($union)
1141            ->pluck('l_from');
1142
1143        return $xrefs->map(function (string $xref): GedcomRecord {
1144            $record = Registry::gedcomRecordFactory()->make($xref, $this->tree);
1145            assert($record instanceof GedcomRecord);
1146
1147            return $record;
1148        })->all();
1149    }
1150
1151    /**
1152     * Each object type may have its own special rules, and re-implement this function.
1153     *
1154     * @param int $access_level
1155     *
1156     * @return bool
1157     */
1158    protected function canShowByType(int $access_level): bool
1159    {
1160        $fact_privacy = $this->tree->getFactPrivacy();
1161
1162        if (isset($fact_privacy[static::RECORD_TYPE])) {
1163            // Restriction found
1164            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
1165        }
1166
1167        // No restriction found - must be public:
1168        return true;
1169    }
1170
1171    /**
1172     * Generate a private version of this record
1173     *
1174     * @param int $access_level
1175     *
1176     * @return string
1177     */
1178    protected function createPrivateGedcomRecord(int $access_level): string
1179    {
1180        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
1181    }
1182
1183    /**
1184     * Convert a name record into sortable and full/display versions. This default
1185     * should be OK for simple record types. INDI/FAM records will need to redefine it.
1186     *
1187     * @param string $type
1188     * @param string $value
1189     * @param string $gedcom
1190     *
1191     * @return void
1192     */
1193    protected function addName(string $type, string $value, string $gedcom): void
1194    {
1195        $this->getAllNames[] = [
1196            'type'   => $type,
1197            'sort'   => preg_replace_callback('/(\d+)/', static function (array $matches): string {
1198                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
1199            }, $value),
1200            'full'   => '<bdi>' . e($value) . '</bdi>',
1201            // This is used for display
1202            'fullNN' => $value,
1203            // This goes into the database
1204        ];
1205    }
1206
1207    /**
1208     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
1209     * Records without a name (e.g. FAM) will need to redefine this function.
1210     * Parameters: the level 1 fact containing the name.
1211     * Return value: an array of name structures, each containing
1212     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
1213     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
1214     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
1215     *
1216     * @param int              $level
1217     * @param string           $fact_type
1218     * @param Collection<int,Fact> $facts
1219     *
1220     * @return void
1221     */
1222    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
1223    {
1224        $sublevel    = $level + 1;
1225        $subsublevel = $sublevel + 1;
1226        foreach ($facts as $fact) {
1227            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1228                foreach ($matches as $match) {
1229                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1230                    if ($match[1] === 'NAME' && str_contains($match[3], "\n2 TYPE married")) {
1231                        $this->addName('_MARNM', $match[2], $fact->gedcom());
1232                    } else {
1233                        $this->addName($match[1], $match[2], $fact->gedcom());
1234                    }
1235                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
1236                        foreach ($submatches as $submatch) {
1237                            $this->addName($submatch[1], $submatch[2], $match[3]);
1238                        }
1239                    }
1240                }
1241            }
1242        }
1243    }
1244
1245    /**
1246     * Split the record into facts
1247     *
1248     * @return array<Fact>
1249     */
1250    private function parseFacts(): array
1251    {
1252        // Split the record into facts
1253        if ($this->gedcom) {
1254            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
1255            array_shift($gedcom_facts);
1256        } else {
1257            $gedcom_facts = [];
1258        }
1259        if ($this->pending) {
1260            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
1261            array_shift($pending_facts);
1262        } else {
1263            $pending_facts = [];
1264        }
1265
1266        $facts = [];
1267
1268        foreach ($gedcom_facts as $gedcom_fact) {
1269            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
1270            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
1271                $fact->setPendingDeletion();
1272            }
1273            $facts[] = $fact;
1274        }
1275        foreach ($pending_facts as $pending_fact) {
1276            if (!in_array($pending_fact, $gedcom_facts, true)) {
1277                $fact = new Fact($pending_fact, $this, md5($pending_fact));
1278                $fact->setPendingAddition();
1279                $facts[] = $fact;
1280            }
1281        }
1282
1283        return $facts;
1284    }
1285
1286    /**
1287     * Work out whether this record can be shown to a user with a given access level
1288     *
1289     * @param int $access_level
1290     *
1291     * @return bool
1292     */
1293    private function canShowRecord(int $access_level): bool
1294    {
1295        // This setting would better be called "$ENABLE_PRIVACY"
1296        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
1297            return true;
1298        }
1299
1300        // We should always be able to see our own record (unless an admin is applying download restrictions)
1301        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
1302            return true;
1303        }
1304
1305        // Does this record have a RESN?
1306        if (str_contains($this->gedcom, "\n1 RESN confidential")) {
1307            return Auth::PRIV_NONE >= $access_level;
1308        }
1309        if (str_contains($this->gedcom, "\n1 RESN privacy")) {
1310            return Auth::PRIV_USER >= $access_level;
1311        }
1312        if (str_contains($this->gedcom, "\n1 RESN none")) {
1313            return true;
1314        }
1315
1316        // Does this record have a default RESN?
1317        $individual_privacy = $this->tree->getIndividualPrivacy();
1318        if (isset($individual_privacy[$this->xref()])) {
1319            return $individual_privacy[$this->xref()] >= $access_level;
1320        }
1321
1322        // Privacy rules do not apply to admins
1323        if (Auth::PRIV_NONE >= $access_level) {
1324            return true;
1325        }
1326
1327        // Different types of record have different privacy rules
1328        return $this->canShowByType($access_level);
1329    }
1330
1331    /**
1332     * Lock the database row, to prevent concurrent edits.
1333     */
1334    public function lock(): void
1335    {
1336        DB::table('other')
1337            ->where('o_file', '=', $this->tree->id())
1338            ->where('o_id', '=', $this->xref())
1339            ->lockForUpdate()
1340            ->get();
1341    }
1342}
1343