1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2019 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 Exception; 24use Fisharebest\Webtrees\Functions\FunctionsPrint; 25use Fisharebest\Webtrees\Http\RequestHandlers\GedcomRecordPage; 26use Fisharebest\Webtrees\Services\PendingChangesService; 27use Illuminate\Database\Capsule\Manager as DB; 28use Illuminate\Database\Query\Builder; 29use Illuminate\Database\Query\Expression; 30use Illuminate\Database\Query\JoinClause; 31use Illuminate\Support\Collection; 32use stdClass; 33 34use function app; 35 36/** 37 * A GEDCOM object. 38 */ 39class GedcomRecord 40{ 41 public const RECORD_TYPE = 'UNKNOWN'; 42 43 protected const ROUTE_NAME = GedcomRecordPage::class; 44 45 /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */ 46 public static $gedcom_record_cache; 47 /** @var stdClass[][] Fetch all pending edits in one database query */ 48 public static $pending_record_cache; 49 /** @var string The record identifier */ 50 protected $xref; 51 /** @var Tree The family tree to which this record belongs */ 52 protected $tree; 53 /** @var string GEDCOM data (before any pending edits) */ 54 protected $gedcom; 55 /** @var string|null GEDCOM data (after any pending edits) */ 56 protected $pending; 57 /** @var Fact[] facts extracted from $gedcom/$pending */ 58 protected $facts; 59 /** @var string[][] All the names of this individual */ 60 protected $getAllNames; 61 /** @var int|null Cached result */ 62 protected $getPrimaryName; 63 /** @var int|null Cached result */ 64 protected $getSecondaryName; 65 66 /** 67 * Create a GedcomRecord object from raw GEDCOM data. 68 * 69 * @param string $xref 70 * @param string $gedcom an empty string for new/pending records 71 * @param string|null $pending null for a record with no pending edits, 72 * empty string for records with pending deletions 73 * @param Tree $tree 74 */ 75 public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree) 76 { 77 $this->xref = $xref; 78 $this->gedcom = $gedcom; 79 $this->pending = $pending; 80 $this->tree = $tree; 81 82 $this->parseFacts(); 83 } 84 85 /** 86 * A closure which will create a record from a database row. 87 * 88 * @param Tree $tree 89 * 90 * @return Closure 91 */ 92 public static function rowMapper(Tree $tree): Closure 93 { 94 return static function (stdClass $row) use ($tree): GedcomRecord { 95 return GedcomRecord::getInstance($row->o_id, $tree, $row->o_gedcom); 96 }; 97 } 98 99 /** 100 * A closure which will filter out private records. 101 * 102 * @return Closure 103 */ 104 public static function accessFilter(): Closure 105 { 106 return static function (GedcomRecord $record): bool { 107 return $record->canShow(); 108 }; 109 } 110 111 /** 112 * A closure which will compare records by name. 113 * 114 * @return Closure 115 */ 116 public static function nameComparator(): Closure 117 { 118 return static function (GedcomRecord $x, GedcomRecord $y): int { 119 if ($x->canShowName()) { 120 if ($y->canShowName()) { 121 return I18N::strcasecmp($x->sortName(), $y->sortName()); 122 } 123 124 return -1; // only $y is private 125 } 126 127 if ($y->canShowName()) { 128 return 1; // only $x is private 129 } 130 131 return 0; // both $x and $y private 132 }; 133 } 134 135 /** 136 * A closure which will compare records by change time. 137 * 138 * @param int $direction +1 to sort ascending, -1 to sort descending 139 * 140 * @return Closure 141 */ 142 public static function lastChangeComparator(int $direction = 1): Closure 143 { 144 return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int { 145 return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp()); 146 }; 147 } 148 149 /** 150 * Get an instance of a GedcomRecord object. For single records, 151 * we just receive the XREF. For bulk records (such as lists 152 * and search results) we can receive the GEDCOM data as well. 153 * 154 * @param string $xref 155 * @param Tree $tree 156 * @param string|null $gedcom 157 * 158 * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|null 159 * @throws Exception 160 */ 161 public static function getInstance(string $xref, Tree $tree, string $gedcom = null) 162 { 163 $tree_id = $tree->id(); 164 165 // Is this record already in the cache? 166 if (isset(self::$gedcom_record_cache[$xref][$tree_id])) { 167 return self::$gedcom_record_cache[$xref][$tree_id]; 168 } 169 170 // Do we need to fetch the record from the database? 171 if ($gedcom === null) { 172 $gedcom = static::fetchGedcomRecord($xref, $tree_id); 173 } 174 175 // If we can edit, then we also need to be able to see pending records. 176 if (Auth::isEditor($tree)) { 177 if (!isset(self::$pending_record_cache[$tree_id])) { 178 // Fetch all pending records in one database query 179 self::$pending_record_cache[$tree_id] = []; 180 $rows = DB::table('change') 181 ->where('gedcom_id', '=', $tree_id) 182 ->where('status', '=', 'pending') 183 ->orderBy('change_id') 184 ->select(['xref', 'new_gedcom']) 185 ->get(); 186 187 foreach ($rows as $row) { 188 self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom; 189 } 190 } 191 192 $pending = self::$pending_record_cache[$tree_id][$xref] ?? null; 193 } else { 194 // There are no pending changes for this record 195 $pending = null; 196 } 197 198 // No such record exists 199 if ($gedcom === null && $pending === null) { 200 return null; 201 } 202 203 // No such record, but a pending creation exists 204 if ($gedcom === null) { 205 $gedcom = ''; 206 } 207 208 // Create the object 209 if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedcom . $pending, $match)) { 210 $xref = $match[1]; // Collation - we may have requested I123 and found i123 211 $type = $match[2]; 212 } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) { 213 $xref = $match[1]; 214 $type = $match[1]; 215 } elseif ($gedcom . $pending) { 216 throw new Exception('Unrecognized GEDCOM record: ' . $gedcom); 217 } else { 218 // A record with both pending creation and pending deletion 219 $type = static::RECORD_TYPE; 220 } 221 222 switch ($type) { 223 case 'INDI': 224 $record = new Individual($xref, $gedcom, $pending, $tree); 225 break; 226 case 'FAM': 227 $record = new Family($xref, $gedcom, $pending, $tree); 228 break; 229 case 'SOUR': 230 $record = new Source($xref, $gedcom, $pending, $tree); 231 break; 232 case 'OBJE': 233 $record = new Media($xref, $gedcom, $pending, $tree); 234 break; 235 case 'REPO': 236 $record = new Repository($xref, $gedcom, $pending, $tree); 237 break; 238 case 'NOTE': 239 $record = new Note($xref, $gedcom, $pending, $tree); 240 break; 241 default: 242 $record = new self($xref, $gedcom, $pending, $tree); 243 break; 244 } 245 246 // Store it in the cache 247 self::$gedcom_record_cache[$xref][$tree_id] = $record; 248 249 return $record; 250 } 251 252 /** 253 * Fetch data from the database 254 * 255 * @param string $xref 256 * @param int $tree_id 257 * 258 * @return string|null 259 */ 260 protected static function fetchGedcomRecord(string $xref, int $tree_id): ?string 261 { 262 // We don't know what type of object this is. Try each one in turn. 263 $data = Individual::fetchGedcomRecord($xref, $tree_id); 264 if ($data !== null) { 265 return $data; 266 } 267 $data = Family::fetchGedcomRecord($xref, $tree_id); 268 if ($data !== null) { 269 return $data; 270 } 271 $data = Source::fetchGedcomRecord($xref, $tree_id); 272 if ($data !== null) { 273 return $data; 274 } 275 $data = Repository::fetchGedcomRecord($xref, $tree_id); 276 if ($data !== null) { 277 return $data; 278 } 279 $data = Media::fetchGedcomRecord($xref, $tree_id); 280 if ($data !== null) { 281 return $data; 282 } 283 $data = Note::fetchGedcomRecord($xref, $tree_id); 284 if ($data !== null) { 285 return $data; 286 } 287 288 // Some other type of record... 289 return DB::table('other') 290 ->where('o_file', '=', $tree_id) 291 ->where('o_id', '=', $xref) 292 ->value('o_gedcom'); 293 } 294 295 /** 296 * Get the XREF for this record 297 * 298 * @return string 299 */ 300 public function xref(): string 301 { 302 return $this->xref; 303 } 304 305 /** 306 * Get the tree to which this record belongs 307 * 308 * @return Tree 309 */ 310 public function tree(): Tree 311 { 312 return $this->tree; 313 } 314 315 /** 316 * Application code should access data via Fact objects. 317 * This function exists to support old code. 318 * 319 * @return string 320 */ 321 public function gedcom(): string 322 { 323 return $this->pending ?? $this->gedcom; 324 } 325 326 /** 327 * Does this record have a pending change? 328 * 329 * @return bool 330 */ 331 public function isPendingAddition(): bool 332 { 333 return $this->pending !== null; 334 } 335 336 /** 337 * Does this record have a pending deletion? 338 * 339 * @return bool 340 */ 341 public function isPendingDeletion(): bool 342 { 343 return $this->pending === ''; 344 } 345 346 /** 347 * Generate a "slug" to use in pretty URLs. 348 * 349 * @return string 350 */ 351 public function slug(): string 352 { 353 return strip_tags($this->fullName()); 354 } 355 356 /** 357 * Generate a URL to this record. 358 * 359 * @return string 360 */ 361 public function url(): string 362 { 363 return route(static::ROUTE_NAME, [ 364 'xref' => $this->xref(), 365 'tree' => $this->tree->name(), 366 'slug' => $this->slug(), 367 ]); 368 } 369 370 /** 371 * Can the details of this record be shown? 372 * 373 * @param int|null $access_level 374 * 375 * @return bool 376 */ 377 public function canShow(int $access_level = null): bool 378 { 379 $access_level = $access_level ?? Auth::accessLevel($this->tree); 380 381 // We use this value to bypass privacy checks. For example, 382 // when downloading data or when calculating privacy itself. 383 if ($access_level === Auth::PRIV_HIDE) { 384 return true; 385 } 386 387 $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level; 388 389 return app('cache.array')->remember($cache_key, function () use ($access_level) { 390 return $this->canShowRecord($access_level); 391 }); 392 } 393 394 /** 395 * Can the name of this record be shown? 396 * 397 * @param int|null $access_level 398 * 399 * @return bool 400 */ 401 public function canShowName(int $access_level = null): bool 402 { 403 return $this->canShow($access_level); 404 } 405 406 /** 407 * Can we edit this record? 408 * 409 * @return bool 410 */ 411 public function canEdit(): bool 412 { 413 if ($this->isPendingDeletion()) { 414 return false; 415 } 416 417 if (Auth::isManager($this->tree)) { 418 return true; 419 } 420 421 return Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false; 422 } 423 424 /** 425 * Remove private data from the raw gedcom record. 426 * Return both the visible and invisible data. We need the invisible data when editing. 427 * 428 * @param int $access_level 429 * 430 * @return string 431 */ 432 public function privatizeGedcom(int $access_level): string 433 { 434 if ($access_level === Auth::PRIV_HIDE) { 435 // We may need the original record, for example when downloading a GEDCOM or clippings cart 436 return $this->gedcom; 437 } 438 439 if ($this->canShow($access_level)) { 440 // The record is not private, but the individual facts may be. 441 442 // Include the entire first line (for NOTE records) 443 [$gedrec] = explode("\n", $this->gedcom, 2); 444 445 // Check each of the facts for access 446 foreach ($this->facts([], false, $access_level) as $fact) { 447 $gedrec .= "\n" . $fact->gedcom(); 448 } 449 450 return $gedrec; 451 } 452 453 // We cannot display the details, but we may be able to display 454 // limited data, such as links to other records. 455 return $this->createPrivateGedcomRecord($access_level); 456 } 457 458 /** 459 * Default for "other" object types 460 * 461 * @return void 462 */ 463 public function extractNames(): void 464 { 465 $this->addName(static::RECORD_TYPE, $this->getFallBackName(), ''); 466 } 467 468 /** 469 * Derived classes should redefine this function, otherwise the object will have no name 470 * 471 * @return string[][] 472 */ 473 public function getAllNames(): array 474 { 475 if ($this->getAllNames === null) { 476 $this->getAllNames = []; 477 if ($this->canShowName()) { 478 // Ask the record to extract its names 479 $this->extractNames(); 480 // No name found? Use a fallback. 481 if (!$this->getAllNames) { 482 $this->addName(static::RECORD_TYPE, $this->getFallBackName(), ''); 483 } 484 } else { 485 $this->addName(static::RECORD_TYPE, I18N::translate('Private'), ''); 486 } 487 } 488 489 return $this->getAllNames; 490 } 491 492 /** 493 * If this object has no name, what do we call it? 494 * 495 * @return string 496 */ 497 public function getFallBackName(): string 498 { 499 return e($this->xref()); 500 } 501 502 /** 503 * Which of the (possibly several) names of this record is the primary one. 504 * 505 * @return int 506 */ 507 public function getPrimaryName(): int 508 { 509 static $language_script; 510 511 if ($language_script === null) { 512 $language_script = $language_script ?? I18N::locale()->script()->code(); 513 } 514 515 if ($this->getPrimaryName === null) { 516 // Generally, the first name is the primary one.... 517 $this->getPrimaryName = 0; 518 // ...except when the language/name use different character sets 519 foreach ($this->getAllNames() as $n => $name) { 520 if (I18N::textScript($name['sort']) === $language_script) { 521 $this->getPrimaryName = $n; 522 break; 523 } 524 } 525 } 526 527 return $this->getPrimaryName; 528 } 529 530 /** 531 * Which of the (possibly several) names of this record is the secondary one. 532 * 533 * @return int 534 */ 535 public function getSecondaryName(): int 536 { 537 if ($this->getSecondaryName === null) { 538 // Generally, the primary and secondary names are the same 539 $this->getSecondaryName = $this->getPrimaryName(); 540 // ....except when there are names with different character sets 541 $all_names = $this->getAllNames(); 542 if (count($all_names) > 1) { 543 $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']); 544 foreach ($all_names as $n => $name) { 545 if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) { 546 $this->getSecondaryName = $n; 547 break; 548 } 549 } 550 } 551 } 552 553 return $this->getSecondaryName; 554 } 555 556 /** 557 * Allow the choice of primary name to be overidden, e.g. in a search result 558 * 559 * @param int|null $n 560 * 561 * @return void 562 */ 563 public function setPrimaryName(int $n = null): void 564 { 565 $this->getPrimaryName = $n; 566 $this->getSecondaryName = null; 567 } 568 569 /** 570 * Allow native PHP functions such as array_unique() to work with objects 571 * 572 * @return string 573 */ 574 public function __toString() 575 { 576 return $this->xref . '@' . $this->tree->id(); 577 } 578 579 /** 580 * /** 581 * Get variants of the name 582 * 583 * @return string 584 */ 585 public function fullName(): string 586 { 587 if ($this->canShowName()) { 588 $tmp = $this->getAllNames(); 589 590 return $tmp[$this->getPrimaryName()]['full']; 591 } 592 593 return I18N::translate('Private'); 594 } 595 596 /** 597 * Get a sortable version of the name. Do not display this! 598 * 599 * @return string 600 */ 601 public function sortName(): string 602 { 603 // The sortable name is never displayed, no need to call canShowName() 604 $tmp = $this->getAllNames(); 605 606 return $tmp[$this->getPrimaryName()]['sort']; 607 } 608 609 /** 610 * Get the full name in an alternative character set 611 * 612 * @return string|null 613 */ 614 public function alternateName(): ?string 615 { 616 if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) { 617 $all_names = $this->getAllNames(); 618 619 return $all_names[$this->getSecondaryName()]['full']; 620 } 621 622 return null; 623 } 624 625 /** 626 * Format this object for display in a list 627 * 628 * @return string 629 */ 630 public function formatList(): string 631 { 632 $html = '<a href="' . e($this->url()) . '" class="list_item">'; 633 $html .= '<b>' . $this->fullName() . '</b>'; 634 $html .= $this->formatListDetails(); 635 $html .= '</a>'; 636 637 return $html; 638 } 639 640 /** 641 * This function should be redefined in derived classes to show any major 642 * identifying characteristics of this record. 643 * 644 * @return string 645 */ 646 public function formatListDetails(): string 647 { 648 return ''; 649 } 650 651 /** 652 * Extract/format the first fact from a list of facts. 653 * 654 * @param string[] $facts 655 * @param int $style 656 * 657 * @return string 658 */ 659 public function formatFirstMajorFact(array $facts, int $style): string 660 { 661 foreach ($this->facts($facts, true) as $event) { 662 // Only display if it has a date or place (or both) 663 if ($event->date()->isOK() && $event->place()->gedcomName() !== '') { 664 $joiner = ' — '; 665 } else { 666 $joiner = ''; 667 } 668 if ($event->date()->isOK() || $event->place()->gedcomName() !== '') { 669 switch ($style) { 670 case 1: 671 return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>'; 672 case 2: 673 return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>'; 674 } 675 } 676 } 677 678 return ''; 679 } 680 681 /** 682 * Find individuals linked to this record. 683 * 684 * @param string $link 685 * 686 * @return Collection 687 */ 688 public function linkedIndividuals(string $link): Collection 689 { 690 return DB::table('individuals') 691 ->join('link', static function (JoinClause $join): void { 692 $join 693 ->on('l_file', '=', 'i_file') 694 ->on('l_from', '=', 'i_id'); 695 }) 696 ->where('i_file', '=', $this->tree->id()) 697 ->where('l_type', '=', $link) 698 ->where('l_to', '=', $this->xref) 699 ->select(['individuals.*']) 700 ->get() 701 ->map(Individual::rowMapper($this->tree)) 702 ->filter(self::accessFilter()); 703 } 704 705 /** 706 * Find families linked to this record. 707 * 708 * @param string $link 709 * 710 * @return Collection 711 */ 712 public function linkedFamilies(string $link): Collection 713 { 714 return DB::table('families') 715 ->join('link', static function (JoinClause $join): void { 716 $join 717 ->on('l_file', '=', 'f_file') 718 ->on('l_from', '=', 'f_id'); 719 }) 720 ->where('f_file', '=', $this->tree->id()) 721 ->where('l_type', '=', $link) 722 ->where('l_to', '=', $this->xref) 723 ->select(['families.*']) 724 ->get() 725 ->map(Family::rowMapper($this->tree)) 726 ->filter(self::accessFilter()); 727 } 728 729 /** 730 * Find sources linked to this record. 731 * 732 * @param string $link 733 * 734 * @return Collection 735 */ 736 public function linkedSources(string $link): Collection 737 { 738 return DB::table('sources') 739 ->join('link', static function (JoinClause $join): void { 740 $join 741 ->on('l_file', '=', 's_file') 742 ->on('l_from', '=', 's_id'); 743 }) 744 ->where('s_file', '=', $this->tree->id()) 745 ->where('l_type', '=', $link) 746 ->where('l_to', '=', $this->xref) 747 ->select(['sources.*']) 748 ->get() 749 ->map(Source::rowMapper($this->tree)) 750 ->filter(self::accessFilter()); 751 } 752 753 /** 754 * Find media objects linked to this record. 755 * 756 * @param string $link 757 * 758 * @return Collection 759 */ 760 public function linkedMedia(string $link): Collection 761 { 762 return DB::table('media') 763 ->join('link', static function (JoinClause $join): void { 764 $join 765 ->on('l_file', '=', 'm_file') 766 ->on('l_from', '=', 'm_id'); 767 }) 768 ->where('m_file', '=', $this->tree->id()) 769 ->where('l_type', '=', $link) 770 ->where('l_to', '=', $this->xref) 771 ->select(['media.*']) 772 ->get() 773 ->map(Media::rowMapper($this->tree)) 774 ->filter(self::accessFilter()); 775 } 776 777 /** 778 * Find notes linked to this record. 779 * 780 * @param string $link 781 * 782 * @return Collection 783 */ 784 public function linkedNotes(string $link): Collection 785 { 786 return DB::table('other') 787 ->join('link', static function (JoinClause $join): void { 788 $join 789 ->on('l_file', '=', 'o_file') 790 ->on('l_from', '=', 'o_id'); 791 }) 792 ->where('o_file', '=', $this->tree->id()) 793 ->where('o_type', '=', 'NOTE') 794 ->where('l_type', '=', $link) 795 ->where('l_to', '=', $this->xref) 796 ->select(['other.*']) 797 ->get() 798 ->map(Note::rowMapper($this->tree)) 799 ->filter(self::accessFilter()); 800 } 801 802 /** 803 * Find repositories linked to this record. 804 * 805 * @param string $link 806 * 807 * @return Collection 808 */ 809 public function linkedRepositories(string $link): Collection 810 { 811 return DB::table('other') 812 ->join('link', static function (JoinClause $join): void { 813 $join 814 ->on('l_file', '=', 'o_file') 815 ->on('l_from', '=', 'o_id'); 816 }) 817 ->where('o_file', '=', $this->tree->id()) 818 ->where('o_type', '=', 'REPO') 819 ->where('l_type', '=', $link) 820 ->where('l_to', '=', $this->xref) 821 ->select(['other.*']) 822 ->get() 823 ->map(Repository::rowMapper($this->tree)) 824 ->filter(self::accessFilter()); 825 } 826 827 /** 828 * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR). 829 * This is used to display multiple events on the individual/family lists. 830 * Multiple events can exist because of uncertainty in dates, dates in different 831 * calendars, place-names in both latin and hebrew character sets, etc. 832 * It also allows us to combine dates/places from different events in the summaries. 833 * 834 * @param string[] $events 835 * 836 * @return Date[] 837 */ 838 public function getAllEventDates(array $events): array 839 { 840 $dates = []; 841 foreach ($this->facts($events) as $event) { 842 if ($event->date()->isOK()) { 843 $dates[] = $event->date(); 844 } 845 } 846 847 return $dates; 848 } 849 850 /** 851 * Get all the places for a particular type of event 852 * 853 * @param string[] $events 854 * 855 * @return Place[] 856 */ 857 public function getAllEventPlaces(array $events): array 858 { 859 $places = []; 860 foreach ($this->facts($events) as $event) { 861 if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) { 862 foreach ($ged_places[1] as $ged_place) { 863 $places[] = new Place($ged_place, $this->tree); 864 } 865 } 866 } 867 868 return $places; 869 } 870 871 /** 872 * The facts and events for this record. 873 * 874 * @param string[] $filter 875 * @param bool $sort 876 * @param int|null $access_level 877 * @param bool $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES. 878 * 879 * @return Collection 880 */ 881 public function facts(array $filter = [], bool $sort = false, int $access_level = null, bool $override = false): Collection 882 { 883 $access_level = $access_level ?? Auth::accessLevel($this->tree); 884 885 $facts = new Collection(); 886 if ($this->canShow($access_level) || $override) { 887 foreach ($this->facts as $fact) { 888 if (($filter === [] || in_array($fact->getTag(), $filter, true)) && $fact->canShow($access_level)) { 889 $facts->push($fact); 890 } 891 } 892 } 893 894 if ($sort) { 895 $facts = Fact::sortFacts($facts); 896 } 897 898 return new Collection($facts); 899 } 900 901 /** 902 * Get the last-change timestamp for this record 903 * 904 * @return Carbon 905 */ 906 public function lastChangeTimestamp(): Carbon 907 { 908 /** @var Fact|null $chan */ 909 $chan = $this->facts(['CHAN'])->first(); 910 911 if ($chan instanceof Fact) { 912 // The record does have a CHAN event 913 $d = $chan->date()->minimumDate(); 914 915 if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) { 916 return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]); 917 } 918 919 if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) { 920 return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]); 921 } 922 923 return Carbon::create($d->year(), $d->month(), $d->day()); 924 } 925 926 // The record does not have a CHAN event 927 return Carbon::createFromTimestamp(0); 928 } 929 930 /** 931 * Get the last-change user for this record 932 * 933 * @return string 934 */ 935 public function lastChangeUser(): string 936 { 937 $chan = $this->facts(['CHAN'])->first(); 938 939 if ($chan === null) { 940 return I18N::translate('Unknown'); 941 } 942 943 $chan_user = $chan->attribute('_WT_USER'); 944 if ($chan_user === '') { 945 return I18N::translate('Unknown'); 946 } 947 948 return $chan_user; 949 } 950 951 /** 952 * Add a new fact to this record 953 * 954 * @param string $gedcom 955 * @param bool $update_chan 956 * 957 * @return void 958 */ 959 public function createFact(string $gedcom, bool $update_chan): void 960 { 961 $this->updateFact('', $gedcom, $update_chan); 962 } 963 964 /** 965 * Delete a fact from this record 966 * 967 * @param string $fact_id 968 * @param bool $update_chan 969 * 970 * @return void 971 */ 972 public function deleteFact(string $fact_id, bool $update_chan): void 973 { 974 $this->updateFact($fact_id, '', $update_chan); 975 } 976 977 /** 978 * Replace a fact with a new gedcom data. 979 * 980 * @param string $fact_id 981 * @param string $gedcom 982 * @param bool $update_chan 983 * 984 * @return void 985 * @throws Exception 986 */ 987 public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void 988 { 989 // MSDOS line endings will break things in horrible ways 990 $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom); 991 $gedcom = trim($gedcom); 992 993 if ($this->pending === '') { 994 throw new Exception('Cannot edit a deleted record'); 995 } 996 if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) { 997 throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')'); 998 } 999 1000 if ($this->pending) { 1001 $old_gedcom = $this->pending; 1002 } else { 1003 $old_gedcom = $this->gedcom; 1004 } 1005 1006 // First line of record may contain data - e.g. NOTE records. 1007 [$new_gedcom] = explode("\n", $old_gedcom, 2); 1008 1009 // Replacing (or deleting) an existing fact 1010 foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) { 1011 if (!$fact->isPendingDeletion()) { 1012 if ($fact->id() === $fact_id) { 1013 if ($gedcom !== '') { 1014 $new_gedcom .= "\n" . $gedcom; 1015 } 1016 $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact 1017 } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) { 1018 $new_gedcom .= "\n" . $fact->gedcom(); 1019 } 1020 } 1021 } 1022 if ($update_chan) { 1023 $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName(); 1024 } 1025 1026 // Adding a new fact 1027 if ($fact_id === '') { 1028 $new_gedcom .= "\n" . $gedcom; 1029 } 1030 1031 if ($new_gedcom !== $old_gedcom) { 1032 // Save the changes 1033 DB::table('change')->insert([ 1034 'gedcom_id' => $this->tree->id(), 1035 'xref' => $this->xref, 1036 'old_gedcom' => $old_gedcom, 1037 'new_gedcom' => $new_gedcom, 1038 'user_id' => Auth::id(), 1039 ]); 1040 1041 $this->pending = $new_gedcom; 1042 1043 if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') { 1044 app(PendingChangesService::class)->acceptRecord($this); 1045 $this->gedcom = $new_gedcom; 1046 $this->pending = null; 1047 } 1048 } 1049 $this->parseFacts(); 1050 } 1051 1052 /** 1053 * Update this record 1054 * 1055 * @param string $gedcom 1056 * @param bool $update_chan 1057 * 1058 * @return void 1059 */ 1060 public function updateRecord(string $gedcom, bool $update_chan): void 1061 { 1062 // MSDOS line endings will break things in horrible ways 1063 $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom); 1064 $gedcom = trim($gedcom); 1065 1066 // Update the CHAN record 1067 if ($update_chan) { 1068 $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom); 1069 $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName(); 1070 } 1071 1072 // Create a pending change 1073 DB::table('change')->insert([ 1074 'gedcom_id' => $this->tree->id(), 1075 'xref' => $this->xref, 1076 'old_gedcom' => $this->gedcom(), 1077 'new_gedcom' => $gedcom, 1078 'user_id' => Auth::id(), 1079 ]); 1080 1081 // Clear the cache 1082 $this->pending = $gedcom; 1083 1084 // Accept this pending change 1085 if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') { 1086 app(PendingChangesService::class)->acceptRecord($this); 1087 $this->gedcom = $gedcom; 1088 $this->pending = null; 1089 } 1090 1091 $this->parseFacts(); 1092 1093 Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree); 1094 } 1095 1096 /** 1097 * Delete this record 1098 * 1099 * @return void 1100 */ 1101 public function deleteRecord(): void 1102 { 1103 // Create a pending change 1104 if (!$this->isPendingDeletion()) { 1105 DB::table('change')->insert([ 1106 'gedcom_id' => $this->tree->id(), 1107 'xref' => $this->xref, 1108 'old_gedcom' => $this->gedcom(), 1109 'new_gedcom' => '', 1110 'user_id' => Auth::id(), 1111 ]); 1112 } 1113 1114 // Auto-accept this pending change 1115 if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') { 1116 app(PendingChangesService::class)->acceptRecord($this); 1117 } 1118 1119 // Clear the cache 1120 self::$gedcom_record_cache = []; 1121 self::$pending_record_cache = []; 1122 1123 Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree); 1124 } 1125 1126 /** 1127 * Remove all links from this record to $xref 1128 * 1129 * @param string $xref 1130 * @param bool $update_chan 1131 * 1132 * @return void 1133 */ 1134 public function removeLinks(string $xref, bool $update_chan): void 1135 { 1136 $value = '@' . $xref . '@'; 1137 1138 foreach ($this->facts() as $fact) { 1139 if ($fact->value() === $value) { 1140 $this->deleteFact($fact->id(), $update_chan); 1141 } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) { 1142 $gedcom = $fact->gedcom(); 1143 foreach ($matches as $match) { 1144 $next_level = $match[1] + 1; 1145 $next_levels = '[' . $next_level . '-9]'; 1146 $gedcom = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom); 1147 } 1148 $this->updateFact($fact->id(), $gedcom, $update_chan); 1149 } 1150 } 1151 } 1152 1153 /** 1154 * Fetch XREFs of all records linked to a record - when deleting an object, we must 1155 * also delete all links to it. 1156 * 1157 * @return GedcomRecord[] 1158 */ 1159 public function linkingRecords(): array 1160 { 1161 $union = DB::table('change') 1162 ->where('gedcom_id', '=', $this->tree()->id()) 1163 ->whereContains('new_gedcom', '@' . $this->xref() . '@') 1164 ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%') 1165 ->whereIn('change_id', function (Builder $query): void { 1166 $query->select(new Expression('MAX(change_id)')) 1167 ->from('change') 1168 ->where('gedcom_id', '=', $this->tree->id()) 1169 ->where('status', '=', 'pending') 1170 ->groupBy(['xref']); 1171 }) 1172 ->select(['xref']); 1173 1174 $xrefs = DB::table('link') 1175 ->where('l_file', '=', $this->tree()->id()) 1176 ->where('l_to', '=', $this->xref()) 1177 ->select(['l_from']) 1178 ->union($union) 1179 ->pluck('l_from'); 1180 1181 return $xrefs->map(function (string $xref): GedcomRecord { 1182 return GedcomRecord::getInstance($xref, $this->tree); 1183 })->all(); 1184 } 1185 1186 /** 1187 * Each object type may have its own special rules, and re-implement this function. 1188 * 1189 * @param int $access_level 1190 * 1191 * @return bool 1192 */ 1193 protected function canShowByType(int $access_level): bool 1194 { 1195 $fact_privacy = $this->tree->getFactPrivacy(); 1196 1197 if (isset($fact_privacy[static::RECORD_TYPE])) { 1198 // Restriction found 1199 return $fact_privacy[static::RECORD_TYPE] >= $access_level; 1200 } 1201 1202 // No restriction found - must be public: 1203 return true; 1204 } 1205 1206 /** 1207 * Generate a private version of this record 1208 * 1209 * @param int $access_level 1210 * 1211 * @return string 1212 */ 1213 protected function createPrivateGedcomRecord(int $access_level): string 1214 { 1215 return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private'); 1216 } 1217 1218 /** 1219 * Convert a name record into sortable and full/display versions. This default 1220 * should be OK for simple record types. INDI/FAM records will need to redefine it. 1221 * 1222 * @param string $type 1223 * @param string $value 1224 * @param string $gedcom 1225 * 1226 * @return void 1227 */ 1228 protected function addName(string $type, string $value, string $gedcom): void 1229 { 1230 $this->getAllNames[] = [ 1231 'type' => $type, 1232 'sort' => preg_replace_callback('/([0-9]+)/', static function (array $matches): string { 1233 return str_pad($matches[0], 10, '0', STR_PAD_LEFT); 1234 }, $value), 1235 'full' => '<span dir="auto">' . e($value) . '</span>', 1236 // This is used for display 1237 'fullNN' => $value, 1238 // This goes into the database 1239 ]; 1240 } 1241 1242 /** 1243 * Get all the names of a record, including ROMN, FONE and _HEB alternatives. 1244 * Records without a name (e.g. FAM) will need to redefine this function. 1245 * Parameters: the level 1 fact containing the name. 1246 * Return value: an array of name structures, each containing 1247 * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc. 1248 * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown' 1249 * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John' 1250 * 1251 * @param int $level 1252 * @param string $fact_type 1253 * @param Collection $facts 1254 * 1255 * @return void 1256 */ 1257 protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void 1258 { 1259 $sublevel = $level + 1; 1260 $subsublevel = $sublevel + 1; 1261 foreach ($facts as $fact) { 1262 if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) { 1263 foreach ($matches as $match) { 1264 // Treat 1 NAME / 2 TYPE married the same as _MARNM 1265 if ($match[1] === 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) { 1266 $this->addName('_MARNM', $match[2], $fact->gedcom()); 1267 } else { 1268 $this->addName($match[1], $match[2], $fact->gedcom()); 1269 } 1270 if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) { 1271 foreach ($submatches as $submatch) { 1272 $this->addName($submatch[1], $submatch[2], $match[3]); 1273 } 1274 } 1275 } 1276 } 1277 } 1278 } 1279 1280 /** 1281 * Split the record into facts 1282 * 1283 * @return void 1284 */ 1285 private function parseFacts(): void 1286 { 1287 // Split the record into facts 1288 if ($this->gedcom) { 1289 $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom); 1290 array_shift($gedcom_facts); 1291 } else { 1292 $gedcom_facts = []; 1293 } 1294 if ($this->pending) { 1295 $pending_facts = preg_split('/\n(?=1)/s', $this->pending); 1296 array_shift($pending_facts); 1297 } else { 1298 $pending_facts = []; 1299 } 1300 1301 $this->facts = []; 1302 1303 foreach ($gedcom_facts as $gedcom_fact) { 1304 $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact)); 1305 if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) { 1306 $fact->setPendingDeletion(); 1307 } 1308 $this->facts[] = $fact; 1309 } 1310 foreach ($pending_facts as $pending_fact) { 1311 if (!in_array($pending_fact, $gedcom_facts, true)) { 1312 $fact = new Fact($pending_fact, $this, md5($pending_fact)); 1313 $fact->setPendingAddition(); 1314 $this->facts[] = $fact; 1315 } 1316 } 1317 } 1318 1319 /** 1320 * Work out whether this record can be shown to a user with a given access level 1321 * 1322 * @param int $access_level 1323 * 1324 * @return bool 1325 */ 1326 private function canShowRecord(int $access_level): bool 1327 { 1328 // This setting would better be called "$ENABLE_PRIVACY" 1329 if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) { 1330 return true; 1331 } 1332 1333 // We should always be able to see our own record (unless an admin is applying download restrictions) 1334 if ($this->xref() === $this->tree->getUserPreference(Auth::user(), User::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) { 1335 return true; 1336 } 1337 1338 // Does this record have a RESN? 1339 if (strpos($this->gedcom, "\n1 RESN confidential") !== false) { 1340 return Auth::PRIV_NONE >= $access_level; 1341 } 1342 if (strpos($this->gedcom, "\n1 RESN privacy") !== false) { 1343 return Auth::PRIV_USER >= $access_level; 1344 } 1345 if (strpos($this->gedcom, "\n1 RESN none") !== false) { 1346 return true; 1347 } 1348 1349 // Does this record have a default RESN? 1350 $individual_privacy = $this->tree->getIndividualPrivacy(); 1351 if (isset($individual_privacy[$this->xref()])) { 1352 return $individual_privacy[$this->xref()] >= $access_level; 1353 } 1354 1355 // Privacy rules do not apply to admins 1356 if (Auth::PRIV_NONE >= $access_level) { 1357 return true; 1358 } 1359 1360 // Different types of record have different privacy rules 1361 return $this->canShowByType($access_level); 1362 } 1363} 1364