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