xref: /webtrees/app/Fact.php (revision 544f68e34057eabe32bff7b1387373b8130c0437)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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 Fisharebest\Webtrees\Elements\RestrictionNotice;
24use Fisharebest\Webtrees\Services\GedcomService;
25use Illuminate\Support\Collection;
26use InvalidArgumentException;
27
28use function array_flip;
29use function array_key_exists;
30use function count;
31use function e;
32use function implode;
33use function in_array;
34use function preg_match;
35use function preg_match_all;
36use function preg_replace;
37use function str_contains;
38use function str_ends_with;
39use function usort;
40
41use const PREG_SET_ORDER;
42
43/**
44 * A GEDCOM fact or event object.
45 */
46class Fact
47{
48    private const FACT_ORDER = [
49        'BIRT',
50        '_HNM',
51        'ALIA',
52        '_AKA',
53        '_AKAN',
54        'ADOP',
55        '_ADPF',
56        '_ADPF',
57        '_BRTM',
58        'CHR',
59        'BAPM',
60        'FCOM',
61        'CONF',
62        'BARM',
63        'BASM',
64        'EDUC',
65        'GRAD',
66        '_DEG',
67        'EMIG',
68        'IMMI',
69        'NATU',
70        '_MILI',
71        '_MILT',
72        'ENGA',
73        'MARB',
74        'MARC',
75        'MARL',
76        '_MARI',
77        '_MBON',
78        'MARR',
79        '_COML',
80        '_STAT',
81        '_SEPR',
82        'DIVF',
83        'MARS',
84        'DIV',
85        'ANUL',
86        'CENS',
87        'OCCU',
88        'RESI',
89        'PROP',
90        'CHRA',
91        'RETI',
92        'FACT',
93        'EVEN',
94        '_NMR',
95        '_NMAR',
96        'NMR',
97        'NCHI',
98        'WILL',
99        '_HOL',
100        '_????_',
101        'DEAT',
102        '_FNRL',
103        'CREM',
104        'BURI',
105        '_INTE',
106        '_YART',
107        '_NLIV',
108        'PROB',
109        'TITL',
110        'COMM',
111        'NATI',
112        'CITN',
113        'CAST',
114        'RELI',
115        'SSN',
116        'IDNO',
117        'TEMP',
118        'SLGC',
119        'BAPL',
120        'CONL',
121        'ENDL',
122        'SLGS',
123        'NO',
124        'ADDR',
125        'PHON',
126        'EMAIL',
127        '_EMAIL',
128        'EMAL',
129        'FAX',
130        'WWW',
131        'URL',
132        '_URL',
133        '_FSFTID',
134        'AFN',
135        'REFN',
136        '_PRMN',
137        'REF',
138        'RIN',
139        '_UID',
140        'OBJE',
141        'NOTE',
142        'SOUR',
143        'CREA',
144        'CHAN',
145        '_TODO',
146    ];
147
148    // Unique identifier for this fact (currently implemented as a hash of the raw data).
149    private string $id;
150
151    // The GEDCOM record from which this fact is taken
152    private GedcomRecord $record;
153
154    // The raw GEDCOM data for this fact
155    private string $gedcom;
156
157    // The GEDCOM tag for this record
158    private string $tag;
159
160    private bool $pending_deletion = false;
161
162    private bool $pending_addition = false;
163
164    private Date $date;
165
166    private Place $place;
167
168    // Used to sort facts
169    public int $sortOrder;
170
171    // Used by anniversary calculations
172    public int $jd;
173    public int $anniv;
174
175    /**
176     * Create an event object from a gedcom fragment.
177     * We need the parent object (to check privacy) and a (pseudo) fact ID to
178     * identify the fact within the record.
179     *
180     * @param string       $gedcom
181     * @param GedcomRecord $parent
182     * @param string       $id
183     *
184     * @throws InvalidArgumentException
185     */
186    public function __construct(string $gedcom, GedcomRecord $parent, string $id)
187    {
188        if (preg_match('/^1 (' . Gedcom::REGEX_TAG . ')/', $gedcom, $match)) {
189            $this->gedcom = $gedcom;
190            $this->record = $parent;
191            $this->id     = $id;
192            $this->tag    = $match[1];
193        } else {
194            throw new InvalidArgumentException('Invalid GEDCOM data passed to Fact::_construct(' . $gedcom . ',' . $parent->xref() . ')');
195        }
196    }
197
198    /**
199     * Get the value of level 1 data in the fact
200     * Allow for multi-line values
201     *
202     * @return string
203     */
204    public function value(): string
205    {
206        if (preg_match('/^1 ' . $this->tag . ' ?(.*(?:\n2 CONT ?.*)*)/', $this->gedcom, $match)) {
207            return preg_replace("/\n2 CONT ?/", "\n", $match[1]);
208        }
209
210        return '';
211    }
212
213    /**
214     * Get the record to which this fact links
215     *
216     * @return Family|GedcomRecord|Individual|Location|Media|Note|Repository|Source|Submission|Submitter|null
217     */
218    public function target()
219    {
220        if (!preg_match('/^@(' . Gedcom::REGEX_XREF . ')@$/', $this->value(), $match)) {
221            return null;
222        }
223
224        $xref = $match[1];
225
226        switch ($this->tag) {
227            case 'FAMC':
228            case 'FAMS':
229                return Registry::familyFactory()->make($xref, $this->record()->tree());
230            case 'HUSB':
231            case 'WIFE':
232            case 'ALIA':
233            case 'CHIL':
234            case '_ASSO':
235                return Registry::individualFactory()->make($xref, $this->record()->tree());
236            case 'ASSO':
237                return
238                    Registry::individualFactory()->make($xref, $this->record()->tree()) ??
239                    Registry::submitterFactory()->make($xref, $this->record()->tree());
240            case 'SOUR':
241                return Registry::sourceFactory()->make($xref, $this->record()->tree());
242            case 'OBJE':
243                return Registry::mediaFactory()->make($xref, $this->record()->tree());
244            case 'REPO':
245                return Registry::repositoryFactory()->make($xref, $this->record()->tree());
246            case 'NOTE':
247                return Registry::noteFactory()->make($xref, $this->record()->tree());
248            case 'ANCI':
249            case 'DESI':
250            case 'SUBM':
251                return Registry::submitterFactory()->make($xref, $this->record()->tree());
252            case 'SUBN':
253                return Registry::submissionFactory()->make($xref, $this->record()->tree());
254            case '_LOC':
255                return Registry::locationFactory()->make($xref, $this->record()->tree());
256            default:
257                return Registry::gedcomRecordFactory()->make($xref, $this->record()->tree());
258        }
259    }
260
261    /**
262     * Get the value of level 2 data in the fact
263     *
264     * @param string $tag
265     *
266     * @return string
267     */
268    public function attribute(string $tag): string
269    {
270        if (preg_match('/\n2 ' . $tag . '\b ?(.*(?:(?:\n3 CONT ?.*)*)*)/', $this->gedcom, $match)) {
271            $value = preg_replace("/\n3 CONT ?/", "\n", $match[1]);
272
273            return Registry::elementFactory()->make($this->tag() . ':' . $tag)->canonical($value);
274        }
275
276        return '';
277    }
278
279    /**
280     * Get the PLAC:MAP:LATI for the fact.
281     *
282     * @return float|null
283     */
284    public function latitude(): ?float
285    {
286        if (preg_match('/\n4 LATI (.+)/', $this->gedcom, $match)) {
287            $gedcom_service = new GedcomService();
288
289            return $gedcom_service->readLatitude($match[1]);
290        }
291
292        return null;
293    }
294
295    /**
296     * Get the PLAC:MAP:LONG for the fact.
297     *
298     * @return float|null
299     */
300    public function longitude(): ?float
301    {
302        if (preg_match('/\n4 LONG (.+)/', $this->gedcom, $match)) {
303            $gedcom_service = new GedcomService();
304
305            return $gedcom_service->readLongitude($match[1]);
306        }
307
308        return null;
309    }
310
311    /**
312     * Do the privacy rules allow us to display this fact to the current user
313     *
314     * @param int|null $access_level
315     *
316     * @return bool
317     */
318    public function canShow(int $access_level = null): bool
319    {
320        $access_level = $access_level ?? Auth::accessLevel($this->record->tree());
321
322        // Does this record have an explicit restriction notice?
323        $restriction = $this->attribute('RESN');
324
325        if (str_ends_with($restriction, RestrictionNotice::VALUE_CONFIDENTIAL)) {
326            return Auth::PRIV_NONE >= $access_level;
327        }
328
329        if (str_ends_with($restriction, RestrictionNotice::VALUE_PRIVACY)) {
330            return Auth::PRIV_USER >= $access_level;
331        }
332        if (str_ends_with($restriction, RestrictionNotice::VALUE_NONE)) {
333            return true;
334        }
335
336        // A link to a record of the same type: NOTE=>NOTE, OBJE=>OBJE, SOUR=>SOUR, etc.
337        // Use the privacy of the target record.
338        $target = $this->target();
339
340        if ($target instanceof GedcomRecord && $target->tag() === $this->tag) {
341            return $target->canShow($access_level);
342        }
343
344        // Does this record have a default RESN?
345        $xref                    = $this->record->xref();
346        $fact_privacy            = $this->record->tree()->getFactPrivacy();
347        $individual_fact_privacy = $this->record->tree()->getIndividualFactPrivacy();
348        if (isset($individual_fact_privacy[$xref][$this->tag])) {
349            return $individual_fact_privacy[$xref][$this->tag] >= $access_level;
350        }
351        if (isset($fact_privacy[$this->tag])) {
352            return $fact_privacy[$this->tag] >= $access_level;
353        }
354
355        // No restrictions - it must be public
356        return true;
357    }
358
359    /**
360     * Check whether this fact is protected against edit
361     *
362     * @return bool
363     */
364    public function canEdit(): bool
365    {
366        if ($this->isPendingDeletion()) {
367            return false;
368        }
369
370        if (Auth::isManager($this->record->tree())) {
371            return true;
372        }
373
374        // Members cannot edit RESN, CHAN and locked records
375        return Auth::isEditor($this->record->tree()) && !str_ends_with($this->attribute('RESN'), RestrictionNotice::VALUE_LOCKED) && $this->tag !== 'RESN' && $this->tag !== 'CHAN';
376    }
377
378    /**
379     * The place where the event occured.
380     *
381     * @return Place
382     */
383    public function place(): Place
384    {
385        $this->place ??= new Place($this->attribute('PLAC'), $this->record()->tree());
386
387        return $this->place;
388    }
389
390    /**
391     * Get the date for this fact.
392     * We can call this function many times, especially when sorting,
393     * so keep a copy of the date.
394     *
395     * @return Date
396     */
397    public function date(): Date
398    {
399        $this->date ??= new Date($this->attribute('DATE'));
400
401        return $this->date;
402    }
403
404    /**
405     * The raw GEDCOM data for this fact
406     *
407     * @return string
408     */
409    public function gedcom(): string
410    {
411        return $this->gedcom;
412    }
413
414    /**
415     * Get a (pseudo) primary key for this fact.
416     *
417     * @return string
418     */
419    public function id(): string
420    {
421        return $this->id;
422    }
423
424    /**
425     * What is the tag (type) of this fact, such as BIRT, MARR or DEAT.
426     *
427     * @return string
428     */
429    public function tag(): string
430    {
431        return $this->record->tag() . ':' . $this->tag;
432    }
433
434    /**
435     * The GEDCOM record where this Fact came from
436     *
437     * @return GedcomRecord
438     */
439    public function record(): GedcomRecord
440    {
441        return $this->record;
442    }
443
444    /**
445     * Get the name of this fact type, for use as a label.
446     *
447     * @return string
448     */
449    public function label(): string
450    {
451        // Marriages
452        if ($this->tag() === 'FAM:MARR') {
453            $element = Registry::elementFactory()->make('FAM:MARR:TYPE');
454            $type = $this->attribute('TYPE');
455
456            if ($type !== '') {
457                return $element->value($type, $this->record->tree());
458            }
459        }
460
461        // Custom FACT/EVEN - with a TYPE
462        if ($this->tag === 'FACT' || $this->tag === 'EVEN') {
463            $type = $this->attribute('TYPE');
464
465            if ($type !== '') {
466                if (!str_contains($type, '%')) {
467                    // Allow user-translations of custom types.
468                    $translated = I18N::translate($type);
469
470                    if ($translated !== $type) {
471                        return $translated;
472                    }
473                }
474
475                return e($type);
476            }
477        }
478
479        return Registry::elementFactory()->make($this->tag())->label();
480    }
481
482    /**
483     * This is a newly deleted fact, pending approval.
484     *
485     * @return void
486     */
487    public function setPendingDeletion(): void
488    {
489        $this->pending_deletion = true;
490        $this->pending_addition = false;
491    }
492
493    /**
494     * Is this a newly deleted fact, pending approval.
495     *
496     * @return bool
497     */
498    public function isPendingDeletion(): bool
499    {
500        return $this->pending_deletion;
501    }
502
503    /**
504     * This is a newly added fact, pending approval.
505     *
506     * @return void
507     */
508    public function setPendingAddition(): void
509    {
510        $this->pending_addition = true;
511        $this->pending_deletion = false;
512    }
513
514    /**
515     * Is this a newly added fact, pending approval.
516     *
517     * @return bool
518     */
519    public function isPendingAddition(): bool
520    {
521        return $this->pending_addition;
522    }
523
524    /**
525     * Source citations linked to this fact
526     *
527     * @return array<string>
528     */
529    public function getCitations(): array
530    {
531        preg_match_all('/\n(2 SOUR @(' . Gedcom::REGEX_XREF . ')@(?:\n[3-9] .*)*)/', $this->gedcom(), $matches, PREG_SET_ORDER);
532        $citations = [];
533        foreach ($matches as $match) {
534            $source = Registry::sourceFactory()->make($match[2], $this->record()->tree());
535            if ($source && $source->canShow()) {
536                $citations[] = $match[1];
537            }
538        }
539
540        return $citations;
541    }
542
543    /**
544     * Notes (inline and objects) linked to this fact
545     *
546     * @return array<string|Note>
547     */
548    public function getNotes(): array
549    {
550        $notes = [];
551        preg_match_all('/\n2 NOTE ?(.*(?:\n3.*)*)/', $this->gedcom(), $matches);
552        foreach ($matches[1] as $match) {
553            $note = preg_replace("/\n3 CONT ?/", "\n", $match);
554            if (preg_match('/@(' . Gedcom::REGEX_XREF . ')@/', $note, $nmatch)) {
555                $note = Registry::noteFactory()->make($nmatch[1], $this->record()->tree());
556                if ($note && $note->canShow()) {
557                    // A note object
558                    $notes[] = $note;
559                }
560            } else {
561                // An inline note
562                $notes[] = $note;
563            }
564        }
565
566        return $notes;
567    }
568
569    /**
570     * Media objects linked to this fact
571     *
572     * @return array<Media>
573     */
574    public function getMedia(): array
575    {
576        $media = [];
577        preg_match_all('/\n2 OBJE @(' . Gedcom::REGEX_XREF . ')@/', $this->gedcom(), $matches);
578        foreach ($matches[1] as $match) {
579            $obje = Registry::mediaFactory()->make($match, $this->record()->tree());
580            if ($obje && $obje->canShow()) {
581                $media[] = $obje;
582            }
583        }
584
585        return $media;
586    }
587
588    /**
589     * A one-line summary of the fact - for charts, etc.
590     *
591     * @return string
592     */
593    public function summary(): string
594    {
595        $attributes = [];
596        $target     = $this->target();
597        if ($target instanceof GedcomRecord) {
598            $attributes[] = $target->fullName();
599        } else {
600            // Fact value
601            $value = $this->value();
602            if ($value !== '' && $value !== 'Y') {
603                $attributes[] = '<bdi>' . e($value) . '</bdi>';
604            }
605            // Fact date
606            $date = $this->date();
607            if ($date->isOK()) {
608                if ($this->record() instanceof Individual && in_array($this->tag, Gedcom::BIRTH_EVENTS, true) && $this->record()->tree()->getPreference('SHOW_PARENTS_AGE')) {
609                    $attributes[] = $date->display() . view('fact-parents-age', ['individual' => $this->record(), 'birth_date' => $date]);
610                } else {
611                    $attributes[] = $date->display();
612                }
613            }
614            // Fact place
615            if ($this->place()->gedcomName() !== '') {
616                $attributes[] = $this->place()->shortName();
617            }
618        }
619
620        $class = 'fact_' . $this->tag;
621        if ($this->isPendingAddition()) {
622            $class .= ' wt-new';
623        } elseif ($this->isPendingDeletion()) {
624            $class .= ' wt-old';
625        }
626
627        $label = '<span class="label">' . $this->label() . '</span>';
628        $value = '<span class="field" dir="auto">' . implode(' — ', $attributes) . '</span>';
629
630        /* I18N: a label/value pair, such as “Occupation: Farmer”. Some languages may need to change the punctuation. */
631        return '<div class="' . $class . '">' . I18N::translate('%1$s: %2$s', $label, $value) . '</div>';
632    }
633
634    /**
635     * A one-line summary of the fact - for the clipboard, etc.
636     *
637     * @return string
638     */
639    public function name(): string
640    {
641        $items  = [$this->label()];
642        $target = $this->target();
643
644        if ($target instanceof GedcomRecord) {
645            $items[] = '<bdi>' . $target->fullName() . '</bdi>';
646        } else {
647            // Fact value
648            $value = $this->value();
649            if ($value !== '' && $value !== 'Y') {
650                $items[] = '<bdi>' . e($value) . '</bdi>';
651            }
652
653            // Fact date
654            if ($this->date()->isOK()) {
655                $items[] = $this->date()->minimumDate()->format('%Y');
656            }
657
658            // Fact place
659            if ($this->place()->gedcomName() !== '') {
660                $items[] = $this->place()->shortName();
661            }
662        }
663
664        return implode(' — ', $items);
665    }
666
667    /**
668     * Helper functions to sort facts
669     *
670     * @return Closure
671     */
672    private static function dateComparator(): Closure
673    {
674        return static function (Fact $a, Fact $b): int {
675            if ($a->date()->isOK() && $b->date()->isOK()) {
676                // If both events have dates, compare by date
677                $ret = Date::compare($a->date(), $b->date());
678
679                if ($ret === 0) {
680                    // If dates overlap, compare by fact type
681                    $ret = self::typeComparator()($a, $b);
682
683                    // If the fact type is also the same, retain the initial order
684                    if ($ret === 0) {
685                        $ret = $a->sortOrder <=> $b->sortOrder;
686                    }
687                }
688
689                return $ret;
690            }
691
692            // One or both events have no date - retain the initial order
693            return $a->sortOrder <=> $b->sortOrder;
694        };
695    }
696
697    /**
698     * Helper functions to sort facts.
699     *
700     * @return Closure
701     */
702    public static function typeComparator(): Closure
703    {
704        static $factsort = [];
705
706        if ($factsort === []) {
707            $factsort = array_flip(self::FACT_ORDER);
708        }
709
710        return static function (Fact $a, Fact $b) use ($factsort): int {
711            // Facts from same families stay grouped together
712            // Keep MARR and DIV from the same families from mixing with events from other FAMs
713            // Use the original order in which the facts were added
714            if ($a->record instanceof Family && $b->record instanceof Family && $a->record !== $b->record) {
715                return $a->sortOrder - $b->sortOrder;
716            }
717
718            $atag = $a->tag;
719            $btag = $b->tag;
720
721            // Events not in the above list get mapped onto one that is.
722            if (!array_key_exists($atag, $factsort)) {
723                $atag = '_????_';
724            }
725
726            if (!array_key_exists($btag, $factsort)) {
727                $btag = '_????_';
728            }
729
730            // - Don't let dated after DEAT/BURI facts sort non-dated facts before DEAT/BURI
731            // - Treat dated after BURI facts as BURI instead
732            if ($a->attribute('DATE') !== '' && $factsort[$atag] > $factsort['BURI'] && $factsort[$atag] < $factsort['CHAN']) {
733                $atag = 'BURI';
734            }
735
736            if ($b->attribute('DATE') !== '' && $factsort[$btag] > $factsort['BURI'] && $factsort[$btag] < $factsort['CHAN']) {
737                $btag = 'BURI';
738            }
739
740            $ret = $factsort[$atag] - $factsort[$btag];
741
742            // If facts are the same then put dated facts before non-dated facts
743            if ($ret === 0) {
744                if ($a->attribute('DATE') !== '' && $b->attribute('DATE') === '') {
745                    return -1;
746                }
747
748                if ($b->attribute('DATE') !== '' && $a->attribute('DATE') === '') {
749                    return 1;
750                }
751
752                // If no sorting preference, then keep original ordering
753                $ret = $a->sortOrder - $b->sortOrder;
754            }
755
756            return $ret;
757        };
758    }
759
760    /**
761     * A multi-key sort
762     * 1. First divide the facts into two arrays one set with dates and one set without dates
763     * 2. Sort each of the two new arrays, the date using the compare date function, the non-dated
764     * using the compare type function
765     * 3. Then merge the arrays back into the original array using the compare type function
766     *
767     * @param Collection<int,Fact> $unsorted
768     *
769     * @return Collection<int,Fact>
770     */
771    public static function sortFacts(Collection $unsorted): Collection
772    {
773        $dated    = [];
774        $nondated = [];
775        $sorted   = [];
776
777        // Split the array into dated and non-dated arrays
778        $order = 0;
779
780        foreach ($unsorted as $fact) {
781            $fact->sortOrder = $order;
782            $order++;
783
784            if ($fact->date()->isOK()) {
785                $dated[] = $fact;
786            } else {
787                $nondated[] = $fact;
788            }
789        }
790
791        usort($dated, self::dateComparator());
792        usort($nondated, self::typeComparator());
793
794        // Merge the arrays
795        $dc = count($dated);
796        $nc = count($nondated);
797        $i  = 0;
798        $j  = 0;
799
800        // while there is anything in the dated array continue merging
801        while ($i < $dc) {
802            // compare each fact by type to merge them in order
803            if ($j < $nc && self::typeComparator()($dated[$i], $nondated[$j]) > 0) {
804                $sorted[] = $nondated[$j];
805                $j++;
806            } else {
807                $sorted[] = $dated[$i];
808                $i++;
809            }
810        }
811
812        // get anything that might be left in the nondated array
813        while ($j < $nc) {
814            $sorted[] = $nondated[$j];
815            $j++;
816        }
817
818        return new Collection($sorted);
819    }
820
821    /**
822     * Sort fact/event tags using the same order that we use for facts.
823     *
824     * @param Collection<int,string> $unsorted
825     *
826     * @return Collection<int,string>
827     */
828    public static function sortFactTags(Collection $unsorted): Collection
829    {
830        $tag_order = array_flip(self::FACT_ORDER);
831
832        return $unsorted->sort(static function (string $x, string $y) use ($tag_order): int {
833            $sort_x = $tag_order[$x] ?? $tag_order['_????_'];
834            $sort_y = $tag_order[$y] ?? $tag_order['_????_'];
835
836            return $sort_x - $sort_y;
837        });
838    }
839
840    /**
841     * Allow native PHP functions such as array_unique() to work with objects
842     *
843     * @return string
844     */
845    public function __toString(): string
846    {
847        return $this->id . '@' . $this->record->xref();
848    }
849}
850