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