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