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