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