xref: /webtrees/app/Individual.php (revision f94b830f9a4ef11b0a336999817b29b5b6e0acf0)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Closure;
23use Fisharebest\ExtCalendar\GregorianCalendar;
24use Fisharebest\Webtrees\Contracts\UserInterface;
25use Fisharebest\Webtrees\Elements\PedigreeLinkageType;
26use Fisharebest\Webtrees\Http\RequestHandlers\IndividualPage;
27use Illuminate\Database\Capsule\Manager as DB;
28use Illuminate\Support\Collection;
29
30use function array_key_exists;
31use function count;
32use function in_array;
33use function preg_match;
34
35/**
36 * A GEDCOM individual (INDI) object.
37 */
38class Individual extends GedcomRecord
39{
40    public const RECORD_TYPE = 'INDI';
41
42    // Placeholders to indicate unknown names
43    public const NOMEN_NESCIO     = '@N.N.';
44    public const PRAENOMEN_NESCIO = '@P.N.';
45
46    protected const ROUTE_NAME = IndividualPage::class;
47
48    /** Used in some lists to keep track of this individual’s generation in that list */
49    public ?int $generation = null;
50
51    private ?Date $estimated_birth_date = null;
52
53    private ?Date $estimated_death_date = null;
54
55    /**
56     * A closure which will compare individuals by birth date.
57     *
58     * @return Closure(Individual,Individual):int
59     */
60    public static function birthDateComparator(): Closure
61    {
62        return static function (Individual $x, Individual $y): int {
63            return Date::compare($x->getEstimatedBirthDate(), $y->getEstimatedBirthDate());
64        };
65    }
66
67    /**
68     * A closure which will compare individuals by death date.
69     *
70     * @return Closure(Individual,Individual):int
71     */
72    public static function deathDateComparator(): Closure
73    {
74        return static function (Individual $x, Individual $y): int {
75            return Date::compare($x->getEstimatedDeathDate(), $y->getEstimatedDeathDate());
76        };
77    }
78
79    /**
80     * Can the name of this record be shown?
81     *
82     * @param int|null $access_level
83     *
84     * @return bool
85     */
86    public function canShowName(int $access_level = null): bool
87    {
88        $access_level ??= Auth::accessLevel($this->tree);
89
90        return (int) $this->tree->getPreference('SHOW_LIVING_NAMES') >= $access_level || $this->canShow($access_level);
91    }
92
93    /**
94     * Can this individual be shown?
95     *
96     * @param int $access_level
97     *
98     * @return bool
99     */
100    protected function canShowByType(int $access_level): bool
101    {
102        // Dead people...
103        if ((int) $this->tree->getPreference('SHOW_DEAD_PEOPLE') >= $access_level && $this->isDead()) {
104            $keep_alive             = false;
105            $KEEP_ALIVE_YEARS_BIRTH = (int) $this->tree->getPreference('KEEP_ALIVE_YEARS_BIRTH');
106            if ($KEEP_ALIVE_YEARS_BIRTH) {
107                preg_match_all('/\n1 (?:' . implode('|', Gedcom::BIRTH_EVENTS) . ').*(?:\n[2-9].*)*\n2 DATE (.+)/', $this->gedcom, $matches, PREG_SET_ORDER);
108                foreach ($matches as $match) {
109                    $date = new Date($match[1]);
110                    if ($date->isOK() && $date->gregorianYear() + $KEEP_ALIVE_YEARS_BIRTH > date('Y')) {
111                        $keep_alive = true;
112                        break;
113                    }
114                }
115            }
116            $KEEP_ALIVE_YEARS_DEATH = (int) $this->tree->getPreference('KEEP_ALIVE_YEARS_DEATH');
117            if ($KEEP_ALIVE_YEARS_DEATH) {
118                preg_match_all('/\n1 (?:' . implode('|', Gedcom::DEATH_EVENTS) . ').*(?:\n[2-9].*)*\n2 DATE (.+)/', $this->gedcom, $matches, PREG_SET_ORDER);
119                foreach ($matches as $match) {
120                    $date = new Date($match[1]);
121                    if ($date->isOK() && $date->gregorianYear() + $KEEP_ALIVE_YEARS_DEATH > date('Y')) {
122                        $keep_alive = true;
123                        break;
124                    }
125                }
126            }
127            if (!$keep_alive) {
128                return true;
129            }
130        }
131        // Consider relationship privacy (unless an admin is applying download restrictions)
132        $user_path_length = (int) $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_PATH_LENGTH);
133        $gedcomid         = $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF);
134
135        if ($gedcomid !== '' && $user_path_length > 0) {
136            return self::isRelated($this, $user_path_length);
137        }
138
139        // No restriction found - show living people to members only:
140        return Auth::PRIV_USER >= $access_level;
141    }
142
143    /**
144     * For relationship privacy calculations - is this individual a close relative?
145     *
146     * @param Individual $target
147     * @param int        $distance
148     *
149     * @return bool
150     */
151    private static function isRelated(Individual $target, int $distance): bool
152    {
153        static $cache = null;
154
155        $user_individual = Registry::individualFactory()->make($target->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF), $target->tree);
156        if ($user_individual) {
157            if (!$cache) {
158                $cache = [
159                    0 => [$user_individual],
160                    1 => [],
161                ];
162                foreach ($user_individual->facts(['FAMC', 'FAMS'], false, Auth::PRIV_HIDE) as $fact) {
163                    $family = $fact->target();
164                    if ($family instanceof Family) {
165                        $cache[1][] = $family;
166                    }
167                }
168            }
169        } else {
170            // No individual linked to this account? Cannot use relationship privacy.
171            return true;
172        }
173
174        // Double the distance, as we count the INDI-FAM and FAM-INDI links separately
175        $distance *= 2;
176
177        // Consider each path length in turn
178        for ($n = 0; $n <= $distance; ++$n) {
179            if (array_key_exists($n, $cache)) {
180                // We have already calculated all records with this length
181                if ($n % 2 === 0 && in_array($target, $cache[$n], true)) {
182                    return true;
183                }
184            } else {
185                // Need to calculate these paths
186                $cache[$n] = [];
187                if ($n % 2 === 0) {
188                    // Add FAM->INDI links
189                    foreach ($cache[$n - 1] as $family) {
190                        foreach ($family->facts(['HUSB', 'WIFE', 'CHIL'], false, Auth::PRIV_HIDE) as $fact) {
191                            $individual = $fact->target();
192                            // Don’t backtrack
193                            if ($individual instanceof self && !in_array($individual, $cache[$n - 2], true)) {
194                                $cache[$n][] = $individual;
195                            }
196                        }
197                    }
198                    if (in_array($target, $cache[$n], true)) {
199                        return true;
200                    }
201                } else {
202                    // Add INDI->FAM links
203                    foreach ($cache[$n - 1] as $individual) {
204                        foreach ($individual->facts(['FAMC', 'FAMS'], false, Auth::PRIV_HIDE) as $fact) {
205                            $family = $fact->target();
206                            // Don’t backtrack
207                            if ($family instanceof Family && !in_array($family, $cache[$n - 2], true)) {
208                                $cache[$n][] = $family;
209                            }
210                        }
211                    }
212                }
213            }
214        }
215
216        return false;
217    }
218
219    /**
220     * Generate a private version of this record
221     *
222     * @param int $access_level
223     *
224     * @return string
225     */
226    protected function createPrivateGedcomRecord(int $access_level): string
227    {
228        $SHOW_PRIVATE_RELATIONSHIPS = (bool) $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
229
230        $rec = '0 @' . $this->xref . '@ INDI';
231        if ((int) $this->tree->getPreference('SHOW_LIVING_NAMES') >= $access_level) {
232            // Show all the NAME tags, including subtags
233            foreach ($this->facts(['NAME']) as $fact) {
234                $rec .= "\n" . $fact->gedcom();
235            }
236        }
237        // Just show the 1 FAMC/FAMS tag, not any subtags, which may contain private data
238        preg_match_all('/\n1 (?:FAMC|FAMS) @(' . Gedcom::REGEX_XREF . ')@/', $this->gedcom, $matches, PREG_SET_ORDER);
239        foreach ($matches as $match) {
240            $rela = Registry::familyFactory()->make($match[1], $this->tree);
241            if ($rela && ($SHOW_PRIVATE_RELATIONSHIPS || $rela->canShow($access_level))) {
242                $rec .= $match[0];
243            }
244        }
245        // Don’t privatize sex.
246        if (preg_match('/\n1 SEX [MFU]/', $this->gedcom, $match)) {
247            $rec .= $match[0];
248        }
249
250        return $rec;
251    }
252
253    /**
254     * Calculate whether this individual is living or dead.
255     * If not known to be dead, then assume living.
256     *
257     * @return bool
258     */
259    public function isDead(): bool
260    {
261        $MAX_ALIVE_AGE = (int) $this->tree->getPreference('MAX_ALIVE_AGE');
262        $today_jd      = Registry::timestampFactory()->now()->julianDay();
263
264        // "1 DEAT Y" or "1 DEAT/2 DATE" or "1 DEAT/2 PLAC"
265        if (preg_match('/\n1 (?:' . implode('|', Gedcom::DEATH_EVENTS) . ')(?: Y|(?:\n[2-9].+)*\n2 (DATE|PLAC) )/', $this->gedcom)) {
266            return true;
267        }
268
269        // If any event occurred more than $MAX_ALIVE_AGE years ago, then assume the individual is dead
270        if (preg_match_all('/\n2 DATE (.+)/', $this->gedcom, $date_matches)) {
271            foreach ($date_matches[1] as $date_match) {
272                $date = new Date($date_match);
273                if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * $MAX_ALIVE_AGE) {
274                    return true;
275                }
276            }
277            // The individual has one or more dated events. All are less than $MAX_ALIVE_AGE years ago.
278            // If one of these is a birth, the individual must be alive.
279            if (preg_match('/\n1 BIRT(?:\n[2-9].+)*\n2 DATE /', $this->gedcom)) {
280                return false;
281            }
282        }
283
284        // If we found no conclusive dates then check the dates of close relatives.
285
286        // Check parents (birth and adopted)
287        foreach ($this->childFamilies(Auth::PRIV_HIDE) as $family) {
288            foreach ($family->spouses(Auth::PRIV_HIDE) as $parent) {
289                // Assume parents are no more than 45 years older than their children
290                preg_match_all('/\n2 DATE (.+)/', $parent->gedcom, $date_matches);
291                foreach ($date_matches[1] as $date_match) {
292                    $date = new Date($date_match);
293                    if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE + 45)) {
294                        return true;
295                    }
296                }
297            }
298        }
299
300        // Check spouses
301        foreach ($this->spouseFamilies(Auth::PRIV_HIDE) as $family) {
302            preg_match_all('/\n2 DATE (.+)/', $family->gedcom, $date_matches);
303            foreach ($date_matches[1] as $date_match) {
304                $date = new Date($date_match);
305                // Assume marriage occurs after age of 10
306                if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE - 10)) {
307                    return true;
308                }
309            }
310            // Check spouse dates
311            $spouse = $family->spouse($this, Auth::PRIV_HIDE);
312            if ($spouse) {
313                preg_match_all('/\n2 DATE (.+)/', $spouse->gedcom, $date_matches);
314                foreach ($date_matches[1] as $date_match) {
315                    $date = new Date($date_match);
316                    // Assume max age difference between spouses of 40 years
317                    if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE + 40)) {
318                        return true;
319                    }
320                }
321            }
322            // Check child dates
323            foreach ($family->children(Auth::PRIV_HIDE) as $child) {
324                preg_match_all('/\n2 DATE (.+)/', $child->gedcom, $date_matches);
325                // Assume children born after age of 15
326                foreach ($date_matches[1] as $date_match) {
327                    $date = new Date($date_match);
328                    if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE - 15)) {
329                        return true;
330                    }
331                }
332                // Check grandchildren
333                foreach ($child->spouseFamilies(Auth::PRIV_HIDE) as $child_family) {
334                    foreach ($child_family->children(Auth::PRIV_HIDE) as $grandchild) {
335                        preg_match_all('/\n2 DATE (.+)/', $grandchild->gedcom, $date_matches);
336                        // Assume grandchildren born after age of 30
337                        foreach ($date_matches[1] as $date_match) {
338                            $date = new Date($date_match);
339                            if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE - 30)) {
340                                return true;
341                            }
342                        }
343                    }
344                }
345            }
346        }
347
348        return false;
349    }
350
351    /**
352     * Find the highlighted media object for an individual
353     *
354     * @return MediaFile|null
355     */
356    public function findHighlightedMediaFile(): ?MediaFile
357    {
358        $fact = $this->facts(['OBJE'])
359            ->first(static function (Fact $fact): bool {
360                $media = $fact->target();
361
362                return $media instanceof Media && $media->firstImageFile() instanceof MediaFile;
363            });
364
365        if ($fact instanceof Fact && $fact->target() instanceof Media) {
366            return $fact->target()->firstImageFile();
367        }
368
369        return null;
370    }
371
372    /**
373     * Display the preferred image for this individual.
374     * Use an icon if no image is available.
375     *
376     * @param int           $width      Pixels
377     * @param int           $height     Pixels
378     * @param string        $fit        "crop" or "contain"
379     * @param array<string> $attributes Additional HTML attributes
380     *
381     * @return string
382     */
383    public function displayImage(int $width, int $height, string $fit, array $attributes): string
384    {
385        $media_file = $this->findHighlightedMediaFile();
386
387        if ($media_file !== null) {
388            return $media_file->displayImage($width, $height, $fit, $attributes);
389        }
390
391        if ($this->tree->getPreference('USE_SILHOUETTE')) {
392            return '<i class="icon-silhouette icon-silhouette-' . strtolower($this->sex()) . ' wt-icon-flip-rtl"></i>';
393        }
394
395        return '';
396    }
397
398    /**
399     * Get the date of birth
400     *
401     * @return Date
402     */
403    public function getBirthDate(): Date
404    {
405        foreach ($this->getAllBirthDates() as $date) {
406            if ($date->isOK()) {
407                return $date;
408            }
409        }
410
411        return new Date('');
412    }
413
414    /**
415     * Get the place of birth
416     *
417     * @return Place
418     */
419    public function getBirthPlace(): Place
420    {
421        foreach ($this->getAllBirthPlaces() as $place) {
422            return $place;
423        }
424
425        return new Place('', $this->tree);
426    }
427
428    /**
429     * Get the date of death
430     *
431     * @return Date
432     */
433    public function getDeathDate(): Date
434    {
435        foreach ($this->getAllDeathDates() as $date) {
436            if ($date->isOK()) {
437                return $date;
438            }
439        }
440
441        return new Date('');
442    }
443
444    /**
445     * Get the place of death
446     *
447     * @return Place
448     */
449    public function getDeathPlace(): Place
450    {
451        foreach ($this->getAllDeathPlaces() as $place) {
452            return $place;
453        }
454
455        return new Place('', $this->tree);
456    }
457
458    /**
459     * Get the range of years in which a individual lived. e.g. “1870–”, “1870–1920”, “–1920”.
460     * Provide the place and full date using a tooltip.
461     * For consistent layout in charts, etc., show just a “–” when no dates are known.
462     * Note that this is a (non-breaking) en-dash, and not a hyphen.
463     *
464     * @return string
465     */
466    public function lifespan(): string
467    {
468        // Just the first part of the place name.
469        $birth_place = strip_tags($this->getBirthPlace()->shortName());
470        $death_place = strip_tags($this->getDeathPlace()->shortName());
471
472        // Remove markup from dates.  Use UTF_FSI / UTF_PDI instead of <bdi></bdi>, as
473        // we cannot use HTML markup in title attributes.
474        $birth_date = "\u{2068}" . strip_tags($this->getBirthDate()->display()) . "\u{2069}";
475        $death_date = "\u{2068}" . strip_tags($this->getDeathDate()->display()) . "\u{2069}";
476
477        // Use minimum and maximum dates - to agree with the age calculations.
478        $birth_year = $this->getBirthDate()->minimumDate()->format('%Y');
479        $death_year = $this->getDeathDate()->maximumDate()->format('%Y');
480
481        if ($birth_year === '') {
482            $birth_year = I18N::translate('…');
483        }
484
485        if ($death_year === '' && $this->isDead()) {
486            $death_year = I18N::translate('…');
487        }
488
489        /* I18N: A range of years, e.g. “1870–”, “1870–1920”, “–1920” */
490        return I18N::translate(
491            '%1$s–%2$s',
492            '<span title="' . $birth_place . ' ' . $birth_date . '">' . $birth_year . '</span>',
493            '<span title="' . $death_place . ' ' . $death_date . '">' . $death_year . '</span>'
494        );
495    }
496
497    /**
498     * Get all the birth dates - for the individual lists.
499     *
500     * @return array<Date>
501     */
502    public function getAllBirthDates(): array
503    {
504        foreach (Gedcom::BIRTH_EVENTS as $event) {
505            $dates = $this->getAllEventDates([$event]);
506
507            if ($dates !== []) {
508                return $dates;
509            }
510        }
511
512        return [];
513    }
514
515    /**
516     * Gat all the birth places - for the individual lists.
517     *
518     * @return array<Place>
519     */
520    public function getAllBirthPlaces(): array
521    {
522        foreach (Gedcom::BIRTH_EVENTS as $event) {
523            $places = $this->getAllEventPlaces([$event]);
524
525            if ($places !== []) {
526                return $places;
527            }
528        }
529
530        return [];
531    }
532
533    /**
534     * Get all the death dates - for the individual lists.
535     *
536     * @return array<Date>
537     */
538    public function getAllDeathDates(): array
539    {
540        foreach (Gedcom::DEATH_EVENTS as $event) {
541            $dates = $this->getAllEventDates([$event]);
542
543            if ($dates !== []) {
544                return $dates;
545            }
546        }
547
548        return [];
549    }
550
551    /**
552     * Get all the death places - for the individual lists.
553     *
554     * @return array<Place>
555     */
556    public function getAllDeathPlaces(): array
557    {
558        foreach (Gedcom::DEATH_EVENTS as $event) {
559            $places = $this->getAllEventPlaces([$event]);
560
561            if ($places !== []) {
562                return $places;
563            }
564        }
565
566        return [];
567    }
568
569    /**
570     * Generate an estimate for the date of birth, based on dates of parents/children/spouses
571     *
572     * @return Date
573     */
574    public function getEstimatedBirthDate(): Date
575    {
576        if ($this->estimated_birth_date === null) {
577            foreach ($this->getAllBirthDates() as $date) {
578                if ($date->isOK()) {
579                    $this->estimated_birth_date = $date;
580                    break;
581                }
582            }
583            if ($this->estimated_birth_date === null) {
584                $min = [];
585                $max = [];
586                $tmp = $this->getDeathDate();
587                if ($tmp->isOK()) {
588                    $min[] = $tmp->minimumJulianDay() - $this->tree->getPreference('MAX_ALIVE_AGE') * 365;
589                    $max[] = $tmp->maximumJulianDay();
590                }
591                foreach ($this->childFamilies() as $family) {
592                    $tmp = $family->getMarriageDate();
593                    if ($tmp->isOK()) {
594                        $min[] = $tmp->maximumJulianDay() - 365 * 1;
595                        $max[] = $tmp->minimumJulianDay() + 365 * 30;
596                    }
597                    $husband = $family->husband();
598                    if ($husband instanceof self) {
599                        $tmp = $husband->getBirthDate();
600                        if ($tmp->isOK()) {
601                            $min[] = $tmp->maximumJulianDay() + 365 * 15;
602                            $max[] = $tmp->minimumJulianDay() + 365 * 65;
603                        }
604                    }
605                    $wife = $family->wife();
606                    if ($wife instanceof self) {
607                        $tmp = $wife->getBirthDate();
608                        if ($tmp->isOK()) {
609                            $min[] = $tmp->maximumJulianDay() + 365 * 15;
610                            $max[] = $tmp->minimumJulianDay() + 365 * 45;
611                        }
612                    }
613                    foreach ($family->children() as $child) {
614                        $tmp = $child->getBirthDate();
615                        if ($tmp->isOK()) {
616                            $min[] = $tmp->maximumJulianDay() - 365 * 30;
617                            $max[] = $tmp->minimumJulianDay() + 365 * 30;
618                        }
619                    }
620                }
621                foreach ($this->spouseFamilies() as $family) {
622                    $tmp = $family->getMarriageDate();
623                    if ($tmp->isOK()) {
624                        $min[] = $tmp->maximumJulianDay() - 365 * 45;
625                        $max[] = $tmp->minimumJulianDay() - 365 * 15;
626                    }
627                    $spouse = $family->spouse($this);
628                    if ($spouse) {
629                        $tmp = $spouse->getBirthDate();
630                        if ($tmp->isOK()) {
631                            $min[] = $tmp->maximumJulianDay() - 365 * 25;
632                            $max[] = $tmp->minimumJulianDay() + 365 * 25;
633                        }
634                    }
635                    foreach ($family->children() as $child) {
636                        $tmp = $child->getBirthDate();
637                        if ($tmp->isOK()) {
638                            $min[] = $tmp->maximumJulianDay() - 365 * ($this->sex() === 'F' ? 45 : 65);
639                            $max[] = $tmp->minimumJulianDay() - 365 * 15;
640                        }
641                    }
642                }
643                if ($min && $max) {
644                    $gregorian_calendar = new GregorianCalendar();
645
646                    [$year] = $gregorian_calendar->jdToYmd(intdiv(max($min) + min($max), 2));
647                    $this->estimated_birth_date = new Date('EST ' . $year);
648                } else {
649                    $this->estimated_birth_date = new Date(''); // always return a date object
650                }
651            }
652        }
653
654        return $this->estimated_birth_date;
655    }
656
657    /**
658     * Generate an estimated date of death.
659     *
660     * @return Date
661     */
662    public function getEstimatedDeathDate(): Date
663    {
664        if ($this->estimated_death_date === null) {
665            foreach ($this->getAllDeathDates() as $date) {
666                if ($date->isOK()) {
667                    $this->estimated_death_date = $date;
668                    break;
669                }
670            }
671            if ($this->estimated_death_date === null) {
672                if ($this->getEstimatedBirthDate()->minimumJulianDay()) {
673                    $max_alive_age              = (int) $this->tree->getPreference('MAX_ALIVE_AGE');
674                    $this->estimated_death_date = $this->getEstimatedBirthDate()->addYears($max_alive_age, 'BEF');
675                } else {
676                    $this->estimated_death_date = new Date(''); // always return a date object
677                }
678            }
679        }
680
681        return $this->estimated_death_date;
682    }
683
684    /**
685     * Get the sex - M F or U
686     * Use the un-privatised gedcom record. We call this function during
687     * the privatize-gedcom function, and we are allowed to know this.
688     *
689     * @return string
690     */
691    public function sex(): string
692    {
693        if (preg_match('/\n1 SEX ([MFX])/', $this->gedcom . $this->pending, $match)) {
694            return $match[1];
695        }
696
697        return 'U';
698    }
699
700    /**
701     * Get a list of this individual’s spouse families
702     *
703     * @param int|null $access_level
704     *
705     * @return Collection<int,Family>
706     */
707    public function spouseFamilies(int $access_level = null): Collection
708    {
709        $access_level ??= Auth::accessLevel($this->tree);
710
711        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
712            $access_level = Auth::PRIV_HIDE;
713        }
714
715        $families = new Collection();
716        foreach ($this->facts(['FAMS'], false, $access_level) as $fact) {
717            $family = $fact->target();
718            if ($family instanceof Family && $family->canShow($access_level)) {
719                $families->push($family);
720            }
721        }
722
723        return new Collection($families);
724    }
725
726    /**
727     * Get the current spouse of this individual.
728     *
729     * Where an individual has multiple spouses, assume they are stored
730     * in chronological order, and take the last one found.
731     *
732     * @return Individual|null
733     */
734    public function getCurrentSpouse(): ?Individual
735    {
736        $family = $this->spouseFamilies()->last();
737
738        if ($family instanceof Family) {
739            return $family->spouse($this);
740        }
741
742        return null;
743    }
744
745    /**
746     * Count the children belonging to this individual.
747     *
748     * @return int
749     */
750    public function numberOfChildren(): int
751    {
752        if (preg_match('/\n1 NCHI (\d+)(?:\n|$)/', $this->gedcom(), $match)) {
753            return (int) $match[1];
754        }
755
756        $children = [];
757        foreach ($this->spouseFamilies() as $fam) {
758            foreach ($fam->children() as $child) {
759                $children[$child->xref()] = true;
760            }
761        }
762
763        return count($children);
764    }
765
766    /**
767     * Get a list of this individual’s child families (i.e. their parents).
768     *
769     * @param int|null $access_level
770     *
771     * @return Collection<int,Family>
772     */
773    public function childFamilies(int $access_level = null): Collection
774    {
775        $access_level ??= Auth::accessLevel($this->tree);
776
777        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
778            $access_level = Auth::PRIV_HIDE;
779        }
780
781        $families = new Collection();
782
783        foreach ($this->facts(['FAMC'], false, $access_level) as $fact) {
784            $family = $fact->target();
785            if ($family instanceof Family && $family->canShow($access_level)) {
786                $families->push($family);
787            }
788        }
789
790        return $families;
791    }
792
793    /**
794     * Get a list of step-parent families.
795     *
796     * @return Collection<int,Family>
797     */
798    public function childStepFamilies(): Collection
799    {
800        $step_families = new Collection();
801        $families      = $this->childFamilies();
802        foreach ($families as $family) {
803            foreach ($family->spouses() as $parent) {
804                foreach ($parent->spouseFamilies() as $step_family) {
805                    if (!$families->containsStrict($step_family)) {
806                        $step_families->add($step_family);
807                    }
808                }
809            }
810        }
811
812        return $step_families->uniqueStrict(static function (Family $family): string {
813            return $family->xref();
814        });
815    }
816
817    /**
818     * Get a list of step-parent families.
819     *
820     * @return Collection<int,Family>
821     */
822    public function spouseStepFamilies(): Collection
823    {
824        $step_families = [];
825        $families      = $this->spouseFamilies();
826
827        foreach ($families as $family) {
828            $spouse = $family->spouse($this);
829
830            if ($spouse instanceof self) {
831                foreach ($family->spouse($this)->spouseFamilies() as $step_family) {
832                    if (!$families->containsStrict($step_family)) {
833                        $step_families[] = $step_family;
834                    }
835                }
836            }
837        }
838
839        return new Collection($step_families);
840    }
841
842    /**
843     * A label for a parental family group
844     *
845     * @param Family $family
846     *
847     * @return string
848     */
849    public function getChildFamilyLabel(Family $family): string
850    {
851        $fact = $this->facts(['FAMC'])->first(static fn (Fact $fact): bool => $fact->target() === $family);
852
853        if ($fact instanceof Fact) {
854            $pedigree = $fact->attribute('PEDI');
855        } else {
856            $pedigree = '';
857        }
858
859        $values = [
860            PedigreeLinkageType::VALUE_BIRTH   => I18N::translate('Family with parents'),
861            PedigreeLinkageType::VALUE_ADOPTED => I18N::translate('Family with adoptive parents'),
862            PedigreeLinkageType::VALUE_FOSTER  => I18N::translate('Family with foster parents'),
863            /* I18N: “sealing” is a Mormon ceremony. */
864            PedigreeLinkageType::VALUE_SEALING => I18N::translate('Family with sealing parents'),
865            /* I18N: “rada” is an Arabic word, pronounced “ra DAH”. It is child-to-parent pedigree, established by wet-nursing. */
866            PedigreeLinkageType::VALUE_RADA    => I18N::translate('Family with rada parents'),
867        ];
868
869        return $values[$pedigree] ?? $values[PedigreeLinkageType::VALUE_BIRTH];
870    }
871
872    /**
873     * Create a label for a step family
874     *
875     * @param Family $step_family
876     *
877     * @return string
878     */
879    public function getStepFamilyLabel(Family $step_family): string
880    {
881        foreach ($this->childFamilies() as $family) {
882            if ($family !== $step_family) {
883                // Must be a step-family
884                foreach ($family->spouses() as $parent) {
885                    foreach ($step_family->spouses() as $step_parent) {
886                        if ($parent === $step_parent) {
887                            // One common parent - must be a step family
888                            if ($parent->sex() === 'M') {
889                                // Father’s family with someone else
890                                if ($step_family->spouse($step_parent)) {
891                                    /* I18N: A step-family. %s is an individual’s name */
892                                    return I18N::translate('Father’s family with %s', $step_family->spouse($step_parent)->fullName());
893                                }
894
895                                /* I18N: A step-family. */
896                                return I18N::translate('Father’s family with an unknown individual');
897                            }
898
899                            // Mother’s family with someone else
900                            if ($step_family->spouse($step_parent)) {
901                                /* I18N: A step-family. %s is an individual’s name */
902                                return I18N::translate('Mother’s family with %s', $step_family->spouse($step_parent)->fullName());
903                            }
904
905                            /* I18N: A step-family. */
906                            return I18N::translate('Mother’s family with an unknown individual');
907                        }
908                    }
909                }
910            }
911        }
912
913        // Perahps same parents - but a different family record?
914        return I18N::translate('Family with parents');
915    }
916
917    /**
918     * Get the description for the family.
919     *
920     * For example, "XXX's family with new wife".
921     *
922     * @param Family $family
923     *
924     * @return string
925     */
926    public function getSpouseFamilyLabel(Family $family): string
927    {
928        $spouse = $family->spouse($this);
929        if ($spouse) {
930            /* I18N: %s is the spouse name */
931            return I18N::translate('Family with %s', $spouse->fullName());
932        }
933
934        return $family->fullName();
935    }
936
937    /**
938     * If this object has no name, what do we call it?
939     *
940     * @return string
941     */
942    public function getFallBackName(): string
943    {
944        return '@P.N. /@N.N./';
945    }
946
947    /**
948     * Convert a name record into ‘full’ and ‘sort’ versions.
949     * Use the NAME field to generate the ‘full’ version, as the
950     * gedcom spec says that this is the individual’s name, as they would write it.
951     * Use the SURN field to generate the sortable names. Note that this field
952     * may also be used for the ‘true’ surname, perhaps spelt differently to that
953     * recorded in the NAME field. e.g.
954     *
955     * 1 NAME Robert /de Gliderow/
956     * 2 GIVN Robert
957     * 2 SPFX de
958     * 2 SURN CLITHEROW
959     * 2 NICK The Bald
960     *
961     * full=>'Robert de Gliderow 'The Bald''
962     * sort=>'CLITHEROW, ROBERT'
963     *
964     * Handle multiple surnames, either as;
965     *
966     * 1 NAME Carlos /Vasquez/ y /Sante/
967     * or
968     * 1 NAME Carlos /Vasquez y Sante/
969     * 2 GIVN Carlos
970     * 2 SURN Vasquez,Sante
971     *
972     * @param string $type
973     * @param string $value
974     * @param string $gedcom
975     *
976     * @return void
977     */
978    protected function addName(string $type, string $value, string $gedcom): void
979    {
980        ////////////////////////////////////////////////////////////////////////////
981        // Extract the structured name parts - use for "sortable" names and indexes
982        ////////////////////////////////////////////////////////////////////////////
983
984        $sublevel = 1 + (int) substr($gedcom, 0, 1);
985        $GIVN     = preg_match('/\n' . $sublevel . ' GIVN (.+)/', $gedcom, $match) === 1 ? $match[1] : '';
986        $SURN     = preg_match('/\n' . $sublevel . ' SURN (.+)/', $gedcom, $match) === 1 ? $match[1] : '';
987
988        // SURN is an comma-separated list of surnames...
989        if ($SURN !== '') {
990            $SURNS = preg_split('/ *, */', $SURN);
991        } else {
992            $SURNS = [];
993        }
994
995        // ...so is GIVN - but nobody uses it like that
996        $GIVN = str_replace('/ *, */', ' ', $GIVN);
997
998        ////////////////////////////////////////////////////////////////////////////
999        // Extract the components from NAME - use for the "full" names
1000        ////////////////////////////////////////////////////////////////////////////
1001
1002        // Fix bad slashes. e.g. 'John/Smith' => 'John/Smith/'
1003        if (substr_count($value, '/') % 2 === 1) {
1004            $value .= '/';
1005        }
1006
1007        // GEDCOM uses "//" to indicate an unknown surname
1008        $full = preg_replace('/\/\//', '/@N.N./', $value);
1009
1010        // Extract the surname.
1011        // Note, there may be multiple surnames, e.g. Jean /Vasquez/ y /Cortes/
1012        if (preg_match('/\/.*\//', $full, $match)) {
1013            $surname = str_replace('/', '', $match[0]);
1014        } else {
1015            $surname = '';
1016        }
1017
1018        // If we don’t have a SURN record, extract it from the NAME
1019        if (!$SURNS) {
1020            if (preg_match_all('/\/([^\/]*)\//', $full, $matches)) {
1021                // There can be many surnames, each wrapped with '/'
1022                $SURNS = $matches[1];
1023                foreach ($SURNS as $n => $SURN) {
1024                    // Remove surname prefixes, such as "van de ", "d'" and "'t " (lower case only)
1025                    $SURNS[$n] = preg_replace('/^(?:[a-z]+ |[a-z]+\' ?|\'[a-z]+ )+/', '', $SURN);
1026                }
1027            } else {
1028                // It is valid not to have a surname at all
1029                $SURNS = [''];
1030            }
1031        }
1032
1033        // If we don’t have a GIVN record, extract it from the NAME
1034        if (!$GIVN) {
1035            // remove surname
1036            $GIVN = preg_replace('/ ?\/.*\/ ?/', ' ', $full);
1037            // remove nickname
1038            $GIVN = preg_replace('/ ?".+"/', ' ', $GIVN);
1039            // multiple spaces, caused by the above
1040            $GIVN = preg_replace('/ {2,}/', ' ', $GIVN);
1041            // leading/trailing spaces, caused by the above
1042            $GIVN = preg_replace('/^ | $/', '', $GIVN);
1043        }
1044
1045        // Add placeholder for unknown given name
1046        if (!$GIVN) {
1047            $GIVN = self::PRAENOMEN_NESCIO;
1048            $pos  = (int) strpos($full, '/');
1049            $full = substr($full, 0, $pos) . '@P.N. ' . substr($full, $pos);
1050        }
1051
1052        // Remove slashes - they don’t get displayed
1053        // $fullNN keeps the @N.N. placeholders, for the database
1054        // $full is for display on-screen
1055        $fullNN = str_replace('/', '', $full);
1056
1057        // Insert placeholders for any missing/unknown names
1058        $full = str_replace(self::NOMEN_NESCIO, I18N::translateContext('Unknown surname', '…'), $full);
1059        $full = str_replace(self::PRAENOMEN_NESCIO, I18N::translateContext('Unknown given name', '…'), $full);
1060        // Format for display
1061        $full = '<span class="NAME" dir="auto" translate="no">' . preg_replace('/\/([^\/]*)\//', '<span class="SURN">$1</span>', e($full)) . '</span>';
1062        // Localise quotation marks around the nickname
1063        $full = preg_replace_callback('/&quot;([^&]*)&quot;/', static function (array $matches): string {
1064            return '<q class="wt-nickname">' . $matches[1] . '</q>';
1065        }, $full);
1066
1067        // A suffix of “*” indicates a preferred name
1068        $full = preg_replace('/([^ >\x{200C}]*)\*/u', '<span class="starredname">\\1</span>', $full);
1069
1070        // Remove prefered-name indicater - they don’t go in the database
1071        $GIVN   = str_replace('*', '', $GIVN);
1072        $fullNN = str_replace('*', '', $fullNN);
1073
1074        foreach ($SURNS as $SURN) {
1075            // Scottish 'Mc and Mac ' prefixes both sort under 'Mac'
1076            if (strcasecmp(substr($SURN, 0, 2), 'Mc') === 0) {
1077                $SURN = substr_replace($SURN, 'Mac', 0, 2);
1078            } elseif (strcasecmp(substr($SURN, 0, 4), 'Mac ') === 0) {
1079                $SURN = substr_replace($SURN, 'Mac', 0, 4);
1080            }
1081
1082            $this->getAllNames[] = [
1083                'type'    => $type,
1084                'sort'    => $SURN . ',' . $GIVN,
1085                'full'    => $full,
1086                // This is used for display
1087                'fullNN'  => $fullNN,
1088                // This goes into the database
1089                'surname' => $surname,
1090                // This goes into the database
1091                'givn'    => $GIVN,
1092                // This goes into the database
1093                'surn'    => $SURN,
1094                // This goes into the database
1095            ];
1096        }
1097    }
1098
1099    /**
1100     * Extract names from the GEDCOM record.
1101     *
1102     * @return void
1103     */
1104    public function extractNames(): void
1105    {
1106        $access_level = $this->canShowName() ? Auth::PRIV_HIDE : Auth::accessLevel($this->tree);
1107
1108        $this->extractNamesFromFacts(
1109            1,
1110            'NAME',
1111            $this->facts(['NAME'], false, $access_level)
1112        );
1113    }
1114
1115    /**
1116     * Extra info to display when displaying this record in a list of
1117     * selection items or favorites.
1118     *
1119     * @return string
1120     */
1121    public function formatListDetails(): string
1122    {
1123        return
1124            $this->formatFirstMajorFact(Gedcom::BIRTH_EVENTS, 1) .
1125            $this->formatFirstMajorFact(Gedcom::DEATH_EVENTS, 1);
1126    }
1127
1128    /**
1129     * Lock the database row, to prevent concurrent edits.
1130     */
1131    public function lock(): void
1132    {
1133        DB::table('individuals')
1134            ->where('i_file', '=', $this->tree->id())
1135            ->where('i_id', '=', $this->xref())
1136            ->lockForUpdate()
1137            ->get();
1138    }
1139}
1140