GedcomRecord::updateFact()   F
last analyzed

Complexity

Conditions 17
Paths 244

Size

Total Lines 72
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 41
nc 244
nop 3
dl 0
loc 72
rs 3.8333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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