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