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