xref: /webtrees/app/GedcomRecord.php (revision 589feda391b943b928aea0b4107591eb0e7bbf89)
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 Cached result */
63    protected $getPrimaryName;
64
65    /** @var int 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                foreach ($rows as $row) {
170                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
171                }
172            }
173
174            if (isset(self::$pending_record_cache[$tree_id][$xref])) {
175                // A pending edit exists for this record
176                $pending = self::$pending_record_cache[$tree_id][$xref];
177            } else {
178                $pending = null;
179            }
180        } else {
181            // There are no pending changes for this record
182            $pending = null;
183        }
184
185        // No such record exists
186        if ($gedcom === null && $pending === null) {
187            return null;
188        }
189
190        // Create the object
191        if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom . $pending, $match)) {
192            $xref = $match[1]; // Collation - we may have requested I123 and found i123
193            $type = $match[2];
194        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
195            $xref = $match[1];
196            $type = $match[1];
197        } elseif ($gedcom . $pending) {
198            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
199        } else {
200            // A record with both pending creation and pending deletion
201            $type = static::RECORD_TYPE;
202        }
203
204        switch ($type) {
205            case 'INDI':
206                $record = new Individual($xref, $gedcom, $pending, $tree);
207                break;
208            case 'FAM':
209                $record = new Family($xref, $gedcom, $pending, $tree);
210                break;
211            case 'SOUR':
212                $record = new Source($xref, $gedcom, $pending, $tree);
213                break;
214            case 'OBJE':
215                $record = new Media($xref, $gedcom, $pending, $tree);
216                break;
217            case 'REPO':
218                $record = new Repository($xref, $gedcom, $pending, $tree);
219                break;
220            case 'NOTE':
221                $record = new Note($xref, $gedcom, $pending, $tree);
222                break;
223            default:
224                $record = new self($xref, $gedcom, $pending, $tree);
225                break;
226        }
227
228        // Store it in the cache
229        self::$gedcom_record_cache[$xref][$tree_id] = $record;
230
231        return $record;
232    }
233
234    /**
235     * Fetch data from the database
236     *
237     * @param string $xref
238     * @param int    $tree_id
239     *
240     * @return null|string
241     */
242    protected static function fetchGedcomRecord(string $xref, int $tree_id)
243    {
244        // We don't know what type of object this is. Try each one in turn.
245        $data = Individual::fetchGedcomRecord($xref, $tree_id);
246        if ($data) {
247            return $data;
248        }
249        $data = Family::fetchGedcomRecord($xref, $tree_id);
250        if ($data) {
251            return $data;
252        }
253        $data = Source::fetchGedcomRecord($xref, $tree_id);
254        if ($data) {
255            return $data;
256        }
257        $data = Repository::fetchGedcomRecord($xref, $tree_id);
258        if ($data) {
259            return $data;
260        }
261        $data = Media::fetchGedcomRecord($xref, $tree_id);
262        if ($data) {
263            return $data;
264        }
265        $data = Note::fetchGedcomRecord($xref, $tree_id);
266        if ($data) {
267            return $data;
268        }
269
270        // Some other type of record...
271
272        return Database::prepare(
273            "SELECT o_gedcom FROM `##other` WHERE o_id = :xref AND o_file = :tree_id"
274        )->execute([
275            'xref'    => $xref,
276            'tree_id' => $tree_id,
277        ])->fetchOne();
278    }
279
280    /**
281     * Get the XREF for this record
282     *
283     * @return string
284     */
285    public function getXref(): string
286    {
287        return $this->xref;
288    }
289
290    /**
291     * Get the tree to which this record belongs
292     *
293     * @return Tree
294     */
295    public function getTree(): Tree
296    {
297        return $this->tree;
298    }
299
300    /**
301     * Application code should access data via Fact objects.
302     * This function exists to support old code.
303     *
304     * @return string
305     */
306    public function getGedcom()
307    {
308        return $this->pending ?? $this->gedcom;
309    }
310
311    /**
312     * Does this record have a pending change?
313     *
314     * @return bool
315     */
316    public function isPendingAddition(): bool
317    {
318        return $this->pending !== null;
319    }
320
321    /**
322     * Does this record have a pending deletion?
323     *
324     * @return bool
325     */
326    public function isPendingDeletion(): bool
327    {
328        return $this->pending === '';
329    }
330
331    /**
332     * Generate a URL to this record, suitable for use in HTML, etc.
333     *
334     * @deprecated
335     *
336     * @return string
337     */
338    public function getHtmlUrl(): string
339    {
340        return e($this->url());
341    }
342
343    /**
344     * Generate a URL to this record.
345     *
346     * @deprecated
347     *
348     * @return string
349     */
350    public function getRawUrl(): string
351    {
352        return $this->url();
353    }
354
355    /**
356     * Generate a URL to this record.
357     *
358     * @return string
359     */
360    public function url(): string
361    {
362        return route(static::ROUTE_NAME, [
363            'xref' => $this->getXref(),
364            'ged'  => $this->tree->getName(),
365        ]);
366    }
367
368    /**
369     * Work out whether this record can be shown to a user with a given access level
370     *
371     * @param int $access_level
372     *
373     * @return bool
374     */
375    private function canShowRecord(int $access_level): bool
376    {
377        // This setting would better be called "$ENABLE_PRIVACY"
378        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
379            return true;
380        }
381
382        // We should always be able to see our own record (unless an admin is applying download restrictions)
383        if ($this->getXref() === $this->tree->getUserPreference(Auth::user(), 'gedcomid') && $access_level === Auth::accessLevel($this->tree)) {
384            return true;
385        }
386
387        // Does this record have a RESN?
388        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
389            return Auth::PRIV_NONE >= $access_level;
390        }
391        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
392            return Auth::PRIV_USER >= $access_level;
393        }
394        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
395            return true;
396        }
397
398        // Does this record have a default RESN?
399        $individual_privacy = $this->tree->getIndividualPrivacy();
400        if (isset($individual_privacy[$this->getXref()])) {
401            return $individual_privacy[$this->getXref()] >= $access_level;
402        }
403
404        // Privacy rules do not apply to admins
405        if (Auth::PRIV_NONE >= $access_level) {
406            return true;
407        }
408
409        // Different types of record have different privacy rules
410        return $this->canShowByType($access_level);
411    }
412
413    /**
414     * Each object type may have its own special rules, and re-implement this function.
415     *
416     * @param int $access_level
417     *
418     * @return bool
419     */
420    protected function canShowByType(int $access_level): bool
421    {
422        $fact_privacy = $this->tree->getFactPrivacy();
423
424        if (isset($fact_privacy[static::RECORD_TYPE])) {
425            // Restriction found
426            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
427        }
428
429        // No restriction found - must be public:
430        return true;
431    }
432
433    /**
434     * Can the details of this record be shown?
435     *
436     * @param int|null $access_level
437     *
438     * @return bool
439     */
440    public function canShow(int $access_level = null): bool
441    {
442        if ($access_level === null) {
443            $access_level = Auth::accessLevel($this->tree);
444        }
445
446        // CACHING: this function can take three different parameters,
447        // and therefore needs three different caches for the result.
448        switch ($access_level) {
449            case Auth::PRIV_PRIVATE: // visitor
450                if ($this->disp_public === null) {
451                    $this->disp_public = $this->canShowRecord(Auth::PRIV_PRIVATE);
452                }
453
454                return $this->disp_public;
455            case Auth::PRIV_USER: // member
456                if ($this->disp_user === null) {
457                    $this->disp_user = $this->canShowRecord(Auth::PRIV_USER);
458                }
459
460                return $this->disp_user;
461            case Auth::PRIV_NONE: // admin
462                if ($this->disp_none === null) {
463                    $this->disp_none = $this->canShowRecord(Auth::PRIV_NONE);
464                }
465
466                return $this->disp_none;
467            case Auth::PRIV_HIDE: // hidden from admins
468                // We use this value to bypass privacy checks. For example,
469                // when downloading data or when calculating privacy itself.
470                return true;
471            default:
472                // Should never get here.
473                return false;
474        }
475    }
476
477    /**
478     * Can the name of this record be shown?
479     *
480     * @param int|null $access_level
481     *
482     * @return bool
483     */
484    public function canShowName(int $access_level = null): bool
485    {
486        if ($access_level === null) {
487            $access_level = Auth::accessLevel($this->tree);
488        }
489
490        return $this->canShow($access_level);
491    }
492
493    /**
494     * Can we edit this record?
495     *
496     * @return bool
497     */
498    public function canEdit(): bool
499    {
500        return Auth::isManager($this->tree) || Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
501    }
502
503    /**
504     * Remove private data from the raw gedcom record.
505     * Return both the visible and invisible data. We need the invisible data when editing.
506     *
507     * @param int $access_level
508     *
509     * @return string
510     */
511    public function privatizeGedcom(int $access_level)
512    {
513        if ($access_level == Auth::PRIV_HIDE) {
514            // We may need the original record, for example when downloading a GEDCOM or clippings cart
515            return $this->gedcom;
516        }
517
518        if ($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        }
531
532        // We cannot display the details, but we may be able to display
533        // limited data, such as links to other records.
534        return $this->createPrivateGedcomRecord($access_level);
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(), '');
636                }
637            } else {
638                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
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(int $n = null)
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            }
747
748            return -1; // only $y is private
749        }
750
751        if ($y->canShowName()) {
752            return 1; // only $x is private
753        }
754
755        return 0; // both $x and $y private
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        }
770
771        return I18N::translate('Private');
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        }
799
800        return null;
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|int
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            }
1175
1176            return strip_tags(FunctionsDate::formatTimestamp($t));
1177        }
1178
1179        // The record does not have a CHAN event
1180        if ($sorting) {
1181            return '0';
1182        }
1183
1184        return '';
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        }
1199
1200        $chan_user = $chan->getAttribute('_WT_USER');
1201        if ($chan_user === '') {
1202            return I18N::translate('Unknown');
1203        }
1204
1205        return $chan_user;
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, '', $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