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