xref: /webtrees/app/Individual.php (revision 6fd7250f6c16d6ac1ede6f02b0e2892379acc193)
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     * Generate the CSS class to be used for drawing this individual
769     *
770     * @return string
771     */
772    public function getBoxStyle(): string
773    {
774        $tmp = [
775            'M' => '',
776            'F' => 'F',
777            'U' => 'NN',
778        ];
779
780        return 'person_box' . $tmp[$this->sex()];
781    }
782
783    /**
784     * Get a list of this individual’s spouse families
785     *
786     * @param int|null $access_level
787     *
788     * @return Collection<Family>
789     */
790    public function spouseFamilies($access_level = null): Collection
791    {
792        $access_level = $access_level ?? Auth::accessLevel($this->tree);
793
794        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
795            $access_level = Auth::PRIV_HIDE;
796        }
797
798        $families = new Collection();
799        foreach ($this->facts(['FAMS'], false, $access_level) as $fact) {
800            $family = $fact->target();
801            if ($family instanceof Family && $family->canShow($access_level)) {
802                $families->push($family);
803            }
804        }
805
806        return new Collection($families);
807    }
808
809    /**
810     * Get the current spouse of this individual.
811     *
812     * Where an individual has multiple spouses, assume they are stored
813     * in chronological order, and take the last one found.
814     *
815     * @return Individual|null
816     */
817    public function getCurrentSpouse(): ?Individual
818    {
819        $family = $this->spouseFamilies()->last();
820
821        if ($family instanceof Family) {
822            return $family->spouse($this);
823        }
824
825        return null;
826    }
827
828    /**
829     * Count the children belonging to this individual.
830     *
831     * @return int
832     */
833    public function numberOfChildren(): int
834    {
835        if (preg_match('/\n1 NCHI (\d+)(?:\n|$)/', $this->gedcom(), $match)) {
836            return (int) $match[1];
837        }
838
839        $children = [];
840        foreach ($this->spouseFamilies() as $fam) {
841            foreach ($fam->children() as $child) {
842                $children[$child->xref()] = true;
843            }
844        }
845
846        return count($children);
847    }
848
849    /**
850     * Get a list of this individual’s child families (i.e. their parents).
851     *
852     * @param int|null $access_level
853     *
854     * @return Collection<Family>
855     */
856    public function childFamilies($access_level = null): Collection
857    {
858        $access_level = $access_level ?? Auth::accessLevel($this->tree);
859
860        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
861            $access_level = Auth::PRIV_HIDE;
862        }
863
864        $families = new Collection();
865
866        foreach ($this->facts(['FAMC'], false, $access_level) as $fact) {
867            $family = $fact->target();
868            if ($family instanceof Family && $family->canShow($access_level)) {
869                $families->push($family);
870            }
871        }
872
873        return $families;
874    }
875
876    /**
877     * Get a list of step-parent families.
878     *
879     * @return Collection<Family>
880     */
881    public function childStepFamilies(): Collection
882    {
883        $step_families = new Collection();
884        $families      = $this->childFamilies();
885        foreach ($families as $family) {
886            foreach ($family->spouses() as $parent) {
887                foreach ($parent->spouseFamilies() as $step_family) {
888                    if (!$families->containsStrict($step_family)) {
889                        $step_families->add($step_family);
890                    }
891                }
892            }
893        }
894
895        return $step_families->uniqueStrict(static function (Family $family): string {
896            return $family->xref();
897        });
898    }
899
900    /**
901     * Get a list of step-parent families.
902     *
903     * @return Collection<Family>
904     */
905    public function spouseStepFamilies(): Collection
906    {
907        $step_families = [];
908        $families      = $this->spouseFamilies();
909
910        foreach ($families as $family) {
911            $spouse = $family->spouse($this);
912
913            if ($spouse instanceof self) {
914                foreach ($family->spouse($this)->spouseFamilies() as $step_family) {
915                    if (!$families->containsStrict($step_family)) {
916                        $step_families[] = $step_family;
917                    }
918                }
919            }
920        }
921
922        return new Collection($step_families);
923    }
924
925    /**
926     * A label for a parental family group
927     *
928     * @param Family $family
929     *
930     * @return string
931     */
932    public function getChildFamilyLabel(Family $family): string
933    {
934        preg_match('/\n1 FAMC @' . $family->xref() . '@(?:\n[2-9].*)*\n2 PEDI (.+)/', $this->gedcom(), $match);
935
936        $values = [
937            'birth'   => I18N::translate('Family with parents'),
938            'adopted' => I18N::translate('Family with adoptive parents'),
939            'foster'  => I18N::translate('Family with foster parents'),
940            'sealing' => /* I18N: “sealing” is a Mormon ceremony. */
941                I18N::translate('Family with sealing parents'),
942            'rada'    => /* I18N: “rada” is an Arabic word, pronounced “ra DAH”. It is child-to-parent pedigree, established by wet-nursing. */
943                I18N::translate('Family with rada parents'),
944        ];
945
946        return $values[$match[1] ?? 'birth'] ?? $values['birth'];
947    }
948
949    /**
950     * Create a label for a step family
951     *
952     * @param Family $step_family
953     *
954     * @return string
955     */
956    public function getStepFamilyLabel(Family $step_family): string
957    {
958        foreach ($this->childFamilies() as $family) {
959            if ($family !== $step_family) {
960                // Must be a step-family
961                foreach ($family->spouses() as $parent) {
962                    foreach ($step_family->spouses() as $step_parent) {
963                        if ($parent === $step_parent) {
964                            // One common parent - must be a step family
965                            if ($parent->sex() === 'M') {
966                                // Father’s family with someone else
967                                if ($step_family->spouse($step_parent)) {
968                                    /* I18N: A step-family. %s is an individual’s name */
969                                    return I18N::translate('Father’s family with %s', $step_family->spouse($step_parent)->fullName());
970                                }
971
972                                /* I18N: A step-family. */
973                                return I18N::translate('Father’s family with an unknown individual');
974                            }
975
976                            // Mother’s family with someone else
977                            if ($step_family->spouse($step_parent)) {
978                                /* I18N: A step-family. %s is an individual’s name */
979                                return I18N::translate('Mother’s family with %s', $step_family->spouse($step_parent)->fullName());
980                            }
981
982                            /* I18N: A step-family. */
983                            return I18N::translate('Mother’s family with an unknown individual');
984                        }
985                    }
986                }
987            }
988        }
989
990        // Perahps same parents - but a different family record?
991        return I18N::translate('Family with parents');
992    }
993
994    /**
995     * Get the description for the family.
996     *
997     * For example, "XXX's family with new wife".
998     *
999     * @param Family $family
1000     *
1001     * @return string
1002     */
1003    public function getSpouseFamilyLabel(Family $family): string
1004    {
1005        $spouse = $family->spouse($this);
1006        if ($spouse) {
1007            /* I18N: %s is the spouse name */
1008            return I18N::translate('Family with %s', $spouse->fullName());
1009        }
1010
1011        return $family->fullName();
1012    }
1013
1014    /**
1015     * If this object has no name, what do we call it?
1016     *
1017     * @return string
1018     */
1019    public function getFallBackName(): string
1020    {
1021        return '@P.N. /@N.N./';
1022    }
1023
1024    /**
1025     * Convert a name record into ‘full’ and ‘sort’ versions.
1026     * Use the NAME field to generate the ‘full’ version, as the
1027     * gedcom spec says that this is the individual’s name, as they would write it.
1028     * Use the SURN field to generate the sortable names. Note that this field
1029     * may also be used for the ‘true’ surname, perhaps spelt differently to that
1030     * recorded in the NAME field. e.g.
1031     *
1032     * 1 NAME Robert /de Gliderow/
1033     * 2 GIVN Robert
1034     * 2 SPFX de
1035     * 2 SURN CLITHEROW
1036     * 2 NICK The Bald
1037     *
1038     * full=>'Robert de Gliderow 'The Bald''
1039     * sort=>'CLITHEROW, ROBERT'
1040     *
1041     * Handle multiple surnames, either as;
1042     *
1043     * 1 NAME Carlos /Vasquez/ y /Sante/
1044     * or
1045     * 1 NAME Carlos /Vasquez y Sante/
1046     * 2 GIVN Carlos
1047     * 2 SURN Vasquez,Sante
1048     *
1049     * @param string $type
1050     * @param string $full
1051     * @param string $gedcom
1052     *
1053     * @return void
1054     */
1055    protected function addName(string $type, string $full, string $gedcom): void
1056    {
1057        ////////////////////////////////////////////////////////////////////////////
1058        // Extract the structured name parts - use for "sortable" names and indexes
1059        ////////////////////////////////////////////////////////////////////////////
1060
1061        $sublevel = 1 + (int) substr($gedcom, 0, 1);
1062        $GIVN     = preg_match("/\n{$sublevel} GIVN (.+)/", $gedcom, $match) ? $match[1] : '';
1063        $SURN     = preg_match("/\n{$sublevel} SURN (.+)/", $gedcom, $match) ? $match[1] : '';
1064
1065        // SURN is an comma-separated list of surnames...
1066        if ($SURN !== '') {
1067            $SURNS = preg_split('/ *, */', $SURN);
1068        } else {
1069            $SURNS = [];
1070        }
1071
1072        // ...so is GIVN - but nobody uses it like that
1073        $GIVN = str_replace('/ *, */', ' ', $GIVN);
1074
1075        ////////////////////////////////////////////////////////////////////////////
1076        // Extract the components from NAME - use for the "full" names
1077        ////////////////////////////////////////////////////////////////////////////
1078
1079        // Fix bad slashes. e.g. 'John/Smith' => 'John/Smith/'
1080        if (substr_count($full, '/') % 2 === 1) {
1081            $full .= '/';
1082        }
1083
1084        // GEDCOM uses "//" to indicate an unknown surname
1085        $full = preg_replace('/\/\//', '/@N.N./', $full);
1086
1087        // Extract the surname.
1088        // Note, there may be multiple surnames, e.g. Jean /Vasquez/ y /Cortes/
1089        if (preg_match('/\/.*\//', $full, $match)) {
1090            $surname = str_replace('/', '', $match[0]);
1091        } else {
1092            $surname = '';
1093        }
1094
1095        // If we don’t have a SURN record, extract it from the NAME
1096        if (!$SURNS) {
1097            if (preg_match_all('/\/([^\/]*)\//', $full, $matches)) {
1098                // There can be many surnames, each wrapped with '/'
1099                $SURNS = $matches[1];
1100                foreach ($SURNS as $n => $SURN) {
1101                    // Remove surname prefixes, such as "van de ", "d'" and "'t " (lower case only)
1102                    $SURNS[$n] = preg_replace('/^(?:[a-z]+ |[a-z]+\' ?|\'[a-z]+ )+/', '', $SURN);
1103                }
1104            } else {
1105                // It is valid not to have a surname at all
1106                $SURNS = [''];
1107            }
1108        }
1109
1110        // If we don’t have a GIVN record, extract it from the NAME
1111        if (!$GIVN) {
1112            $GIVN = preg_replace(
1113                [
1114                    '/ ?\/.*\/ ?/',
1115                    // remove surname
1116                    '/ ?".+"/',
1117                    // remove nickname
1118                    '/ {2,}/',
1119                    // multiple spaces, caused by the above
1120                    '/^ | $/',
1121                    // leading/trailing spaces, caused by the above
1122                ],
1123                [
1124                    ' ',
1125                    ' ',
1126                    ' ',
1127                    '',
1128                ],
1129                $full
1130            );
1131        }
1132
1133        // Add placeholder for unknown given name
1134        if (!$GIVN) {
1135            $GIVN = self::PRAENOMEN_NESCIO;
1136            $pos  = (int) strpos($full, '/');
1137            $full = substr($full, 0, $pos) . '@P.N. ' . substr($full, $pos);
1138        }
1139
1140        // Remove slashes - they don’t get displayed
1141        // $fullNN keeps the @N.N. placeholders, for the database
1142        // $full is for display on-screen
1143        $fullNN = str_replace('/', '', $full);
1144
1145        // Insert placeholders for any missing/unknown names
1146        $full = str_replace(self::NOMEN_NESCIO, I18N::translateContext('Unknown surname', '…'), $full);
1147        $full = str_replace(self::PRAENOMEN_NESCIO, I18N::translateContext('Unknown given name', '…'), $full);
1148        // Format for display
1149        $full = '<span class="NAME" dir="auto" translate="no">' . preg_replace('/\/([^\/]*)\//', '<span class="SURN">$1</span>', e($full)) . '</span>';
1150        // Localise quotation marks around the nickname
1151        $full = preg_replace_callback('/&quot;([^&]*)&quot;/', static function (array $matches): string {
1152            return '<q class="wt-nickname">' . $matches[1] . '</q>';
1153        }, $full);
1154
1155        // A suffix of “*” indicates a preferred name
1156        $full = preg_replace('/([^ >]*)\*/', '<span class="starredname">\\1</span>', $full);
1157
1158        // Remove prefered-name indicater - they don’t go in the database
1159        $GIVN   = str_replace('*', '', $GIVN);
1160        $fullNN = str_replace('*', '', $fullNN);
1161
1162        foreach ($SURNS as $SURN) {
1163            // Scottish 'Mc and Mac ' prefixes both sort under 'Mac'
1164            if (strcasecmp(substr($SURN, 0, 2), 'Mc') === 0) {
1165                $SURN = substr_replace($SURN, 'Mac', 0, 2);
1166            } elseif (strcasecmp(substr($SURN, 0, 4), 'Mac ') === 0) {
1167                $SURN = substr_replace($SURN, 'Mac', 0, 4);
1168            }
1169
1170            $this->getAllNames[] = [
1171                'type'    => $type,
1172                'sort'    => $SURN . ',' . $GIVN,
1173                'full'    => $full,
1174                // This is used for display
1175                'fullNN'  => $fullNN,
1176                // This goes into the database
1177                'surname' => $surname,
1178                // This goes into the database
1179                'givn'    => $GIVN,
1180                // This goes into the database
1181                'surn'    => $SURN,
1182                // This goes into the database
1183            ];
1184        }
1185    }
1186
1187    /**
1188     * Extract names from the GEDCOM record.
1189     *
1190     * @return void
1191     */
1192    public function extractNames(): void
1193    {
1194        $access_level = $this->canShowName() ? Auth::PRIV_HIDE : Auth::accessLevel($this->tree);
1195
1196        $this->extractNamesFromFacts(
1197            1,
1198            'NAME',
1199            $this->facts(['NAME'], false, $access_level)
1200        );
1201    }
1202
1203    /**
1204     * Extra info to display when displaying this record in a list of
1205     * selection items or favorites.
1206     *
1207     * @return string
1208     */
1209    public function formatListDetails(): string
1210    {
1211        return
1212            $this->formatFirstMajorFact(Gedcom::BIRTH_EVENTS, 1) .
1213            $this->formatFirstMajorFact(Gedcom::DEATH_EVENTS, 1);
1214    }
1215
1216    /**
1217     * Lock the database row, to prevent concurrent edits.
1218     */
1219    public function lock(): void
1220    {
1221        DB::table('individuals')
1222            ->where('i_file', '=', $this->tree->id())
1223            ->where('i_id', '=', $this->xref())
1224            ->lockForUpdate()
1225            ->get();
1226    }
1227}
1228