xref: /webtrees/app/Individual.php (revision ef475b14d08542378dc3f165515f9182552984ef)
1a25f0a04SGreg Roach<?php
23976b470SGreg Roach
3a25f0a04SGreg Roach/**
4a25f0a04SGreg Roach * webtrees: online genealogy
55bfc6897SGreg Roach * Copyright (C) 2022 webtrees development team
6a25f0a04SGreg Roach * This program is free software: you can redistribute it and/or modify
7a25f0a04SGreg Roach * it under the terms of the GNU General Public License as published by
8a25f0a04SGreg Roach * the Free Software Foundation, either version 3 of the License, or
9a25f0a04SGreg Roach * (at your option) any later version.
10a25f0a04SGreg Roach * This program is distributed in the hope that it will be useful,
11a25f0a04SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
12a25f0a04SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13a25f0a04SGreg Roach * GNU General Public License for more details.
14a25f0a04SGreg Roach * You should have received a copy of the GNU General Public License
1589f7189bSGreg Roach * along with this program. If not, see <https://www.gnu.org/licenses/>.
16a25f0a04SGreg Roach */
17fcfa147eSGreg Roach
18e7f56f2aSGreg Roachdeclare(strict_types=1);
19e7f56f2aSGreg Roach
2076692c8bSGreg Roachnamespace Fisharebest\Webtrees;
21a25f0a04SGreg Roach
22886b77daSGreg Roachuse Closure;
23a25f0a04SGreg Roachuse Fisharebest\ExtCalendar\GregorianCalendar;
241fe542e9SGreg Roachuse Fisharebest\Webtrees\Contracts\UserInterface;
25665e281aSGreg Roachuse Fisharebest\Webtrees\Elements\PedigreeLinkageType;
26852ede8cSGreg Roachuse Fisharebest\Webtrees\Http\RequestHandlers\IndividualPage;
272e5b4452SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
2839ca88baSGreg Roachuse Illuminate\Support\Collection;
29a25f0a04SGreg Roach
3010e06497SGreg Roachuse function array_key_exists;
3110e06497SGreg Roachuse function count;
3210e06497SGreg Roachuse function in_array;
337d70e4a7SGreg Roachuse function preg_match;
347d70e4a7SGreg Roach
35a25f0a04SGreg Roach/**
3676692c8bSGreg Roach * A GEDCOM individual (INDI) object.
37a25f0a04SGreg Roach */
38c1010edaSGreg Roachclass Individual extends GedcomRecord
39c1010edaSGreg Roach{
4016d6367aSGreg Roach    public const RECORD_TYPE = 'INDI';
4116d6367aSGreg Roach
428fb4e87cSGreg Roach    // Placeholders to indicate unknown names
438fb4e87cSGreg Roach    public const NOMEN_NESCIO     = '@N.N.';
448fb4e87cSGreg Roach    public const PRAENOMEN_NESCIO = '@P.N.';
458fb4e87cSGreg Roach
46852ede8cSGreg Roach    protected const ROUTE_NAME = IndividualPage::class;
47a25f0a04SGreg Roach
487fa97a69SGreg Roach    /** Used in some lists to keep track of this individual’s generation in that list */
497fa97a69SGreg Roach    public ?int $generation = null;
50a25f0a04SGreg Roach
517fa97a69SGreg Roach    private ?Date $estimated_birth_date = null;
52a25f0a04SGreg Roach
537fa97a69SGreg Roach    private ?Date $estimated_death_date = null;
54a25f0a04SGreg Roach
55a25f0a04SGreg Roach    /**
56c156e8f5SGreg Roach     * A closure which will compare individuals by birth date.
57c156e8f5SGreg Roach     *
58c156e8f5SGreg Roach     * @return Closure
59c156e8f5SGreg Roach     */
60c156e8f5SGreg Roach    public static function birthDateComparator(): Closure
61c156e8f5SGreg Roach    {
626c2179e2SGreg Roach        return static function (Individual $x, Individual $y): int {
63c156e8f5SGreg Roach            return Date::compare($x->getEstimatedBirthDate(), $y->getEstimatedBirthDate());
64c156e8f5SGreg Roach        };
65c156e8f5SGreg Roach    }
66c156e8f5SGreg Roach
67c156e8f5SGreg Roach    /**
68c156e8f5SGreg Roach     * A closure which will compare individuals by death date.
69c156e8f5SGreg Roach     *
70c156e8f5SGreg Roach     * @return Closure
71c156e8f5SGreg Roach     */
72c156e8f5SGreg Roach    public static function deathDateComparator(): Closure
73c156e8f5SGreg Roach    {
746c2179e2SGreg Roach        return static function (Individual $x, Individual $y): int {
7510e21aa9SGreg Roach            return Date::compare($x->getEstimatedDeathDate(), $y->getEstimatedDeathDate());
76c156e8f5SGreg Roach        };
77c156e8f5SGreg Roach    }
78c156e8f5SGreg Roach
79c156e8f5SGreg Roach    /**
80a25f0a04SGreg Roach     * Can the name of this record be shown?
81a25f0a04SGreg Roach     *
8276692c8bSGreg Roach     * @param int|null $access_level
8376692c8bSGreg Roach     *
8476692c8bSGreg Roach     * @return bool
85a25f0a04SGreg Roach     */
8635584196SGreg Roach    public function canShowName(int $access_level = null): bool
87c1010edaSGreg Roach    {
88d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
894b9ff166SGreg Roach
90f56b86d2SGreg Roach        return (int) $this->tree->getPreference('SHOW_LIVING_NAMES') >= $access_level || $this->canShow($access_level);
91a25f0a04SGreg Roach    }
92a25f0a04SGreg Roach
93a25f0a04SGreg Roach    /**
9476692c8bSGreg Roach     * Can this individual be shown?
95a25f0a04SGreg Roach     *
9676692c8bSGreg Roach     * @param int $access_level
9776692c8bSGreg Roach     *
9876692c8bSGreg Roach     * @return bool
99a25f0a04SGreg Roach     */
10035584196SGreg Roach    protected function canShowByType(int $access_level): bool
101c1010edaSGreg Roach    {
102a25f0a04SGreg Roach        // Dead people...
103f56b86d2SGreg Roach        if ((int) $this->tree->getPreference('SHOW_DEAD_PEOPLE') >= $access_level && $this->isDead()) {
104a25f0a04SGreg Roach            $keep_alive             = false;
10554ba7dc5SGreg Roach            $KEEP_ALIVE_YEARS_BIRTH = (int) $this->tree->getPreference('KEEP_ALIVE_YEARS_BIRTH');
106a25f0a04SGreg Roach            if ($KEEP_ALIVE_YEARS_BIRTH) {
107dce4f3a4SGreg Roach                preg_match_all('/\n1 (?:' . implode('|', Gedcom::BIRTH_EVENTS) . ').*(?:\n[2-9].*)*\n2 DATE (.+)/', $this->gedcom, $matches, PREG_SET_ORDER);
108a25f0a04SGreg Roach                foreach ($matches as $match) {
109a25f0a04SGreg Roach                    $date = new Date($match[1]);
110a25f0a04SGreg Roach                    if ($date->isOK() && $date->gregorianYear() + $KEEP_ALIVE_YEARS_BIRTH > date('Y')) {
111a25f0a04SGreg Roach                        $keep_alive = true;
112a25f0a04SGreg Roach                        break;
113a25f0a04SGreg Roach                    }
114a25f0a04SGreg Roach                }
115a25f0a04SGreg Roach            }
11654ba7dc5SGreg Roach            $KEEP_ALIVE_YEARS_DEATH = (int) $this->tree->getPreference('KEEP_ALIVE_YEARS_DEATH');
117a25f0a04SGreg Roach            if ($KEEP_ALIVE_YEARS_DEATH) {
118dce4f3a4SGreg Roach                preg_match_all('/\n1 (?:' . implode('|', Gedcom::DEATH_EVENTS) . ').*(?:\n[2-9].*)*\n2 DATE (.+)/', $this->gedcom, $matches, PREG_SET_ORDER);
119a25f0a04SGreg Roach                foreach ($matches as $match) {
120a25f0a04SGreg Roach                    $date = new Date($match[1]);
121a25f0a04SGreg Roach                    if ($date->isOK() && $date->gregorianYear() + $KEEP_ALIVE_YEARS_DEATH > date('Y')) {
122a25f0a04SGreg Roach                        $keep_alive = true;
123a25f0a04SGreg Roach                        break;
124a25f0a04SGreg Roach                    }
125a25f0a04SGreg Roach                }
126a25f0a04SGreg Roach            }
127a25f0a04SGreg Roach            if (!$keep_alive) {
128a25f0a04SGreg Roach                return true;
129a25f0a04SGreg Roach            }
130a25f0a04SGreg Roach        }
131a25f0a04SGreg Roach        // Consider relationship privacy (unless an admin is applying download restrictions)
1321fe542e9SGreg Roach        $user_path_length = (int) $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_PATH_LENGTH);
1331fe542e9SGreg Roach        $gedcomid         = $this->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF);
1347c4add84SGreg Roach
13554ba7dc5SGreg Roach        if ($gedcomid !== '' && $user_path_length > 0) {
1364b9ff166SGreg Roach            return self::isRelated($this, $user_path_length);
137a25f0a04SGreg Roach        }
138a25f0a04SGreg Roach
139a25f0a04SGreg Roach        // No restriction found - show living people to members only:
1404b9ff166SGreg Roach        return Auth::PRIV_USER >= $access_level;
141a25f0a04SGreg Roach    }
142a25f0a04SGreg Roach
143a25f0a04SGreg Roach    /**
144a25f0a04SGreg Roach     * For relationship privacy calculations - is this individual a close relative?
145a25f0a04SGreg Roach     *
146a25f0a04SGreg Roach     * @param Individual $target
147cbc1590aSGreg Roach     * @param int        $distance
148a25f0a04SGreg Roach     *
149cbc1590aSGreg Roach     * @return bool
150a25f0a04SGreg Roach     */
15124f2a3afSGreg Roach    private static function isRelated(Individual $target, int $distance): bool
152c1010edaSGreg Roach    {
153a25f0a04SGreg Roach        static $cache = null;
154a25f0a04SGreg Roach
1551fe542e9SGreg Roach        $user_individual = Registry::individualFactory()->make($target->tree->getUserPreference(Auth::user(), UserInterface::PREF_TREE_ACCOUNT_XREF), $target->tree);
156a25f0a04SGreg Roach        if ($user_individual) {
157a25f0a04SGreg Roach            if (!$cache) {
15813abd6f3SGreg Roach                $cache = [
15913abd6f3SGreg Roach                    0 => [$user_individual],
16013abd6f3SGreg Roach                    1 => [],
16113abd6f3SGreg Roach                ];
1628d0ebef0SGreg Roach                foreach ($user_individual->facts(['FAMC', 'FAMS'], false, Auth::PRIV_HIDE) as $fact) {
163dc124885SGreg Roach                    $family = $fact->target();
164e24444eeSGreg Roach                    if ($family instanceof Family) {
165a25f0a04SGreg Roach                        $cache[1][] = $family;
166a25f0a04SGreg Roach                    }
167a25f0a04SGreg Roach                }
168a25f0a04SGreg Roach            }
169a25f0a04SGreg Roach        } else {
170a25f0a04SGreg Roach            // No individual linked to this account? Cannot use relationship privacy.
171a25f0a04SGreg Roach            return true;
172a25f0a04SGreg Roach        }
173a25f0a04SGreg Roach
174a25f0a04SGreg Roach        // Double the distance, as we count the INDI-FAM and FAM-INDI links separately
175a25f0a04SGreg Roach        $distance *= 2;
176a25f0a04SGreg Roach
177a25f0a04SGreg Roach        // Consider each path length in turn
178a25f0a04SGreg Roach        for ($n = 0; $n <= $distance; ++$n) {
179a25f0a04SGreg Roach            if (array_key_exists($n, $cache)) {
180a25f0a04SGreg Roach                // We have already calculated all records with this length
181e364afe4SGreg Roach                if ($n % 2 === 0 && in_array($target, $cache[$n], true)) {
182a25f0a04SGreg Roach                    return true;
183a25f0a04SGreg Roach                }
184a25f0a04SGreg Roach            } else {
185a25f0a04SGreg Roach                // Need to calculate these paths
18613abd6f3SGreg Roach                $cache[$n] = [];
187e364afe4SGreg Roach                if ($n % 2 === 0) {
188a25f0a04SGreg Roach                    // Add FAM->INDI links
189a25f0a04SGreg Roach                    foreach ($cache[$n - 1] as $family) {
1908d0ebef0SGreg Roach                        foreach ($family->facts(['HUSB', 'WIFE', 'CHIL'], false, Auth::PRIV_HIDE) as $fact) {
191dc124885SGreg Roach                            $individual = $fact->target();
192a25f0a04SGreg Roach                            // Don’t backtrack
193e364afe4SGreg Roach                            if ($individual instanceof self && !in_array($individual, $cache[$n - 2], true)) {
194a25f0a04SGreg Roach                                $cache[$n][] = $individual;
195a25f0a04SGreg Roach                            }
196a25f0a04SGreg Roach                        }
197a25f0a04SGreg Roach                    }
198a25f0a04SGreg Roach                    if (in_array($target, $cache[$n], true)) {
199a25f0a04SGreg Roach                        return true;
200a25f0a04SGreg Roach                    }
201a25f0a04SGreg Roach                } else {
202a25f0a04SGreg Roach                    // Add INDI->FAM links
203a25f0a04SGreg Roach                    foreach ($cache[$n - 1] as $individual) {
2048d0ebef0SGreg Roach                        foreach ($individual->facts(['FAMC', 'FAMS'], false, Auth::PRIV_HIDE) as $fact) {
205dc124885SGreg Roach                            $family = $fact->target();
206a25f0a04SGreg Roach                            // Don’t backtrack
207e24444eeSGreg Roach                            if ($family instanceof Family && !in_array($family, $cache[$n - 2], true)) {
208a25f0a04SGreg Roach                                $cache[$n][] = $family;
209a25f0a04SGreg Roach                            }
210a25f0a04SGreg Roach                        }
211a25f0a04SGreg Roach                    }
212a25f0a04SGreg Roach                }
213a25f0a04SGreg Roach            }
214a25f0a04SGreg Roach        }
215a25f0a04SGreg Roach
216a25f0a04SGreg Roach        return false;
217a25f0a04SGreg Roach    }
218a25f0a04SGreg Roach
21976692c8bSGreg Roach    /**
22076692c8bSGreg Roach     * Generate a private version of this record
22176692c8bSGreg Roach     *
22276692c8bSGreg Roach     * @param int $access_level
22376692c8bSGreg Roach     *
22476692c8bSGreg Roach     * @return string
22576692c8bSGreg Roach     */
2263c90ed31SGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
227c1010edaSGreg Roach    {
228acf76a54SGreg Roach        $SHOW_PRIVATE_RELATIONSHIPS = (bool) $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
229a25f0a04SGreg Roach
230a25f0a04SGreg Roach        $rec = '0 @' . $this->xref . '@ INDI';
231f56b86d2SGreg Roach        if ((int) $this->tree->getPreference('SHOW_LIVING_NAMES') >= $access_level) {
232a25f0a04SGreg Roach            // Show all the NAME tags, including subtags
2338d0ebef0SGreg Roach            foreach ($this->facts(['NAME']) as $fact) {
234138ca96cSGreg Roach                $rec .= "\n" . $fact->gedcom();
235a25f0a04SGreg Roach            }
236a25f0a04SGreg Roach        }
237a25f0a04SGreg Roach        // Just show the 1 FAMC/FAMS tag, not any subtags, which may contain private data
2388d0ebef0SGreg Roach        preg_match_all('/\n1 (?:FAMC|FAMS) @(' . Gedcom::REGEX_XREF . ')@/', $this->gedcom, $matches, PREG_SET_ORDER);
239a25f0a04SGreg Roach        foreach ($matches as $match) {
2406b9cb339SGreg Roach            $rela = Registry::familyFactory()->make($match[1], $this->tree);
241a25f0a04SGreg Roach            if ($rela && ($SHOW_PRIVATE_RELATIONSHIPS || $rela->canShow($access_level))) {
242a25f0a04SGreg Roach                $rec .= $match[0];
243a25f0a04SGreg Roach            }
244a25f0a04SGreg Roach        }
245a25f0a04SGreg Roach        // Don’t privatize sex.
246a25f0a04SGreg Roach        if (preg_match('/\n1 SEX [MFU]/', $this->gedcom, $match)) {
247a25f0a04SGreg Roach            $rec .= $match[0];
248a25f0a04SGreg Roach        }
249a25f0a04SGreg Roach
250a25f0a04SGreg Roach        return $rec;
251a25f0a04SGreg Roach    }
252a25f0a04SGreg Roach
25376692c8bSGreg Roach    /**
254a25f0a04SGreg Roach     * Calculate whether this individual is living or dead.
255a25f0a04SGreg Roach     * If not known to be dead, then assume living.
256a25f0a04SGreg Roach     *
257cbc1590aSGreg Roach     * @return bool
258a25f0a04SGreg Roach     */
2598f53f488SRico Sonntag    public function isDead(): bool
260c1010edaSGreg Roach    {
261c4b3e5a2SGreg Roach        $MAX_ALIVE_AGE = (int) $this->tree->getPreference('MAX_ALIVE_AGE');
262d97083feSGreg Roach        $today_jd      = Registry::timestampFactory()->now()->julianDay();
263a25f0a04SGreg Roach
264a25f0a04SGreg Roach        // "1 DEAT Y" or "1 DEAT/2 DATE" or "1 DEAT/2 PLAC"
2658d0ebef0SGreg Roach        if (preg_match('/\n1 (?:' . implode('|', Gedcom::DEATH_EVENTS) . ')(?: Y|(?:\n[2-9].+)*\n2 (DATE|PLAC) )/', $this->gedcom)) {
266a25f0a04SGreg Roach            return true;
267a25f0a04SGreg Roach        }
268a25f0a04SGreg Roach
269a25f0a04SGreg Roach        // If any event occured more than $MAX_ALIVE_AGE years ago, then assume the individual is dead
270a25f0a04SGreg Roach        if (preg_match_all('/\n2 DATE (.+)/', $this->gedcom, $date_matches)) {
271a25f0a04SGreg Roach            foreach ($date_matches[1] as $date_match) {
272a25f0a04SGreg Roach                $date = new Date($date_match);
273269fd10dSGreg Roach                if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * $MAX_ALIVE_AGE) {
274a25f0a04SGreg Roach                    return true;
275a25f0a04SGreg Roach                }
276a25f0a04SGreg Roach            }
277a25f0a04SGreg Roach            // The individual has one or more dated events. All are less than $MAX_ALIVE_AGE years ago.
278a25f0a04SGreg Roach            // If one of these is a birth, the individual must be alive.
279a25f0a04SGreg Roach            if (preg_match('/\n1 BIRT(?:\n[2-9].+)*\n2 DATE /', $this->gedcom)) {
280a25f0a04SGreg Roach                return false;
281a25f0a04SGreg Roach            }
282a25f0a04SGreg Roach        }
283a25f0a04SGreg Roach
284a25f0a04SGreg Roach        // If we found no conclusive dates then check the dates of close relatives.
285a25f0a04SGreg Roach
286a25f0a04SGreg Roach        // Check parents (birth and adopted)
28739ca88baSGreg Roach        foreach ($this->childFamilies(Auth::PRIV_HIDE) as $family) {
28839ca88baSGreg Roach            foreach ($family->spouses(Auth::PRIV_HIDE) as $parent) {
289a25f0a04SGreg Roach                // Assume parents are no more than 45 years older than their children
290a25f0a04SGreg Roach                preg_match_all('/\n2 DATE (.+)/', $parent->gedcom, $date_matches);
291a25f0a04SGreg Roach                foreach ($date_matches[1] as $date_match) {
292a25f0a04SGreg Roach                    $date = new Date($date_match);
293269fd10dSGreg Roach                    if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE + 45)) {
294a25f0a04SGreg Roach                        return true;
295a25f0a04SGreg Roach                    }
296a25f0a04SGreg Roach                }
297a25f0a04SGreg Roach            }
298a25f0a04SGreg Roach        }
299a25f0a04SGreg Roach
300a25f0a04SGreg Roach        // Check spouses
30139ca88baSGreg Roach        foreach ($this->spouseFamilies(Auth::PRIV_HIDE) as $family) {
302a25f0a04SGreg Roach            preg_match_all('/\n2 DATE (.+)/', $family->gedcom, $date_matches);
303a25f0a04SGreg Roach            foreach ($date_matches[1] as $date_match) {
304a25f0a04SGreg Roach                $date = new Date($date_match);
305a25f0a04SGreg Roach                // Assume marriage occurs after age of 10
306269fd10dSGreg Roach                if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE - 10)) {
307a25f0a04SGreg Roach                    return true;
308a25f0a04SGreg Roach                }
309a25f0a04SGreg Roach            }
310a25f0a04SGreg Roach            // Check spouse dates
31139ca88baSGreg Roach            $spouse = $family->spouse($this, Auth::PRIV_HIDE);
312a25f0a04SGreg Roach            if ($spouse) {
313a25f0a04SGreg Roach                preg_match_all('/\n2 DATE (.+)/', $spouse->gedcom, $date_matches);
314a25f0a04SGreg Roach                foreach ($date_matches[1] as $date_match) {
315a25f0a04SGreg Roach                    $date = new Date($date_match);
316a25f0a04SGreg Roach                    // Assume max age difference between spouses of 40 years
317269fd10dSGreg Roach                    if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE + 40)) {
318a25f0a04SGreg Roach                        return true;
319a25f0a04SGreg Roach                    }
320a25f0a04SGreg Roach                }
321a25f0a04SGreg Roach            }
322a25f0a04SGreg Roach            // Check child dates
32339ca88baSGreg Roach            foreach ($family->children(Auth::PRIV_HIDE) as $child) {
324a25f0a04SGreg Roach                preg_match_all('/\n2 DATE (.+)/', $child->gedcom, $date_matches);
325a25f0a04SGreg Roach                // Assume children born after age of 15
326a25f0a04SGreg Roach                foreach ($date_matches[1] as $date_match) {
327a25f0a04SGreg Roach                    $date = new Date($date_match);
328269fd10dSGreg Roach                    if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE - 15)) {
329a25f0a04SGreg Roach                        return true;
330a25f0a04SGreg Roach                    }
331a25f0a04SGreg Roach                }
332a25f0a04SGreg Roach                // Check grandchildren
33339ca88baSGreg Roach                foreach ($child->spouseFamilies(Auth::PRIV_HIDE) as $child_family) {
33439ca88baSGreg Roach                    foreach ($child_family->children(Auth::PRIV_HIDE) as $grandchild) {
335a25f0a04SGreg Roach                        preg_match_all('/\n2 DATE (.+)/', $grandchild->gedcom, $date_matches);
336a25f0a04SGreg Roach                        // Assume grandchildren born after age of 30
337a25f0a04SGreg Roach                        foreach ($date_matches[1] as $date_match) {
338a25f0a04SGreg Roach                            $date = new Date($date_match);
339269fd10dSGreg Roach                            if ($date->isOK() && $date->maximumJulianDay() <= $today_jd - 365 * ($MAX_ALIVE_AGE - 30)) {
340a25f0a04SGreg Roach                                return true;
341a25f0a04SGreg Roach                            }
342a25f0a04SGreg Roach                        }
343a25f0a04SGreg Roach                    }
344a25f0a04SGreg Roach                }
345a25f0a04SGreg Roach            }
346a25f0a04SGreg Roach        }
347a25f0a04SGreg Roach
348a25f0a04SGreg Roach        return false;
349a25f0a04SGreg Roach    }
350a25f0a04SGreg Roach
351a25f0a04SGreg Roach    /**
352a25f0a04SGreg Roach     * Find the highlighted media object for an individual
353a25f0a04SGreg Roach     *
354e364afe4SGreg Roach     * @return MediaFile|null
355a25f0a04SGreg Roach     */
356e364afe4SGreg Roach    public function findHighlightedMediaFile(): ?MediaFile
357c1010edaSGreg Roach    {
35892647683SGreg Roach        $fact = $this->facts(['OBJE'])
35919d319e7SGreg Roach            ->first(static function (Fact $fact): bool {
360dc124885SGreg Roach                $media = $fact->target();
36119d319e7SGreg Roach
36219d319e7SGreg Roach                return $media instanceof Media && $media->firstImageFile() instanceof MediaFile;
36319d319e7SGreg Roach            });
36419d319e7SGreg Roach
36592647683SGreg Roach        if ($fact instanceof Fact && $fact->target() instanceof Media) {
36692647683SGreg Roach            return $fact->target()->firstImageFile();
367a25f0a04SGreg Roach        }
368a25f0a04SGreg Roach
369a25f0a04SGreg Roach        return null;
370a25f0a04SGreg Roach    }
371a25f0a04SGreg Roach
372a25f0a04SGreg Roach    /**
3737b0d562eSGreg Roach     * Display the preferred image for this individual.
374a25f0a04SGreg Roach     * Use an icon if no image is available.
375a25f0a04SGreg Roach     *
376dce07401SGreg Roach     * @param int           $width      Pixels
377dce07401SGreg Roach     * @param int           $height     Pixels
378dce07401SGreg Roach     * @param string        $fit        "crop" or "contain"
37909482a55SGreg Roach     * @param array<string> $attributes Additional HTML attributes
380dce07401SGreg Roach     *
381a25f0a04SGreg Roach     * @return string
382a25f0a04SGreg Roach     */
38324f2a3afSGreg Roach    public function displayImage(int $width, int $height, string $fit, array $attributes): string
384c1010edaSGreg Roach    {
3854a9f750fSGreg Roach        $media_file = $this->findHighlightedMediaFile();
3864a9f750fSGreg Roach
3874a9f750fSGreg Roach        if ($media_file !== null) {
3884a9f750fSGreg Roach            return $media_file->displayImage($width, $height, $fit, $attributes);
389a25f0a04SGreg Roach        }
3904a9f750fSGreg Roach
3914a9f750fSGreg Roach        if ($this->tree->getPreference('USE_SILHOUETTE')) {
39268b631f1SGreg Roach            return '<i class="icon-silhouette icon-silhouette-' . strtolower($this->sex()) . ' wt-icon-flip-rtl"></i>';
3934a9f750fSGreg Roach        }
3944a9f750fSGreg Roach
3954a9f750fSGreg Roach        return '';
396a25f0a04SGreg Roach    }
397a25f0a04SGreg Roach
398a25f0a04SGreg Roach    /**
399a25f0a04SGreg Roach     * Get the date of birth
400a25f0a04SGreg Roach     *
401a25f0a04SGreg Roach     * @return Date
402a25f0a04SGreg Roach     */
4038f53f488SRico Sonntag    public function getBirthDate(): Date
404c1010edaSGreg Roach    {
405a25f0a04SGreg Roach        foreach ($this->getAllBirthDates() as $date) {
406a25f0a04SGreg Roach            if ($date->isOK()) {
407a25f0a04SGreg Roach                return $date;
408a25f0a04SGreg Roach            }
409a25f0a04SGreg Roach        }
410a25f0a04SGreg Roach
411a25f0a04SGreg Roach        return new Date('');
412a25f0a04SGreg Roach    }
413a25f0a04SGreg Roach
414a25f0a04SGreg Roach    /**
415a25f0a04SGreg Roach     * Get the place of birth
416a25f0a04SGreg Roach     *
41716d0b7f7SRico Sonntag     * @return Place
418a25f0a04SGreg Roach     */
4198f53f488SRico Sonntag    public function getBirthPlace(): Place
420c1010edaSGreg Roach    {
421a25f0a04SGreg Roach        foreach ($this->getAllBirthPlaces() as $place) {
422a25f0a04SGreg Roach            return $place;
423a25f0a04SGreg Roach        }
424a25f0a04SGreg Roach
425b20ddbf9SGreg Roach        return new Place('', $this->tree);
426a25f0a04SGreg Roach    }
427a25f0a04SGreg Roach
428a25f0a04SGreg Roach    /**
429a25f0a04SGreg Roach     * Get the date of death
430a25f0a04SGreg Roach     *
431a25f0a04SGreg Roach     * @return Date
432a25f0a04SGreg Roach     */
4338f53f488SRico Sonntag    public function getDeathDate(): Date
434c1010edaSGreg Roach    {
435a25f0a04SGreg Roach        foreach ($this->getAllDeathDates() as $date) {
436a25f0a04SGreg Roach            if ($date->isOK()) {
437a25f0a04SGreg Roach                return $date;
438a25f0a04SGreg Roach            }
439a25f0a04SGreg Roach        }
440a25f0a04SGreg Roach
441a25f0a04SGreg Roach        return new Date('');
442a25f0a04SGreg Roach    }
443a25f0a04SGreg Roach
444a25f0a04SGreg Roach    /**
445a25f0a04SGreg Roach     * Get the place of death
446a25f0a04SGreg Roach     *
44716d0b7f7SRico Sonntag     * @return Place
448a25f0a04SGreg Roach     */
4498f53f488SRico Sonntag    public function getDeathPlace(): Place
450c1010edaSGreg Roach    {
451a25f0a04SGreg Roach        foreach ($this->getAllDeathPlaces() as $place) {
452a25f0a04SGreg Roach            return $place;
453a25f0a04SGreg Roach        }
454a25f0a04SGreg Roach
455b20ddbf9SGreg Roach        return new Place('', $this->tree);
456a25f0a04SGreg Roach    }
457a25f0a04SGreg Roach
458a25f0a04SGreg Roach    /**
459a25f0a04SGreg Roach     * Get the range of years in which a individual lived. e.g. “1870–”, “1870–1920”, “–1920”.
46015d603e7SGreg Roach     * Provide the place and full date using a tooltip.
461a25f0a04SGreg Roach     * For consistent layout in charts, etc., show just a “–” when no dates are known.
462a25f0a04SGreg Roach     * Note that this is a (non-breaking) en-dash, and not a hyphen.
463a25f0a04SGreg Roach     *
464a25f0a04SGreg Roach     * @return string
465a25f0a04SGreg Roach     */
4665e6816beSGreg Roach    public function lifespan(): string
467c1010edaSGreg Roach    {
46853f5ca04SGreg Roach        // Just the first part of the place name.
469392561bbSGreg Roach        $birth_place = strip_tags($this->getBirthPlace()->shortName());
470392561bbSGreg Roach        $death_place = strip_tags($this->getDeathPlace()->shortName());
47153f5ca04SGreg Roach
47281b9dc5dSGreg Roach        // Remove markup from dates.  Use UTF_FSI / UTF_PDI instead of <bdi></bdi>, as
47381b9dc5dSGreg Roach        // we cannot use HTML markup in title attributes.
47481b9dc5dSGreg Roach        $birth_date = "\u{2068}" . strip_tags($this->getBirthDate()->display()) . "\u{2069}";
47581b9dc5dSGreg Roach        $death_date = "\u{2068}" . strip_tags($this->getDeathDate()->display()) . "\u{2069}";
47615d603e7SGreg Roach
47753f5ca04SGreg Roach        // Use minimum and maximum dates - to agree with the age calculations.
47853f5ca04SGreg Roach        $birth_year = $this->getBirthDate()->minimumDate()->format('%Y');
47953f5ca04SGreg Roach        $death_year = $this->getDeathDate()->maximumDate()->format('%Y');
48053f5ca04SGreg Roach
481c1010edaSGreg Roach        /* I18N: A range of years, e.g. “1870–”, “1870–1920”, “–1920” */
482dacfe33cSGreg Roach        return I18N::translate(
483a25f0a04SGreg Roach            '%1$s–%2$s',
48453f5ca04SGreg Roach            '<span title="' . $birth_place . ' ' . $birth_date . '">' . $birth_year . '</span>',
48553f5ca04SGreg Roach            '<span title="' . $death_place . ' ' . $death_date . '">' . $death_year . '</span>'
486a25f0a04SGreg Roach        );
487a25f0a04SGreg Roach    }
488a25f0a04SGreg Roach
489a25f0a04SGreg Roach    /**
490a25f0a04SGreg Roach     * Get all the birth dates - for the individual lists.
491a25f0a04SGreg Roach     *
49209482a55SGreg Roach     * @return array<Date>
493a25f0a04SGreg Roach     */
4948f53f488SRico Sonntag    public function getAllBirthDates(): array
495c1010edaSGreg Roach    {
4968d0ebef0SGreg Roach        foreach (Gedcom::BIRTH_EVENTS as $event) {
497d240bb87SGreg Roach            $dates = $this->getAllEventDates([$event]);
498d240bb87SGreg Roach
499d240bb87SGreg Roach            if ($dates !== []) {
500d240bb87SGreg Roach                return $dates;
501a25f0a04SGreg Roach            }
502a25f0a04SGreg Roach        }
503a25f0a04SGreg Roach
50413abd6f3SGreg Roach        return [];
505a25f0a04SGreg Roach    }
506a25f0a04SGreg Roach
507a25f0a04SGreg Roach    /**
508a25f0a04SGreg Roach     * Gat all the birth places - for the individual lists.
509a25f0a04SGreg Roach     *
51009482a55SGreg Roach     * @return array<Place>
511a25f0a04SGreg Roach     */
5128f53f488SRico Sonntag    public function getAllBirthPlaces(): array
513c1010edaSGreg Roach    {
5148d0ebef0SGreg Roach        foreach (Gedcom::BIRTH_EVENTS as $event) {
5158d0ebef0SGreg Roach            $places = $this->getAllEventPlaces([$event]);
516d240bb87SGreg Roach
51754c1ab5eSGreg Roach            if ($places !== []) {
5184080d558SGreg Roach                return $places;
519a25f0a04SGreg Roach            }
520a25f0a04SGreg Roach        }
521a25f0a04SGreg Roach
52213abd6f3SGreg Roach        return [];
523a25f0a04SGreg Roach    }
524a25f0a04SGreg Roach
525a25f0a04SGreg Roach    /**
526a25f0a04SGreg Roach     * Get all the death dates - for the individual lists.
527a25f0a04SGreg Roach     *
52809482a55SGreg Roach     * @return array<Date>
529a25f0a04SGreg Roach     */
5308f53f488SRico Sonntag    public function getAllDeathDates(): array
531c1010edaSGreg Roach    {
5328d0ebef0SGreg Roach        foreach (Gedcom::DEATH_EVENTS as $event) {
533d240bb87SGreg Roach            $dates = $this->getAllEventDates([$event]);
534d240bb87SGreg Roach
535d240bb87SGreg Roach            if ($dates !== []) {
536d240bb87SGreg Roach                return $dates;
537a25f0a04SGreg Roach            }
538a25f0a04SGreg Roach        }
539a25f0a04SGreg Roach
54013abd6f3SGreg Roach        return [];
541a25f0a04SGreg Roach    }
542a25f0a04SGreg Roach
543a25f0a04SGreg Roach    /**
544a25f0a04SGreg Roach     * Get all the death places - for the individual lists.
545a25f0a04SGreg Roach     *
54609482a55SGreg Roach     * @return array<Place>
547a25f0a04SGreg Roach     */
5488f53f488SRico Sonntag    public function getAllDeathPlaces(): array
549c1010edaSGreg Roach    {
5508d0ebef0SGreg Roach        foreach (Gedcom::DEATH_EVENTS as $event) {
5518d0ebef0SGreg Roach            $places = $this->getAllEventPlaces([$event]);
552d240bb87SGreg Roach
55354c1ab5eSGreg Roach            if ($places !== []) {
5544080d558SGreg Roach                return $places;
555a25f0a04SGreg Roach            }
556a25f0a04SGreg Roach        }
557a25f0a04SGreg Roach
55813abd6f3SGreg Roach        return [];
559a25f0a04SGreg Roach    }
560a25f0a04SGreg Roach
561a25f0a04SGreg Roach    /**
562a25f0a04SGreg Roach     * Generate an estimate for the date of birth, based on dates of parents/children/spouses
563a25f0a04SGreg Roach     *
564a25f0a04SGreg Roach     * @return Date
565a25f0a04SGreg Roach     */
5668f53f488SRico Sonntag    public function getEstimatedBirthDate(): Date
567c1010edaSGreg Roach    {
5688f038c36SRico Sonntag        if ($this->estimated_birth_date === null) {
569a25f0a04SGreg Roach            foreach ($this->getAllBirthDates() as $date) {
570a25f0a04SGreg Roach                if ($date->isOK()) {
5714686330aSGreg Roach                    $this->estimated_birth_date = $date;
572a25f0a04SGreg Roach                    break;
573a25f0a04SGreg Roach                }
574a25f0a04SGreg Roach            }
5758f038c36SRico Sonntag            if ($this->estimated_birth_date === null) {
57613abd6f3SGreg Roach                $min = [];
57713abd6f3SGreg Roach                $max = [];
578a25f0a04SGreg Roach                $tmp = $this->getDeathDate();
579f5b60decSGreg Roach                if ($tmp->isOK()) {
580f5b60decSGreg Roach                    $min[] = $tmp->minimumJulianDay() - $this->tree->getPreference('MAX_ALIVE_AGE') * 365;
581f5b60decSGreg Roach                    $max[] = $tmp->maximumJulianDay();
582a25f0a04SGreg Roach                }
58339ca88baSGreg Roach                foreach ($this->childFamilies() as $family) {
584a25f0a04SGreg Roach                    $tmp = $family->getMarriageDate();
585f5b60decSGreg Roach                    if ($tmp->isOK()) {
586f5b60decSGreg Roach                        $min[] = $tmp->maximumJulianDay() - 365 * 1;
587f5b60decSGreg Roach                        $max[] = $tmp->minimumJulianDay() + 365 * 30;
588a25f0a04SGreg Roach                    }
58939ca88baSGreg Roach                    $husband = $family->husband();
590e364afe4SGreg Roach                    if ($husband instanceof self) {
5912e5b4452SGreg Roach                        $tmp = $husband->getBirthDate();
592f5b60decSGreg Roach                        if ($tmp->isOK()) {
593f5b60decSGreg Roach                            $min[] = $tmp->maximumJulianDay() + 365 * 15;
594f5b60decSGreg Roach                            $max[] = $tmp->minimumJulianDay() + 365 * 65;
595a25f0a04SGreg Roach                        }
596a25f0a04SGreg Roach                    }
59739ca88baSGreg Roach                    $wife = $family->wife();
598e364afe4SGreg Roach                    if ($wife instanceof self) {
5992e5b4452SGreg Roach                        $tmp = $wife->getBirthDate();
600f5b60decSGreg Roach                        if ($tmp->isOK()) {
601f5b60decSGreg Roach                            $min[] = $tmp->maximumJulianDay() + 365 * 15;
602f5b60decSGreg Roach                            $max[] = $tmp->minimumJulianDay() + 365 * 45;
603a25f0a04SGreg Roach                        }
604a25f0a04SGreg Roach                    }
60539ca88baSGreg Roach                    foreach ($family->children() as $child) {
606a25f0a04SGreg Roach                        $tmp = $child->getBirthDate();
607f5b60decSGreg Roach                        if ($tmp->isOK()) {
608f5b60decSGreg Roach                            $min[] = $tmp->maximumJulianDay() - 365 * 30;
609f5b60decSGreg Roach                            $max[] = $tmp->minimumJulianDay() + 365 * 30;
610a25f0a04SGreg Roach                        }
611a25f0a04SGreg Roach                    }
612a25f0a04SGreg Roach                }
61339ca88baSGreg Roach                foreach ($this->spouseFamilies() as $family) {
614a25f0a04SGreg Roach                    $tmp = $family->getMarriageDate();
615f5b60decSGreg Roach                    if ($tmp->isOK()) {
616f5b60decSGreg Roach                        $min[] = $tmp->maximumJulianDay() - 365 * 45;
617f5b60decSGreg Roach                        $max[] = $tmp->minimumJulianDay() - 365 * 15;
618a25f0a04SGreg Roach                    }
61939ca88baSGreg Roach                    $spouse = $family->spouse($this);
620a25f0a04SGreg Roach                    if ($spouse) {
621a25f0a04SGreg Roach                        $tmp = $spouse->getBirthDate();
622f5b60decSGreg Roach                        if ($tmp->isOK()) {
623f5b60decSGreg Roach                            $min[] = $tmp->maximumJulianDay() - 365 * 25;
624f5b60decSGreg Roach                            $max[] = $tmp->minimumJulianDay() + 365 * 25;
625a25f0a04SGreg Roach                        }
626a25f0a04SGreg Roach                    }
62739ca88baSGreg Roach                    foreach ($family->children() as $child) {
628a25f0a04SGreg Roach                        $tmp = $child->getBirthDate();
629f5b60decSGreg Roach                        if ($tmp->isOK()) {
630e364afe4SGreg Roach                            $min[] = $tmp->maximumJulianDay() - 365 * ($this->sex() === 'F' ? 45 : 65);
631f5b60decSGreg Roach                            $max[] = $tmp->minimumJulianDay() - 365 * 15;
632a25f0a04SGreg Roach                        }
633a25f0a04SGreg Roach                    }
634a25f0a04SGreg Roach                }
635a25f0a04SGreg Roach                if ($min && $max) {
63659f2f229SGreg Roach                    $gregorian_calendar = new GregorianCalendar();
637a25f0a04SGreg Roach
63865e02381SGreg Roach                    [$year] = $gregorian_calendar->jdToYmd(intdiv(max($min) + min($max), 2));
6394686330aSGreg Roach                    $this->estimated_birth_date = new Date('EST ' . $year);
640a25f0a04SGreg Roach                } else {
6414686330aSGreg Roach                    $this->estimated_birth_date = new Date(''); // always return a date object
642a25f0a04SGreg Roach                }
643a25f0a04SGreg Roach            }
644a25f0a04SGreg Roach        }
645a25f0a04SGreg Roach
6464686330aSGreg Roach        return $this->estimated_birth_date;
647a25f0a04SGreg Roach    }
648a25f0a04SGreg Roach
649a25f0a04SGreg Roach    /**
650a25f0a04SGreg Roach     * Generate an estimated date of death.
651a25f0a04SGreg Roach     *
652a25f0a04SGreg Roach     * @return Date
653a25f0a04SGreg Roach     */
6548f53f488SRico Sonntag    public function getEstimatedDeathDate(): Date
655c1010edaSGreg Roach    {
6564686330aSGreg Roach        if ($this->estimated_death_date === null) {
657a25f0a04SGreg Roach            foreach ($this->getAllDeathDates() as $date) {
658a25f0a04SGreg Roach                if ($date->isOK()) {
6594686330aSGreg Roach                    $this->estimated_death_date = $date;
660a25f0a04SGreg Roach                    break;
661a25f0a04SGreg Roach                }
662a25f0a04SGreg Roach            }
6634686330aSGreg Roach            if ($this->estimated_death_date === null) {
664f5b60decSGreg Roach                if ($this->getEstimatedBirthDate()->minimumJulianDay()) {
665c4b3e5a2SGreg Roach                    $max_alive_age              = (int) $this->tree->getPreference('MAX_ALIVE_AGE');
6664686330aSGreg Roach                    $this->estimated_death_date = $this->getEstimatedBirthDate()->addYears($max_alive_age, 'BEF');
667a25f0a04SGreg Roach                } else {
6684686330aSGreg Roach                    $this->estimated_death_date = new Date(''); // always return a date object
669a25f0a04SGreg Roach                }
670a25f0a04SGreg Roach            }
671a25f0a04SGreg Roach        }
672a25f0a04SGreg Roach
6734686330aSGreg Roach        return $this->estimated_death_date;
674a25f0a04SGreg Roach    }
675a25f0a04SGreg Roach
676a25f0a04SGreg Roach    /**
677a25f0a04SGreg Roach     * Get the sex - M F or U
678a25f0a04SGreg Roach     * Use the un-privatised gedcom record. We call this function during
679a25f0a04SGreg Roach     * the privatize-gedcom function, and we are allowed to know this.
680a25f0a04SGreg Roach     *
681a25f0a04SGreg Roach     * @return string
682a25f0a04SGreg Roach     */
683e364afe4SGreg Roach    public function sex(): string
684c1010edaSGreg Roach    {
6851baf69deSGreg Roach        if (preg_match('/\n1 SEX ([MFX])/', $this->gedcom . $this->pending, $match)) {
686a25f0a04SGreg Roach            return $match[1];
687a25f0a04SGreg Roach        }
688b2ce94c6SRico Sonntag
689b2ce94c6SRico Sonntag        return 'U';
690a25f0a04SGreg Roach    }
691a25f0a04SGreg Roach
692a25f0a04SGreg Roach    /**
693a25f0a04SGreg Roach     * Get a list of this individual’s spouse families
694a25f0a04SGreg Roach     *
695cbc1590aSGreg Roach     * @param int|null $access_level
696a25f0a04SGreg Roach     *
69736779af1SGreg Roach     * @return Collection<int,Family>
698a25f0a04SGreg Roach     */
69973d58381SGreg Roach    public function spouseFamilies(int $access_level = null): Collection
700c1010edaSGreg Roach    {
701d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
702d9e083e7SGreg Roach
703d9e083e7SGreg Roach        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
704d9e083e7SGreg Roach            $access_level = Auth::PRIV_HIDE;
7054b9ff166SGreg Roach        }
7064b9ff166SGreg Roach
70739ca88baSGreg Roach        $families = new Collection();
708d9e083e7SGreg Roach        foreach ($this->facts(['FAMS'], false, $access_level) as $fact) {
709dc124885SGreg Roach            $family = $fact->target();
710d9e083e7SGreg Roach            if ($family instanceof Family && $family->canShow($access_level)) {
71139ca88baSGreg Roach                $families->push($family);
712a25f0a04SGreg Roach            }
713a25f0a04SGreg Roach        }
714a25f0a04SGreg Roach
71539ca88baSGreg Roach        return new Collection($families);
716a25f0a04SGreg Roach    }
717a25f0a04SGreg Roach
718a25f0a04SGreg Roach    /**
719a25f0a04SGreg Roach     * Get the current spouse of this individual.
720a25f0a04SGreg Roach     *
721a25f0a04SGreg Roach     * Where an individual has multiple spouses, assume they are stored
722a25f0a04SGreg Roach     * in chronological order, and take the last one found.
723a25f0a04SGreg Roach     *
724a25f0a04SGreg Roach     * @return Individual|null
725a25f0a04SGreg Roach     */
726e364afe4SGreg Roach    public function getCurrentSpouse(): ?Individual
727c1010edaSGreg Roach    {
72839ca88baSGreg Roach        $family = $this->spouseFamilies()->last();
72939ca88baSGreg Roach
73039ca88baSGreg Roach        if ($family instanceof Family) {
73139ca88baSGreg Roach            return $family->spouse($this);
732a25f0a04SGreg Roach        }
733b2ce94c6SRico Sonntag
734b2ce94c6SRico Sonntag        return null;
735a25f0a04SGreg Roach    }
736a25f0a04SGreg Roach
737a25f0a04SGreg Roach    /**
738a25f0a04SGreg Roach     * Count the children belonging to this individual.
739a25f0a04SGreg Roach     *
740cbc1590aSGreg Roach     * @return int
741a25f0a04SGreg Roach     */
742e364afe4SGreg Roach    public function numberOfChildren(): int
743c1010edaSGreg Roach    {
7447d0db648SGreg Roach        if (preg_match('/\n1 NCHI (\d+)(?:\n|$)/', $this->gedcom(), $match)) {
7453dc7bbe9SGreg Roach            return (int) $match[1];
746b2ce94c6SRico Sonntag        }
747b2ce94c6SRico Sonntag
74813abd6f3SGreg Roach        $children = [];
74939ca88baSGreg Roach        foreach ($this->spouseFamilies() as $fam) {
75039ca88baSGreg Roach            foreach ($fam->children() as $child) {
751c0935879SGreg Roach                $children[$child->xref()] = true;
752a25f0a04SGreg Roach            }
753a25f0a04SGreg Roach        }
754a25f0a04SGreg Roach
755a25f0a04SGreg Roach        return count($children);
756a25f0a04SGreg Roach    }
757a25f0a04SGreg Roach
758a25f0a04SGreg Roach    /**
759a25f0a04SGreg Roach     * Get a list of this individual’s child families (i.e. their parents).
760a25f0a04SGreg Roach     *
761cbc1590aSGreg Roach     * @param int|null $access_level
762a25f0a04SGreg Roach     *
76336779af1SGreg Roach     * @return Collection<int,Family>
764a25f0a04SGreg Roach     */
76573d58381SGreg Roach    public function childFamilies(int $access_level = null): Collection
766c1010edaSGreg Roach    {
767d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
7684b9ff166SGreg Roach
769d9e083e7SGreg Roach        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
770d9e083e7SGreg Roach            $access_level = Auth::PRIV_HIDE;
771d9e083e7SGreg Roach        }
772a25f0a04SGreg Roach
77339ca88baSGreg Roach        $families = new Collection();
77439ca88baSGreg Roach
775d9e083e7SGreg Roach        foreach ($this->facts(['FAMC'], false, $access_level) as $fact) {
776dc124885SGreg Roach            $family = $fact->target();
777d9e083e7SGreg Roach            if ($family instanceof Family && $family->canShow($access_level)) {
77839ca88baSGreg Roach                $families->push($family);
779a25f0a04SGreg Roach            }
780a25f0a04SGreg Roach        }
781a25f0a04SGreg Roach
782a25f0a04SGreg Roach        return $families;
783a25f0a04SGreg Roach    }
784a25f0a04SGreg Roach
785a25f0a04SGreg Roach    /**
786a25f0a04SGreg Roach     * Get a list of step-parent families.
787a25f0a04SGreg Roach     *
78836779af1SGreg Roach     * @return Collection<int,Family>
789a25f0a04SGreg Roach     */
790820b62dfSGreg Roach    public function childStepFamilies(): Collection
791c1010edaSGreg Roach    {
792ed5b6227SGreg Roach        $step_families = new Collection();
79339ca88baSGreg Roach        $families      = $this->childFamilies();
794a25f0a04SGreg Roach        foreach ($families as $family) {
795ed5b6227SGreg Roach            foreach ($family->spouses() as $parent) {
796ed5b6227SGreg Roach                foreach ($parent->spouseFamilies() as $step_family) {
79739ca88baSGreg Roach                    if (!$families->containsStrict($step_family)) {
798ed5b6227SGreg Roach                        $step_families->add($step_family);
799a25f0a04SGreg Roach                    }
800a25f0a04SGreg Roach                }
801a25f0a04SGreg Roach            }
802a25f0a04SGreg Roach        }
803a25f0a04SGreg Roach
8048c627a69SGreg Roach        return $step_families->uniqueStrict(static function (Family $family): string {
8058c627a69SGreg Roach            return $family->xref();
8068c627a69SGreg Roach        });
807a25f0a04SGreg Roach    }
808a25f0a04SGreg Roach
809a25f0a04SGreg Roach    /**
810a25f0a04SGreg Roach     * Get a list of step-parent families.
811a25f0a04SGreg Roach     *
81236779af1SGreg Roach     * @return Collection<int,Family>
813a25f0a04SGreg Roach     */
814820b62dfSGreg Roach    public function spouseStepFamilies(): Collection
815c1010edaSGreg Roach    {
81613abd6f3SGreg Roach        $step_families = [];
81739ca88baSGreg Roach        $families      = $this->spouseFamilies();
818820b62dfSGreg Roach
819a25f0a04SGreg Roach        foreach ($families as $family) {
82039ca88baSGreg Roach            $spouse = $family->spouse($this);
821820b62dfSGreg Roach
822d823340dSGreg Roach            if ($spouse instanceof self) {
82339ca88baSGreg Roach                foreach ($family->spouse($this)->spouseFamilies() as $step_family) {
82439ca88baSGreg Roach                    if (!$families->containsStrict($step_family)) {
825a25f0a04SGreg Roach                        $step_families[] = $step_family;
826a25f0a04SGreg Roach                    }
827a25f0a04SGreg Roach                }
828a25f0a04SGreg Roach            }
829a25f0a04SGreg Roach        }
830a25f0a04SGreg Roach
831820b62dfSGreg Roach        return new Collection($step_families);
832a25f0a04SGreg Roach    }
833a25f0a04SGreg Roach
834a25f0a04SGreg Roach    /**
835a25f0a04SGreg Roach     * A label for a parental family group
836a25f0a04SGreg Roach     *
837a25f0a04SGreg Roach     * @param Family $family
838a25f0a04SGreg Roach     *
839a25f0a04SGreg Roach     * @return string
840a25f0a04SGreg Roach     */
841820b62dfSGreg Roach    public function getChildFamilyLabel(Family $family): string
842c1010edaSGreg Roach    {
8430e7e67a6SGreg Roach        $fact = $this->facts(['FAMC'])->first(static fn (Fact $fact): bool => $fact->target() === $family);
8440e7e67a6SGreg Roach
8450e7e67a6SGreg Roach        if ($fact instanceof Fact) {
8460e7e67a6SGreg Roach            $pedigree = $fact->attribute('PEDI');
8470e7e67a6SGreg Roach        } else {
8480e7e67a6SGreg Roach            $pedigree = '';
8490e7e67a6SGreg Roach        }
850b2ce94c6SRico Sonntag
8517d70e4a7SGreg Roach        $values = [
85288a03560SGreg Roach            PedigreeLinkageType::VALUE_BIRTH   => I18N::translate('Family with parents'),
85388a03560SGreg Roach            PedigreeLinkageType::VALUE_ADOPTED => I18N::translate('Family with adoptive parents'),
85488a03560SGreg Roach            PedigreeLinkageType::VALUE_FOSTER  => I18N::translate('Family with foster parents'),
855665e281aSGreg Roach            /* I18N: “sealing” is a Mormon ceremony. */
85688a03560SGreg Roach            PedigreeLinkageType::VALUE_SEALING => I18N::translate('Family with sealing parents'),
857665e281aSGreg Roach            /* I18N: “rada” is an Arabic word, pronounced “ra DAH”. It is child-to-parent pedigree, established by wet-nursing. */
85888a03560SGreg Roach            PedigreeLinkageType::VALUE_RADA    => I18N::translate('Family with rada parents'),
8597d70e4a7SGreg Roach        ];
8607d70e4a7SGreg Roach
86188a03560SGreg Roach        return $values[$pedigree] ?? $values[PedigreeLinkageType::VALUE_BIRTH];
862a25f0a04SGreg Roach    }
863a25f0a04SGreg Roach
864a25f0a04SGreg Roach    /**
865a25f0a04SGreg Roach     * Create a label for a step family
866a25f0a04SGreg Roach     *
867a25f0a04SGreg Roach     * @param Family $step_family
868a25f0a04SGreg Roach     *
869a25f0a04SGreg Roach     * @return string
870a25f0a04SGreg Roach     */
8718f53f488SRico Sonntag    public function getStepFamilyLabel(Family $step_family): string
872c1010edaSGreg Roach    {
87339ca88baSGreg Roach        foreach ($this->childFamilies() as $family) {
874a25f0a04SGreg Roach            if ($family !== $step_family) {
875a25f0a04SGreg Roach                // Must be a step-family
87639ca88baSGreg Roach                foreach ($family->spouses() as $parent) {
87739ca88baSGreg Roach                    foreach ($step_family->spouses() as $step_parent) {
878a25f0a04SGreg Roach                        if ($parent === $step_parent) {
879a25f0a04SGreg Roach                            // One common parent - must be a step family
880e364afe4SGreg Roach                            if ($parent->sex() === 'M') {
881a25f0a04SGreg Roach                                // Father’s family with someone else
88239ca88baSGreg Roach                                if ($step_family->spouse($step_parent)) {
883a25f0a04SGreg Roach                                    /* I18N: A step-family. %s is an individual’s name */
88439ca88baSGreg Roach                                    return I18N::translate('Father’s family with %s', $step_family->spouse($step_parent)->fullName());
885b2ce94c6SRico Sonntag                                }
886b2ce94c6SRico Sonntag
887a25f0a04SGreg Roach                                /* I18N: A step-family. */
888bbb76c12SGreg Roach                                return I18N::translate('Father’s family with an unknown individual');
889a25f0a04SGreg Roach                            }
890b2ce94c6SRico Sonntag
891a25f0a04SGreg Roach                            // Mother’s family with someone else
89239ca88baSGreg Roach                            if ($step_family->spouse($step_parent)) {
893a25f0a04SGreg Roach                                /* I18N: A step-family. %s is an individual’s name */
89439ca88baSGreg Roach                                return I18N::translate('Mother’s family with %s', $step_family->spouse($step_parent)->fullName());
895b2ce94c6SRico Sonntag                            }
896b2ce94c6SRico Sonntag
897a25f0a04SGreg Roach                            /* I18N: A step-family. */
898bbb76c12SGreg Roach                            return I18N::translate('Mother’s family with an unknown individual');
899a25f0a04SGreg Roach                        }
900a25f0a04SGreg Roach                    }
901a25f0a04SGreg Roach                }
902a25f0a04SGreg Roach            }
903a25f0a04SGreg Roach        }
904a25f0a04SGreg Roach
905a25f0a04SGreg Roach        // Perahps same parents - but a different family record?
906a25f0a04SGreg Roach        return I18N::translate('Family with parents');
907a25f0a04SGreg Roach    }
908a25f0a04SGreg Roach
909225e381fSGreg Roach    /**
910225e381fSGreg Roach     * Get the description for the family.
911225e381fSGreg Roach     *
912225e381fSGreg Roach     * For example, "XXX's family with new wife".
913225e381fSGreg Roach     *
914225e381fSGreg Roach     * @param Family $family
915225e381fSGreg Roach     *
916225e381fSGreg Roach     * @return string
917225e381fSGreg Roach     */
918e364afe4SGreg Roach    public function getSpouseFamilyLabel(Family $family): string
919c1010edaSGreg Roach    {
92039ca88baSGreg Roach        $spouse = $family->spouse($this);
921225e381fSGreg Roach        if ($spouse) {
922225e381fSGreg Roach            /* I18N: %s is the spouse name */
92339ca88baSGreg Roach            return I18N::translate('Family with %s', $spouse->fullName());
924225e381fSGreg Roach        }
925b2ce94c6SRico Sonntag
92639ca88baSGreg Roach        return $family->fullName();
927225e381fSGreg Roach    }
928225e381fSGreg Roach
929a25f0a04SGreg Roach    /**
930961ec755SGreg Roach     * If this object has no name, what do we call it?
931961ec755SGreg Roach     *
932961ec755SGreg Roach     * @return string
933961ec755SGreg Roach     */
9348f53f488SRico Sonntag    public function getFallBackName(): string
935c1010edaSGreg Roach    {
936a25f0a04SGreg Roach        return '@P.N. /@N.N./';
937a25f0a04SGreg Roach    }
938a25f0a04SGreg Roach
939a25f0a04SGreg Roach    /**
940a25f0a04SGreg Roach     * Convert a name record into ‘full’ and ‘sort’ versions.
941a25f0a04SGreg Roach     * Use the NAME field to generate the ‘full’ version, as the
942a25f0a04SGreg Roach     * gedcom spec says that this is the individual’s name, as they would write it.
943a25f0a04SGreg Roach     * Use the SURN field to generate the sortable names. Note that this field
944a25f0a04SGreg Roach     * may also be used for the ‘true’ surname, perhaps spelt differently to that
945a25f0a04SGreg Roach     * recorded in the NAME field. e.g.
946a25f0a04SGreg Roach     *
947a25f0a04SGreg Roach     * 1 NAME Robert /de Gliderow/
948a25f0a04SGreg Roach     * 2 GIVN Robert
949a25f0a04SGreg Roach     * 2 SPFX de
950a25f0a04SGreg Roach     * 2 SURN CLITHEROW
951a25f0a04SGreg Roach     * 2 NICK The Bald
952a25f0a04SGreg Roach     *
953a25f0a04SGreg Roach     * full=>'Robert de Gliderow 'The Bald''
954a25f0a04SGreg Roach     * sort=>'CLITHEROW, ROBERT'
955a25f0a04SGreg Roach     *
956a25f0a04SGreg Roach     * Handle multiple surnames, either as;
957a25f0a04SGreg Roach     *
958a25f0a04SGreg Roach     * 1 NAME Carlos /Vasquez/ y /Sante/
959a25f0a04SGreg Roach     * or
960a25f0a04SGreg Roach     * 1 NAME Carlos /Vasquez y Sante/
961a25f0a04SGreg Roach     * 2 GIVN Carlos
962a25f0a04SGreg Roach     * 2 SURN Vasquez,Sante
963a25f0a04SGreg Roach     *
964a25f0a04SGreg Roach     * @param string $type
96551928f9aSGreg Roach     * @param string $value
966a25f0a04SGreg Roach     * @param string $gedcom
967e364afe4SGreg Roach     *
968e364afe4SGreg Roach     * @return void
969a25f0a04SGreg Roach     */
97051928f9aSGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
971c1010edaSGreg Roach    {
972a25f0a04SGreg Roach        ////////////////////////////////////////////////////////////////////////////
973a25f0a04SGreg Roach        // Extract the structured name parts - use for "sortable" names and indexes
974a25f0a04SGreg Roach        ////////////////////////////////////////////////////////////////////////////
975a25f0a04SGreg Roach
97676f666f4SGreg Roach        $sublevel = 1 + (int) substr($gedcom, 0, 1);
977*ef475b14SGreg Roach        $GIVN     = preg_match('/\n' . $sublevel . ' GIVN (.+)/', $gedcom, $match) === 1 ? $match[1] : '';
978*ef475b14SGreg Roach        $SURN     = preg_match('/\n' . $sublevel . ' SURN (.+)/', $gedcom, $match) === 1 ? $match[1] : '';
979a25f0a04SGreg Roach
980a25f0a04SGreg Roach        // SURN is an comma-separated list of surnames...
98176f666f4SGreg Roach        if ($SURN !== '') {
982a25f0a04SGreg Roach            $SURNS = preg_split('/ *, */', $SURN);
983a25f0a04SGreg Roach        } else {
98413abd6f3SGreg Roach            $SURNS = [];
985a25f0a04SGreg Roach        }
98676f666f4SGreg Roach
987a25f0a04SGreg Roach        // ...so is GIVN - but nobody uses it like that
988a25f0a04SGreg Roach        $GIVN = str_replace('/ *, */', ' ', $GIVN);
989a25f0a04SGreg Roach
990a25f0a04SGreg Roach        ////////////////////////////////////////////////////////////////////////////
991a25f0a04SGreg Roach        // Extract the components from NAME - use for the "full" names
992a25f0a04SGreg Roach        ////////////////////////////////////////////////////////////////////////////
993a25f0a04SGreg Roach
994a25f0a04SGreg Roach        // Fix bad slashes. e.g. 'John/Smith' => 'John/Smith/'
99551928f9aSGreg Roach        if (substr_count($value, '/') % 2 === 1) {
99651928f9aSGreg Roach            $value .= '/';
997a25f0a04SGreg Roach        }
998a25f0a04SGreg Roach
999a25f0a04SGreg Roach        // GEDCOM uses "//" to indicate an unknown surname
100051928f9aSGreg Roach        $full = preg_replace('/\/\//', '/@N.N./', $value);
1001a25f0a04SGreg Roach
1002a25f0a04SGreg Roach        // Extract the surname.
1003a25f0a04SGreg Roach        // Note, there may be multiple surnames, e.g. Jean /Vasquez/ y /Cortes/
1004a25f0a04SGreg Roach        if (preg_match('/\/.*\//', $full, $match)) {
1005a25f0a04SGreg Roach            $surname = str_replace('/', '', $match[0]);
1006a25f0a04SGreg Roach        } else {
1007a25f0a04SGreg Roach            $surname = '';
1008a25f0a04SGreg Roach        }
1009a25f0a04SGreg Roach
1010a25f0a04SGreg Roach        // If we don’t have a SURN record, extract it from the NAME
1011a25f0a04SGreg Roach        if (!$SURNS) {
1012a25f0a04SGreg Roach            if (preg_match_all('/\/([^\/]*)\//', $full, $matches)) {
1013a25f0a04SGreg Roach                // There can be many surnames, each wrapped with '/'
1014a25f0a04SGreg Roach                $SURNS = $matches[1];
1015a25f0a04SGreg Roach                foreach ($SURNS as $n => $SURN) {
1016a25f0a04SGreg Roach                    // Remove surname prefixes, such as "van de ", "d'" and "'t " (lower case only)
1017a25f0a04SGreg Roach                    $SURNS[$n] = preg_replace('/^(?:[a-z]+ |[a-z]+\' ?|\'[a-z]+ )+/', '', $SURN);
1018a25f0a04SGreg Roach                }
1019a25f0a04SGreg Roach            } else {
1020a25f0a04SGreg Roach                // It is valid not to have a surname at all
102113abd6f3SGreg Roach                $SURNS = [''];
1022a25f0a04SGreg Roach            }
1023a25f0a04SGreg Roach        }
1024a25f0a04SGreg Roach
1025a25f0a04SGreg Roach        // If we don’t have a GIVN record, extract it from the NAME
1026a25f0a04SGreg Roach        if (!$GIVN) {
1027c1010edaSGreg Roach            // remove surname
1028c72b7fa4SGreg Roach            $GIVN = preg_replace('/ ?\/.*\/ ?/', ' ', $full);
1029c1010edaSGreg Roach            // remove nickname
1030c72b7fa4SGreg Roach            $GIVN = preg_replace('/ ?".+"/', ' ', $GIVN);
1031c1010edaSGreg Roach            // multiple spaces, caused by the above
1032c72b7fa4SGreg Roach            $GIVN = preg_replace('/ {2,}/', ' ', $GIVN);
1033c1010edaSGreg Roach            // leading/trailing spaces, caused by the above
1034c72b7fa4SGreg Roach            $GIVN = preg_replace('/^ | $/', '', $GIVN);
1035a25f0a04SGreg Roach        }
1036a25f0a04SGreg Roach
1037a25f0a04SGreg Roach        // Add placeholder for unknown given name
1038a25f0a04SGreg Roach        if (!$GIVN) {
1039d823340dSGreg Roach            $GIVN = self::PRAENOMEN_NESCIO;
104073f4f553SGreg Roach            $pos  = (int) strpos($full, '/');
1041a25f0a04SGreg Roach            $full = substr($full, 0, $pos) . '@P.N. ' . substr($full, $pos);
1042a25f0a04SGreg Roach        }
1043a25f0a04SGreg Roach
1044a25f0a04SGreg Roach        // Remove slashes - they don’t get displayed
1045a25f0a04SGreg Roach        // $fullNN keeps the @N.N. placeholders, for the database
1046a25f0a04SGreg Roach        // $full is for display on-screen
1047a25f0a04SGreg Roach        $fullNN = str_replace('/', '', $full);
1048a25f0a04SGreg Roach
1049a25f0a04SGreg Roach        // Insert placeholders for any missing/unknown names
1050d823340dSGreg Roach        $full = str_replace(self::NOMEN_NESCIO, I18N::translateContext('Unknown surname', '…'), $full);
1051d823340dSGreg Roach        $full = str_replace(self::PRAENOMEN_NESCIO, I18N::translateContext('Unknown given name', '…'), $full);
1052c6f196c3SGreg Roach        // Format for display
1053d53324c9SGreg Roach        $full = '<span class="NAME" dir="auto" translate="no">' . preg_replace('/\/([^\/]*)\//', '<span class="SURN">$1</span>', e($full)) . '</span>';
1054acc34ea1SGreg Roach        // Localise quotation marks around the nickname
10550b5fd0a6SGreg Roach        $full = preg_replace_callback('/&quot;([^&]*)&quot;/', static function (array $matches): string {
1056c652cdbdSGreg Roach            return '<q class="wt-nickname">' . $matches[1] . '</q>';
10578d68cabeSGreg Roach        }, $full);
1058a25f0a04SGreg Roach
1059c6f196c3SGreg Roach        // A suffix of “*” indicates a preferred name
1060ee51991cSGreg Roach        $full = preg_replace('/([^ >\x{200C}]*)\*/u', '<span class="starredname">\\1</span>', $full);
1061a25f0a04SGreg Roach
1062a25f0a04SGreg Roach        // Remove prefered-name indicater - they don’t go in the database
1063a25f0a04SGreg Roach        $GIVN   = str_replace('*', '', $GIVN);
1064a25f0a04SGreg Roach        $fullNN = str_replace('*', '', $fullNN);
1065a25f0a04SGreg Roach
1066ffd703eaSGreg Roach        foreach ($SURNS as $SURN) {
1067a25f0a04SGreg Roach            // Scottish 'Mc and Mac ' prefixes both sort under 'Mac'
1068e364afe4SGreg Roach            if (strcasecmp(substr($SURN, 0, 2), 'Mc') === 0) {
1069a25f0a04SGreg Roach                $SURN = substr_replace($SURN, 'Mac', 0, 2);
1070e364afe4SGreg Roach            } elseif (strcasecmp(substr($SURN, 0, 4), 'Mac ') === 0) {
1071a25f0a04SGreg Roach                $SURN = substr_replace($SURN, 'Mac', 0, 4);
1072a25f0a04SGreg Roach            }
1073a25f0a04SGreg Roach
1074bdb3725aSGreg Roach            $this->getAllNames[] = [
1075a25f0a04SGreg Roach                'type'    => $type,
1076a25f0a04SGreg Roach                'sort'    => $SURN . ',' . $GIVN,
1077c1010edaSGreg Roach                'full'    => $full,
1078c1010edaSGreg Roach                // This is used for display
1079c1010edaSGreg Roach                'fullNN'  => $fullNN,
1080c1010edaSGreg Roach                // This goes into the database
1081c1010edaSGreg Roach                'surname' => $surname,
1082c1010edaSGreg Roach                // This goes into the database
1083c1010edaSGreg Roach                'givn'    => $GIVN,
1084c1010edaSGreg Roach                // This goes into the database
1085c1010edaSGreg Roach                'surn'    => $SURN,
1086c1010edaSGreg Roach                // This goes into the database
108713abd6f3SGreg Roach            ];
1088a25f0a04SGreg Roach        }
1089a25f0a04SGreg Roach    }
1090a25f0a04SGreg Roach
1091a25f0a04SGreg Roach    /**
109276692c8bSGreg Roach     * Extract names from the GEDCOM record.
1093c7ff4153SGreg Roach     *
1094c7ff4153SGreg Roach     * @return void
1095a25f0a04SGreg Roach     */
1096e364afe4SGreg Roach    public function extractNames(): void
1097c1010edaSGreg Roach    {
1098d9e083e7SGreg Roach        $access_level = $this->canShowName() ? Auth::PRIV_HIDE : Auth::accessLevel($this->tree);
1099d9e083e7SGreg Roach
11008f53f488SRico Sonntag        $this->extractNamesFromFacts(
11018f53f488SRico Sonntag            1,
11028f53f488SRico Sonntag            'NAME',
1103d9e083e7SGreg Roach            $this->facts(['NAME'], false, $access_level)
11048f53f488SRico Sonntag        );
1105a25f0a04SGreg Roach    }
1106a25f0a04SGreg Roach
1107a25f0a04SGreg Roach    /**
1108a25f0a04SGreg Roach     * Extra info to display when displaying this record in a list of
1109a25f0a04SGreg Roach     * selection items or favorites.
1110a25f0a04SGreg Roach     *
1111a25f0a04SGreg Roach     * @return string
1112a25f0a04SGreg Roach     */
11138f53f488SRico Sonntag    public function formatListDetails(): string
1114c1010edaSGreg Roach    {
1115a25f0a04SGreg Roach        return
11168d0ebef0SGreg Roach            $this->formatFirstMajorFact(Gedcom::BIRTH_EVENTS, 1) .
11178d0ebef0SGreg Roach            $this->formatFirstMajorFact(Gedcom::DEATH_EVENTS, 1);
1118a25f0a04SGreg Roach    }
11198091bfd1SGreg Roach
11208091bfd1SGreg Roach    /**
11218091bfd1SGreg Roach     * Lock the database row, to prevent concurrent edits.
11228091bfd1SGreg Roach     */
11238091bfd1SGreg Roach    public function lock(): void
11248091bfd1SGreg Roach    {
11258091bfd1SGreg Roach        DB::table('individuals')
11268091bfd1SGreg Roach            ->where('i_file', '=', $this->tree->id())
11278091bfd1SGreg Roach            ->where('i_id', '=', $this->xref())
11288091bfd1SGreg Roach            ->lockForUpdate()
11298091bfd1SGreg Roach            ->get();
11308091bfd1SGreg Roach    }
1131a25f0a04SGreg Roach}
1132