xref: /webtrees/app/GedcomRecord.php (revision 873953697c930fadbf3243d2b8c0029fd684da0e)
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     * @return void
608     */
609    public function extractNames()
610    {
611        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), null);
612    }
613
614    /**
615     * Derived classes should redefine this function, otherwise the object will have no name
616     *
617     * @return string[][]
618     */
619    public function getAllNames(): array
620    {
621        if ($this->getAllNames === null) {
622            $this->getAllNames = [];
623            if ($this->canShowName()) {
624                // Ask the record to extract its names
625                $this->extractNames();
626                // No name found? Use a fallback.
627                if (!$this->getAllNames) {
628                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), null);
629                }
630            } else {
631                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), null);
632            }
633        }
634
635        return $this->getAllNames;
636    }
637
638    /**
639     * If this object has no name, what do we call it?
640     *
641     * @return string
642     */
643    public function getFallBackName(): string
644    {
645        return e($this->getXref());
646    }
647
648    /**
649     * Which of the (possibly several) names of this record is the primary one.
650     *
651     * @return int
652     */
653    public function getPrimaryName(): int
654    {
655        static $language_script;
656
657        if ($language_script === null) {
658            $language_script = I18N::languageScript(WT_LOCALE);
659        }
660
661        if ($this->getPrimaryName === null) {
662            // Generally, the first name is the primary one....
663            $this->getPrimaryName = 0;
664            // ...except when the language/name use different character sets
665            foreach ($this->getAllNames() as $n => $name) {
666                if (I18N::textScript($name['sort']) === $language_script) {
667                    $this->getPrimaryName = $n;
668                    break;
669                }
670            }
671        }
672
673        return $this->getPrimaryName;
674    }
675
676    /**
677     * Which of the (possibly several) names of this record is the secondary one.
678     *
679     * @return int
680     */
681    public function getSecondaryName(): int
682    {
683        if ($this->getSecondaryName === null) {
684            // Generally, the primary and secondary names are the same
685            $this->getSecondaryName = $this->getPrimaryName();
686            // ....except when there are names with different character sets
687            $all_names = $this->getAllNames();
688            if (count($all_names) > 1) {
689                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
690                foreach ($all_names as $n => $name) {
691                    if ($n != $this->getPrimaryName() && $name['type'] != '_MARNM' && I18N::textScript($name['sort']) != $primary_script) {
692                        $this->getSecondaryName = $n;
693                        break;
694                    }
695                }
696            }
697        }
698
699        return $this->getSecondaryName;
700    }
701
702    /**
703     * Allow the choice of primary name to be overidden, e.g. in a search result
704     *
705     * @param int $n
706     */
707    public function setPrimaryName($n)
708    {
709        $this->getPrimaryName   = $n;
710        $this->getSecondaryName = null;
711    }
712
713    /**
714     * Allow native PHP functions such as array_unique() to work with objects
715     *
716     * @return string
717     */
718    public function __toString()
719    {
720        return $this->xref . '@' . $this->tree->getTreeId();
721    }
722
723    /**
724     * Static helper function to sort an array of objects by name
725     * Records whose names cannot be displayed are sorted at the end.
726     *
727     * @param GedcomRecord $x
728     * @param GedcomRecord $y
729     *
730     * @return int
731     */
732    public static function compare(GedcomRecord $x, GedcomRecord $y)
733    {
734        if ($x->canShowName()) {
735            if ($y->canShowName()) {
736                return I18N::strcasecmp($x->getSortName(), $y->getSortName());
737            } else {
738                return -1; // only $y is private
739            }
740        } else {
741            if ($y->canShowName()) {
742                return 1; // only $x is private
743            } else {
744                return 0; // both $x and $y private
745            }
746        }
747    }
748
749    /**
750     * Get variants of the name
751     *
752     * @return string
753     */
754    public function getFullName()
755    {
756        if ($this->canShowName()) {
757            $tmp = $this->getAllNames();
758
759            return $tmp[$this->getPrimaryName()]['full'];
760        } else {
761            return I18N::translate('Private');
762        }
763    }
764
765    /**
766     * Get a sortable version of the name. Do not display this!
767     *
768     * @return string
769     */
770    public function getSortName(): string
771    {
772        // The sortable name is never displayed, no need to call canShowName()
773        $tmp = $this->getAllNames();
774
775        return $tmp[$this->getPrimaryName()]['sort'];
776    }
777
778    /**
779     * Get the full name in an alternative character set
780     *
781     * @return null|string
782     */
783    public function getAddName()
784    {
785        if ($this->canShowName() && $this->getPrimaryName() != $this->getSecondaryName()) {
786            $all_names = $this->getAllNames();
787
788            return $all_names[$this->getSecondaryName()]['full'];
789        } else {
790            return null;
791        }
792    }
793
794    /**
795     * Format this object for display in a list
796     *
797     * @return string
798     */
799    public function formatList(): string
800    {
801        $html = '<a href="' . e($this->url()) . '" class="list_item">';
802        $html .= '<b>' . $this->getFullName() . '</b>';
803        $html .= $this->formatListDetails();
804        $html .= '</a>';
805
806        return $html;
807    }
808
809    /**
810     * This function should be redefined in derived classes to show any major
811     * identifying characteristics of this record.
812     *
813     * @return string
814     */
815    public function formatListDetails(): string
816    {
817        return '';
818    }
819
820    /**
821     * Extract/format the first fact from a list of facts.
822     *
823     * @param string $facts
824     * @param int    $style
825     *
826     * @return string
827     */
828    public function formatFirstMajorFact($facts, $style): string
829    {
830        foreach ($this->getFacts($facts, true) as $event) {
831            // Only display if it has a date or place (or both)
832            if ($event->getDate()->isOK() && !$event->getPlace()->isEmpty()) {
833                $joiner = ' — ';
834            } else {
835                $joiner = '';
836            }
837            if ($event->getDate()->isOK() || !$event->getPlace()->isEmpty()) {
838                switch ($style) {
839                    case 1:
840                        return '<br><em>' . $event->getLabel() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
841                    case 2:
842                        return '<dl><dt class="label">' . $event->getLabel() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
843                }
844            }
845        }
846
847        return '';
848    }
849
850    /**
851     * Find individuals linked to this record.
852     *
853     * @param string $link
854     *
855     * @return Individual[]
856     */
857    public function linkedIndividuals($link): array
858    {
859        $rows = Database::prepare(
860            "SELECT i_id AS xref, i_gedcom AS gedcom" .
861            " FROM `##individuals`" .
862            " JOIN `##link` ON i_file = l_file AND i_id = l_from" .
863            " LEFT JOIN `##name` ON i_file = n_file AND i_id = n_id AND n_num = 0" .
864            " WHERE i_file = :tree_id AND l_type = :link AND l_to = :xref" .
865            " ORDER BY n_sort COLLATE :collation"
866        )->execute([
867            'tree_id'   => $this->tree->getTreeId(),
868            'link'      => $link,
869            'xref'      => $this->xref,
870            'collation' => I18N::collation(),
871        ])->fetchAll();
872
873        $list = [];
874        foreach ($rows as $row) {
875            $record = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
876            if ($record->canShowName()) {
877                $list[] = $record;
878            }
879        }
880
881        return $list;
882    }
883
884    /**
885     * Find families linked to this record.
886     *
887     * @param string $link
888     *
889     * @return Family[]
890     */
891    public function linkedFamilies($link): array
892    {
893        $rows = Database::prepare(
894            "SELECT f_id AS xref, f_gedcom AS gedcom" .
895            " FROM `##families`" .
896            " JOIN `##link` ON f_file = l_file AND f_id = l_from" .
897            " LEFT JOIN `##name` ON f_file = n_file AND f_id = n_id AND n_num = 0" .
898            " WHERE f_file = :tree_id AND l_type = :link AND l_to = :xref"
899        )->execute([
900            'tree_id' => $this->tree->getTreeId(),
901            'link'    => $link,
902            'xref'    => $this->xref,
903        ])->fetchAll();
904
905        $list = [];
906        foreach ($rows as $row) {
907            $record = Family::getInstance($row->xref, $this->tree, $row->gedcom);
908            if ($record->canShowName()) {
909                $list[] = $record;
910            }
911        }
912
913        return $list;
914    }
915
916    /**
917     * Find sources linked to this record.
918     *
919     * @param string $link
920     *
921     * @return Source[]
922     */
923    public function linkedSources($link): array
924    {
925        $rows = Database::prepare(
926            "SELECT s_id AS xref, s_gedcom AS gedcom" .
927            " FROM `##sources`" .
928            " JOIN `##link` ON s_file = l_file AND s_id = l_from" .
929            " WHERE s_file = :tree_id AND l_type = :link AND l_to = :xref" .
930            " ORDER BY s_name COLLATE :collation"
931        )->execute([
932            'tree_id'   => $this->tree->getTreeId(),
933            'link'      => $link,
934            'xref'      => $this->xref,
935            'collation' => I18N::collation(),
936        ])->fetchAll();
937
938        $list = [];
939        foreach ($rows as $row) {
940            $record = Source::getInstance($row->xref, $this->tree, $row->gedcom);
941            if ($record->canShowName()) {
942                $list[] = $record;
943            }
944        }
945
946        return $list;
947    }
948
949    /**
950     * Find media objects linked to this record.
951     *
952     * @param string $link
953     *
954     * @return Media[]
955     */
956    public function linkedMedia($link): array
957    {
958        $rows = Database::prepare(
959            "SELECT m_id AS xref, m_gedcom AS gedcom" .
960            " FROM `##media`" .
961            " JOIN `##link` ON m_file = l_file AND m_id = l_from" .
962            " WHERE m_file = :tree_id AND l_type = :link AND l_to = :xref"
963        )->execute([
964            'tree_id' => $this->tree->getTreeId(),
965            'link'    => $link,
966            'xref'    => $this->xref,
967        ])->fetchAll();
968
969        $list = [];
970        foreach ($rows as $row) {
971            $record = Media::getInstance($row->xref, $this->tree, $row->gedcom);
972            if ($record->canShowName()) {
973                $list[] = $record;
974            }
975        }
976
977        return $list;
978    }
979
980    /**
981     * Find notes linked to this record.
982     *
983     * @param string $link
984     *
985     * @return Note[]
986     */
987    public function linkedNotes($link): array
988    {
989        $rows = Database::prepare(
990            "SELECT o_id AS xref, o_gedcom AS gedcom" .
991            " FROM `##other`" .
992            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
993            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
994            " WHERE o_file = :tree_id AND o_type = 'NOTE' AND l_type = :link AND l_to = :xref" .
995            " ORDER BY n_sort COLLATE :collation"
996        )->execute([
997            'tree_id'   => $this->tree->getTreeId(),
998            'link'      => $link,
999            'xref'      => $this->xref,
1000            'collation' => I18N::collation(),
1001        ])->fetchAll();
1002
1003        $list = [];
1004        foreach ($rows as $row) {
1005            $record = Note::getInstance($row->xref, $this->tree, $row->gedcom);
1006            if ($record->canShowName()) {
1007                $list[] = $record;
1008            }
1009        }
1010
1011        return $list;
1012    }
1013
1014    /**
1015     * Find repositories linked to this record.
1016     *
1017     * @param string $link
1018     *
1019     * @return Repository[]
1020     */
1021    public function linkedRepositories($link): array
1022    {
1023        $rows = Database::prepare(
1024            "SELECT o_id AS xref, o_gedcom AS gedcom" .
1025            " FROM `##other`" .
1026            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
1027            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
1028            " WHERE o_file = :tree_id AND o_type = 'REPO' AND l_type = :link AND l_to = :xref" .
1029            " ORDER BY n_sort COLLATE :collation"
1030        )->execute([
1031            'tree_id'   => $this->tree->getTreeId(),
1032            'link'      => $link,
1033            'xref'      => $this->xref,
1034            'collation' => I18N::collation(),
1035        ])->fetchAll();
1036
1037        $list = [];
1038        foreach ($rows as $row) {
1039            $record = Repository::getInstance($row->xref, $this->tree, $row->gedcom);
1040            if ($record->canShowName()) {
1041                $list[] = $record;
1042            }
1043        }
1044
1045        return $list;
1046    }
1047
1048    /**
1049     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
1050     * This is used to display multiple events on the individual/family lists.
1051     * Multiple events can exist because of uncertainty in dates, dates in different
1052     * calendars, place-names in both latin and hebrew character sets, etc.
1053     * It also allows us to combine dates/places from different events in the summaries.
1054     *
1055     * @param string $event_type
1056     *
1057     * @return Date[]
1058     */
1059    public function getAllEventDates($event_type): array
1060    {
1061        $dates = [];
1062        foreach ($this->getFacts($event_type) as $event) {
1063            if ($event->getDate()->isOK()) {
1064                $dates[] = $event->getDate();
1065            }
1066        }
1067
1068        return $dates;
1069    }
1070
1071    /**
1072     * Get all the places for a particular type of event
1073     *
1074     * @param string $event_type
1075     *
1076     * @return Place[]
1077     */
1078    public function getAllEventPlaces($event_type): array
1079    {
1080        $places = [];
1081        foreach ($this->getFacts($event_type) as $event) {
1082            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->getGedcom(), $ged_places)) {
1083                foreach ($ged_places[1] as $ged_place) {
1084                    $places[] = new Place($ged_place, $this->tree);
1085                }
1086            }
1087        }
1088
1089        return $places;
1090    }
1091
1092    /**
1093     * Get the first (i.e. prefered) Fact for the given fact type
1094     *
1095     * @param string $tag
1096     *
1097     * @return Fact|null
1098     */
1099    public function getFirstFact($tag)
1100    {
1101        foreach ($this->getFacts() as $fact) {
1102            if ($fact->getTag() === $tag) {
1103                return $fact;
1104            }
1105        }
1106
1107        return null;
1108    }
1109
1110    /**
1111     * The facts and events for this record.
1112     *
1113     * @param string   $filter
1114     * @param bool     $sort
1115     * @param int|null $access_level
1116     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1117     *
1118     * @return Fact[]
1119     */
1120    public function getFacts($filter = null, $sort = false, $access_level = null, $override = false): array
1121    {
1122        if ($access_level === null) {
1123            $access_level = Auth::accessLevel($this->tree);
1124        }
1125
1126        $facts = [];
1127        if ($this->canShow($access_level) || $override) {
1128            foreach ($this->facts as $fact) {
1129                if (($filter === null || preg_match('/^' . $filter . '$/', $fact->getTag())) && $fact->canShow($access_level)) {
1130                    $facts[] = $fact;
1131                }
1132            }
1133        }
1134        if ($sort) {
1135            Functions::sortFacts($facts);
1136        }
1137
1138        return $facts;
1139    }
1140
1141    /**
1142     * Get the last-change timestamp for this record, either as a formatted string
1143     * (for display) or as a unix timestamp (for sorting)
1144     *
1145     * @param bool $sorting
1146     *
1147     * @return string
1148     */
1149    public function lastChangeTimestamp($sorting = false)
1150    {
1151        $chan = $this->getFirstFact('CHAN');
1152
1153        if ($chan) {
1154            // The record does have a CHAN event
1155            $d = $chan->getDate()->minimumDate();
1156            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->getGedcom(), $match)) {
1157                $t = mktime((int)$match[1], (int)$match[2], (int)$match[3], (int)$d->format('%n'), (int)$d->format('%j'), (int)$d->format('%Y'));
1158            } elseif (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->getGedcom(), $match)) {
1159                $t = mktime((int)$match[1], (int)$match[2], 0, (int)$d->format('%n'), (int)$d->format('%j'), (int)$d->format('%Y'));
1160            } else {
1161                $t = mktime(0, 0, 0, (int)$d->format('%n'), (int)$d->format('%j'), (int)$d->format('%Y'));
1162            }
1163            if ($sorting) {
1164                return $t;
1165            } else {
1166                return strip_tags(FunctionsDate::formatTimestamp($t));
1167            }
1168        } else {
1169            // The record does not have a CHAN event
1170            if ($sorting) {
1171                return '0';
1172            } else {
1173                return '';
1174            }
1175        }
1176    }
1177
1178    /**
1179     * Get the last-change user for this record
1180     *
1181     * @return string
1182     */
1183    public function lastChangeUser()
1184    {
1185        $chan = $this->getFirstFact('CHAN');
1186
1187        if ($chan === null) {
1188            return I18N::translate('Unknown');
1189        } else {
1190            $chan_user = $chan->getAttribute('_WT_USER');
1191            if ($chan_user === '') {
1192                return I18N::translate('Unknown');
1193            } else {
1194                return $chan_user;
1195            }
1196        }
1197    }
1198
1199    /**
1200     * Add a new fact to this record
1201     *
1202     * @param string $gedcom
1203     * @param bool   $update_chan
1204     */
1205    public function createFact($gedcom, $update_chan)
1206    {
1207        $this->updateFact(null, $gedcom, $update_chan);
1208    }
1209
1210    /**
1211     * Delete a fact from this record
1212     *
1213     * @param string $fact_id
1214     * @param bool   $update_chan
1215     */
1216    public function deleteFact($fact_id, $update_chan)
1217    {
1218        $this->updateFact($fact_id, null, $update_chan);
1219    }
1220
1221    /**
1222     * Replace a fact with a new gedcom data.
1223     *
1224     * @param string $fact_id
1225     * @param string $gedcom
1226     * @param bool   $update_chan
1227     *
1228     * @throws \Exception
1229     */
1230    public function updateFact($fact_id, $gedcom, $update_chan)
1231    {
1232        // MSDOS line endings will break things in horrible ways
1233        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1234        $gedcom = trim($gedcom);
1235
1236        if ($this->pending === '') {
1237            throw new \Exception('Cannot edit a deleted record');
1238        }
1239        if ($gedcom && !preg_match('/^1 ' . WT_REGEX_TAG . '/', $gedcom)) {
1240            throw new \Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1241        }
1242
1243        if ($this->pending) {
1244            $old_gedcom = $this->pending;
1245        } else {
1246            $old_gedcom = $this->gedcom;
1247        }
1248
1249        // First line of record may contain data - e.g. NOTE records.
1250        list($new_gedcom) = explode("\n", $old_gedcom, 2);
1251
1252        // Replacing (or deleting) an existing fact
1253        foreach ($this->getFacts(null, false, Auth::PRIV_HIDE) as $fact) {
1254            if (!$fact->isPendingDeletion()) {
1255                if ($fact->getFactId() === $fact_id) {
1256                    if ($gedcom) {
1257                        $new_gedcom .= "\n" . $gedcom;
1258                    }
1259                    $fact_id = true; // Only replace/delete one copy of a duplicate fact
1260                } elseif ($fact->getTag() != 'CHAN' || !$update_chan) {
1261                    $new_gedcom .= "\n" . $fact->getGedcom();
1262                }
1263            }
1264        }
1265        if ($update_chan) {
1266            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1267        }
1268
1269        // Adding a new fact
1270        if (!$fact_id) {
1271            $new_gedcom .= "\n" . $gedcom;
1272        }
1273
1274        if ($new_gedcom != $old_gedcom) {
1275            // Save the changes
1276            Database::prepare(
1277                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
1278            )->execute([
1279                $this->tree->getTreeId(),
1280                $this->xref,
1281                $old_gedcom,
1282                $new_gedcom,
1283                Auth::id(),
1284            ]);
1285
1286            $this->pending = $new_gedcom;
1287
1288            if (Auth::user()->getPreference('auto_accept')) {
1289                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1290                $this->gedcom  = $new_gedcom;
1291                $this->pending = null;
1292            }
1293        }
1294        $this->parseFacts();
1295    }
1296
1297    /**
1298     * Update this record
1299     *
1300     * @param string $gedcom
1301     * @param bool   $update_chan
1302     */
1303    public function updateRecord($gedcom, $update_chan)
1304    {
1305        // MSDOS line endings will break things in horrible ways
1306        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1307        $gedcom = trim($gedcom);
1308
1309        // Update the CHAN record
1310        if ($update_chan) {
1311            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1312            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1313        }
1314
1315        // Create a pending change
1316        Database::prepare(
1317            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
1318        )->execute([
1319            $this->tree->getTreeId(),
1320            $this->xref,
1321            $this->getGedcom(),
1322            $gedcom,
1323            Auth::id(),
1324        ]);
1325
1326        // Clear the cache
1327        $this->pending = $gedcom;
1328
1329        // Accept this pending change
1330        if (Auth::user()->getPreference('auto_accept')) {
1331            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1332            $this->gedcom  = $gedcom;
1333            $this->pending = null;
1334        }
1335
1336        $this->parseFacts();
1337
1338        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1339    }
1340
1341    /**
1342     * Delete this record
1343     */
1344    public function deleteRecord()
1345    {
1346        // Create a pending change
1347        if (!$this->isPendingDeletion()) {
1348            Database::prepare(
1349                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, '', ?)"
1350            )->execute([
1351                $this->tree->getTreeId(),
1352                $this->xref,
1353                $this->getGedcom(),
1354                Auth::id(),
1355            ]);
1356        }
1357
1358        // Auto-accept this pending change
1359        if (Auth::user()->getPreference('auto_accept')) {
1360            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1361        }
1362
1363        // Clear the cache
1364        self::$gedcom_record_cache  = null;
1365        self::$pending_record_cache = null;
1366
1367        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1368    }
1369
1370    /**
1371     * Remove all links from this record to $xref
1372     *
1373     * @param string $xref
1374     * @param bool   $update_chan
1375     */
1376    public function removeLinks($xref, $update_chan)
1377    {
1378        $value = '@' . $xref . '@';
1379
1380        foreach ($this->getFacts() as $fact) {
1381            if ($fact->getValue() === $value) {
1382                $this->deleteFact($fact->getFactId(), $update_chan);
1383            } elseif (preg_match_all('/\n(\d) ' . WT_REGEX_TAG . ' ' . $value . '/', $fact->getGedcom(), $matches, PREG_SET_ORDER)) {
1384                $gedcom = $fact->getGedcom();
1385                foreach ($matches as $match) {
1386                    $next_level  = $match[1] + 1;
1387                    $next_levels = '[' . $next_level . '-9]';
1388                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1389                }
1390                $this->updateFact($fact->getFactId(), $gedcom, $update_chan);
1391            }
1392        }
1393    }
1394}
1395