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