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