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