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