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