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