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