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