xref: /webtrees/app/Individual.php (revision 3a3c35160db2b0ae62787c386f75885682bfd3bd)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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\Elements\PedigreeLinkageType;
26use Fisharebest\Webtrees\Http\RequestHandlers\IndividualPage;
27use Illuminate\Database\Capsule\Manager as DB;
28use Illuminate\Support\Collection;
29
30use function preg_match;
31
32/**
33 * A GEDCOM individual (INDI) object.
34 */
35class Individual extends GedcomRecord
36{
37    public const RECORD_TYPE = 'INDI';
38
39    // Placeholders to indicate unknown names
40    public const NOMEN_NESCIO     = '@N.N.';
41    public const PRAENOMEN_NESCIO = '@P.N.';
42
43    protected const ROUTE_NAME = IndividualPage::class;
44
45    /** Used in some lists to keep track of this individual’s generation in that list */
46    public ?int $generation = null;
47
48    private ?Date $estimated_birth_date = null;
49
50    private ?Date $estimated_death_date = null;
51
52    /**
53     * A closure which will compare individuals by birth date.
54     *
55     * @return Closure
56     */
57    public static function birthDateComparator(): Closure
58    {
59        return static function (Individual $x, Individual $y): int {
60            return Date::compare($x->getEstimatedBirthDate(), $y->getEstimatedBirthDate());
61        };
62    }
63
64    /**
65     * A closure which will compare individuals by death date.
66     *
67     * @return Closure
68     */
69    public static function deathDateComparator(): Closure
70    {
71        return static function (Individual $x, Individual $y): int {
72            return Date::compare($x->getEstimatedDeathDate(), $y->getEstimatedDeathDate());
73        };
74    }
75
76    /**
77     * Can the name of this record be shown?
78     *
79     * @param int|null $access_level
80     *
81     * @return bool
82     */
83    public function canShowName(int $access_level = null): bool
84    {
85        $access_level = $access_level ?? Auth::accessLevel($this->tree);
86
87        return (int) $this->tree->getPreference('SHOW_LIVING_NAMES') >= $access_level || $this->canShow($access_level);
88    }
89
90    /**
91     * Can this individual be shown?
92     *
93     * @param int $access_level
94     *
95     * @return bool
96     */
97    protected function canShowByType(int $access_level): bool
98    {
99        // Dead people...
100        if ((int) $this->tree->getPreference('SHOW_DEAD_PEOPLE') >= $access_level && $this->isDead()) {
101            $keep_alive             = false;
102            $KEEP_ALIVE_YEARS_BIRTH = (int) $this->tree->getPreference('KEEP_ALIVE_YEARS_BIRTH');
103            if ($KEEP_ALIVE_YEARS_BIRTH) {
104                preg_match_all('/\n1 (?:' . implode('|', Gedcom::BIRTH_EVENTS) . ').*(?:\n[2-9].*)*\n2 DATE (.+)/', $this->gedcom, $matches, PREG_SET_ORDER);
105                foreach ($matches as $match) {
106                    $date = new Date($match[1]);
107                    if ($date->isOK() && $date->gregorianYear() + $KEEP_ALIVE_YEARS_BIRTH > date('Y')) {
108                        $keep_alive = true;
109                        break;
110                    }
111                }
112            }
113            $KEEP_ALIVE_YEARS_DEATH = (int) $this->tree->getPreference('KEEP_ALIVE_YEARS_DEATH');
114            if ($KEEP_ALIVE_YEARS_DEATH) {
115                preg_match_all('/\n1 (?:' . implode('|', Gedcom::DEATH_EVENTS) . ').*(?:\n[2-9].*)*\n2 DATE (.+)/', $this->gedcom, $matches, PREG_SET_ORDER);
116                foreach ($matches as $match) {
117                    $date = new Date($match[1]);
118                    if ($date->isOK() && $date->gregorianYear() + $KEEP_ALIVE_YEARS_DEATH > date('Y')) {
119                        $keep_alive = true;
120                        break;
121                    }
122                }
123            }
124            if (!$keep_alive) {
125                return true;
126            }
127        }
128        // Consider relationship privacy (unless an admin is applying download restrictions)
129        $user_path_length = (int) $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_PATH_LENGTH);
130        $gedcomid         = $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF);
131
132        if ($gedcomid !== '' && $user_path_length > 0) {
133            return self::isRelated($this, $user_path_length);
134        }
135
136        // No restriction found - show living people to members only:
137        return Auth::PRIV_USER >= $access_level;
138    }
139
140    /**
141     * For relationship privacy calculations - is this individual a close relative?
142     *
143     * @param Individual $target
144     * @param int        $distance
145     *
146     * @return bool
147     */
148    private static function isRelated(Individual $target, int $distance): bool
149    {
150        static $cache = null;
151
152        $user_individual = Registry::individualFactory()->make($target->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF), $target->tree);
153        if ($user_individual) {
154            if (!$cache) {
155                $cache = [
156                    0 => [$user_individual],
157                    1 => [],
158                ];
159                foreach ($user_individual->facts(['FAMC', 'FAMS'], false, Auth::PRIV_HIDE) as $fact) {
160                    $family = $fact->target();
161                    if ($family instanceof Family) {
162                        $cache[1][] = $family;
163                    }
164                }
165            }
166        } else {
167            // No individual linked to this account? Cannot use relationship privacy.
168            return true;
169        }
170
171        // Double the distance, as we count the INDI-FAM and FAM-INDI links separately
172        $distance *= 2;
173
174        // Consider each path length in turn
175        for ($n = 0; $n <= $distance; ++$n) {
176            if (array_key_exists($n, $cache)) {
177                // We have already calculated all records with this length
178                if ($n % 2 === 0 && in_array($target, $cache[$n], true)) {
179                    return true;
180                }
181            } else {
182                // Need to calculate these paths
183                $cache[$n] = [];
184                if ($n % 2 === 0) {
185                    // Add FAM->INDI links
186                    foreach ($cache[$n - 1] as $family) {
187                        foreach ($family->facts(['HUSB', 'WIFE', 'CHIL'], false, Auth::PRIV_HIDE) as $fact) {
188                            $individual = $fact->target();
189                            // Don’t backtrack
190                            if ($individual instanceof self && !in_array($individual, $cache[$n - 2], true)) {
191                                $cache[$n][] = $individual;
192                            }
193                        }
194                    }
195                    if (in_array($target, $cache[$n], true)) {
196                        return true;
197                    }
198                } else {
199                    // Add INDI->FAM links
200                    foreach ($cache[$n - 1] as $individual) {
201                        foreach ($individual->facts(['FAMC', 'FAMS'], false, Auth::PRIV_HIDE) as $fact) {
202                            $family = $fact->target();
203                            // Don’t backtrack
204                            if ($family instanceof Family && !in_array($family, $cache[$n - 2], true)) {
205                                $cache[$n][] = $family;
206                            }
207                        }
208                    }
209                }
210            }
211        }
212
213        return false;
214    }
215
216    /**
217     * Generate a private version of this record
218     *
219     * @param int $access_level
220     *
221     * @return string
222     */
223    protected function createPrivateGedcomRecord(int $access_level): string
224    {
225        $SHOW_PRIVATE_RELATIONSHIPS = (bool) $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
226
227        $rec = '0 @' . $this->xref . '@ INDI';
228        if ((int) $this->tree->getPreference('SHOW_LIVING_NAMES') >= $access_level) {
229            // Show all the NAME tags, including subtags
230            foreach ($this->facts(['NAME']) as $fact) {
231                $rec .= "\n" . $fact->gedcom();
232            }
233        }
234        // Just show the 1 FAMC/FAMS tag, not any subtags, which may contain private data
235        preg_match_all('/\n1 (?:FAMC|FAMS) @(' . Gedcom::REGEX_XREF . ')@/', $this->gedcom, $matches, PREG_SET_ORDER);
236        foreach ($matches as $match) {
237            $rela = Registry::familyFactory()->make($match[1], $this->tree);
238            if ($rela && ($SHOW_PRIVATE_RELATIONSHIPS || $rela->canShow($access_level))) {
239                $rec .= $match[0];
240            }
241        }
242        // Don’t privatize sex.
243        if (preg_match('/\n1 SEX [MFU]/', $this->gedcom, $match)) {
244            $rec .= $match[0];
245        }
246
247        return $rec;
248    }
249
250    /**
251     * Calculate whether this individual is living or dead.
252     * If not known to be dead, then assume living.
253     *
254     * @return bool
255     */
256    public function isDead(): bool
257    {
258        $MAX_ALIVE_AGE = (int) $this->tree->getPreference('MAX_ALIVE_AGE');
259        $today_jd      = Registry::timestampFactory()->now()->julianDay();
260
261        // "1 DEAT Y" or "1 DEAT/2 DATE" or "1 DEAT/2 PLAC"
262        if (preg_match('/\n1 (?:' . implode('|', Gedcom::DEATH_EVENTS) . ')(?: Y|(?:\n[2-9].+)*\n2 (DATE|PLAC) )/', $this->gedcom)) {
263            return true;
264        }
265
266        // If any event occured more than $MAX_ALIVE_AGE years ago, then assume the individual is dead
267        if (preg_match_all('/\n2 DATE (.+)/', $this->gedcom, $date_matches)) {
268            foreach ($date_matches[1] as $date_match) {
269                $date = new Date($date_match);
270                if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * $MAX_ALIVE_AGE) {
271                    return true;
272                }
273            }
274            // The individual has one or more dated events. All are less than $MAX_ALIVE_AGE years ago.
275            // If one of these is a birth, the individual must be alive.
276            if (preg_match('/\n1 BIRT(?:\n[2-9].+)*\n2 DATE /', $this->gedcom)) {
277                return false;
278            }
279        }
280
281        // If we found no conclusive dates then check the dates of close relatives.
282
283        // Check parents (birth and adopted)
284        foreach ($this->childFamilies(Auth::PRIV_HIDE) as $family) {
285            foreach ($family->spouses(Auth::PRIV_HIDE) as $parent) {
286                // Assume parents are no more than 45 years older than their children
287                preg_match_all('/\n2 DATE (.+)/', $parent->gedcom, $date_matches);
288                foreach ($date_matches[1] as $date_match) {
289                    $date = new Date($date_match);
290                    if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE + 45)) {
291                        return true;
292                    }
293                }
294            }
295        }
296
297        // Check spouses
298        foreach ($this->spouseFamilies(Auth::PRIV_HIDE) as $family) {
299            preg_match_all('/\n2 DATE (.+)/', $family->gedcom, $date_matches);
300            foreach ($date_matches[1] as $date_match) {
301                $date = new Date($date_match);
302                // Assume marriage occurs after age of 10
303                if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE - 10)) {
304                    return true;
305                }
306            }
307            // Check spouse dates
308            $spouse = $family->spouse($this, Auth::PRIV_HIDE);
309            if ($spouse) {
310                preg_match_all('/\n2 DATE (.+)/', $spouse->gedcom, $date_matches);
311                foreach ($date_matches[1] as $date_match) {
312                    $date = new Date($date_match);
313                    // Assume max age difference between spouses of 40 years
314                    if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE + 40)) {
315                        return true;
316                    }
317                }
318            }
319            // Check child dates
320            foreach ($family->children(Auth::PRIV_HIDE) as $child) {
321                preg_match_all('/\n2 DATE (.+)/', $child->gedcom, $date_matches);
322                // Assume children born after age of 15
323                foreach ($date_matches[1] as $date_match) {
324                    $date = new Date($date_match);
325                    if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE - 15)) {
326                        return true;
327                    }
328                }
329                // Check grandchildren
330                foreach ($child->spouseFamilies(Auth::PRIV_HIDE) as $child_family) {
331                    foreach ($child_family->children(Auth::PRIV_HIDE) as $grandchild) {
332                        preg_match_all('/\n2 DATE (.+)/', $grandchild->gedcom, $date_matches);
333                        // Assume grandchildren born after age of 30
334                        foreach ($date_matches[1] as $date_match) {
335                            $date = new Date($date_match);
336                            if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE - 30)) {
337                                return true;
338                            }
339                        }
340                    }
341                }
342            }
343        }
344
345        return false;
346    }
347
348    /**
349     * Find the highlighted media object for an individual
350     *
351     * @return MediaFile|null
352     */
353    public function findHighlightedMediaFile(): ?MediaFile
354    {
355        $fact = $this->facts(['OBJE'])
356            ->first(static function (Fact $fact): bool {
357                $media = $fact->target();
358
359                return $media instanceof Media && $media->firstImageFile() instanceof MediaFile;
360            });
361
362        if ($fact instanceof Fact && $fact->target() instanceof Media) {
363            return $fact->target()->firstImageFile();
364        }
365
366        return null;
367    }
368
369    /**
370     * Display the preferred image for this individual.
371     * Use an icon if no image is available.
372     *
373     * @param int           $width      Pixels
374     * @param int           $height     Pixels
375     * @param string        $fit        "crop" or "contain"
376     * @param array<string> $attributes Additional HTML attributes
377     *
378     * @return string
379     */
380    public function displayImage(int $width, int $height, string $fit, array $attributes): string
381    {
382        $media_file = $this->findHighlightedMediaFile();
383
384        if ($media_file !== null) {
385            return $media_file->displayImage($width, $height, $fit, $attributes);
386        }
387
388        if ($this->tree->getPreference('USE_SILHOUETTE')) {
389            return '<i class="icon-silhouette icon-silhouette-' . strtolower($this->sex()) . ' wt-icon-flip-rtl"></i>';
390        }
391
392        return '';
393    }
394
395    /**
396     * Get the date of birth
397     *
398     * @return Date
399     */
400    public function getBirthDate(): Date
401    {
402        foreach ($this->getAllBirthDates() as $date) {
403            if ($date->isOK()) {
404                return $date;
405            }
406        }
407
408        return new Date('');
409    }
410
411    /**
412     * Get the place of birth
413     *
414     * @return Place
415     */
416    public function getBirthPlace(): Place
417    {
418        foreach ($this->getAllBirthPlaces() as $place) {
419            return $place;
420        }
421
422        return new Place('', $this->tree);
423    }
424
425    /**
426     * Get the date of death
427     *
428     * @return Date
429     */
430    public function getDeathDate(): Date
431    {
432        foreach ($this->getAllDeathDates() as $date) {
433            if ($date->isOK()) {
434                return $date;
435            }
436        }
437
438        return new Date('');
439    }
440
441    /**
442     * Get the place of death
443     *
444     * @return Place
445     */
446    public function getDeathPlace(): Place
447    {
448        foreach ($this->getAllDeathPlaces() as $place) {
449            return $place;
450        }
451
452        return new Place('', $this->tree);
453    }
454
455    /**
456     * Get the range of years in which a individual lived. e.g. “1870–”, “1870–1920”, “–1920”.
457     * Provide the place and full date using a tooltip.
458     * For consistent layout in charts, etc., show just a “–” when no dates are known.
459     * Note that this is a (non-breaking) en-dash, and not a hyphen.
460     *
461     * @return string
462     */
463    public function lifespan(): string
464    {
465        // Just the first part of the place name.
466        $birth_place = strip_tags($this->getBirthPlace()->shortName());
467        $death_place = strip_tags($this->getDeathPlace()->shortName());
468
469        // Remove markup from dates.  Use UTF_FSI / UTF_PDI instead of <bdi></bdi>, as
470        // we cannot use HTML markup in title attributes.
471        $birth_date = "\u{2068}" . strip_tags($this->getBirthDate()->display()) . "\u{2069}";
472        $death_date = "\u{2068}" . strip_tags($this->getDeathDate()->display()) . "\u{2069}";
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 array<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 array<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 array<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 array<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 ([MFX])/', $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<int,Family>
695     */
696    public function spouseFamilies(int $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<int,Family>
761     */
762    public function childFamilies(int $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<int,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<int,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        $fact = $this->facts(['FAMC'])->first(static fn (Fact $fact): bool => $fact->target() === $family);
841
842        if ($fact instanceof Fact) {
843            $pedigree = $fact->attribute('PEDI');
844        } else {
845            $pedigree = '';
846        }
847
848        $values = [
849            PedigreeLinkageType::VALUE_BIRTH   => I18N::translate('Family with parents'),
850            PedigreeLinkageType::VALUE_ADOPTED => I18N::translate('Family with adoptive parents'),
851            PedigreeLinkageType::VALUE_FOSTER  => I18N::translate('Family with foster parents'),
852            /* I18N: “sealing” is a Mormon ceremony. */
853            PedigreeLinkageType::VALUE_SEALING => I18N::translate('Family with sealing parents'),
854            /* I18N: “rada” is an Arabic word, pronounced “ra DAH”. It is child-to-parent pedigree, established by wet-nursing. */
855            PedigreeLinkageType::VALUE_RADA    => I18N::translate('Family with rada parents'),
856        ];
857
858        return $values[$pedigree] ?? $values[PedigreeLinkageType::VALUE_BIRTH];
859    }
860
861    /**
862     * Create a label for a step family
863     *
864     * @param Family $step_family
865     *
866     * @return string
867     */
868    public function getStepFamilyLabel(Family $step_family): string
869    {
870        foreach ($this->childFamilies() as $family) {
871            if ($family !== $step_family) {
872                // Must be a step-family
873                foreach ($family->spouses() as $parent) {
874                    foreach ($step_family->spouses() as $step_parent) {
875                        if ($parent === $step_parent) {
876                            // One common parent - must be a step family
877                            if ($parent->sex() === 'M') {
878                                // Father’s family with someone else
879                                if ($step_family->spouse($step_parent)) {
880                                    /* I18N: A step-family. %s is an individual’s name */
881                                    return I18N::translate('Father’s family with %s', $step_family->spouse($step_parent)->fullName());
882                                }
883
884                                /* I18N: A step-family. */
885                                return I18N::translate('Father’s family with an unknown individual');
886                            }
887
888                            // Mother’s family with someone else
889                            if ($step_family->spouse($step_parent)) {
890                                /* I18N: A step-family. %s is an individual’s name */
891                                return I18N::translate('Mother’s family with %s', $step_family->spouse($step_parent)->fullName());
892                            }
893
894                            /* I18N: A step-family. */
895                            return I18N::translate('Mother’s family with an unknown individual');
896                        }
897                    }
898                }
899            }
900        }
901
902        // Perahps same parents - but a different family record?
903        return I18N::translate('Family with parents');
904    }
905
906    /**
907     * Get the description for the family.
908     *
909     * For example, "XXX's family with new wife".
910     *
911     * @param Family $family
912     *
913     * @return string
914     */
915    public function getSpouseFamilyLabel(Family $family): string
916    {
917        $spouse = $family->spouse($this);
918        if ($spouse) {
919            /* I18N: %s is the spouse name */
920            return I18N::translate('Family with %s', $spouse->fullName());
921        }
922
923        return $family->fullName();
924    }
925
926    /**
927     * If this object has no name, what do we call it?
928     *
929     * @return string
930     */
931    public function getFallBackName(): string
932    {
933        return '@P.N. /@N.N./';
934    }
935
936    /**
937     * Convert a name record into ‘full’ and ‘sort’ versions.
938     * Use the NAME field to generate the ‘full’ version, as the
939     * gedcom spec says that this is the individual’s name, as they would write it.
940     * Use the SURN field to generate the sortable names. Note that this field
941     * may also be used for the ‘true’ surname, perhaps spelt differently to that
942     * recorded in the NAME field. e.g.
943     *
944     * 1 NAME Robert /de Gliderow/
945     * 2 GIVN Robert
946     * 2 SPFX de
947     * 2 SURN CLITHEROW
948     * 2 NICK The Bald
949     *
950     * full=>'Robert de Gliderow 'The Bald''
951     * sort=>'CLITHEROW, ROBERT'
952     *
953     * Handle multiple surnames, either as;
954     *
955     * 1 NAME Carlos /Vasquez/ y /Sante/
956     * or
957     * 1 NAME Carlos /Vasquez y Sante/
958     * 2 GIVN Carlos
959     * 2 SURN Vasquez,Sante
960     *
961     * @param string $type
962     * @param string $value
963     * @param string $gedcom
964     *
965     * @return void
966     */
967    protected function addName(string $type, string $value, string $gedcom): void
968    {
969        ////////////////////////////////////////////////////////////////////////////
970        // Extract the structured name parts - use for "sortable" names and indexes
971        ////////////////////////////////////////////////////////////////////////////
972
973        $sublevel = 1 + (int) substr($gedcom, 0, 1);
974        $GIVN     = preg_match('/\n' . $sublevel . ' GIVN (.+)/', $gedcom, $match) ? $match[1] : '';
975        $SURN     = preg_match('/\n' . $sublevel . ' SURN (.+)/', $gedcom, $match) ? $match[1] : '';
976
977        // SURN is an comma-separated list of surnames...
978        if ($SURN !== '') {
979            $SURNS = preg_split('/ *, */', $SURN);
980        } else {
981            $SURNS = [];
982        }
983
984        // ...so is GIVN - but nobody uses it like that
985        $GIVN = str_replace('/ *, */', ' ', $GIVN);
986
987        ////////////////////////////////////////////////////////////////////////////
988        // Extract the components from NAME - use for the "full" names
989        ////////////////////////////////////////////////////////////////////////////
990
991        // Fix bad slashes. e.g. 'John/Smith' => 'John/Smith/'
992        if (substr_count($value, '/') % 2 === 1) {
993            $value .= '/';
994        }
995
996        // GEDCOM uses "//" to indicate an unknown surname
997        $full = preg_replace('/\/\//', '/@N.N./', $value);
998
999        // Extract the surname.
1000        // Note, there may be multiple surnames, e.g. Jean /Vasquez/ y /Cortes/
1001        if (preg_match('/\/.*\//', $full, $match)) {
1002            $surname = str_replace('/', '', $match[0]);
1003        } else {
1004            $surname = '';
1005        }
1006
1007        // If we don’t have a SURN record, extract it from the NAME
1008        if (!$SURNS) {
1009            if (preg_match_all('/\/([^\/]*)\//', $full, $matches)) {
1010                // There can be many surnames, each wrapped with '/'
1011                $SURNS = $matches[1];
1012                foreach ($SURNS as $n => $SURN) {
1013                    // Remove surname prefixes, such as "van de ", "d'" and "'t " (lower case only)
1014                    $SURNS[$n] = preg_replace('/^(?:[a-z]+ |[a-z]+\' ?|\'[a-z]+ )+/', '', $SURN);
1015                }
1016            } else {
1017                // It is valid not to have a surname at all
1018                $SURNS = [''];
1019            }
1020        }
1021
1022        // If we don’t have a GIVN record, extract it from the NAME
1023        if (!$GIVN) {
1024            // remove surname
1025            $GIVN = preg_replace('/ ?\/.*\/ ?/', ' ', $full);
1026            // remove nickname
1027            $GIVN = preg_replace('/ ?".+"/', ' ', $GIVN);
1028            // multiple spaces, caused by the above
1029            $GIVN = preg_replace('/ {2,}/', ' ', $GIVN);
1030            // leading/trailing spaces, caused by the above
1031            $GIVN = preg_replace('/^ | $/', '', $GIVN);
1032        }
1033
1034        // Add placeholder for unknown given name
1035        if (!$GIVN) {
1036            $GIVN = self::PRAENOMEN_NESCIO;
1037            $pos  = (int) strpos($full, '/');
1038            $full = substr($full, 0, $pos) . '@P.N. ' . substr($full, $pos);
1039        }
1040
1041        // Remove slashes - they don’t get displayed
1042        // $fullNN keeps the @N.N. placeholders, for the database
1043        // $full is for display on-screen
1044        $fullNN = str_replace('/', '', $full);
1045
1046        // Insert placeholders for any missing/unknown names
1047        $full = str_replace(self::NOMEN_NESCIO, I18N::translateContext('Unknown surname', '…'), $full);
1048        $full = str_replace(self::PRAENOMEN_NESCIO, I18N::translateContext('Unknown given name', '…'), $full);
1049        // Format for display
1050        $full = '<span class="NAME" dir="auto" translate="no">' . preg_replace('/\/([^\/]*)\//', '<span class="SURN">$1</span>', e($full)) . '</span>';
1051        // Localise quotation marks around the nickname
1052        $full = preg_replace_callback('/&quot;([^&]*)&quot;/', static function (array $matches): string {
1053            return '<q class="wt-nickname">' . $matches[1] . '</q>';
1054        }, $full);
1055
1056        // A suffix of “*” indicates a preferred name
1057        $full = preg_replace('/([^ >\x{200C}]*)\*/u', '<span class="starredname">\\1</span>', $full);
1058
1059        // Remove prefered-name indicater - they don’t go in the database
1060        $GIVN   = str_replace('*', '', $GIVN);
1061        $fullNN = str_replace('*', '', $fullNN);
1062
1063        foreach ($SURNS as $SURN) {
1064            // Scottish 'Mc and Mac ' prefixes both sort under 'Mac'
1065            if (strcasecmp(substr($SURN, 0, 2), 'Mc') === 0) {
1066                $SURN = substr_replace($SURN, 'Mac', 0, 2);
1067            } elseif (strcasecmp(substr($SURN, 0, 4), 'Mac ') === 0) {
1068                $SURN = substr_replace($SURN, 'Mac', 0, 4);
1069            }
1070
1071            $this->getAllNames[] = [
1072                'type'    => $type,
1073                'sort'    => $SURN . ',' . $GIVN,
1074                'full'    => $full,
1075                // This is used for display
1076                'fullNN'  => $fullNN,
1077                // This goes into the database
1078                'surname' => $surname,
1079                // This goes into the database
1080                'givn'    => $GIVN,
1081                // This goes into the database
1082                'surn'    => $SURN,
1083                // This goes into the database
1084            ];
1085        }
1086    }
1087
1088    /**
1089     * Extract names from the GEDCOM record.
1090     *
1091     * @return void
1092     */
1093    public function extractNames(): void
1094    {
1095        $access_level = $this->canShowName() ? Auth::PRIV_HIDE : Auth::accessLevel($this->tree);
1096
1097        $this->extractNamesFromFacts(
1098            1,
1099            'NAME',
1100            $this->facts(['NAME'], false, $access_level)
1101        );
1102    }
1103
1104    /**
1105     * Extra info to display when displaying this record in a list of
1106     * selection items or favorites.
1107     *
1108     * @return string
1109     */
1110    public function formatListDetails(): string
1111    {
1112        return
1113            $this->formatFirstMajorFact(Gedcom::BIRTH_EVENTS, 1) .
1114            $this->formatFirstMajorFact(Gedcom::DEATH_EVENTS, 1);
1115    }
1116
1117    /**
1118     * Lock the database row, to prevent concurrent edits.
1119     */
1120    public function lock(): void
1121    {
1122        DB::table('individuals')
1123            ->where('i_file', '=', $this->tree->id())
1124            ->where('i_id', '=', $this->xref())
1125            ->lockForUpdate()
1126            ->get();
1127    }
1128}
1129