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