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