xref: /webtrees/app/Individual.php (revision 7ecbeefda352ca6acade0e92d75cf01cf63e6f5b)
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 ($death_year === '' && $this->isDead()) {
482            $death_year = I18N::translate('…');
483        }
484
485        /* I18N: A range of years, e.g. “1870–”, “1870–1920”, “–1920” */
486        return I18N::translate(
487            '%1$s–%2$s',
488            '<span title="' . $birth_place . ' ' . $birth_date . '">' . $birth_year . '</span>',
489            '<span title="' . $death_place . ' ' . $death_date . '">' . $death_year . '</span>'
490        );
491    }
492
493    /**
494     * Get all the birth dates - for the individual lists.
495     *
496     * @return array<Date>
497     */
498    public function getAllBirthDates(): array
499    {
500        foreach (Gedcom::BIRTH_EVENTS as $event) {
501            $dates = $this->getAllEventDates([$event]);
502
503            if ($dates !== []) {
504                return $dates;
505            }
506        }
507
508        return [];
509    }
510
511    /**
512     * Gat all the birth places - for the individual lists.
513     *
514     * @return array<Place>
515     */
516    public function getAllBirthPlaces(): array
517    {
518        foreach (Gedcom::BIRTH_EVENTS as $event) {
519            $places = $this->getAllEventPlaces([$event]);
520
521            if ($places !== []) {
522                return $places;
523            }
524        }
525
526        return [];
527    }
528
529    /**
530     * Get all the death dates - for the individual lists.
531     *
532     * @return array<Date>
533     */
534    public function getAllDeathDates(): array
535    {
536        foreach (Gedcom::DEATH_EVENTS as $event) {
537            $dates = $this->getAllEventDates([$event]);
538
539            if ($dates !== []) {
540                return $dates;
541            }
542        }
543
544        return [];
545    }
546
547    /**
548     * Get all the death places - for the individual lists.
549     *
550     * @return array<Place>
551     */
552    public function getAllDeathPlaces(): array
553    {
554        foreach (Gedcom::DEATH_EVENTS as $event) {
555            $places = $this->getAllEventPlaces([$event]);
556
557            if ($places !== []) {
558                return $places;
559            }
560        }
561
562        return [];
563    }
564
565    /**
566     * Generate an estimate for the date of birth, based on dates of parents/children/spouses
567     *
568     * @return Date
569     */
570    public function getEstimatedBirthDate(): Date
571    {
572        if ($this->estimated_birth_date === null) {
573            foreach ($this->getAllBirthDates() as $date) {
574                if ($date->isOK()) {
575                    $this->estimated_birth_date = $date;
576                    break;
577                }
578            }
579            if ($this->estimated_birth_date === null) {
580                $min = [];
581                $max = [];
582                $tmp = $this->getDeathDate();
583                if ($tmp->isOK()) {
584                    $min[] = $tmp->minimumJulianDay() - $this->tree->getPreference('MAX_ALIVE_AGE') * 365;
585                    $max[] = $tmp->maximumJulianDay();
586                }
587                foreach ($this->childFamilies() as $family) {
588                    $tmp = $family->getMarriageDate();
589                    if ($tmp->isOK()) {
590                        $min[] = $tmp->maximumJulianDay() - 365 * 1;
591                        $max[] = $tmp->minimumJulianDay() + 365 * 30;
592                    }
593                    $husband = $family->husband();
594                    if ($husband instanceof self) {
595                        $tmp = $husband->getBirthDate();
596                        if ($tmp->isOK()) {
597                            $min[] = $tmp->maximumJulianDay() + 365 * 15;
598                            $max[] = $tmp->minimumJulianDay() + 365 * 65;
599                        }
600                    }
601                    $wife = $family->wife();
602                    if ($wife instanceof self) {
603                        $tmp = $wife->getBirthDate();
604                        if ($tmp->isOK()) {
605                            $min[] = $tmp->maximumJulianDay() + 365 * 15;
606                            $max[] = $tmp->minimumJulianDay() + 365 * 45;
607                        }
608                    }
609                    foreach ($family->children() as $child) {
610                        $tmp = $child->getBirthDate();
611                        if ($tmp->isOK()) {
612                            $min[] = $tmp->maximumJulianDay() - 365 * 30;
613                            $max[] = $tmp->minimumJulianDay() + 365 * 30;
614                        }
615                    }
616                }
617                foreach ($this->spouseFamilies() as $family) {
618                    $tmp = $family->getMarriageDate();
619                    if ($tmp->isOK()) {
620                        $min[] = $tmp->maximumJulianDay() - 365 * 45;
621                        $max[] = $tmp->minimumJulianDay() - 365 * 15;
622                    }
623                    $spouse = $family->spouse($this);
624                    if ($spouse) {
625                        $tmp = $spouse->getBirthDate();
626                        if ($tmp->isOK()) {
627                            $min[] = $tmp->maximumJulianDay() - 365 * 25;
628                            $max[] = $tmp->minimumJulianDay() + 365 * 25;
629                        }
630                    }
631                    foreach ($family->children() as $child) {
632                        $tmp = $child->getBirthDate();
633                        if ($tmp->isOK()) {
634                            $min[] = $tmp->maximumJulianDay() - 365 * ($this->sex() === 'F' ? 45 : 65);
635                            $max[] = $tmp->minimumJulianDay() - 365 * 15;
636                        }
637                    }
638                }
639                if ($min && $max) {
640                    $gregorian_calendar = new GregorianCalendar();
641
642                    [$year] = $gregorian_calendar->jdToYmd(intdiv(max($min) + min($max), 2));
643                    $this->estimated_birth_date = new Date('EST ' . $year);
644                } else {
645                    $this->estimated_birth_date = new Date(''); // always return a date object
646                }
647            }
648        }
649
650        return $this->estimated_birth_date;
651    }
652
653    /**
654     * Generate an estimated date of death.
655     *
656     * @return Date
657     */
658    public function getEstimatedDeathDate(): Date
659    {
660        if ($this->estimated_death_date === null) {
661            foreach ($this->getAllDeathDates() as $date) {
662                if ($date->isOK()) {
663                    $this->estimated_death_date = $date;
664                    break;
665                }
666            }
667            if ($this->estimated_death_date === null) {
668                if ($this->getEstimatedBirthDate()->minimumJulianDay()) {
669                    $max_alive_age              = (int) $this->tree->getPreference('MAX_ALIVE_AGE');
670                    $this->estimated_death_date = $this->getEstimatedBirthDate()->addYears($max_alive_age, 'BEF');
671                } else {
672                    $this->estimated_death_date = new Date(''); // always return a date object
673                }
674            }
675        }
676
677        return $this->estimated_death_date;
678    }
679
680    /**
681     * Get the sex - M F or U
682     * Use the un-privatised gedcom record. We call this function during
683     * the privatize-gedcom function, and we are allowed to know this.
684     *
685     * @return string
686     */
687    public function sex(): string
688    {
689        if (preg_match('/\n1 SEX ([MFX])/', $this->gedcom . $this->pending, $match)) {
690            return $match[1];
691        }
692
693        return 'U';
694    }
695
696    /**
697     * Get a list of this individual’s spouse families
698     *
699     * @param int|null $access_level
700     *
701     * @return Collection<int,Family>
702     */
703    public function spouseFamilies(int $access_level = null): Collection
704    {
705        $access_level ??= Auth::accessLevel($this->tree);
706
707        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
708            $access_level = Auth::PRIV_HIDE;
709        }
710
711        $families = new Collection();
712        foreach ($this->facts(['FAMS'], false, $access_level) as $fact) {
713            $family = $fact->target();
714            if ($family instanceof Family && $family->canShow($access_level)) {
715                $families->push($family);
716            }
717        }
718
719        return new Collection($families);
720    }
721
722    /**
723     * Get the current spouse of this individual.
724     *
725     * Where an individual has multiple spouses, assume they are stored
726     * in chronological order, and take the last one found.
727     *
728     * @return Individual|null
729     */
730    public function getCurrentSpouse(): ?Individual
731    {
732        $family = $this->spouseFamilies()->last();
733
734        if ($family instanceof Family) {
735            return $family->spouse($this);
736        }
737
738        return null;
739    }
740
741    /**
742     * Count the children belonging to this individual.
743     *
744     * @return int
745     */
746    public function numberOfChildren(): int
747    {
748        if (preg_match('/\n1 NCHI (\d+)(?:\n|$)/', $this->gedcom(), $match)) {
749            return (int) $match[1];
750        }
751
752        $children = [];
753        foreach ($this->spouseFamilies() as $fam) {
754            foreach ($fam->children() as $child) {
755                $children[$child->xref()] = true;
756            }
757        }
758
759        return count($children);
760    }
761
762    /**
763     * Get a list of this individual’s child families (i.e. their parents).
764     *
765     * @param int|null $access_level
766     *
767     * @return Collection<int,Family>
768     */
769    public function childFamilies(int $access_level = null): Collection
770    {
771        $access_level ??= Auth::accessLevel($this->tree);
772
773        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
774            $access_level = Auth::PRIV_HIDE;
775        }
776
777        $families = new Collection();
778
779        foreach ($this->facts(['FAMC'], false, $access_level) as $fact) {
780            $family = $fact->target();
781            if ($family instanceof Family && $family->canShow($access_level)) {
782                $families->push($family);
783            }
784        }
785
786        return $families;
787    }
788
789    /**
790     * Get a list of step-parent families.
791     *
792     * @return Collection<int,Family>
793     */
794    public function childStepFamilies(): Collection
795    {
796        $step_families = new Collection();
797        $families      = $this->childFamilies();
798        foreach ($families as $family) {
799            foreach ($family->spouses() as $parent) {
800                foreach ($parent->spouseFamilies() as $step_family) {
801                    if (!$families->containsStrict($step_family)) {
802                        $step_families->add($step_family);
803                    }
804                }
805            }
806        }
807
808        return $step_families->uniqueStrict(static function (Family $family): string {
809            return $family->xref();
810        });
811    }
812
813    /**
814     * Get a list of step-parent families.
815     *
816     * @return Collection<int,Family>
817     */
818    public function spouseStepFamilies(): Collection
819    {
820        $step_families = [];
821        $families      = $this->spouseFamilies();
822
823        foreach ($families as $family) {
824            $spouse = $family->spouse($this);
825
826            if ($spouse instanceof self) {
827                foreach ($family->spouse($this)->spouseFamilies() as $step_family) {
828                    if (!$families->containsStrict($step_family)) {
829                        $step_families[] = $step_family;
830                    }
831                }
832            }
833        }
834
835        return new Collection($step_families);
836    }
837
838    /**
839     * A label for a parental family group
840     *
841     * @param Family $family
842     *
843     * @return string
844     */
845    public function getChildFamilyLabel(Family $family): string
846    {
847        $fact = $this->facts(['FAMC'])->first(static fn (Fact $fact): bool => $fact->target() === $family);
848
849        if ($fact instanceof Fact) {
850            $pedigree = $fact->attribute('PEDI');
851        } else {
852            $pedigree = '';
853        }
854
855        $values = [
856            PedigreeLinkageType::VALUE_BIRTH   => I18N::translate('Family with parents'),
857            PedigreeLinkageType::VALUE_ADOPTED => I18N::translate('Family with adoptive parents'),
858            PedigreeLinkageType::VALUE_FOSTER  => I18N::translate('Family with foster parents'),
859            /* I18N: “sealing” is a Mormon ceremony. */
860            PedigreeLinkageType::VALUE_SEALING => I18N::translate('Family with sealing parents'),
861            /* I18N: “rada” is an Arabic word, pronounced “ra DAH”. It is child-to-parent pedigree, established by wet-nursing. */
862            PedigreeLinkageType::VALUE_RADA    => I18N::translate('Family with rada parents'),
863        ];
864
865        return $values[$pedigree] ?? $values[PedigreeLinkageType::VALUE_BIRTH];
866    }
867
868    /**
869     * Create a label for a step family
870     *
871     * @param Family $step_family
872     *
873     * @return string
874     */
875    public function getStepFamilyLabel(Family $step_family): string
876    {
877        foreach ($this->childFamilies() as $family) {
878            if ($family !== $step_family) {
879                // Must be a step-family
880                foreach ($family->spouses() as $parent) {
881                    foreach ($step_family->spouses() as $step_parent) {
882                        if ($parent === $step_parent) {
883                            // One common parent - must be a step family
884                            if ($parent->sex() === 'M') {
885                                // Father’s family with someone else
886                                if ($step_family->spouse($step_parent)) {
887                                    /* I18N: A step-family. %s is an individual’s name */
888                                    return I18N::translate('Father’s family with %s', $step_family->spouse($step_parent)->fullName());
889                                }
890
891                                /* I18N: A step-family. */
892                                return I18N::translate('Father’s family with an unknown individual');
893                            }
894
895                            // Mother’s family with someone else
896                            if ($step_family->spouse($step_parent)) {
897                                /* I18N: A step-family. %s is an individual’s name */
898                                return I18N::translate('Mother’s family with %s', $step_family->spouse($step_parent)->fullName());
899                            }
900
901                            /* I18N: A step-family. */
902                            return I18N::translate('Mother’s family with an unknown individual');
903                        }
904                    }
905                }
906            }
907        }
908
909        // Perahps same parents - but a different family record?
910        return I18N::translate('Family with parents');
911    }
912
913    /**
914     * Get the description for the family.
915     *
916     * For example, "XXX's family with new wife".
917     *
918     * @param Family $family
919     *
920     * @return string
921     */
922    public function getSpouseFamilyLabel(Family $family): string
923    {
924        $spouse = $family->spouse($this);
925        if ($spouse) {
926            /* I18N: %s is the spouse name */
927            return I18N::translate('Family with %s', $spouse->fullName());
928        }
929
930        return $family->fullName();
931    }
932
933    /**
934     * If this object has no name, what do we call it?
935     *
936     * @return string
937     */
938    public function getFallBackName(): string
939    {
940        return '@P.N. /@N.N./';
941    }
942
943    /**
944     * Convert a name record into ‘full’ and ‘sort’ versions.
945     * Use the NAME field to generate the ‘full’ version, as the
946     * gedcom spec says that this is the individual’s name, as they would write it.
947     * Use the SURN field to generate the sortable names. Note that this field
948     * may also be used for the ‘true’ surname, perhaps spelt differently to that
949     * recorded in the NAME field. e.g.
950     *
951     * 1 NAME Robert /de Gliderow/
952     * 2 GIVN Robert
953     * 2 SPFX de
954     * 2 SURN CLITHEROW
955     * 2 NICK The Bald
956     *
957     * full=>'Robert de Gliderow 'The Bald''
958     * sort=>'CLITHEROW, ROBERT'
959     *
960     * Handle multiple surnames, either as;
961     *
962     * 1 NAME Carlos /Vasquez/ y /Sante/
963     * or
964     * 1 NAME Carlos /Vasquez y Sante/
965     * 2 GIVN Carlos
966     * 2 SURN Vasquez,Sante
967     *
968     * @param string $type
969     * @param string $value
970     * @param string $gedcom
971     *
972     * @return void
973     */
974    protected function addName(string $type, string $value, string $gedcom): void
975    {
976        ////////////////////////////////////////////////////////////////////////////
977        // Extract the structured name parts - use for "sortable" names and indexes
978        ////////////////////////////////////////////////////////////////////////////
979
980        $sublevel = 1 + (int) substr($gedcom, 0, 1);
981        $GIVN     = preg_match('/\n' . $sublevel . ' GIVN (.+)/', $gedcom, $match) === 1 ? $match[1] : '';
982        $SURN     = preg_match('/\n' . $sublevel . ' SURN (.+)/', $gedcom, $match) === 1 ? $match[1] : '';
983
984        // SURN is an comma-separated list of surnames...
985        if ($SURN !== '') {
986            $SURNS = preg_split('/ *, */', $SURN);
987        } else {
988            $SURNS = [];
989        }
990
991        // ...so is GIVN - but nobody uses it like that
992        $GIVN = str_replace('/ *, */', ' ', $GIVN);
993
994        ////////////////////////////////////////////////////////////////////////////
995        // Extract the components from NAME - use for the "full" names
996        ////////////////////////////////////////////////////////////////////////////
997
998        // Fix bad slashes. e.g. 'John/Smith' => 'John/Smith/'
999        if (substr_count($value, '/') % 2 === 1) {
1000            $value .= '/';
1001        }
1002
1003        // GEDCOM uses "//" to indicate an unknown surname
1004        $full = preg_replace('/\/\//', '/@N.N./', $value);
1005
1006        // Extract the surname.
1007        // Note, there may be multiple surnames, e.g. Jean /Vasquez/ y /Cortes/
1008        if (preg_match('/\/.*\//', $full, $match)) {
1009            $surname = str_replace('/', '', $match[0]);
1010        } else {
1011            $surname = '';
1012        }
1013
1014        // If we don’t have a SURN record, extract it from the NAME
1015        if (!$SURNS) {
1016            if (preg_match_all('/\/([^\/]*)\//', $full, $matches)) {
1017                // There can be many surnames, each wrapped with '/'
1018                $SURNS = $matches[1];
1019                foreach ($SURNS as $n => $SURN) {
1020                    // Remove surname prefixes, such as "van de ", "d'" and "'t " (lower case only)
1021                    $SURNS[$n] = preg_replace('/^(?:[a-z]+ |[a-z]+\' ?|\'[a-z]+ )+/', '', $SURN);
1022                }
1023            } else {
1024                // It is valid not to have a surname at all
1025                $SURNS = [''];
1026            }
1027        }
1028
1029        // If we don’t have a GIVN record, extract it from the NAME
1030        if (!$GIVN) {
1031            // remove surname
1032            $GIVN = preg_replace('/ ?\/.*\/ ?/', ' ', $full);
1033            // remove nickname
1034            $GIVN = preg_replace('/ ?".+"/', ' ', $GIVN);
1035            // multiple spaces, caused by the above
1036            $GIVN = preg_replace('/ {2,}/', ' ', $GIVN);
1037            // leading/trailing spaces, caused by the above
1038            $GIVN = preg_replace('/^ | $/', '', $GIVN);
1039        }
1040
1041        // Add placeholder for unknown given name
1042        if (!$GIVN) {
1043            $GIVN = self::PRAENOMEN_NESCIO;
1044            $pos  = (int) strpos($full, '/');
1045            $full = substr($full, 0, $pos) . '@P.N. ' . substr($full, $pos);
1046        }
1047
1048        // Remove slashes - they don’t get displayed
1049        // $fullNN keeps the @N.N. placeholders, for the database
1050        // $full is for display on-screen
1051        $fullNN = str_replace('/', '', $full);
1052
1053        // Insert placeholders for any missing/unknown names
1054        $full = str_replace(self::NOMEN_NESCIO, I18N::translateContext('Unknown surname', '…'), $full);
1055        $full = str_replace(self::PRAENOMEN_NESCIO, I18N::translateContext('Unknown given name', '…'), $full);
1056        // Format for display
1057        $full = '<span class="NAME" dir="auto" translate="no">' . preg_replace('/\/([^\/]*)\//', '<span class="SURN">$1</span>', e($full)) . '</span>';
1058        // Localise quotation marks around the nickname
1059        $full = preg_replace_callback('/&quot;([^&]*)&quot;/', static function (array $matches): string {
1060            return '<q class="wt-nickname">' . $matches[1] . '</q>';
1061        }, $full);
1062
1063        // A suffix of “*” indicates a preferred name
1064        $full = preg_replace('/([^ >\x{200C}]*)\*/u', '<span class="starredname">\\1</span>', $full);
1065
1066        // Remove prefered-name indicater - they don’t go in the database
1067        $GIVN   = str_replace('*', '', $GIVN);
1068        $fullNN = str_replace('*', '', $fullNN);
1069
1070        foreach ($SURNS as $SURN) {
1071            // Scottish 'Mc and Mac ' prefixes both sort under 'Mac'
1072            if (strcasecmp(substr($SURN, 0, 2), 'Mc') === 0) {
1073                $SURN = substr_replace($SURN, 'Mac', 0, 2);
1074            } elseif (strcasecmp(substr($SURN, 0, 4), 'Mac ') === 0) {
1075                $SURN = substr_replace($SURN, 'Mac', 0, 4);
1076            }
1077
1078            $this->getAllNames[] = [
1079                'type'    => $type,
1080                'sort'    => $SURN . ',' . $GIVN,
1081                'full'    => $full,
1082                // This is used for display
1083                'fullNN'  => $fullNN,
1084                // This goes into the database
1085                'surname' => $surname,
1086                // This goes into the database
1087                'givn'    => $GIVN,
1088                // This goes into the database
1089                'surn'    => $SURN,
1090                // This goes into the database
1091            ];
1092        }
1093    }
1094
1095    /**
1096     * Extract names from the GEDCOM record.
1097     *
1098     * @return void
1099     */
1100    public function extractNames(): void
1101    {
1102        $access_level = $this->canShowName() ? Auth::PRIV_HIDE : Auth::accessLevel($this->tree);
1103
1104        $this->extractNamesFromFacts(
1105            1,
1106            'NAME',
1107            $this->facts(['NAME'], false, $access_level)
1108        );
1109    }
1110
1111    /**
1112     * Extra info to display when displaying this record in a list of
1113     * selection items or favorites.
1114     *
1115     * @return string
1116     */
1117    public function formatListDetails(): string
1118    {
1119        return
1120            $this->formatFirstMajorFact(Gedcom::BIRTH_EVENTS, 1) .
1121            $this->formatFirstMajorFact(Gedcom::DEATH_EVENTS, 1);
1122    }
1123
1124    /**
1125     * Lock the database row, to prevent concurrent edits.
1126     */
1127    public function lock(): void
1128    {
1129        DB::table('individuals')
1130            ->where('i_file', '=', $this->tree->id())
1131            ->where('i_id', '=', $this->xref())
1132            ->lockForUpdate()
1133            ->get();
1134    }
1135}
1136