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