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