xref: /webtrees/app/GedcomRecord.php (revision bf4eb5429295fac4d577af25e48680f677a30acd)
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 stdClass;
27
28/**
29 * A GEDCOM object.
30 */
31class GedcomRecord
32{
33    const RECORD_TYPE = 'UNKNOWN';
34    const ROUTE_NAME  = 'record';
35
36    /** @var string The record identifier */
37    protected $xref;
38
39    /** @var Tree  The family tree to which this record belongs */
40    protected $tree;
41
42    /** @var string  GEDCOM data (before any pending edits) */
43    protected $gedcom;
44
45    /** @var string|null  GEDCOM data (after any pending edits) */
46    protected $pending;
47
48    /** @var Fact[] facts extracted from $gedcom/$pending */
49    protected $facts;
50
51    /** @var bool Can we display details of this record to Auth::PRIV_PRIVATE */
52    private $disp_public;
53
54    /** @var bool Can we display details of this record to Auth::PRIV_USER */
55    private $disp_user;
56
57    /** @var bool Can we display details of this record to Auth::PRIV_NONE */
58    private $disp_none;
59
60    /** @var string[][] All the names of this individual */
61    protected $getAllNames;
62
63    /** @var int|null Cached result */
64    protected $getPrimaryName;
65
66    /** @var int|null Cached result */
67    protected $getSecondaryName;
68
69    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
70    protected static $gedcom_record_cache;
71
72    /** @var stdClass[][] Fetch all pending edits in one database query */
73    private static $pending_record_cache;
74
75    /**
76     * Create a GedcomRecord object from raw GEDCOM data.
77     *
78     * @param string      $xref
79     * @param string      $gedcom  an empty string for new/pending records
80     * @param string|null $pending null for a record with no pending edits,
81     *                             empty string for records with pending deletions
82     * @param Tree        $tree
83     */
84    public function __construct(string $xref, string $gedcom, $pending, Tree $tree)
85    {
86        $this->xref    = $xref;
87        $this->gedcom  = $gedcom;
88        $this->pending = $pending;
89        $this->tree    = $tree;
90
91        $this->parseFacts();
92    }
93
94    /**
95     * Split the record into facts
96     *
97     * @return void
98     */
99    private function parseFacts()
100    {
101        // Split the record into facts
102        if ($this->gedcom) {
103            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
104            array_shift($gedcom_facts);
105        } else {
106            $gedcom_facts = [];
107        }
108        if ($this->pending) {
109            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
110            array_shift($pending_facts);
111        } else {
112            $pending_facts = [];
113        }
114
115        $this->facts = [];
116
117        foreach ($gedcom_facts as $gedcom_fact) {
118            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
119            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts)) {
120                $fact->setPendingDeletion();
121            }
122            $this->facts[] = $fact;
123        }
124        foreach ($pending_facts as $pending_fact) {
125            if (!in_array($pending_fact, $gedcom_facts)) {
126                $fact = new Fact($pending_fact, $this, md5($pending_fact));
127                $fact->setPendingAddition();
128                $this->facts[] = $fact;
129            }
130        }
131    }
132
133    /**
134     * Get an instance of a GedcomRecord object. For single records,
135     * we just receive the XREF. For bulk records (such as lists
136     * and search results) we can receive the GEDCOM data as well.
137     *
138     * @param string      $xref
139     * @param Tree        $tree
140     * @param string|null $gedcom
141     *
142     * @throws Exception
143     *
144     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|null
145     */
146    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
147    {
148        $tree_id = $tree->id();
149
150        // Is this record already in the cache?
151        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
152            return self::$gedcom_record_cache[$xref][$tree_id];
153        }
154
155        // Do we need to fetch the record from the database?
156        if ($gedcom === null) {
157            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
158        }
159
160        // If we can edit, then we also need to be able to see pending records.
161        if (Auth::isEditor($tree)) {
162            if (!isset(self::$pending_record_cache[$tree_id])) {
163                // Fetch all pending records in one database query
164                self::$pending_record_cache[$tree_id] = [];
165                $rows                                 = Database::prepare(
166                    "SELECT xref, new_gedcom FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id ORDER BY change_id"
167                )->execute([
168                    'tree_id' => $tree_id,
169                ])->fetchAll();
170
171                foreach ($rows as $row) {
172                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
173                }
174            }
175
176            $pending = self::$pending_record_cache[$tree_id][$xref] ?? null;
177        } else {
178            // There are no pending changes for this record
179            $pending = null;
180        }
181
182        // No such record exists
183        if ($gedcom === null && $pending === null) {
184            return null;
185        }
186
187        // No such record, but a pending creation exists
188        if ($gedcom === null) {
189            $gedcom = '';
190        }
191
192        // Create the object
193        if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedcom . $pending, $match)) {
194            $xref = $match[1]; // Collation - we may have requested I123 and found i123
195            $type = $match[2];
196        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
197            $xref = $match[1];
198            $type = $match[1];
199        } elseif ($gedcom . $pending) {
200            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
201        } else {
202            // A record with both pending creation and pending deletion
203            $type = static::RECORD_TYPE;
204        }
205
206        switch ($type) {
207            case 'INDI':
208                $record = new Individual($xref, $gedcom, $pending, $tree);
209                break;
210            case 'FAM':
211                $record = new Family($xref, $gedcom, $pending, $tree);
212                break;
213            case 'SOUR':
214                $record = new Source($xref, $gedcom, $pending, $tree);
215                break;
216            case 'OBJE':
217                $record = new Media($xref, $gedcom, $pending, $tree);
218                break;
219            case 'REPO':
220                $record = new Repository($xref, $gedcom, $pending, $tree);
221                break;
222            case 'NOTE':
223                $record = new Note($xref, $gedcom, $pending, $tree);
224                break;
225            default:
226                $record = new self($xref, $gedcom, $pending, $tree);
227                break;
228        }
229
230        // Store it in the cache
231        self::$gedcom_record_cache[$xref][$tree_id] = $record;
232
233        return $record;
234    }
235
236    /**
237     * Fetch data from the database
238     *
239     * @param string $xref
240     * @param int    $tree_id
241     *
242     * @return null|string
243     */
244    protected static function fetchGedcomRecord(string $xref, int $tree_id)
245    {
246        // We don't know what type of object this is. Try each one in turn.
247        $data = Individual::fetchGedcomRecord($xref, $tree_id);
248        if ($data) {
249            return $data;
250        }
251        $data = Family::fetchGedcomRecord($xref, $tree_id);
252        if ($data) {
253            return $data;
254        }
255        $data = Source::fetchGedcomRecord($xref, $tree_id);
256        if ($data) {
257            return $data;
258        }
259        $data = Repository::fetchGedcomRecord($xref, $tree_id);
260        if ($data) {
261            return $data;
262        }
263        $data = Media::fetchGedcomRecord($xref, $tree_id);
264        if ($data) {
265            return $data;
266        }
267        $data = Note::fetchGedcomRecord($xref, $tree_id);
268        if ($data) {
269            return $data;
270        }
271
272        // Some other type of record...
273
274        return Database::prepare(
275            "SELECT o_gedcom FROM `##other` WHERE o_id = :xref AND o_file = :tree_id"
276        )->execute([
277            'xref'    => $xref,
278            'tree_id' => $tree_id,
279        ])->fetchOne();
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 = Database::prepare(
847            "SELECT i_id AS xref, i_gedcom AS gedcom" .
848            " FROM `##individuals`" .
849            " JOIN `##link` ON i_file = l_file AND i_id = l_from" .
850            " LEFT JOIN `##name` ON i_file = n_file AND i_id = n_id AND n_num = 0" .
851            " WHERE i_file = :tree_id AND l_type = :link AND l_to = :xref" .
852            " ORDER BY n_sort COLLATE :collation"
853        )->execute([
854            'tree_id'   => $this->tree->id(),
855            'link'      => $link,
856            'xref'      => $this->xref,
857            'collation' => I18N::collation(),
858        ])->fetchAll();
859
860        $list = [];
861        foreach ($rows as $row) {
862            $record = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
863            if ($record->canShowName()) {
864                $list[] = $record;
865            }
866        }
867
868        return $list;
869    }
870
871    /**
872     * Find families linked to this record.
873     *
874     * @param string $link
875     *
876     * @return Family[]
877     */
878    public function linkedFamilies(string $link): array
879    {
880        $rows = Database::prepare(
881            "SELECT f_id AS xref, f_gedcom AS gedcom" .
882            " FROM `##families`" .
883            " JOIN `##link` ON f_file = l_file AND f_id = l_from" .
884            " LEFT JOIN `##name` ON f_file = n_file AND f_id = n_id AND n_num = 0" .
885            " WHERE f_file = :tree_id AND l_type = :link AND l_to = :xref"
886        )->execute([
887            'tree_id' => $this->tree->id(),
888            'link'    => $link,
889            'xref'    => $this->xref,
890        ])->fetchAll();
891
892        $list = [];
893        foreach ($rows as $row) {
894            $record = Family::getInstance($row->xref, $this->tree, $row->gedcom);
895            if ($record->canShowName()) {
896                $list[] = $record;
897            }
898        }
899
900        return $list;
901    }
902
903    /**
904     * Find sources linked to this record.
905     *
906     * @param string $link
907     *
908     * @return Source[]
909     */
910    public function linkedSources(string $link): array
911    {
912        $rows = Database::prepare(
913            "SELECT s_id AS xref, s_gedcom AS gedcom" .
914            " FROM `##sources`" .
915            " JOIN `##link` ON s_file = l_file AND s_id = l_from" .
916            " WHERE s_file = :tree_id AND l_type = :link AND l_to = :xref" .
917            " ORDER BY s_name COLLATE :collation"
918        )->execute([
919            'tree_id'   => $this->tree->id(),
920            'link'      => $link,
921            'xref'      => $this->xref,
922            'collation' => I18N::collation(),
923        ])->fetchAll();
924
925        $list = [];
926        foreach ($rows as $row) {
927            $record = Source::getInstance($row->xref, $this->tree, $row->gedcom);
928            if ($record->canShowName()) {
929                $list[] = $record;
930            }
931        }
932
933        return $list;
934    }
935
936    /**
937     * Find media objects linked to this record.
938     *
939     * @param string $link
940     *
941     * @return Media[]
942     */
943    public function linkedMedia(string $link): array
944    {
945        $rows = Database::prepare(
946            "SELECT m_id AS xref, m_gedcom AS gedcom" .
947            " FROM `##media`" .
948            " JOIN `##link` ON m_file = l_file AND m_id = l_from" .
949            " WHERE m_file = :tree_id AND l_type = :link AND l_to = :xref"
950        )->execute([
951            'tree_id' => $this->tree->id(),
952            'link'    => $link,
953            'xref'    => $this->xref,
954        ])->fetchAll();
955
956        $list = [];
957        foreach ($rows as $row) {
958            $record = Media::getInstance($row->xref, $this->tree, $row->gedcom);
959            if ($record->canShowName()) {
960                $list[] = $record;
961            }
962        }
963
964        return $list;
965    }
966
967    /**
968     * Find notes linked to this record.
969     *
970     * @param string $link
971     *
972     * @return Note[]
973     */
974    public function linkedNotes(string $link): array
975    {
976        $rows = Database::prepare(
977            "SELECT o_id AS xref, o_gedcom AS gedcom" .
978            " FROM `##other`" .
979            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
980            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
981            " WHERE o_file = :tree_id AND o_type = 'NOTE' AND l_type = :link AND l_to = :xref" .
982            " ORDER BY n_sort COLLATE :collation"
983        )->execute([
984            'tree_id'   => $this->tree->id(),
985            'link'      => $link,
986            'xref'      => $this->xref,
987            'collation' => I18N::collation(),
988        ])->fetchAll();
989
990        $list = [];
991        foreach ($rows as $row) {
992            $record = Note::getInstance($row->xref, $this->tree, $row->gedcom);
993            if ($record->canShowName()) {
994                $list[] = $record;
995            }
996        }
997
998        return $list;
999    }
1000
1001    /**
1002     * Find repositories linked to this record.
1003     *
1004     * @param string $link
1005     *
1006     * @return Repository[]
1007     */
1008    public function linkedRepositories(string $link): array
1009    {
1010        $rows = Database::prepare(
1011            "SELECT o_id AS xref, o_gedcom AS gedcom" .
1012            " FROM `##other`" .
1013            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
1014            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
1015            " WHERE o_file = :tree_id AND o_type = 'REPO' AND l_type = :link AND l_to = :xref" .
1016            " ORDER BY n_sort COLLATE :collation"
1017        )->execute([
1018            'tree_id'   => $this->tree->id(),
1019            'link'      => $link,
1020            'xref'      => $this->xref,
1021            'collation' => I18N::collation(),
1022        ])->fetchAll();
1023
1024        $list = [];
1025        foreach ($rows as $row) {
1026            $record = Repository::getInstance($row->xref, $this->tree, $row->gedcom);
1027            if ($record->canShowName()) {
1028                $list[] = $record;
1029            }
1030        }
1031
1032        return $list;
1033    }
1034
1035    /**
1036     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
1037     * This is used to display multiple events on the individual/family lists.
1038     * Multiple events can exist because of uncertainty in dates, dates in different
1039     * calendars, place-names in both latin and hebrew character sets, etc.
1040     * It also allows us to combine dates/places from different events in the summaries.
1041     *
1042     * @param string[] $events
1043     *
1044     * @return Date[]
1045     */
1046    public function getAllEventDates(array $events): array
1047    {
1048        $dates = [];
1049        foreach ($this->facts($events) as $event) {
1050            if ($event->date()->isOK()) {
1051                $dates[] = $event->date();
1052            }
1053        }
1054
1055        return $dates;
1056    }
1057
1058    /**
1059     * Get all the places for a particular type of event
1060     *
1061     * @param string[] $events
1062     *
1063     * @return Place[]
1064     */
1065    public function getAllEventPlaces(array $events): array
1066    {
1067        $places = [];
1068        foreach ($this->facts($events) as $event) {
1069            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
1070                foreach ($ged_places[1] as $ged_place) {
1071                    $places[] = new Place($ged_place, $this->tree);
1072                }
1073            }
1074        }
1075
1076        return $places;
1077    }
1078
1079    /**
1080     * Get the first (i.e. prefered) Fact for the given fact type
1081     *
1082     * @param string $tag
1083     *
1084     * @return Fact|null
1085     */
1086    public function getFirstFact(string $tag)
1087    {
1088        foreach ($this->facts() as $fact) {
1089            if ($fact->getTag() === $tag) {
1090                return $fact;
1091            }
1092        }
1093
1094        return null;
1095    }
1096
1097    /**
1098     * The facts and events for this record.
1099     *
1100     * @param string[] $filter
1101     * @param bool     $sort
1102     * @param int|null $access_level
1103     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1104     *
1105     * @return Fact[]
1106     */
1107    public function facts(array $filter = [], bool $sort = false, int $access_level = null, bool $override = false): array
1108    {
1109        if ($access_level === null) {
1110            $access_level = Auth::accessLevel($this->tree);
1111        }
1112
1113        $facts = [];
1114        if ($this->canShow($access_level) || $override) {
1115            foreach ($this->facts as $fact) {
1116                if (($filter === [] || in_array($fact->getTag(), $filter)) && $fact->canShow($access_level)) {
1117                    $facts[] = $fact;
1118                }
1119            }
1120        }
1121
1122        if ($sort) {
1123            Functions::sortFacts($facts);
1124        }
1125
1126        return $facts;
1127    }
1128
1129    /**
1130     * Get the last-change timestamp for this record, either as a formatted string
1131     * (for display) or as a unix timestamp (for sorting)
1132     *
1133     * @param bool $sorting
1134     *
1135     * @return string|int
1136     */
1137    public function lastChangeTimestamp(bool $sorting = false)
1138    {
1139        $chan = $this->getFirstFact('CHAN');
1140
1141        if ($chan) {
1142            // The record does have a CHAN event
1143            $d = $chan->date()->minimumDate();
1144            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1145                $t = mktime((int) $match[1], (int) $match[2], (int) $match[3], (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1146            } elseif (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1147                $t = mktime((int) $match[1], (int) $match[2], 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1148            } else {
1149                $t = mktime(0, 0, 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1150            }
1151            if ($sorting) {
1152                return $t;
1153            }
1154
1155            return strip_tags(FunctionsDate::formatTimestamp($t));
1156        }
1157
1158        // The record does not have a CHAN event
1159        if ($sorting) {
1160            return '0';
1161        }
1162
1163        return '';
1164    }
1165
1166    /**
1167     * Get the last-change user for this record
1168     *
1169     * @return string
1170     */
1171    public function lastChangeUser()
1172    {
1173        $chan = $this->getFirstFact('CHAN');
1174
1175        if ($chan === null) {
1176            return I18N::translate('Unknown');
1177        }
1178
1179        $chan_user = $chan->attribute('_WT_USER');
1180        if ($chan_user === '') {
1181            return I18N::translate('Unknown');
1182        }
1183
1184        return $chan_user;
1185    }
1186
1187    /**
1188     * Add a new fact to this record
1189     *
1190     * @param string $gedcom
1191     * @param bool   $update_chan
1192     *
1193     * @return void
1194     */
1195    public function createFact(string $gedcom, bool $update_chan)
1196    {
1197        $this->updateFact('', $gedcom, $update_chan);
1198    }
1199
1200    /**
1201     * Delete a fact from this record
1202     *
1203     * @param string $fact_id
1204     * @param bool   $update_chan
1205     *
1206     * @return void
1207     */
1208    public function deleteFact(string $fact_id, bool $update_chan)
1209    {
1210        $this->updateFact($fact_id, '', $update_chan);
1211    }
1212
1213    /**
1214     * Replace a fact with a new gedcom data.
1215     *
1216     * @param string $fact_id
1217     * @param string $gedcom
1218     * @param bool   $update_chan
1219     *
1220     * @return void
1221     * @throws Exception
1222     */
1223    public function updateFact(string $fact_id, string $gedcom, bool $update_chan)
1224    {
1225        // MSDOS line endings will break things in horrible ways
1226        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1227        $gedcom = trim($gedcom);
1228
1229        if ($this->pending === '') {
1230            throw new Exception('Cannot edit a deleted record');
1231        }
1232        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
1233            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1234        }
1235
1236        if ($this->pending) {
1237            $old_gedcom = $this->pending;
1238        } else {
1239            $old_gedcom = $this->gedcom;
1240        }
1241
1242        // First line of record may contain data - e.g. NOTE records.
1243        [$new_gedcom] = explode("\n", $old_gedcom, 2);
1244
1245        // Replacing (or deleting) an existing fact
1246        foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) {
1247            if (!$fact->isPendingDeletion()) {
1248                if ($fact->id() === $fact_id) {
1249                    if ($gedcom !== '') {
1250                        $new_gedcom .= "\n" . $gedcom;
1251                    }
1252                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1253                } elseif ($fact->getTag() != 'CHAN' || !$update_chan) {
1254                    $new_gedcom .= "\n" . $fact->gedcom();
1255                }
1256            }
1257        }
1258        if ($update_chan) {
1259            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1260        }
1261
1262        // Adding a new fact
1263        if ($fact_id === '') {
1264            $new_gedcom .= "\n" . $gedcom;
1265        }
1266
1267        if ($new_gedcom != $old_gedcom) {
1268            // Save the changes
1269            Database::prepare(
1270                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
1271            )->execute([
1272                $this->tree->id(),
1273                $this->xref,
1274                $old_gedcom,
1275                $new_gedcom,
1276                Auth::id(),
1277            ]);
1278
1279            $this->pending = $new_gedcom;
1280
1281            if (Auth::user()->getPreference('auto_accept')) {
1282                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1283                $this->gedcom  = $new_gedcom;
1284                $this->pending = null;
1285            }
1286        }
1287        $this->parseFacts();
1288    }
1289
1290    /**
1291     * Update this record
1292     *
1293     * @param string $gedcom
1294     * @param bool   $update_chan
1295     *
1296     * @return void
1297     */
1298    public function updateRecord(string $gedcom, bool $update_chan)
1299    {
1300        // MSDOS line endings will break things in horrible ways
1301        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1302        $gedcom = trim($gedcom);
1303
1304        // Update the CHAN record
1305        if ($update_chan) {
1306            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1307            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1308        }
1309
1310        // Create a pending change
1311        Database::prepare(
1312            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
1313        )->execute([
1314            $this->tree->id(),
1315            $this->xref,
1316            $this->gedcom(),
1317            $gedcom,
1318            Auth::id(),
1319        ]);
1320
1321        // Clear the cache
1322        $this->pending = $gedcom;
1323
1324        // Accept this pending change
1325        if (Auth::user()->getPreference('auto_accept')) {
1326            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1327            $this->gedcom  = $gedcom;
1328            $this->pending = null;
1329        }
1330
1331        $this->parseFacts();
1332
1333        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1334    }
1335
1336    /**
1337     * Delete this record
1338     *
1339     * @return void
1340     */
1341    public function deleteRecord()
1342    {
1343        // Create a pending change
1344        if (!$this->isPendingDeletion()) {
1345            Database::prepare(
1346                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, '', ?)"
1347            )->execute([
1348                $this->tree->id(),
1349                $this->xref,
1350                $this->gedcom(),
1351                Auth::id(),
1352            ]);
1353        }
1354
1355        // Auto-accept this pending change
1356        if (Auth::user()->getPreference('auto_accept')) {
1357            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1358        }
1359
1360        // Clear the cache
1361        self::$gedcom_record_cache  = [];
1362        self::$pending_record_cache = [];
1363
1364        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1365    }
1366
1367    /**
1368     * Remove all links from this record to $xref
1369     *
1370     * @param string $xref
1371     * @param bool   $update_chan
1372     *
1373     * @return void
1374     */
1375    public function removeLinks(string $xref, bool $update_chan)
1376    {
1377        $value = '@' . $xref . '@';
1378
1379        foreach ($this->facts() as $fact) {
1380            if ($fact->value() === $value) {
1381                $this->deleteFact($fact->id(), $update_chan);
1382            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1383                $gedcom = $fact->gedcom();
1384                foreach ($matches as $match) {
1385                    $next_level  = $match[1] + 1;
1386                    $next_levels = '[' . $next_level . '-9]';
1387                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1388                }
1389                $this->updateFact($fact->id(), $gedcom, $update_chan);
1390            }
1391        }
1392    }
1393
1394    /**
1395     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1396     * also delete all links to it.
1397     *
1398     * @return GedcomRecord[]
1399     */
1400    public function linkingRecords(): array
1401    {
1402        $union = DB::table('change')
1403            ->where('gedcom_id', '=', $this->tree()->id())
1404            ->where('new_gedcom', 'LIKE', '%@' . $this->xref() . '@%')
1405            ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%')
1406            ->select(['xref']);
1407
1408        $xrefs = DB::table('link')
1409            ->where('l_file', '=', $this->tree()->id())
1410            ->where('l_to', '=', $this->xref())
1411            ->select('l_from')
1412            ->union($union)
1413            ->pluck('l_from');
1414
1415        return $xrefs->map(function (string $xref): GedcomRecord {
1416            return GedcomRecord::getInstance($xref, $this->tree);
1417        })->all();
1418    }
1419}
1420