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