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