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