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