xref: /webtrees/app/Individual.php (revision 42c92da76e0f6ebca442454357d8e78c877c0178)
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 (int) $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 ((int) $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 ((int) $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 array<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.  Use UTF_FSI / UTF_PDI instead of <bdi></bdi>, as
471        // we cannot use HTML markup in title attributes.
472        $birth_date = "\u{2068}" . strip_tags($this->getBirthDate()->display()) . "\u{2069}";
473        $death_date = "\u{2068}" . strip_tags($this->getDeathDate()->display()) . "\u{2069}";
474
475        // Use minimum and maximum dates - to agree with the age calculations.
476        $birth_year = $this->getBirthDate()->minimumDate()->format('%Y');
477        $death_year = $this->getDeathDate()->maximumDate()->format('%Y');
478
479        /* I18N: A range of years, e.g. “1870–”, “1870–1920”, “–1920” */
480        return I18N::translate(
481            '%1$s–%2$s',
482            '<span title="' . $birth_place . ' ' . $birth_date . '">' . $birth_year . '</span>',
483            '<span title="' . $death_place . ' ' . $death_date . '">' . $death_year . '</span>'
484        );
485    }
486
487    /**
488     * Get all the birth dates - for the individual lists.
489     *
490     * @return array<Date>
491     */
492    public function getAllBirthDates(): array
493    {
494        foreach (Gedcom::BIRTH_EVENTS as $event) {
495            $dates = $this->getAllEventDates([$event]);
496
497            if ($dates !== []) {
498                return $dates;
499            }
500        }
501
502        return [];
503    }
504
505    /**
506     * Gat all the birth places - for the individual lists.
507     *
508     * @return array<Place>
509     */
510    public function getAllBirthPlaces(): array
511    {
512        foreach (Gedcom::BIRTH_EVENTS as $event) {
513            $places = $this->getAllEventPlaces([$event]);
514
515            if ($places !== []) {
516                return $places;
517            }
518        }
519
520        return [];
521    }
522
523    /**
524     * Get all the death dates - for the individual lists.
525     *
526     * @return array<Date>
527     */
528    public function getAllDeathDates(): array
529    {
530        foreach (Gedcom::DEATH_EVENTS as $event) {
531            $dates = $this->getAllEventDates([$event]);
532
533            if ($dates !== []) {
534                return $dates;
535            }
536        }
537
538        return [];
539    }
540
541    /**
542     * Get all the death places - for the individual lists.
543     *
544     * @return array<Place>
545     */
546    public function getAllDeathPlaces(): array
547    {
548        foreach (Gedcom::DEATH_EVENTS as $event) {
549            $places = $this->getAllEventPlaces([$event]);
550
551            if ($places !== []) {
552                return $places;
553            }
554        }
555
556        return [];
557    }
558
559    /**
560     * Generate an estimate for the date of birth, based on dates of parents/children/spouses
561     *
562     * @return Date
563     */
564    public function getEstimatedBirthDate(): Date
565    {
566        if ($this->estimated_birth_date === null) {
567            foreach ($this->getAllBirthDates() as $date) {
568                if ($date->isOK()) {
569                    $this->estimated_birth_date = $date;
570                    break;
571                }
572            }
573            if ($this->estimated_birth_date === null) {
574                $min = [];
575                $max = [];
576                $tmp = $this->getDeathDate();
577                if ($tmp->isOK()) {
578                    $min[] = $tmp->minimumJulianDay() - $this->tree->getPreference('MAX_ALIVE_AGE') * 365;
579                    $max[] = $tmp->maximumJulianDay();
580                }
581                foreach ($this->childFamilies() as $family) {
582                    $tmp = $family->getMarriageDate();
583                    if ($tmp->isOK()) {
584                        $min[] = $tmp->maximumJulianDay() - 365 * 1;
585                        $max[] = $tmp->minimumJulianDay() + 365 * 30;
586                    }
587                    $husband = $family->husband();
588                    if ($husband instanceof self) {
589                        $tmp = $husband->getBirthDate();
590                        if ($tmp->isOK()) {
591                            $min[] = $tmp->maximumJulianDay() + 365 * 15;
592                            $max[] = $tmp->minimumJulianDay() + 365 * 65;
593                        }
594                    }
595                    $wife = $family->wife();
596                    if ($wife instanceof self) {
597                        $tmp = $wife->getBirthDate();
598                        if ($tmp->isOK()) {
599                            $min[] = $tmp->maximumJulianDay() + 365 * 15;
600                            $max[] = $tmp->minimumJulianDay() + 365 * 45;
601                        }
602                    }
603                    foreach ($family->children() as $child) {
604                        $tmp = $child->getBirthDate();
605                        if ($tmp->isOK()) {
606                            $min[] = $tmp->maximumJulianDay() - 365 * 30;
607                            $max[] = $tmp->minimumJulianDay() + 365 * 30;
608                        }
609                    }
610                }
611                foreach ($this->spouseFamilies() as $family) {
612                    $tmp = $family->getMarriageDate();
613                    if ($tmp->isOK()) {
614                        $min[] = $tmp->maximumJulianDay() - 365 * 45;
615                        $max[] = $tmp->minimumJulianDay() - 365 * 15;
616                    }
617                    $spouse = $family->spouse($this);
618                    if ($spouse) {
619                        $tmp = $spouse->getBirthDate();
620                        if ($tmp->isOK()) {
621                            $min[] = $tmp->maximumJulianDay() - 365 * 25;
622                            $max[] = $tmp->minimumJulianDay() + 365 * 25;
623                        }
624                    }
625                    foreach ($family->children() as $child) {
626                        $tmp = $child->getBirthDate();
627                        if ($tmp->isOK()) {
628                            $min[] = $tmp->maximumJulianDay() - 365 * ($this->sex() === 'F' ? 45 : 65);
629                            $max[] = $tmp->minimumJulianDay() - 365 * 15;
630                        }
631                    }
632                }
633                if ($min && $max) {
634                    $gregorian_calendar = new GregorianCalendar();
635
636                    [$year] = $gregorian_calendar->jdToYmd(intdiv(max($min) + min($max), 2));
637                    $this->estimated_birth_date = new Date('EST ' . $year);
638                } else {
639                    $this->estimated_birth_date = new Date(''); // always return a date object
640                }
641            }
642        }
643
644        return $this->estimated_birth_date;
645    }
646
647    /**
648     * Generate an estimated date of death.
649     *
650     * @return Date
651     */
652    public function getEstimatedDeathDate(): Date
653    {
654        if ($this->estimated_death_date === null) {
655            foreach ($this->getAllDeathDates() as $date) {
656                if ($date->isOK()) {
657                    $this->estimated_death_date = $date;
658                    break;
659                }
660            }
661            if ($this->estimated_death_date === null) {
662                if ($this->getEstimatedBirthDate()->minimumJulianDay()) {
663                    $max_alive_age              = (int) $this->tree->getPreference('MAX_ALIVE_AGE');
664                    $this->estimated_death_date = $this->getEstimatedBirthDate()->addYears($max_alive_age, 'BEF');
665                } else {
666                    $this->estimated_death_date = new Date(''); // always return a date object
667                }
668            }
669        }
670
671        return $this->estimated_death_date;
672    }
673
674    /**
675     * Get the sex - M F or U
676     * Use the un-privatised gedcom record. We call this function during
677     * the privatize-gedcom function, and we are allowed to know this.
678     *
679     * @return string
680     */
681    public function sex(): string
682    {
683        if (preg_match('/\n1 SEX ([MF])/', $this->gedcom . $this->pending, $match)) {
684            return $match[1];
685        }
686
687        return 'U';
688    }
689
690    /**
691     * Get a list of this individual’s spouse families
692     *
693     * @param int|null $access_level
694     *
695     * @return Collection<Family>
696     */
697    public function spouseFamilies(int $access_level = null): Collection
698    {
699        $access_level = $access_level ?? Auth::accessLevel($this->tree);
700
701        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
702            $access_level = Auth::PRIV_HIDE;
703        }
704
705        $families = new Collection();
706        foreach ($this->facts(['FAMS'], false, $access_level) as $fact) {
707            $family = $fact->target();
708            if ($family instanceof Family && $family->canShow($access_level)) {
709                $families->push($family);
710            }
711        }
712
713        return new Collection($families);
714    }
715
716    /**
717     * Get the current spouse of this individual.
718     *
719     * Where an individual has multiple spouses, assume they are stored
720     * in chronological order, and take the last one found.
721     *
722     * @return Individual|null
723     */
724    public function getCurrentSpouse(): ?Individual
725    {
726        $family = $this->spouseFamilies()->last();
727
728        if ($family instanceof Family) {
729            return $family->spouse($this);
730        }
731
732        return null;
733    }
734
735    /**
736     * Count the children belonging to this individual.
737     *
738     * @return int
739     */
740    public function numberOfChildren(): int
741    {
742        if (preg_match('/\n1 NCHI (\d+)(?:\n|$)/', $this->gedcom(), $match)) {
743            return (int) $match[1];
744        }
745
746        $children = [];
747        foreach ($this->spouseFamilies() as $fam) {
748            foreach ($fam->children() as $child) {
749                $children[$child->xref()] = true;
750            }
751        }
752
753        return count($children);
754    }
755
756    /**
757     * Get a list of this individual’s child families (i.e. their parents).
758     *
759     * @param int|null $access_level
760     *
761     * @return Collection<Family>
762     */
763    public function childFamilies(int $access_level = null): Collection
764    {
765        $access_level = $access_level ?? Auth::accessLevel($this->tree);
766
767        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
768            $access_level = Auth::PRIV_HIDE;
769        }
770
771        $families = new Collection();
772
773        foreach ($this->facts(['FAMC'], false, $access_level) as $fact) {
774            $family = $fact->target();
775            if ($family instanceof Family && $family->canShow($access_level)) {
776                $families->push($family);
777            }
778        }
779
780        return $families;
781    }
782
783    /**
784     * Get a list of step-parent families.
785     *
786     * @return Collection<Family>
787     */
788    public function childStepFamilies(): Collection
789    {
790        $step_families = new Collection();
791        $families      = $this->childFamilies();
792        foreach ($families as $family) {
793            foreach ($family->spouses() as $parent) {
794                foreach ($parent->spouseFamilies() as $step_family) {
795                    if (!$families->containsStrict($step_family)) {
796                        $step_families->add($step_family);
797                    }
798                }
799            }
800        }
801
802        return $step_families->uniqueStrict(static function (Family $family): string {
803            return $family->xref();
804        });
805    }
806
807    /**
808     * Get a list of step-parent families.
809     *
810     * @return Collection<Family>
811     */
812    public function spouseStepFamilies(): Collection
813    {
814        $step_families = [];
815        $families      = $this->spouseFamilies();
816
817        foreach ($families as $family) {
818            $spouse = $family->spouse($this);
819
820            if ($spouse instanceof self) {
821                foreach ($family->spouse($this)->spouseFamilies() as $step_family) {
822                    if (!$families->containsStrict($step_family)) {
823                        $step_families[] = $step_family;
824                    }
825                }
826            }
827        }
828
829        return new Collection($step_families);
830    }
831
832    /**
833     * A label for a parental family group
834     *
835     * @param Family $family
836     *
837     * @return string
838     */
839    public function getChildFamilyLabel(Family $family): string
840    {
841        preg_match('/\n1 FAMC @' . $family->xref() . '@(?:\n[2-9].*)*\n2 PEDI (.+)/', $this->gedcom(), $match);
842
843        $values = [
844            'birth'   => I18N::translate('Family with parents'),
845            'adopted' => I18N::translate('Family with adoptive parents'),
846            'foster'  => I18N::translate('Family with foster parents'),
847            'sealing' => /* I18N: “sealing” is a Mormon ceremony. */
848                I18N::translate('Family with sealing parents'),
849            'rada'    => /* I18N: “rada” is an Arabic word, pronounced “ra DAH”. It is child-to-parent pedigree, established by wet-nursing. */
850                I18N::translate('Family with rada parents'),
851        ];
852
853        return $values[$match[1] ?? 'birth'] ?? $values['birth'];
854    }
855
856    /**
857     * Create a label for a step family
858     *
859     * @param Family $step_family
860     *
861     * @return string
862     */
863    public function getStepFamilyLabel(Family $step_family): string
864    {
865        foreach ($this->childFamilies() as $family) {
866            if ($family !== $step_family) {
867                // Must be a step-family
868                foreach ($family->spouses() as $parent) {
869                    foreach ($step_family->spouses() as $step_parent) {
870                        if ($parent === $step_parent) {
871                            // One common parent - must be a step family
872                            if ($parent->sex() === 'M') {
873                                // Father’s family with someone else
874                                if ($step_family->spouse($step_parent)) {
875                                    /* I18N: A step-family. %s is an individual’s name */
876                                    return I18N::translate('Father’s family with %s', $step_family->spouse($step_parent)->fullName());
877                                }
878
879                                /* I18N: A step-family. */
880                                return I18N::translate('Father’s family with an unknown individual');
881                            }
882
883                            // Mother’s family with someone else
884                            if ($step_family->spouse($step_parent)) {
885                                /* I18N: A step-family. %s is an individual’s name */
886                                return I18N::translate('Mother’s family with %s', $step_family->spouse($step_parent)->fullName());
887                            }
888
889                            /* I18N: A step-family. */
890                            return I18N::translate('Mother’s family with an unknown individual');
891                        }
892                    }
893                }
894            }
895        }
896
897        // Perahps same parents - but a different family record?
898        return I18N::translate('Family with parents');
899    }
900
901    /**
902     * Get the description for the family.
903     *
904     * For example, "XXX's family with new wife".
905     *
906     * @param Family $family
907     *
908     * @return string
909     */
910    public function getSpouseFamilyLabel(Family $family): string
911    {
912        $spouse = $family->spouse($this);
913        if ($spouse) {
914            /* I18N: %s is the spouse name */
915            return I18N::translate('Family with %s', $spouse->fullName());
916        }
917
918        return $family->fullName();
919    }
920
921    /**
922     * If this object has no name, what do we call it?
923     *
924     * @return string
925     */
926    public function getFallBackName(): string
927    {
928        return '@P.N. /@N.N./';
929    }
930
931    /**
932     * Convert a name record into ‘full’ and ‘sort’ versions.
933     * Use the NAME field to generate the ‘full’ version, as the
934     * gedcom spec says that this is the individual’s name, as they would write it.
935     * Use the SURN field to generate the sortable names. Note that this field
936     * may also be used for the ‘true’ surname, perhaps spelt differently to that
937     * recorded in the NAME field. e.g.
938     *
939     * 1 NAME Robert /de Gliderow/
940     * 2 GIVN Robert
941     * 2 SPFX de
942     * 2 SURN CLITHEROW
943     * 2 NICK The Bald
944     *
945     * full=>'Robert de Gliderow 'The Bald''
946     * sort=>'CLITHEROW, ROBERT'
947     *
948     * Handle multiple surnames, either as;
949     *
950     * 1 NAME Carlos /Vasquez/ y /Sante/
951     * or
952     * 1 NAME Carlos /Vasquez y Sante/
953     * 2 GIVN Carlos
954     * 2 SURN Vasquez,Sante
955     *
956     * @param string $type
957     * @param string $value
958     * @param string $gedcom
959     *
960     * @return void
961     */
962    protected function addName(string $type, string $value, string $gedcom): void
963    {
964        ////////////////////////////////////////////////////////////////////////////
965        // Extract the structured name parts - use for "sortable" names and indexes
966        ////////////////////////////////////////////////////////////////////////////
967
968        $sublevel = 1 + (int) substr($gedcom, 0, 1);
969        $GIVN     = preg_match('/\n' . $sublevel . ' GIVN (.+)/', $gedcom, $match) ? $match[1] : '';
970        $SURN     = preg_match('/\n' . $sublevel . ' SURN (.+)/', $gedcom, $match) ? $match[1] : '';
971
972        // SURN is an comma-separated list of surnames...
973        if ($SURN !== '') {
974            $SURNS = preg_split('/ *, */', $SURN);
975        } else {
976            $SURNS = [];
977        }
978
979        // ...so is GIVN - but nobody uses it like that
980        $GIVN = str_replace('/ *, */', ' ', $GIVN);
981
982        ////////////////////////////////////////////////////////////////////////////
983        // Extract the components from NAME - use for the "full" names
984        ////////////////////////////////////////////////////////////////////////////
985
986        // Fix bad slashes. e.g. 'John/Smith' => 'John/Smith/'
987        if (substr_count($value, '/') % 2 === 1) {
988            $value .= '/';
989        }
990
991        // GEDCOM uses "//" to indicate an unknown surname
992        $full = preg_replace('/\/\//', '/@N.N./', $value);
993
994        // Extract the surname.
995        // Note, there may be multiple surnames, e.g. Jean /Vasquez/ y /Cortes/
996        if (preg_match('/\/.*\//', $full, $match)) {
997            $surname = str_replace('/', '', $match[0]);
998        } else {
999            $surname = '';
1000        }
1001
1002        // If we don’t have a SURN record, extract it from the NAME
1003        if (!$SURNS) {
1004            if (preg_match_all('/\/([^\/]*)\//', $full, $matches)) {
1005                // There can be many surnames, each wrapped with '/'
1006                $SURNS = $matches[1];
1007                foreach ($SURNS as $n => $SURN) {
1008                    // Remove surname prefixes, such as "van de ", "d'" and "'t " (lower case only)
1009                    $SURNS[$n] = preg_replace('/^(?:[a-z]+ |[a-z]+\' ?|\'[a-z]+ )+/', '', $SURN);
1010                }
1011            } else {
1012                // It is valid not to have a surname at all
1013                $SURNS = [''];
1014            }
1015        }
1016
1017        // If we don’t have a GIVN record, extract it from the NAME
1018        if (!$GIVN) {
1019            // remove surname
1020            $GIVN = preg_replace('/ ?\/.*\/ ?/', ' ', $full);
1021            // remove nickname
1022            $GIVN = preg_replace('/ ?".+"/', ' ', $GIVN);
1023            // multiple spaces, caused by the above
1024            $GIVN = preg_replace('/ {2,}/', ' ', $GIVN);
1025            // leading/trailing spaces, caused by the above
1026            $GIVN = preg_replace('/^ | $/', '', $GIVN);
1027        }
1028
1029        // Add placeholder for unknown given name
1030        if (!$GIVN) {
1031            $GIVN = self::PRAENOMEN_NESCIO;
1032            $pos  = (int) strpos($full, '/');
1033            $full = substr($full, 0, $pos) . '@P.N. ' . substr($full, $pos);
1034        }
1035
1036        // Remove slashes - they don’t get displayed
1037        // $fullNN keeps the @N.N. placeholders, for the database
1038        // $full is for display on-screen
1039        $fullNN = str_replace('/', '', $full);
1040
1041        // Insert placeholders for any missing/unknown names
1042        $full = str_replace(self::NOMEN_NESCIO, I18N::translateContext('Unknown surname', '…'), $full);
1043        $full = str_replace(self::PRAENOMEN_NESCIO, I18N::translateContext('Unknown given name', '…'), $full);
1044        // Format for display
1045        $full = '<span class="NAME" dir="auto" translate="no">' . preg_replace('/\/([^\/]*)\//', '<span class="SURN">$1</span>', e($full)) . '</span>';
1046        // Localise quotation marks around the nickname
1047        $full = preg_replace_callback('/&quot;([^&]*)&quot;/', static function (array $matches): string {
1048            return '<q class="wt-nickname">' . $matches[1] . '</q>';
1049        }, $full);
1050
1051        // A suffix of “*” indicates a preferred name
1052        $full = preg_replace('/([^ >\x{200C}]*)\*/u', '<span class="starredname">\\1</span>', $full);
1053
1054        // Remove prefered-name indicater - they don’t go in the database
1055        $GIVN   = str_replace('*', '', $GIVN);
1056        $fullNN = str_replace('*', '', $fullNN);
1057
1058        foreach ($SURNS as $SURN) {
1059            // Scottish 'Mc and Mac ' prefixes both sort under 'Mac'
1060            if (strcasecmp(substr($SURN, 0, 2), 'Mc') === 0) {
1061                $SURN = substr_replace($SURN, 'Mac', 0, 2);
1062            } elseif (strcasecmp(substr($SURN, 0, 4), 'Mac ') === 0) {
1063                $SURN = substr_replace($SURN, 'Mac', 0, 4);
1064            }
1065
1066            $this->getAllNames[] = [
1067                'type'    => $type,
1068                'sort'    => $SURN . ',' . $GIVN,
1069                'full'    => $full,
1070                // This is used for display
1071                'fullNN'  => $fullNN,
1072                // This goes into the database
1073                'surname' => $surname,
1074                // This goes into the database
1075                'givn'    => $GIVN,
1076                // This goes into the database
1077                'surn'    => $SURN,
1078                // This goes into the database
1079            ];
1080        }
1081    }
1082
1083    /**
1084     * Extract names from the GEDCOM record.
1085     *
1086     * @return void
1087     */
1088    public function extractNames(): void
1089    {
1090        $access_level = $this->canShowName() ? Auth::PRIV_HIDE : Auth::accessLevel($this->tree);
1091
1092        $this->extractNamesFromFacts(
1093            1,
1094            'NAME',
1095            $this->facts(['NAME'], false, $access_level)
1096        );
1097    }
1098
1099    /**
1100     * Extra info to display when displaying this record in a list of
1101     * selection items or favorites.
1102     *
1103     * @return string
1104     */
1105    public function formatListDetails(): string
1106    {
1107        return
1108            $this->formatFirstMajorFact(Gedcom::BIRTH_EVENTS, 1) .
1109            $this->formatFirstMajorFact(Gedcom::DEATH_EVENTS, 1);
1110    }
1111
1112    /**
1113     * Lock the database row, to prevent concurrent edits.
1114     */
1115    public function lock(): void
1116    {
1117        DB::table('individuals')
1118            ->where('i_file', '=', $this->tree->id())
1119            ->where('i_id', '=', $this->xref())
1120            ->lockForUpdate()
1121            ->get();
1122    }
1123}
1124