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