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