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