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