xref: /webtrees/app/GedcomRecord.php (revision 1f1ffa65b3b51df2b95b5c68894525436855964a)
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 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(): 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)) {
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 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 Individual[]
854     */
855    public function linkedIndividuals(string $link): array
856    {
857        $rows = DB::table('individuals')
858            ->join('link', static function (JoinClause $join): void {
859                $join->on('l_file', '=', 'i_file')->on('l_from', '=', 'i_id');
860            })
861            ->where('i_file', '=', $this->tree->id())
862            ->where('l_type', '=', $link)
863            ->where('l_to', '=', $this->xref)
864            ->select(['i_id AS xref', 'i_gedcom AS gedcom'])
865            ->get();
866
867        $list = [];
868        foreach ($rows as $row) {
869            $record = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
870            if ($record->canShowName()) {
871                $list[] = $record;
872            }
873        }
874
875        return $list;
876    }
877
878    /**
879     * Find families linked to this record.
880     *
881     * @param string $link
882     *
883     * @return Family[]
884     */
885    public function linkedFamilies(string $link): array
886    {
887        $rows = DB::table('families')
888            ->join('link', static function (JoinClause $join): void {
889                $join->on('l_file', '=', 'f_file')->on('l_from', '=', 'f_id');
890            })
891            ->where('f_file', '=', $this->tree->id())
892            ->where('l_type', '=', $link)
893            ->where('l_to', '=', $this->xref)
894            ->select(['f_id AS xref', 'f_gedcom AS gedcom'])
895            ->get();
896
897        $list = [];
898        foreach ($rows as $row) {
899            $record = Family::getInstance($row->xref, $this->tree, $row->gedcom);
900            if ($record->canShowName()) {
901                $list[] = $record;
902            }
903        }
904
905        return $list;
906    }
907
908    /**
909     * Find sources linked to this record.
910     *
911     * @param string $link
912     *
913     * @return Source[]
914     */
915    public function linkedSources(string $link): array
916    {
917        $rows = DB::table('sources')
918            ->join('link', static function (JoinClause $join): void {
919                $join->on('l_file', '=', 's_file')->on('l_from', '=', 's_id');
920            })
921            ->where('s_file', '=', $this->tree->id())
922            ->where('l_type', '=', $link)
923            ->where('l_to', '=', $this->xref)
924            ->select(['s_id AS xref', 's_gedcom AS gedcom'])
925            ->get();
926
927        $list = [];
928        foreach ($rows as $row) {
929            $record = Source::getInstance($row->xref, $this->tree, $row->gedcom);
930            if ($record->canShowName()) {
931                $list[] = $record;
932            }
933        }
934
935        return $list;
936    }
937
938    /**
939     * Find media objects linked to this record.
940     *
941     * @param string $link
942     *
943     * @return Media[]
944     */
945    public function linkedMedia(string $link): array
946    {
947        $rows = DB::table('media')
948            ->join('link', static function (JoinClause $join): void {
949                $join->on('l_file', '=', 'm_file')->on('l_from', '=', 'm_id');
950            })
951            ->where('m_file', '=', $this->tree->id())
952            ->where('l_type', '=', $link)
953            ->where('l_to', '=', $this->xref)
954            ->select(['m_id AS xref', 'm_gedcom AS gedcom'])
955            ->get();
956
957        $list = [];
958        foreach ($rows as $row) {
959            $record = Media::getInstance($row->xref, $this->tree, $row->gedcom);
960            if ($record->canShowName()) {
961                $list[] = $record;
962            }
963        }
964
965        return $list;
966    }
967
968    /**
969     * Find notes linked to this record.
970     *
971     * @param string $link
972     *
973     * @return Note[]
974     */
975    public function linkedNotes(string $link): array
976    {
977        $rows = DB::table('other')
978            ->join('link', static function (JoinClause $join): void {
979                $join->on('l_file', '=', 'o_file')->on('l_from', '=', 'o_id');
980            })
981            ->where('o_file', '=', $this->tree->id())
982            ->where('o_type', '=', 'NOTE')
983            ->where('l_type', '=', $link)
984            ->where('l_to', '=', $this->xref)
985            ->select(['o_id AS xref', 'o_gedcom AS gedcom'])
986            ->get();
987
988        $list = [];
989        foreach ($rows as $row) {
990            $record = Note::getInstance($row->xref, $this->tree, $row->gedcom);
991            if ($record->canShowName()) {
992                $list[] = $record;
993            }
994        }
995
996        return $list;
997    }
998
999    /**
1000     * Find repositories linked to this record.
1001     *
1002     * @param string $link
1003     *
1004     * @return Repository[]
1005     */
1006    public function linkedRepositories(string $link): array
1007    {
1008        $rows = DB::table('other')
1009            ->join('link', static function (JoinClause $join): void {
1010                $join->on('l_file', '=', 'o_file')->on('l_from', '=', 'o_id');
1011            })
1012            ->where('o_file', '=', $this->tree->id())
1013            ->where('o_type', '=', 'REPO')
1014            ->where('l_type', '=', $link)
1015            ->where('l_to', '=', $this->xref)
1016            ->select(['o_id AS xref', 'o_gedcom AS gedcom'])
1017            ->get();
1018
1019        $list = [];
1020        foreach ($rows as $row) {
1021            $record = Repository::getInstance($row->xref, $this->tree, $row->gedcom);
1022            if ($record->canShowName()) {
1023                $list[] = $record;
1024            }
1025        }
1026
1027        return $list;
1028    }
1029
1030    /**
1031     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
1032     * This is used to display multiple events on the individual/family lists.
1033     * Multiple events can exist because of uncertainty in dates, dates in different
1034     * calendars, place-names in both latin and hebrew character sets, etc.
1035     * It also allows us to combine dates/places from different events in the summaries.
1036     *
1037     * @param string[] $events
1038     *
1039     * @return Date[]
1040     */
1041    public function getAllEventDates(array $events): array
1042    {
1043        $dates = [];
1044        foreach ($this->facts($events) as $event) {
1045            if ($event->date()->isOK()) {
1046                $dates[] = $event->date();
1047            }
1048        }
1049
1050        return $dates;
1051    }
1052
1053    /**
1054     * Get all the places for a particular type of event
1055     *
1056     * @param string[] $events
1057     *
1058     * @return Place[]
1059     */
1060    public function getAllEventPlaces(array $events): array
1061    {
1062        $places = [];
1063        foreach ($this->facts($events) as $event) {
1064            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
1065                foreach ($ged_places[1] as $ged_place) {
1066                    $places[] = new Place($ged_place, $this->tree);
1067                }
1068            }
1069        }
1070
1071        return $places;
1072    }
1073
1074    /**
1075     * The facts and events for this record.
1076     *
1077     * @param string[] $filter
1078     * @param bool     $sort
1079     * @param int|null $access_level
1080     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1081     *
1082     * @return Collection
1083     * @return Fact[]
1084     */
1085    public function facts(array $filter = [], bool $sort = false, int $access_level = null, bool $override = false): Collection
1086    {
1087        if ($access_level === null) {
1088            $access_level = Auth::accessLevel($this->tree);
1089        }
1090
1091        $facts = new Collection();
1092        if ($this->canShow($access_level) || $override) {
1093            foreach ($this->facts as $fact) {
1094                if (($filter === [] || in_array($fact->getTag(), $filter)) && $fact->canShow($access_level)) {
1095                    $facts->push($fact);
1096                }
1097            }
1098        }
1099
1100        if ($sort) {
1101            $facts = Fact::sortFacts($facts);
1102        }
1103
1104        return new Collection($facts);
1105    }
1106
1107    /**
1108     * Get the last-change timestamp for this record
1109     *
1110     * @return Carbon
1111     */
1112    public function lastChangeTimestamp(): Carbon
1113    {
1114        /** @var Fact|null $chan */
1115        $chan = $this->facts(['CHAN'])->first();
1116
1117        if ($chan instanceof Fact) {
1118            // The record does have a CHAN event
1119            $d = $chan->date()->minimumDate();
1120
1121            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1122                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
1123            }
1124
1125            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1126                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
1127            }
1128
1129            return Carbon::create($d->year(), $d->month(), $d->day());
1130        }
1131
1132        // The record does not have a CHAN event
1133        return Carbon::createFromTimestamp(0);
1134    }
1135
1136    /**
1137     * Get the last-change user for this record
1138     *
1139     * @return string
1140     */
1141    public function lastChangeUser(): string
1142    {
1143        $chan = $this->facts(['CHAN'])->first();
1144
1145        if ($chan === null) {
1146            return I18N::translate('Unknown');
1147        }
1148
1149        $chan_user = $chan->attribute('_WT_USER');
1150        if ($chan_user === '') {
1151            return I18N::translate('Unknown');
1152        }
1153
1154        return $chan_user;
1155    }
1156
1157    /**
1158     * Add a new fact to this record
1159     *
1160     * @param string $gedcom
1161     * @param bool   $update_chan
1162     *
1163     * @return void
1164     */
1165    public function createFact(string $gedcom, bool $update_chan): void
1166    {
1167        $this->updateFact('', $gedcom, $update_chan);
1168    }
1169
1170    /**
1171     * Delete a fact from this record
1172     *
1173     * @param string $fact_id
1174     * @param bool   $update_chan
1175     *
1176     * @return void
1177     */
1178    public function deleteFact(string $fact_id, bool $update_chan): void
1179    {
1180        $this->updateFact($fact_id, '', $update_chan);
1181    }
1182
1183    /**
1184     * Replace a fact with a new gedcom data.
1185     *
1186     * @param string $fact_id
1187     * @param string $gedcom
1188     * @param bool   $update_chan
1189     *
1190     * @return void
1191     * @throws Exception
1192     */
1193    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
1194    {
1195        // MSDOS line endings will break things in horrible ways
1196        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1197        $gedcom = trim($gedcom);
1198
1199        if ($this->pending === '') {
1200            throw new Exception('Cannot edit a deleted record');
1201        }
1202        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
1203            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1204        }
1205
1206        if ($this->pending) {
1207            $old_gedcom = $this->pending;
1208        } else {
1209            $old_gedcom = $this->gedcom;
1210        }
1211
1212        // First line of record may contain data - e.g. NOTE records.
1213        [$new_gedcom] = explode("\n", $old_gedcom, 2);
1214
1215        // Replacing (or deleting) an existing fact
1216        foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) {
1217            if (!$fact->isPendingDeletion()) {
1218                if ($fact->id() === $fact_id) {
1219                    if ($gedcom !== '') {
1220                        $new_gedcom .= "\n" . $gedcom;
1221                    }
1222                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1223                } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) {
1224                    $new_gedcom .= "\n" . $fact->gedcom();
1225                }
1226            }
1227        }
1228        if ($update_chan) {
1229            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1230        }
1231
1232        // Adding a new fact
1233        if ($fact_id === '') {
1234            $new_gedcom .= "\n" . $gedcom;
1235        }
1236
1237        if ($new_gedcom !== $old_gedcom) {
1238            // Save the changes
1239            DB::table('change')->insert([
1240                'gedcom_id'  => $this->tree->id(),
1241                'xref'       => $this->xref,
1242                'old_gedcom' => $old_gedcom,
1243                'new_gedcom' => $new_gedcom,
1244                'user_id'    => Auth::id(),
1245            ]);
1246
1247            $this->pending = $new_gedcom;
1248
1249            if (Auth::user()->getPreference('auto_accept')) {
1250                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1251                $this->gedcom  = $new_gedcom;
1252                $this->pending = null;
1253            }
1254        }
1255        $this->parseFacts();
1256    }
1257
1258    /**
1259     * Update this record
1260     *
1261     * @param string $gedcom
1262     * @param bool   $update_chan
1263     *
1264     * @return void
1265     */
1266    public function updateRecord(string $gedcom, bool $update_chan): void
1267    {
1268        // MSDOS line endings will break things in horrible ways
1269        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1270        $gedcom = trim($gedcom);
1271
1272        // Update the CHAN record
1273        if ($update_chan) {
1274            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1275            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1276        }
1277
1278        // Create a pending change
1279        DB::table('change')->insert([
1280            'gedcom_id'  => $this->tree->id(),
1281            'xref'       => $this->xref,
1282            'old_gedcom' => $this->gedcom(),
1283            'new_gedcom' => $gedcom,
1284            'user_id'    => Auth::id(),
1285        ]);
1286
1287        // Clear the cache
1288        $this->pending = $gedcom;
1289
1290        // Accept this pending change
1291        if (Auth::user()->getPreference('auto_accept')) {
1292            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1293            $this->gedcom  = $gedcom;
1294            $this->pending = null;
1295        }
1296
1297        $this->parseFacts();
1298
1299        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1300    }
1301
1302    /**
1303     * Delete this record
1304     *
1305     * @return void
1306     */
1307    public function deleteRecord(): void
1308    {
1309        // Create a pending change
1310        if (!$this->isPendingDeletion()) {
1311            DB::table('change')->insert([
1312                'gedcom_id'  => $this->tree->id(),
1313                'xref'       => $this->xref,
1314                'old_gedcom' => $this->gedcom(),
1315                'new_gedcom' => '',
1316                'user_id'    => Auth::id(),
1317            ]);
1318        }
1319
1320        // Auto-accept this pending change
1321        if (Auth::user()->getPreference('auto_accept')) {
1322            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1323        }
1324
1325        // Clear the cache
1326        self::$gedcom_record_cache  = [];
1327        self::$pending_record_cache = [];
1328
1329        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1330    }
1331
1332    /**
1333     * Remove all links from this record to $xref
1334     *
1335     * @param string $xref
1336     * @param bool   $update_chan
1337     *
1338     * @return void
1339     */
1340    public function removeLinks(string $xref, bool $update_chan): void
1341    {
1342        $value = '@' . $xref . '@';
1343
1344        foreach ($this->facts() as $fact) {
1345            if ($fact->value() === $value) {
1346                $this->deleteFact($fact->id(), $update_chan);
1347            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1348                $gedcom = $fact->gedcom();
1349                foreach ($matches as $match) {
1350                    $next_level  = $match[1] + 1;
1351                    $next_levels = '[' . $next_level . '-9]';
1352                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1353                }
1354                $this->updateFact($fact->id(), $gedcom, $update_chan);
1355            }
1356        }
1357    }
1358
1359    /**
1360     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1361     * also delete all links to it.
1362     *
1363     * @return GedcomRecord[]
1364     */
1365    public function linkingRecords(): array
1366    {
1367        $union = DB::table('change')
1368            ->where('gedcom_id', '=', $this->tree()->id())
1369            ->whereContains('new_gedcom', '@' . $this->xref() . '@')
1370            ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%')
1371            ->select(['xref']);
1372
1373        $xrefs = DB::table('link')
1374            ->where('l_file', '=', $this->tree()->id())
1375            ->where('l_to', '=', $this->xref())
1376            ->select('l_from')
1377            ->union($union)
1378            ->pluck('l_from');
1379
1380        return $xrefs->map(function (string $xref): GedcomRecord {
1381            return GedcomRecord::getInstance($xref, $this->tree);
1382        })->all();
1383    }
1384}
1385