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