xref: /webtrees/app/GedcomRecord.php (revision 202c018b592d5a516e4a465dc6dc515f3be37399)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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 <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Closure;
23use Exception;
24use Fisharebest\Webtrees\Contracts\TimestampInterface;
25use Fisharebest\Webtrees\Contracts\UserInterface;
26use Fisharebest\Webtrees\Elements\RestrictionNotice;
27use Fisharebest\Webtrees\Http\RequestHandlers\GedcomRecordPage;
28use Fisharebest\Webtrees\Services\PendingChangesService;
29use Illuminate\Support\Collection;
30
31use function array_combine;
32use function array_keys;
33use function array_map;
34use function array_search;
35use function array_shift;
36use function count;
37use function date;
38use function e;
39use function explode;
40use function implode;
41use function in_array;
42use function md5;
43use function preg_match;
44use function preg_match_all;
45use function preg_replace;
46use function preg_replace_callback;
47use function preg_split;
48use function range;
49use function route;
50use function str_contains;
51use function str_ends_with;
52use function str_pad;
53use function str_starts_with;
54use function strtoupper;
55use function strtr;
56use function trim;
57use function view;
58
59use const PHP_INT_MAX;
60use const PREG_SET_ORDER;
61use const STR_PAD_LEFT;
62
63/**
64 * A GEDCOM object.
65 */
66class GedcomRecord
67{
68    public const RECORD_TYPE = 'UNKNOWN';
69
70    protected const ROUTE_NAME = GedcomRecordPage::class;
71
72    protected string $xref;
73
74    protected Tree $tree;
75
76    // GEDCOM data (before any pending edits)
77    protected string $gedcom;
78
79    // GEDCOM data (after any pending edits)
80    protected string|null $pending;
81
82    /** @var array<Fact> Facts extracted from $gedcom/$pending */
83    protected array $facts;
84
85    /** @var array<array<string>> All the names of this individual */
86    protected array $getAllNames = [];
87
88    /** @var int|null Cached result */
89    private int|null $getPrimaryName = null;
90
91    /** @var int|null Cached result */
92    private int|null $getSecondaryName = null;
93
94    /**
95     * Create a GedcomRecord object from raw GEDCOM data.
96     *
97     * @param string      $xref
98     * @param string      $gedcom  an empty string for new/pending records
99     * @param string|null $pending null for a record with no pending edits,
100     *                             empty string for records with pending deletions
101     * @param Tree        $tree
102     */
103    public function __construct(string $xref, string $gedcom, string|null $pending, Tree $tree)
104    {
105        $this->xref    = $xref;
106        $this->gedcom  = $gedcom;
107        $this->pending = $pending;
108        $this->tree    = $tree;
109        $this->facts   = $this->parseFacts();
110    }
111
112    /**
113     * A closure which will filter out private records.
114     *
115     * @return Closure(GedcomRecord):bool
116     */
117    public static function accessFilter(): Closure
118    {
119        return static fn(GedcomRecord $record): bool => $record->canShow();
120    }
121
122    /**
123     * A closure which will compare records by name.
124     *
125     * @return Closure(GedcomRecord,GedcomRecord):int
126     */
127    public static function nameComparator(): Closure
128    {
129        return static function (GedcomRecord $x, GedcomRecord $y): int {
130            if ($x->canShowName()) {
131                if ($y->canShowName()) {
132                    return I18N::comparator()($x->sortName(), $y->sortName());
133                }
134
135                return -1; // only $y is private
136            }
137
138            if ($y->canShowName()) {
139                return 1; // only $x is private
140            }
141
142            return 0; // both $x and $y private
143        };
144    }
145
146    /**
147     * A closure which will compare records by change time.
148     *
149     * @param int $direction +1 to sort ascending, -1 to sort descending
150     *
151     * @return Closure(GedcomRecord,GedcomRecord):int
152     */
153    public static function lastChangeComparator(int $direction = 1): Closure
154    {
155        return static fn(GedcomRecord $x, GedcomRecord $y): int => $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
156    }
157
158    /**
159     * Get the GEDCOM tag for this record.
160     *
161     * @return string
162     */
163    public function tag(): string
164    {
165        preg_match('/^0 @[^@]*@ (\w+)/', $this->gedcom(), $match);
166
167        return $match[1] ?? static::RECORD_TYPE;
168    }
169
170    /**
171     * Get the XREF for this record
172     *
173     * @return string
174     */
175    public function xref(): string
176    {
177        return $this->xref;
178    }
179
180    /**
181     * Get the tree to which this record belongs
182     *
183     * @return Tree
184     */
185    public function tree(): Tree
186    {
187        return $this->tree;
188    }
189
190    /**
191     * Application code should access data via Fact objects.
192     * This function exists to support old code.
193     *
194     * @return string
195     */
196    public function gedcom(): string
197    {
198        return $this->pending ?? $this->gedcom;
199    }
200
201    /**
202     * Does this record have a pending change?
203     *
204     * @return bool
205     */
206    public function isPendingAddition(): bool
207    {
208        return $this->pending !== null;
209    }
210
211    /**
212     * Does this record have a pending deletion?
213     *
214     * @return bool
215     */
216    public function isPendingDeletion(): bool
217    {
218        return $this->pending === '';
219    }
220
221    /**
222     * Generate a URL to this record.
223     *
224     * @return string
225     */
226    public function url(): string
227    {
228        return route(static::ROUTE_NAME, [
229            'xref' => $this->xref(),
230            'tree' => $this->tree->name(),
231            'slug' => Registry::slugFactory()->make($this),
232        ]);
233    }
234
235    /**
236     * Can the details of this record be shown?
237     *
238     * @param int|null $access_level
239     *
240     * @return bool
241     */
242    public function canShow(int|null $access_level = null): bool
243    {
244        $access_level ??= Auth::accessLevel($this->tree);
245
246        // We use this value to bypass privacy checks. For example,
247        // when downloading data or when calculating privacy itself.
248        if ($access_level === Auth::PRIV_HIDE) {
249            return true;
250        }
251
252        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
253
254        return Registry::cache()->array()->remember($cache_key, fn() => $this->canShowRecord($access_level));
255    }
256
257    /**
258     * Can the name of this record be shown?
259     *
260     * @param int|null $access_level
261     *
262     * @return bool
263     */
264    public function canShowName(int|null $access_level = null): bool
265    {
266        return $this->canShow($access_level);
267    }
268
269    /**
270     * Can we edit this record?
271     *
272     * @return bool
273     */
274    public function canEdit(): bool
275    {
276        if ($this->isPendingDeletion()) {
277            return false;
278        }
279
280        if (Auth::isManager($this->tree)) {
281            return true;
282        }
283
284        $fact   = $this->facts(['RESN'])->first();
285        $locked = $fact instanceof Fact && str_ends_with($fact->attribute('RESN'), RestrictionNotice::VALUE_LOCKED);
286
287        return Auth::isEditor($this->tree) && !$locked;
288    }
289
290    /**
291     * Remove private data from the raw gedcom record.
292     * Return both the visible and invisible data. We need the invisible data when editing.
293     *
294     * @param int $access_level
295     *
296     * @return string
297     */
298    public function privatizeGedcom(int $access_level): string
299    {
300        if ($access_level === Auth::PRIV_HIDE) {
301            // We may need the original record, for example when downloading a GEDCOM or clippings cart
302            return $this->gedcom;
303        }
304
305        if ($this->canShow($access_level)) {
306            // The record is not private, but the individual facts may be.
307
308            // Include the entire first line (for NOTE records)
309            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
310
311            // Check each of the facts for access
312            foreach ($this->facts([], false, $access_level) as $fact) {
313                $gedrec .= "\n" . $fact->gedcom();
314            }
315
316            return $gedrec;
317        }
318
319        // We cannot display the details, but we may be able to display
320        // limited data, such as links to other records.
321        return $this->createPrivateGedcomRecord($access_level);
322    }
323
324    /**
325     * Default for "other" object types
326     *
327     * @return void
328     */
329    public function extractNames(): void
330    {
331        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
332    }
333
334    /**
335     * Derived classes should redefine this function, otherwise the object will have no name
336     *
337     * @return array<int,array<string,string>>
338     */
339    public function getAllNames(): array
340    {
341        if ($this->getAllNames === []) {
342            if ($this->canShowName()) {
343                // Ask the record to extract its names
344                $this->extractNames();
345                // No name found? Use a fallback.
346                if ($this->getAllNames === []) {
347                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
348                }
349            } else {
350                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
351            }
352        }
353
354        return $this->getAllNames;
355    }
356
357    /**
358     * If this object has no name, what do we call it?
359     *
360     * @return string
361     */
362    public function getFallBackName(): string
363    {
364        return e($this->xref());
365    }
366
367    /**
368     * Which of the (possibly several) names of this record is the primary one.
369     *
370     * @return int
371     */
372    public function getPrimaryName(): int
373    {
374        static $language_script;
375
376        $language_script ??= I18N::locale()->script()->code();
377
378        if ($this->getPrimaryName === null) {
379            // Generally, the first name is the primary one....
380            $this->getPrimaryName = 0;
381            // ...except when the language/name use different character sets
382            foreach ($this->getAllNames() as $n => $name) {
383                if (I18N::textScript($name['sort']) === $language_script) {
384                    $this->getPrimaryName = $n;
385                    break;
386                }
387            }
388        }
389
390        return $this->getPrimaryName;
391    }
392
393    /**
394     * Which of the (possibly several) names of this record is the secondary one.
395     *
396     * @return int
397     */
398    public function getSecondaryName(): int
399    {
400        if ($this->getSecondaryName === null) {
401            // Generally, the primary and secondary names are the same
402            $this->getSecondaryName = $this->getPrimaryName();
403            // ....except when there are names with different character sets
404            $all_names = $this->getAllNames();
405            if (count($all_names) > 1) {
406                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
407                foreach ($all_names as $n => $name) {
408                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
409                        $this->getSecondaryName = $n;
410                        break;
411                    }
412                }
413            }
414        }
415
416        return $this->getSecondaryName;
417    }
418
419    /**
420     * Allow the choice of primary name to be overridden, e.g. in a search result
421     *
422     * @param int|null $n
423     *
424     * @return void
425     */
426    public function setPrimaryName(int|null $n = null): void
427    {
428        $this->getPrimaryName   = $n;
429        $this->getSecondaryName = null;
430    }
431
432    /**
433     * Allow native PHP functions such as array_unique() to work with objects
434     *
435     * @return string
436     */
437    public function __toString(): string
438    {
439        return $this->xref . '@' . $this->tree->id();
440    }
441
442    /**
443     * /**
444     * Get variants of the name
445     *
446     * @return string
447     */
448    public function fullName(): string
449    {
450        if ($this->canShowName()) {
451            $tmp = $this->getAllNames();
452
453            return $tmp[$this->getPrimaryName()]['full'];
454        }
455
456        return I18N::translate('Private');
457    }
458
459    /**
460     * Get a sortable version of the name. Do not display this!
461     *
462     * @return string
463     */
464    public function sortName(): string
465    {
466        // The sortable name is never displayed, no need to call canShowName()
467        $tmp = $this->getAllNames();
468
469        return $tmp[$this->getPrimaryName()]['sort'];
470    }
471
472    /**
473     * Get the full name in an alternative character set
474     *
475     * @return string|null
476     */
477    public function alternateName(): string|null
478    {
479        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
480            $all_names = $this->getAllNames();
481
482            return $all_names[$this->getSecondaryName()]['full'];
483        }
484
485        return null;
486    }
487
488    /**
489     * Format this object for display in a list
490     *
491     * @return string
492     */
493    public function formatList(): string
494    {
495        $html = '<a href="' . e($this->url()) . '">';
496        $html .= '<b>' . $this->fullName() . '</b>';
497        $html .= '</a>';
498        $html .= $this->formatListDetails();
499
500        return $html;
501    }
502
503    /**
504     * This function should be redefined in derived classes to show any major
505     * identifying characteristics of this record.
506     *
507     * @return string
508     */
509    public function formatListDetails(): string
510    {
511        return '';
512    }
513
514    /**
515     * Extract/format the first fact from a list of facts.
516     *
517     * @param array<string> $facts
518     * @param int           $style
519     *
520     * @return string
521     */
522    public function formatFirstMajorFact(array $facts, int $style): string
523    {
524        $fact = $this->facts($facts, true)->first();
525
526        if ($fact === null) {
527            return '';
528        }
529
530        // Only display if it has a date or place (or both)
531        $attributes = [];
532
533        if ($fact->date()->isOK()) {
534            $attributes[] = view('fact-date', ['cal_link' => 'false', 'fact' => $fact, 'record' => $fact->record(), 'time' => false]);
535        }
536
537        if ($fact->place()->gedcomName() !== '' && $style === 2) {
538            $attributes[] = $fact->place()->shortName();
539        }
540
541        if ($attributes === []) {
542            return '';
543        }
544
545        return '<div><em>' . I18N::translate('%1$s: %2$s', $fact->label(), implode(' — ', $attributes)) . '</em></div>';
546    }
547
548    /**
549     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
550     * This is used to display multiple events on the individual/family lists.
551     * Multiple events can exist because of uncertainty in dates, dates in different
552     * calendars, place-names in both latin and hebrew character sets, etc.
553     * It also allows us to combine dates/places from different events in the summaries.
554     *
555     * @param array<string> $events
556     *
557     * @return array<Date>
558     */
559    public function getAllEventDates(array $events): array
560    {
561        $dates = [];
562        foreach ($this->facts($events, false, null, true) as $event) {
563            if ($event->date()->isOK()) {
564                $dates[] = $event->date();
565            }
566        }
567
568        return $dates;
569    }
570
571    /**
572     * Get all the places for a particular type of event
573     *
574     * @param array<string> $events
575     *
576     * @return array<Place>
577     */
578    public function getAllEventPlaces(array $events): array
579    {
580        $places = [];
581        foreach ($this->facts($events) as $event) {
582            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
583                foreach ($ged_places[1] as $ged_place) {
584                    $places[] = new Place($ged_place, $this->tree);
585                }
586            }
587        }
588
589        return $places;
590    }
591
592    /**
593     * The facts and events for this record.
594     *
595     * @param array<string> $filter
596     * @param bool          $sort
597     * @param int|null      $access_level
598     * @param bool          $ignore_deleted
599     *
600     * @return Collection<int,Fact>
601     */
602    public function facts(
603        array $filter = [],
604        bool $sort = false,
605        int|null $access_level = null,
606        bool $ignore_deleted = false
607    ): Collection {
608        $access_level ??= Auth::accessLevel($this->tree);
609
610        // Convert BIRT into INDI:BIRT, etc.
611        $filter = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, $filter);
612
613        $facts = new Collection();
614        if ($this->canShow($access_level)) {
615            foreach ($this->facts as $fact) {
616                if (($filter === [] || in_array($fact->tag(), $filter, true)) && $fact->canShow($access_level)) {
617                    $facts->push($fact);
618                }
619            }
620        }
621
622        if ($sort) {
623            switch ($this->tag()) {
624                case Family::RECORD_TYPE:
625                case Individual::RECORD_TYPE:
626                    $facts = Fact::sortFacts($facts);
627                    break;
628
629                default:
630                    $subtags = Registry::elementFactory()->make($this->tag())->subtags();
631                    $subtags = array_map(fn (string $tag): string => $this->tag() . ':' . $tag, array_keys($subtags));
632
633                    if ($subtags !== []) {
634                        // Renumber keys from 1.
635                        $subtags = array_combine(range(1, count($subtags)), $subtags);
636                    }
637
638
639                    $facts = $facts
640                        ->sort(static function (Fact $x, Fact $y) use ($subtags): int {
641                            $sort_x = array_search($x->tag(), $subtags, true) ?: PHP_INT_MAX;
642                            $sort_y = array_search($y->tag(), $subtags, true) ?: PHP_INT_MAX;
643
644                            return $sort_x <=> $sort_y;
645                        });
646                    break;
647            }
648        }
649
650        if ($ignore_deleted) {
651            $facts = $facts->filter(static fn(Fact $fact): bool => !$fact->isPendingDeletion());
652        }
653
654        return $facts;
655    }
656
657    /**
658     * @return array<string,string>
659     */
660    public function missingFacts(): array
661    {
662        $missing_facts = [];
663
664        foreach (Registry::elementFactory()->make($this->tag())->subtags() as $subtag => $repeat) {
665            [, $max] = explode(':', $repeat);
666            $max = $max === 'M' ? PHP_INT_MAX : (int) $max;
667
668            if ($this->facts([$subtag], false, null, true)->count() < $max) {
669                $missing_facts[$subtag] = $subtag;
670                $missing_facts[$subtag] = Registry::elementFactory()->make($this->tag() . ':' . $subtag)->label();
671            }
672        }
673
674        uasort($missing_facts, I18N::comparator());
675
676        if (!Auth::canUploadMedia($this->tree, Auth::user())) {
677            unset($missing_facts['OBJE']);
678        }
679
680        // We have special code for this.
681        unset($missing_facts['FILE']);
682
683        return $missing_facts;
684    }
685
686    /**
687     * Get the last-change timestamp for this record
688     *
689     * @return TimestampInterface
690     */
691    public function lastChangeTimestamp(): TimestampInterface
692    {
693        $chan = $this->facts(['CHAN'])->first();
694
695        if ($chan instanceof Fact) {
696            // The record has a CHAN event.
697            $date = $chan->date()->minimumDate();
698            $ymd = sprintf('%04d-%02d-%02d', $date->year(), $date->month(), $date->day());
699
700            if ($ymd !== '') {
701                // The CHAN event has a valid DATE.
702                if (preg_match('/\n3 TIME (([01]\d|2[0-3]):([0-5]\d):([0-5]\d))/', $chan->gedcom(), $match) === 1) {
703                    return Registry::timestampFactory()->fromString($ymd . $match[1], 'Y-m-d H:i:s');
704                }
705
706                if (preg_match('/\n3 TIME (([01]\d|2[0-3]):([0-5]\d))/', $chan->gedcom(), $match) === 1) {
707                    return Registry::timestampFactory()->fromString($ymd . $match[1], 'Y-m-d H:i');
708                }
709
710                return Registry::timestampFactory()->fromString($ymd, 'Y-m-d');
711            }
712        }
713
714        // The record does not have a CHAN event
715        return Registry::timestampFactory()->make(0);
716    }
717
718    /**
719     * Get the last-change user for this record
720     *
721     * @return string
722     */
723    public function lastChangeUser(): string
724    {
725        $chan = $this->facts(['CHAN'])->first();
726
727        if ($chan === null) {
728            return I18N::translate('Unknown');
729        }
730
731        $chan_user = $chan->attribute('_WT_USER');
732        if ($chan_user === '') {
733            return I18N::translate('Unknown');
734        }
735
736        return $chan_user;
737    }
738
739    /**
740     * Add a new fact to this record
741     *
742     * @param string $gedcom
743     * @param bool   $update_chan
744     *
745     * @return void
746     */
747    public function createFact(string $gedcom, bool $update_chan): void
748    {
749        $this->updateFact('', $gedcom, $update_chan);
750    }
751
752    /**
753     * Delete a fact from this record
754     *
755     * @param string $fact_id
756     * @param bool   $update_chan
757     *
758     * @return void
759     */
760    public function deleteFact(string $fact_id, bool $update_chan): void
761    {
762        $this->updateFact($fact_id, '', $update_chan);
763    }
764
765    /**
766     * Replace a fact with a new gedcom data.
767     *
768     * @param string $fact_id
769     * @param string $gedcom
770     * @param bool   $update_chan
771     *
772     * @return void
773     * @throws Exception
774     */
775    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
776    {
777        // Not all record types allow a CHAN event.
778        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
779
780        // MSDOS line endings will break things in horrible ways
781        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
782        $gedcom = trim($gedcom);
783
784        if ($this->pending === '') {
785            throw new Exception('Cannot edit a deleted record');
786        }
787        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
788            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
789        }
790
791        if ($this->pending !== null && $this->pending !== '') {
792            $old_gedcom = $this->pending;
793        } else {
794            $old_gedcom = $this->gedcom;
795        }
796
797        // First line of record may contain data - e.g. NOTE records.
798        [$new_gedcom] = explode("\n", $old_gedcom, 2);
799
800        // Replacing (or deleting) an existing fact
801        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
802            if ($fact->id() === $fact_id) {
803                if ($gedcom !== '') {
804                    $new_gedcom .= "\n" . $gedcom;
805                }
806                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
807            } elseif ($update_chan && str_ends_with($fact->tag(), ':CHAN')) {
808                $new_gedcom .= "\n" . $this->updateChange($fact->gedcom());
809            } else {
810                $new_gedcom .= "\n" . $fact->gedcom();
811            }
812        }
813
814        // Adding a new fact
815        if ($fact_id === '') {
816            $new_gedcom .= "\n" . $gedcom;
817        }
818
819        if ($update_chan && !str_contains($new_gedcom, "\n1 CHAN")) {
820            $new_gedcom .= $this->updateChange("\n1 CHAN");
821        }
822
823        if ($new_gedcom !== $old_gedcom) {
824            // Save the changes
825            DB::table('change')->insert([
826                'gedcom_id'  => $this->tree->id(),
827                'xref'       => $this->xref,
828                'old_gedcom' => $old_gedcom,
829                'new_gedcom' => $new_gedcom,
830                'status'     => 'pending',
831                'user_id'    => Auth::id(),
832            ]);
833
834            $this->pending = $new_gedcom;
835
836            if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
837                $pending_changes_service = Registry::container()->get(PendingChangesService::class);
838
839                $pending_changes_service->acceptRecord($this);
840                $this->gedcom  = $new_gedcom;
841                $this->pending = null;
842            }
843        }
844
845        $this->facts = $this->parseFacts();
846    }
847
848    /**
849     * Update this record
850     *
851     * @param string $gedcom
852     * @param bool   $update_chan
853     *
854     * @return void
855     */
856    public function updateRecord(string $gedcom, bool $update_chan): void
857    {
858        // Not all record types allow a CHAN event.
859        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
860
861        // MSDOS line endings will break things in horrible ways
862        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
863        $gedcom = trim($gedcom);
864
865        // Update the CHAN record
866        if ($update_chan) {
867            if (preg_match('/\n1 CHAN(\n[2-9].*)*/', $gedcom, $match)) {
868                $gedcom = strtr($gedcom, [$match[0] => $this->updateChange($match[0])]);
869            } else {
870                $gedcom .= $this->updateChange("\n1 CHAN");
871            }
872        }
873
874        // Create a pending change
875        DB::table('change')->insert([
876            'gedcom_id'  => $this->tree->id(),
877            'xref'       => $this->xref,
878            'old_gedcom' => $this->gedcom(),
879            'new_gedcom' => $gedcom,
880            'status'     => 'pending',
881            'user_id'    => Auth::id(),
882        ]);
883
884        // Clear the cache
885        $this->pending = $gedcom;
886
887        // Accept this pending change
888        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
889            $pending_changes_service = Registry::container()->get(PendingChangesService::class);
890
891            $pending_changes_service->acceptRecord($this);
892            $this->gedcom  = $gedcom;
893            $this->pending = null;
894        }
895
896        $this->facts = $this->parseFacts();
897
898        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
899    }
900
901    /**
902     * Delete this record
903     *
904     * @return void
905     */
906    public function deleteRecord(): void
907    {
908        // Create a pending change
909        if (!$this->isPendingDeletion()) {
910            DB::table('change')->insert([
911                'gedcom_id'  => $this->tree->id(),
912                'xref'       => $this->xref,
913                'old_gedcom' => $this->gedcom(),
914                'new_gedcom' => '',
915                'status'     => 'pending',
916                'user_id'    => Auth::id(),
917            ]);
918        }
919
920        // Auto-accept this pending change
921        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
922            $pending_changes_service = Registry::container()->get(PendingChangesService::class);
923            $pending_changes_service->acceptRecord($this);
924        }
925
926        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
927    }
928
929    /**
930     * Remove all links from this record to $xref
931     *
932     * @param string $xref
933     * @param bool   $update_chan
934     *
935     * @return void
936     */
937    public function removeLinks(string $xref, bool $update_chan): void
938    {
939        $value = '@' . $xref . '@';
940
941        foreach ($this->facts() as $fact) {
942            if ($fact->value() === $value) {
943                $this->deleteFact($fact->id(), $update_chan);
944            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
945                $gedcom = $fact->gedcom();
946                foreach ($matches as $match) {
947                    $next_level  = 1 + (int) $match[1];
948                    $next_levels = '[' . $next_level . '-9]';
949                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
950                }
951                $this->updateFact($fact->id(), $gedcom, $update_chan);
952            }
953        }
954    }
955
956    /**
957     * Each object type may have its own special rules, and re-implement this function.
958     *
959     * @param int $access_level
960     *
961     * @return bool
962     */
963    protected function canShowByType(int $access_level): bool
964    {
965        $fact_privacy = $this->tree->getFactPrivacy();
966
967        if (isset($fact_privacy[static::RECORD_TYPE])) {
968            // Restriction found
969            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
970        }
971
972        // No restriction found - must be public:
973        return true;
974    }
975
976    /**
977     * Generate a private version of this record
978     *
979     * @param int $access_level
980     *
981     * @return string
982     */
983    protected function createPrivateGedcomRecord(int $access_level): string
984    {
985        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE;
986    }
987
988    /**
989     * Convert a name record into sortable and full/display versions. This default
990     * should be OK for simple record types. INDI/FAM records will need to redefine it.
991     *
992     * @param string $type
993     * @param string $value
994     * @param string $gedcom
995     *
996     * @return void
997     */
998    protected function addName(string $type, string $value, string $gedcom): void
999    {
1000        $this->getAllNames[] = [
1001            'type'   => $type,
1002            'sort'   => preg_replace_callback('/(\d+)/', static fn(array $matches): string => str_pad($matches[0], 10, '0', STR_PAD_LEFT), $value),
1003            'full'   => '<bdi>' . e($value) . '</bdi>',
1004            // This is used for display
1005            'fullNN' => $value,
1006            // This goes into the database
1007        ];
1008    }
1009
1010    /**
1011     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
1012     * Records without a name (e.g. FAM) will need to redefine this function.
1013     * Parameters: the level 1 fact containing the name.
1014     * Return value: an array of name structures, each containing
1015     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
1016     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
1017     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
1018     *
1019     * @param int              $level
1020     * @param string           $fact_type
1021     * @param Collection<int,Fact> $facts
1022     *
1023     * @return void
1024     */
1025    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
1026    {
1027        $sublevel    = $level + 1;
1028        $subsublevel = $sublevel + 1;
1029        foreach ($facts as $fact) {
1030            if (preg_match_all('/^' . $level . ' (' . $fact_type . ') (.+)((\n[' . $sublevel . '-9].+)*)/m', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1031                foreach ($matches as $match) {
1032                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
1033                    if ($match[1] === 'NAME' && str_contains(strtoupper($match[3]), "\n2 TYPE MARRIED")) {
1034                        $this->addName('_MARNM', $match[2], $fact->gedcom());
1035                    } else {
1036                        $this->addName($match[1], $match[2], $fact->gedcom());
1037                    }
1038                    if ($match[3] && preg_match_all('/^' . $sublevel . ' (ROMN|FONE|_\w+) (.+)((\n[' . $subsublevel . '-9].+)*)/m', $match[3], $submatches, PREG_SET_ORDER)) {
1039                        foreach ($submatches as $submatch) {
1040                            if ($submatch[1] !== '_RUFNAME') {
1041                                $this->addName($submatch[1], $submatch[2], $match[3]);
1042                            }
1043                        }
1044                    }
1045                }
1046            }
1047        }
1048    }
1049
1050    /**
1051     * Split the record into facts
1052     *
1053     * @return array<Fact>
1054     */
1055    private function parseFacts(): array
1056    {
1057        // Split the record into facts
1058        if ($this->gedcom !== '') {
1059            $gedcom_facts = preg_split('/\n(?=1)/', $this->gedcom);
1060            array_shift($gedcom_facts);
1061        } else {
1062            $gedcom_facts = [];
1063        }
1064        if ($this->pending !== null && $this->pending !== '') {
1065            $pending_facts = preg_split('/\n(?=1)/', $this->pending);
1066            array_shift($pending_facts);
1067        } else {
1068            $pending_facts = [];
1069        }
1070
1071        $facts = [];
1072
1073        foreach ($gedcom_facts as $gedcom_fact) {
1074            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
1075            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
1076                $fact->setPendingDeletion();
1077            }
1078            $facts[] = $fact;
1079        }
1080        foreach ($pending_facts as $pending_fact) {
1081            if (!in_array($pending_fact, $gedcom_facts, true)) {
1082                $fact = new Fact($pending_fact, $this, md5($pending_fact));
1083                $fact->setPendingAddition();
1084                $facts[] = $fact;
1085            }
1086        }
1087
1088        return $facts;
1089    }
1090
1091    /**
1092     * Work out whether this record can be shown to a user with a given access level
1093     *
1094     * @param int $access_level
1095     *
1096     * @return bool
1097     */
1098    private function canShowRecord(int $access_level): bool
1099    {
1100        // This setting would better be called "$ENABLE_PRIVACY"
1101        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
1102            return true;
1103        }
1104
1105        // We should always be able to see our own record (unless an admin is applying download restrictions)
1106        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
1107            return true;
1108        }
1109
1110        // Does this record have a restriction notice?
1111        // Cannot use $this->>fact(), as that function calls this one.
1112        if (preg_match('/\n1 RESN (.+)/', $this->gedcom(), $match)) {
1113            $element     = new RestrictionNotice('');
1114            $restriction = $element->canonical($match[1]);
1115
1116            if (str_starts_with($restriction, RestrictionNotice::VALUE_CONFIDENTIAL)) {
1117                return Auth::PRIV_NONE >= $access_level;
1118            }
1119            if (str_starts_with($restriction, RestrictionNotice::VALUE_PRIVACY)) {
1120                return Auth::PRIV_USER >= $access_level;
1121            }
1122            if (str_starts_with($restriction, RestrictionNotice::VALUE_NONE)) {
1123                return true;
1124            }
1125        }
1126
1127        // Does this record have a default RESN?
1128        $individual_privacy = $this->tree->getIndividualPrivacy();
1129        if (isset($individual_privacy[$this->xref()])) {
1130            return $individual_privacy[$this->xref()] >= $access_level;
1131        }
1132
1133        // Privacy rules do not apply to admins
1134        if (Auth::PRIV_NONE >= $access_level) {
1135            return true;
1136        }
1137
1138        // Different types of record have different privacy rules
1139        return $this->canShowByType($access_level);
1140    }
1141
1142    /**
1143     * Lock the database row, to prevent concurrent edits.
1144     */
1145    public function lock(): void
1146    {
1147        DB::table('other')
1148            ->where('o_file', '=', $this->tree->id())
1149            ->where('o_id', '=', $this->xref())
1150            ->lockForUpdate()
1151            ->get();
1152    }
1153
1154    /**
1155     * Change records may contain notes and other fields.  Just update the date/time/author.
1156     *
1157     * @param string $gedcom
1158     *
1159     * @return string
1160     */
1161    private function updateChange(string $gedcom): string
1162    {
1163        $gedcom = preg_replace('/\n2 (DATE|_WT_USER).*(\n[3-9].*)*/', '', $gedcom);
1164        $today  = strtoupper(date('d M Y'));
1165        $now    = date('H:i:s');
1166        $author = Auth::user()->userName();
1167
1168        return $gedcom . "\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . $author;
1169    }
1170}
1171