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