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