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