Issues (108)

app/Individual.php (1 issue)

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1051
                'sort'    => /** @scrutinizer ignore-type */ $SURN . ',' . $GIVN,
Loading history...
1052
                'full'    => $full,
1053
                // This is used for display
1054
                'fullNN'  => $fullNN,
1055
                // This goes into the database
1056
                'surname' => $surname,
1057
                // This goes into the database
1058
                'givn'    => $GIVN,
1059
                // This goes into the database
1060
                'surn'    => $SURN,
1061
                // This goes into the database
1062
            ];
1063
        }
1064
    }
1065
1066
    /**
1067
     * Extract names from the GEDCOM record.
1068
     *
1069
     * @return void
1070
     */
1071
    public function extractNames(): void
1072
    {
1073
        $access_level = $this->canShowName() ? Auth::PRIV_HIDE : Auth::accessLevel($this->tree);
1074
1075
        $this->extractNamesFromFacts(
1076
            1,
1077
            'NAME',
1078
            $this->facts(['NAME'], false, $access_level)
1079
        );
1080
    }
1081
1082
    /**
1083
     * Extra info to display when displaying this record in a list of
1084
     * selection items or favorites.
1085
     *
1086
     * @return string
1087
     */
1088
    public function formatListDetails(): string
1089
    {
1090
        return
1091
            $this->formatFirstMajorFact(Gedcom::BIRTH_EVENTS, 1) .
1092
            $this->formatFirstMajorFact(Gedcom::DEATH_EVENTS, 1);
1093
    }
1094
1095
    /**
1096
     * Lock the database row, to prevent concurrent edits.
1097
     */
1098
    public function lock(): void
1099
    {
1100
        DB::table('individuals')
1101
            ->where('i_file', '=', $this->tree->id())
1102
            ->where('i_id', '=', $this->xref())
1103
            ->lockForUpdate()
1104
            ->get();
1105
    }
1106
}
1107