xref: /webtrees/app/GedcomRecord.php (revision 3e4bf26f9f16d92152484c56e3629888fb6019d5)
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, $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 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 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 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 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()
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)) {
175                $fact->setPendingDeletion();
176            }
177            $this->facts[] = $fact;
178        }
179        foreach ($pending_facts as $pending_fact) {
180            if (!in_array($pending_fact, $gedcom_facts)) {
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 null|string
298     */
299    protected static function fetchGedcomRecord(string $xref, int $tree_id)
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()
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        return Auth::isManager($this->tree) || Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
507    }
508
509    /**
510     * Remove private data from the raw gedcom record.
511     * Return both the visible and invisible data. We need the invisible data when editing.
512     *
513     * @param int $access_level
514     *
515     * @return string
516     */
517    public function privatizeGedcom(int $access_level)
518    {
519        if ($access_level == Auth::PRIV_HIDE) {
520            // We may need the original record, for example when downloading a GEDCOM or clippings cart
521            return $this->gedcom;
522        }
523
524        if ($this->canShow($access_level)) {
525            // The record is not private, but the individual facts may be.
526
527            // Include the entire first line (for NOTE records)
528            [$gedrec] = explode("\n", $this->gedcom, 2);
529
530            // Check each of the facts for access
531            foreach ($this->facts([], false, $access_level) as $fact) {
532                $gedrec .= "\n" . $fact->gedcom();
533            }
534
535            return $gedrec;
536        }
537
538        // We cannot display the details, but we may be able to display
539        // limited data, such as links to other records.
540        return $this->createPrivateGedcomRecord($access_level);
541    }
542
543    /**
544     * Generate a private version of this record
545     *
546     * @param int $access_level
547     *
548     * @return string
549     */
550    protected function createPrivateGedcomRecord(int $access_level): string
551    {
552        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
553    }
554
555    /**
556     * Convert a name record into sortable and full/display versions. This default
557     * should be OK for simple record types. INDI/FAM records will need to redefine it.
558     *
559     * @param string $type
560     * @param string $value
561     * @param string $gedcom
562     *
563     * @return void
564     */
565    protected function addName(string $type, string $value, string $gedcom)
566    {
567        $this->getAllNames[] = [
568            'type'   => $type,
569            'sort'   => preg_replace_callback('/([0-9]+)/', function (array $matches): string {
570                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
571            }, $value),
572            'full'   => '<span dir="auto">' . e($value) . '</span>',
573            // This is used for display
574            'fullNN' => $value,
575            // This goes into the database
576        ];
577    }
578
579    /**
580     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
581     * Records without a name (e.g. FAM) will need to redefine this function.
582     * Parameters: the level 1 fact containing the name.
583     * Return value: an array of name structures, each containing
584     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
585     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
586     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
587     *
588     * @param int        $level
589     * @param string     $fact_type
590     * @param Collection $facts
591     *
592     * @return void
593     */
594    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts)
595    {
596        $sublevel    = $level + 1;
597        $subsublevel = $sublevel + 1;
598        foreach ($facts as $fact) {
599            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
600                foreach ($matches as $match) {
601                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
602                    if ($match[1] == 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
603                        $this->addName('_MARNM', $match[2], $fact->gedcom());
604                    } else {
605                        $this->addName($match[1], $match[2], $fact->gedcom());
606                    }
607                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
608                        foreach ($submatches as $submatch) {
609                            $this->addName($submatch[1], $submatch[2], $match[3]);
610                        }
611                    }
612                }
613            }
614        }
615    }
616
617    /**
618     * Default for "other" object types
619     *
620     * @return void
621     */
622    public function extractNames()
623    {
624        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
625    }
626
627    /**
628     * Derived classes should redefine this function, otherwise the object will have no name
629     *
630     * @return string[][]
631     */
632    public function getAllNames(): array
633    {
634        if ($this->getAllNames === null) {
635            $this->getAllNames = [];
636            if ($this->canShowName()) {
637                // Ask the record to extract its names
638                $this->extractNames();
639                // No name found? Use a fallback.
640                if (!$this->getAllNames) {
641                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
642                }
643            } else {
644                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
645            }
646        }
647
648        return $this->getAllNames;
649    }
650
651    /**
652     * If this object has no name, what do we call it?
653     *
654     * @return string
655     */
656    public function getFallBackName(): string
657    {
658        return e($this->xref());
659    }
660
661    /**
662     * Which of the (possibly several) names of this record is the primary one.
663     *
664     * @return int
665     */
666    public function getPrimaryName(): int
667    {
668        static $language_script;
669
670        if ($language_script === null) {
671            $language_script = I18N::languageScript(WT_LOCALE);
672        }
673
674        if ($this->getPrimaryName === null) {
675            // Generally, the first name is the primary one....
676            $this->getPrimaryName = 0;
677            // ...except when the language/name use different character sets
678            foreach ($this->getAllNames() as $n => $name) {
679                if (I18N::textScript($name['sort']) === $language_script) {
680                    $this->getPrimaryName = $n;
681                    break;
682                }
683            }
684        }
685
686        return $this->getPrimaryName;
687    }
688
689    /**
690     * Which of the (possibly several) names of this record is the secondary one.
691     *
692     * @return int
693     */
694    public function getSecondaryName(): int
695    {
696        if ($this->getSecondaryName === null) {
697            // Generally, the primary and secondary names are the same
698            $this->getSecondaryName = $this->getPrimaryName();
699            // ....except when there are names with different character sets
700            $all_names = $this->getAllNames();
701            if (count($all_names) > 1) {
702                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
703                foreach ($all_names as $n => $name) {
704                    if ($n != $this->getPrimaryName() && $name['type'] != '_MARNM' && I18N::textScript($name['sort']) != $primary_script) {
705                        $this->getSecondaryName = $n;
706                        break;
707                    }
708                }
709            }
710        }
711
712        return $this->getSecondaryName;
713    }
714
715    /**
716     * Allow the choice of primary name to be overidden, e.g. in a search result
717     *
718     * @param int|null $n
719     *
720     * @return void
721     */
722    public function setPrimaryName(int $n = null)
723    {
724        $this->getPrimaryName   = $n;
725        $this->getSecondaryName = null;
726    }
727
728    /**
729     * Allow native PHP functions such as array_unique() to work with objects
730     *
731     * @return string
732     */
733    public function __toString()
734    {
735        return $this->xref . '@' . $this->tree->id();
736    }
737
738    /**
739     * /**
740     * Get variants of the name
741     *
742     * @return string
743     */
744    public function fullName()
745    {
746        if ($this->canShowName()) {
747            $tmp = $this->getAllNames();
748
749            return $tmp[$this->getPrimaryName()]['full'];
750        }
751
752        return I18N::translate('Private');
753    }
754
755    /**
756     * Get a sortable version of the name. Do not display this!
757     *
758     * @return string
759     */
760    public function sortName(): string
761    {
762        // The sortable name is never displayed, no need to call canShowName()
763        $tmp = $this->getAllNames();
764
765        return $tmp[$this->getPrimaryName()]['sort'];
766    }
767
768    /**
769     * Get the full name in an alternative character set
770     *
771     * @return null|string
772     */
773    public function alternateName()
774    {
775        if ($this->canShowName() && $this->getPrimaryName() != $this->getSecondaryName()) {
776            $all_names = $this->getAllNames();
777
778            return $all_names[$this->getSecondaryName()]['full'];
779        }
780
781        return null;
782    }
783
784    /**
785     * Format this object for display in a list
786     *
787     * @return string
788     */
789    public function formatList(): string
790    {
791        $html = '<a href="' . e($this->url()) . '" class="list_item">';
792        $html .= '<b>' . $this->fullName() . '</b>';
793        $html .= $this->formatListDetails();
794        $html .= '</a>';
795
796        return $html;
797    }
798
799    /**
800     * This function should be redefined in derived classes to show any major
801     * identifying characteristics of this record.
802     *
803     * @return string
804     */
805    public function formatListDetails(): string
806    {
807        return '';
808    }
809
810    /**
811     * Extract/format the first fact from a list of facts.
812     *
813     * @param string[] $facts
814     * @param int      $style
815     *
816     * @return string
817     */
818    public function formatFirstMajorFact(array $facts, int $style): string
819    {
820        foreach ($this->facts($facts, true) as $event) {
821            // Only display if it has a date or place (or both)
822            if ($event->date()->isOK() && $event->place()->gedcomName() <> '') {
823                $joiner = ' — ';
824            } else {
825                $joiner = '';
826            }
827            if ($event->date()->isOK() || $event->place()->gedcomName() <> '') {
828                switch ($style) {
829                    case 1:
830                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
831                    case 2:
832                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
833                }
834            }
835        }
836
837        return '';
838    }
839
840    /**
841     * Find individuals linked to this record.
842     *
843     * @param string $link
844     *
845     * @return Individual[]
846     */
847    public function linkedIndividuals(string $link): array
848    {
849        $rows = DB::table('individuals')
850            ->join('link', function (JoinClause $join): void {
851                $join->on('l_file', '=', 'i_file')->on('l_from', '=', 'i_id');
852            })
853            ->where('i_file', '=', $this->tree->id())
854            ->where('l_type', '=', $link)
855            ->where('l_to', '=', $this->xref)
856            ->select(['i_id AS xref', 'i_gedcom AS gedcom'])
857            ->get();
858
859        $list = [];
860        foreach ($rows as $row) {
861            $record = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
862            if ($record->canShowName()) {
863                $list[] = $record;
864            }
865        }
866
867        return $list;
868    }
869
870    /**
871     * Find families linked to this record.
872     *
873     * @param string $link
874     *
875     * @return Family[]
876     */
877    public function linkedFamilies(string $link): array
878    {
879        $rows = DB::table('families')
880            ->join('link', function (JoinClause $join): void {
881                $join->on('l_file', '=', 'f_file')->on('l_from', '=', 'f_id');
882            })
883            ->where('f_file', '=', $this->tree->id())
884            ->where('l_type', '=', $link)
885            ->where('l_to', '=', $this->xref)
886            ->select(['f_id AS xref', 'f_gedcom AS gedcom'])
887            ->get();
888
889        $list = [];
890        foreach ($rows as $row) {
891            $record = Family::getInstance($row->xref, $this->tree, $row->gedcom);
892            if ($record->canShowName()) {
893                $list[] = $record;
894            }
895        }
896
897        return $list;
898    }
899
900    /**
901     * Find sources linked to this record.
902     *
903     * @param string $link
904     *
905     * @return Source[]
906     */
907    public function linkedSources(string $link): array
908    {
909        $rows = DB::table('sources')
910            ->join('link', function (JoinClause $join): void {
911                $join->on('l_file', '=', 's_file')->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(['s_id AS xref', 's_gedcom AS gedcom'])
917            ->get();
918
919        $list = [];
920        foreach ($rows as $row) {
921            $record = Source::getInstance($row->xref, $this->tree, $row->gedcom);
922            if ($record->canShowName()) {
923                $list[] = $record;
924            }
925        }
926
927        return $list;
928    }
929
930    /**
931     * Find media objects linked to this record.
932     *
933     * @param string $link
934     *
935     * @return Media[]
936     */
937    public function linkedMedia(string $link): array
938    {
939        $rows = DB::table('media')
940            ->join('link', function (JoinClause $join): void {
941                $join->on('l_file', '=', 'm_file')->on('l_from', '=', 'm_id');
942            })
943            ->where('m_file', '=', $this->tree->id())
944            ->where('l_type', '=', $link)
945            ->where('l_to', '=', $this->xref)
946            ->select(['m_id AS xref', 'm_gedcom AS gedcom'])
947            ->get();
948
949        $list = [];
950        foreach ($rows as $row) {
951            $record = Media::getInstance($row->xref, $this->tree, $row->gedcom);
952            if ($record->canShowName()) {
953                $list[] = $record;
954            }
955        }
956
957        return $list;
958    }
959
960    /**
961     * Find notes linked to this record.
962     *
963     * @param string $link
964     *
965     * @return Note[]
966     */
967    public function linkedNotes(string $link): array
968    {
969        $rows = DB::table('other')
970            ->join('link', function (JoinClause $join): void {
971                $join->on('l_file', '=', 'o_file')->on('l_from', '=', 'o_id');
972            })
973            ->where('o_file', '=', $this->tree->id())
974            ->where('o_type', '=', 'NOTE')
975            ->where('l_type', '=', $link)
976            ->where('l_to', '=', $this->xref)
977            ->select(['o_id AS xref', 'o_gedcom AS gedcom'])
978            ->get();
979
980        $list = [];
981        foreach ($rows as $row) {
982            $record = Note::getInstance($row->xref, $this->tree, $row->gedcom);
983            if ($record->canShowName()) {
984                $list[] = $record;
985            }
986        }
987
988        return $list;
989    }
990
991    /**
992     * Find repositories linked to this record.
993     *
994     * @param string $link
995     *
996     * @return Repository[]
997     */
998    public function linkedRepositories(string $link): array
999    {
1000        $rows = DB::table('other')
1001            ->join('link', function (JoinClause $join): void {
1002                $join->on('l_file', '=', 'o_file')->on('l_from', '=', 'o_id');
1003            })
1004            ->where('o_file', '=', $this->tree->id())
1005            ->where('o_type', '=', 'REPO')
1006            ->where('l_type', '=', $link)
1007            ->where('l_to', '=', $this->xref)
1008            ->select(['o_id AS xref', 'o_gedcom AS gedcom'])
1009            ->get();
1010
1011        $list = [];
1012        foreach ($rows as $row) {
1013            $record = Repository::getInstance($row->xref, $this->tree, $row->gedcom);
1014            if ($record->canShowName()) {
1015                $list[] = $record;
1016            }
1017        }
1018
1019        return $list;
1020    }
1021
1022    /**
1023     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
1024     * This is used to display multiple events on the individual/family lists.
1025     * Multiple events can exist because of uncertainty in dates, dates in different
1026     * calendars, place-names in both latin and hebrew character sets, etc.
1027     * It also allows us to combine dates/places from different events in the summaries.
1028     *
1029     * @param string[] $events
1030     *
1031     * @return Date[]
1032     */
1033    public function getAllEventDates(array $events): array
1034    {
1035        $dates = [];
1036        foreach ($this->facts($events) as $event) {
1037            if ($event->date()->isOK()) {
1038                $dates[] = $event->date();
1039            }
1040        }
1041
1042        return $dates;
1043    }
1044
1045    /**
1046     * Get all the places for a particular type of event
1047     *
1048     * @param string[] $events
1049     *
1050     * @return Place[]
1051     */
1052    public function getAllEventPlaces(array $events): array
1053    {
1054        $places = [];
1055        foreach ($this->facts($events) as $event) {
1056            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
1057                foreach ($ged_places[1] as $ged_place) {
1058                    $places[] = new Place($ged_place, $this->tree);
1059                }
1060            }
1061        }
1062
1063        return $places;
1064    }
1065
1066    /**
1067     * The facts and events for this record.
1068     *
1069     * @param string[] $filter
1070     * @param bool     $sort
1071     * @param int|null $access_level
1072     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1073     *
1074     * @return Collection
1075     * @return Fact[]
1076     */
1077    public function facts(array $filter = [], bool $sort = false, int $access_level = null, bool $override = false): Collection
1078    {
1079        if ($access_level === null) {
1080            $access_level = Auth::accessLevel($this->tree);
1081        }
1082
1083        $facts = [];
1084        if ($this->canShow($access_level) || $override) {
1085            foreach ($this->facts as $fact) {
1086                if (($filter === [] || in_array($fact->getTag(), $filter)) && $fact->canShow($access_level)) {
1087                    $facts[] = $fact;
1088                }
1089            }
1090        }
1091
1092        if ($sort) {
1093            $facts = Fact::sortFacts($facts);
1094        }
1095
1096        return new Collection($facts);
1097    }
1098
1099    /**
1100     * Get the last-change timestamp for this record
1101     *
1102     * @return Carbon
1103     */
1104    public function lastChangeTimestamp(): Carbon
1105    {
1106        /** @var Fact|null $chan */
1107        $chan = $this->facts(['CHAN'])->first();
1108
1109        if ($chan instanceof Fact) {
1110            // The record does have a CHAN event
1111            $d = $chan->date()->minimumDate();
1112
1113            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1114                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
1115            } elseif (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1116                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
1117            }
1118
1119            return Carbon::create($d->year(), $d->month(), $d->day());
1120        }
1121
1122        // The record does not have a CHAN event
1123        return Carbon::createFromTimestamp(0);
1124    }
1125
1126    /**
1127     * Get the last-change user for this record
1128     *
1129     * @return string
1130     */
1131    public function lastChangeUser()
1132    {
1133        $chan = $this->facts(['CHAN'])->first();
1134
1135        if ($chan === null) {
1136            return I18N::translate('Unknown');
1137        }
1138
1139        $chan_user = $chan->attribute('_WT_USER');
1140        if ($chan_user === '') {
1141            return I18N::translate('Unknown');
1142        }
1143
1144        return $chan_user;
1145    }
1146
1147    /**
1148     * Add a new fact to this record
1149     *
1150     * @param string $gedcom
1151     * @param bool   $update_chan
1152     *
1153     * @return void
1154     */
1155    public function createFact(string $gedcom, bool $update_chan)
1156    {
1157        $this->updateFact('', $gedcom, $update_chan);
1158    }
1159
1160    /**
1161     * Delete a fact from this record
1162     *
1163     * @param string $fact_id
1164     * @param bool   $update_chan
1165     *
1166     * @return void
1167     */
1168    public function deleteFact(string $fact_id, bool $update_chan)
1169    {
1170        $this->updateFact($fact_id, '', $update_chan);
1171    }
1172
1173    /**
1174     * Replace a fact with a new gedcom data.
1175     *
1176     * @param string $fact_id
1177     * @param string $gedcom
1178     * @param bool   $update_chan
1179     *
1180     * @return void
1181     * @throws Exception
1182     */
1183    public function updateFact(string $fact_id, string $gedcom, bool $update_chan)
1184    {
1185        // MSDOS line endings will break things in horrible ways
1186        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1187        $gedcom = trim($gedcom);
1188
1189        if ($this->pending === '') {
1190            throw new Exception('Cannot edit a deleted record');
1191        }
1192        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
1193            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1194        }
1195
1196        if ($this->pending) {
1197            $old_gedcom = $this->pending;
1198        } else {
1199            $old_gedcom = $this->gedcom;
1200        }
1201
1202        // First line of record may contain data - e.g. NOTE records.
1203        [$new_gedcom] = explode("\n", $old_gedcom, 2);
1204
1205        // Replacing (or deleting) an existing fact
1206        foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) {
1207            if (!$fact->isPendingDeletion()) {
1208                if ($fact->id() === $fact_id) {
1209                    if ($gedcom !== '') {
1210                        $new_gedcom .= "\n" . $gedcom;
1211                    }
1212                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1213                } elseif ($fact->getTag() != 'CHAN' || !$update_chan) {
1214                    $new_gedcom .= "\n" . $fact->gedcom();
1215                }
1216            }
1217        }
1218        if ($update_chan) {
1219            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1220        }
1221
1222        // Adding a new fact
1223        if ($fact_id === '') {
1224            $new_gedcom .= "\n" . $gedcom;
1225        }
1226
1227        if ($new_gedcom != $old_gedcom) {
1228            // Save the changes
1229            DB::table('change')->insert([
1230                'gedcom_id'  => $this->tree->id(),
1231                'xref'       => $this->xref,
1232                'old_gedcom' => $old_gedcom,
1233                'new_gedcom' => $new_gedcom,
1234                'user_id'    => Auth::id(),
1235            ]);
1236
1237            $this->pending = $new_gedcom;
1238
1239            if (Auth::user()->getPreference('auto_accept')) {
1240                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1241                $this->gedcom  = $new_gedcom;
1242                $this->pending = null;
1243            }
1244        }
1245        $this->parseFacts();
1246    }
1247
1248    /**
1249     * Update this record
1250     *
1251     * @param string $gedcom
1252     * @param bool   $update_chan
1253     *
1254     * @return void
1255     */
1256    public function updateRecord(string $gedcom, bool $update_chan)
1257    {
1258        // MSDOS line endings will break things in horrible ways
1259        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1260        $gedcom = trim($gedcom);
1261
1262        // Update the CHAN record
1263        if ($update_chan) {
1264            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1265            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1266        }
1267
1268        // Create a pending change
1269        DB::table('change')->insert([
1270            'gedcom_id'  => $this->tree->id(),
1271            'xref'       => $this->xref,
1272            'old_gedcom' => $this->gedcom(),
1273            'new_gedcom' => $gedcom,
1274            'user_id'    => Auth::id(),
1275        ]);
1276
1277        // Clear the cache
1278        $this->pending = $gedcom;
1279
1280        // Accept this pending change
1281        if (Auth::user()->getPreference('auto_accept')) {
1282            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1283            $this->gedcom  = $gedcom;
1284            $this->pending = null;
1285        }
1286
1287        $this->parseFacts();
1288
1289        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1290    }
1291
1292    /**
1293     * Delete this record
1294     *
1295     * @return void
1296     */
1297    public function deleteRecord()
1298    {
1299        // Create a pending change
1300        if (!$this->isPendingDeletion()) {
1301            DB::table('change')->insert([
1302                'gedcom_id'  => $this->tree->id(),
1303                'xref'       => $this->xref,
1304                'old_gedcom' => $this->gedcom(),
1305                'new_gedcom' => '',
1306                'user_id'    => Auth::id(),
1307            ]);
1308        }
1309
1310        // Auto-accept this pending change
1311        if (Auth::user()->getPreference('auto_accept')) {
1312            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1313        }
1314
1315        // Clear the cache
1316        self::$gedcom_record_cache  = [];
1317        self::$pending_record_cache = [];
1318
1319        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1320    }
1321
1322    /**
1323     * Remove all links from this record to $xref
1324     *
1325     * @param string $xref
1326     * @param bool   $update_chan
1327     *
1328     * @return void
1329     */
1330    public function removeLinks(string $xref, bool $update_chan)
1331    {
1332        $value = '@' . $xref . '@';
1333
1334        foreach ($this->facts() as $fact) {
1335            if ($fact->value() === $value) {
1336                $this->deleteFact($fact->id(), $update_chan);
1337            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1338                $gedcom = $fact->gedcom();
1339                foreach ($matches as $match) {
1340                    $next_level  = $match[1] + 1;
1341                    $next_levels = '[' . $next_level . '-9]';
1342                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1343                }
1344                $this->updateFact($fact->id(), $gedcom, $update_chan);
1345            }
1346        }
1347    }
1348
1349    /**
1350     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1351     * also delete all links to it.
1352     *
1353     * @return GedcomRecord[]
1354     */
1355    public function linkingRecords(): array
1356    {
1357        $union = DB::table('change')
1358            ->where('gedcom_id', '=', $this->tree()->id())
1359            ->whereContains('new_gedcom', '@' . $this->xref() . '@')
1360            ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%')
1361            ->select(['xref']);
1362
1363        $xrefs = DB::table('link')
1364            ->where('l_file', '=', $this->tree()->id())
1365            ->where('l_to', '=', $this->xref())
1366            ->select('l_from')
1367            ->union($union)
1368            ->pluck('l_from');
1369
1370        return $xrefs->map(function (string $xref): GedcomRecord {
1371            return GedcomRecord::getInstance($xref, $this->tree);
1372        })->all();
1373    }
1374}
1375