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