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