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