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 19use PDOException; 20 21/** 22 * Class Tree - Provide an interface to the wt_gedcom table 23 */ 24class Tree { 25 /** @var integer The tree's ID number */ 26 private $tree_id; 27 28 /** @var string The tree's name */ 29 private $name; 30 31 /** @var string The tree's title */ 32 private $title; 33 34 /** @var integer[] Default access rules for facts in this tree */ 35 private $fact_privacy; 36 37 /** @var integer[] Default access rules for individuals in this tree */ 38 private $individual_privacy; 39 40 /** @var integer[][] Default access rules for individual facts in this tree */ 41 private $individual_fact_privacy; 42 43 /** @var Tree[] All trees that we have permission to see. */ 44 private static $trees; 45 46 /** @var string[] Cached copy of the wt_gedcom_setting table. */ 47 private $preferences; 48 49 /** @var string[][] Cached copy of the wt_user_gedcom_setting table. */ 50 private $user_preferences = array(); 51 52 /** 53 * Create a tree object. This is a private constructor - it can only 54 * be called from Tree::getAll() to ensure proper initialisation. 55 * 56 * @param integer $tree_id 57 * @param string $tree_name 58 * @param string $tree_title 59 */ 60 private function __construct($tree_id, $tree_name, $tree_title) { 61 $this->tree_id = $tree_id; 62 $this->name = $tree_name; 63 $this->title = $tree_title; 64 $this->fact_privacy = array(); 65 $this->individual_privacy = array(); 66 $this->individual_fact_privacy = array(); 67 68 // Load the privacy settings for this tree 69 $rows = Database::prepare( 70 "SELECT SQL_CACHE xref, tag_type, CASE resn WHEN 'none' THEN :priv_public WHEN 'privacy' THEN :priv_user WHEN 'confidential' THEN :priv_none WHEN 'hidden' THEN :priv_hide END AS resn" . 71 " FROM `##default_resn` WHERE gedcom_id = :tree_id" 72 )->execute(array( 73 'priv_public' => WT_PRIV_PUBLIC, 74 'priv_user' => WT_PRIV_USER, 75 'priv_none' => WT_PRIV_NONE, 76 'priv_hide' => WT_PRIV_HIDE, 77 'tree_id' => $this->tree_id 78 ))->fetchAll(); 79 80 foreach ($rows as $row) { 81 if ($row->xref !== null) { 82 if ($row->tag_type !== null) { 83 $this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn; 84 } else { 85 $this->individual_privacy[$row->xref] = (int) $row->resn; 86 } 87 } else { 88 $this->fact_privacy[$row->tag_type] = (int) $row->resn; 89 } 90 } 91 92 93 } 94 95 /** 96 * The ID of this tree 97 * 98 * @return integer 99 */ 100 public function getTreeId() { 101 return $this->tree_id; 102 } 103 104 /** 105 * The name of this tree 106 * 107 * @return string 108 */ 109 public function getName() { 110 return $this->name; 111 } 112 113 /** 114 * The name of this tree 115 * 116 * @return string 117 */ 118 public function getNameHtml() { 119 return Filter::escapeHtml($this->name); 120 } 121 122 /** 123 * The name of this tree 124 * 125 * @return string 126 */ 127 public function getNameUrl() { 128 return Filter::escapeUrl($this->name); 129 } 130 131 /** 132 * The title of this tree 133 * 134 * @return string 135 */ 136 public function getTitle() { 137 return $this->title; 138 } 139 140 /** 141 * The title of this tree, with HTML markup 142 * 143 * @return string 144 */ 145 public function getTitleHtml() { 146 return Filter::escapeHtml($this->title); 147 } 148 149 /** 150 * The fact-level privacy for this tree. 151 * 152 * @return integer[] 153 */ 154 public function getFactPrivacy() { 155 return $this->fact_privacy; 156 } 157 158 /** 159 * The individual-level privacy for this tree. 160 * 161 * @return integer[] 162 */ 163 public function getIndividualPrivacy() { 164 return $this->individual_privacy; 165 } 166 167 /** 168 * The individual-fact-level privacy for this tree. 169 * 170 * @return integer[][] 171 */ 172 public function getIndividualFactPrivacy() { 173 return $this->individual_fact_privacy; 174 } 175 176 /** 177 * Get the tree’s configuration settings. 178 * 179 * @param string $setting_name 180 * @param string|null $default 181 * 182 * @return string|null 183 */ 184 public function getPreference($setting_name, $default = null) { 185 if ($this->preferences === null) { 186 $this->preferences = Database::prepare( 187 "SELECT SQL_CACHE setting_name, setting_value FROM `##gedcom_setting` WHERE gedcom_id = ?" 188 )->execute(array($this->tree_id))->fetchAssoc(); 189 } 190 191 if (array_key_exists($setting_name, $this->preferences)) { 192 return $this->preferences[$setting_name]; 193 } else { 194 return $default; 195 } 196 } 197 198 /** 199 * Set the tree’s configuration settings. 200 * 201 * @param string $setting_name 202 * @param string $setting_value 203 * 204 * @return $this 205 */ 206 public function setPreference($setting_name, $setting_value) { 207 if ($setting_value !== $this->getPreference($setting_name)) { 208 // Update the database 209 if ($setting_value === null) { 210 Database::prepare( 211 "DELETE FROM `##gedcom_setting` WHERE gedcom_id = :tree_id AND setting_name = :setting_name" 212 )->execute(array( 213 'tree_id' => $this->tree_id, 214 'setting_name' => $setting_name, 215 )); 216 } else { 217 Database::prepare( 218 "REPLACE INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" . 219 " VALUES (:tree_id, :setting_name, LEFT(:setting_value, 255))" 220 )->execute(array( 221 'tree_id' => $this->tree_id, 222 'setting_name' => $setting_name, 223 'setting_value' => $setting_value, 224 )); 225 } 226 // Update our cache 227 $this->preferences[$setting_name] = $setting_value; 228 // Audit log of changes 229 Log::addConfigurationLog('Tree setting "' . $setting_name . '" set to "' . $setting_value . '"', $this); 230 } 231 232 return $this; 233 } 234 235 /** 236 * Get the tree’s user-configuration settings. 237 * 238 * @param User $user 239 * @param string $setting_name 240 * @param string|null $default 241 * 242 * @return string 243 */ 244 public function getUserPreference(User $user, $setting_name, $default = null) { 245 // There are lots of settings, and we need to fetch lots of them on every page 246 // so it is quicker to fetch them all in one go. 247 if (!array_key_exists($user->getUserId(), $this->user_preferences)) { 248 $this->user_preferences[$user->getUserId()] = Database::prepare( 249 "SELECT SQL_CACHE setting_name, setting_value FROM `##user_gedcom_setting` WHERE user_id = ? AND gedcom_id = ?" 250 )->execute(array($user->getUserId(), $this->tree_id))->fetchAssoc(); 251 } 252 253 if (array_key_exists($setting_name, $this->user_preferences[$user->getUserId()])) { 254 return $this->user_preferences[$user->getUserId()][$setting_name]; 255 } else { 256 return $default; 257 } 258 } 259 260 /** 261 * Set the tree’s user-configuration settings. 262 * 263 * @param User $user 264 * @param string $setting_name 265 * @param string $setting_value 266 * 267 * @return $this 268 */ 269 public function setUserPreference(User $user, $setting_name, $setting_value) { 270 if ($this->getUserPreference($user, $setting_name) !== $setting_value) { 271 // Update the database 272 if ($setting_value === null) { 273 Database::prepare( 274 "DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = :tree_id AND user_id = :user_id AND setting_name = :setting_name" 275 )->execute(array( 276 'tree_id' => $this->tree_id, 277 'user_id' => $user->getUserId(), 278 'setting_name' => $setting_name, 279 )); 280 } else { 281 Database::prepare( 282 "REPLACE INTO `##user_gedcom_setting` (user_id, gedcom_id, setting_name, setting_value) VALUES (:user_id, :tree_id, :setting_name, LEFT(:setting_value, 255))" 283 )->execute(array( 284 'user_id' => $user->getUserId(), 285 'tree_id' => $this->tree_id, 286 'setting_name' => $setting_name, 287 'setting_value' => $setting_value 288 )); 289 } 290 // Update our cache 291 $this->user_preferences[$user->getUserId()][$setting_name] = $setting_value; 292 // Audit log of changes 293 Log::addConfigurationLog('Tree setting "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this); 294 } 295 296 return $this; 297 } 298 299 /** 300 * Can a user accept changes for this tree? 301 * 302 * @param User $user 303 * 304 * @return boolean 305 */ 306 public function canAcceptChanges(User $user) { 307 return Auth::isModerator($this, $user); 308 } 309 310 /** 311 * Fetch all the trees that we have permission to access. 312 * 313 * @return Tree[] 314 */ 315 public static function getAll() { 316 if (self::$trees === null) { 317 self::$trees = array(); 318 $rows = Database::prepare( 319 "SELECT SQL_CACHE g.gedcom_id AS tree_id, g.gedcom_name AS tree_name, gs1.setting_value AS tree_title" . 320 " FROM `##gedcom` g" . 321 " LEFT JOIN `##gedcom_setting` gs1 ON (g.gedcom_id=gs1.gedcom_id AND gs1.setting_name='title')" . 322 " LEFT JOIN `##gedcom_setting` gs2 ON (g.gedcom_id=gs2.gedcom_id AND gs2.setting_name='imported')" . 323 " LEFT JOIN `##gedcom_setting` gs3 ON (g.gedcom_id=gs3.gedcom_id AND gs3.setting_name='REQUIRE_AUTHENTICATION')" . 324 " LEFT JOIN `##user_gedcom_setting` ugs ON (g.gedcom_id=ugs.gedcom_id AND ugs.setting_name='canedit' AND ugs.user_id=?)" . 325 " WHERE " . 326 " g.gedcom_id>0 AND (" . // exclude the "template" tree 327 " EXISTS (SELECT 1 FROM `##user_setting` WHERE user_id=? AND setting_name='canadmin' AND setting_value=1)" . // Admin sees all 328 " ) OR (" . 329 " gs2.setting_value = 1 AND (" . // Allow imported trees, with either: 330 " gs3.setting_value <> 1 OR" . // visitor access 331 " IFNULL(ugs.setting_value, 'none')<>'none'" . // explicit access 332 " )" . 333 " )" . 334 " ORDER BY g.sort_order, 3" 335 )->execute(array(Auth::id(), Auth::id()))->fetchAll(); 336 foreach ($rows as $row) { 337 self::$trees[] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title); 338 } 339 } 340 341 return self::$trees; 342 } 343 344 /** 345 * Find the tree with a specific ID. 346 * 347 * @param integer $tree_id 348 * 349 * @return Tree 350 * @throws \DomainException 351 */ 352 public static function findById($tree_id) { 353 foreach (self::getAll() as $tree) { 354 if ($tree->tree_id == $tree_id) { 355 return $tree; 356 } 357 } 358 throw new \DomainException; 359 } 360 361 /** 362 * Find the tree with a specific name. 363 * 364 * @param string $tree_name 365 * 366 * @return Tree|null 367 */ 368 public static function findByName($tree_name) { 369 foreach (self::getAll() as $tree) { 370 if ($tree->name === $tree_name) { 371 return $tree; 372 } 373 } 374 375 return null; 376 } 377 378 /** 379 * Create arguments to select_edit_control() 380 * Note - these will be escaped later 381 * 382 * @return string[] 383 */ 384 public static function getIdList() { 385 $list = array(); 386 foreach (self::getAll() as $tree) { 387 $list[$tree->tree_id] = $tree->title; 388 } 389 390 return $list; 391 } 392 393 /** 394 * Create arguments to select_edit_control() 395 * Note - these will be escaped later 396 * 397 * @return string[] 398 */ 399 public static function getNameList() { 400 $list = array(); 401 foreach (self::getAll() as $tree) { 402 $list[$tree->name] = $tree->title; 403 } 404 405 return $list; 406 } 407 408 /** 409 * Find the ID number for a tree name 410 * 411 * @param string $tree_name 412 * 413 * @return integer|null 414 */ 415 public static function getIdFromName($tree_name) { 416 foreach (self::getAll() as $tree) { 417 if ($tree->name === $tree_name) { 418 return $tree->tree_id; 419 } 420 } 421 422 return null; 423 } 424 425 /** 426 * Find the tree name from a numeric ID. 427 * @param integer $tree_id 428 * 429 * @return string 430 */ 431 public static function getNameFromId($tree_id) { 432 return self::findById($tree_id)->name; 433 } 434 435 /** 436 * Create a new tree 437 * 438 * @param string $tree_name 439 * @param string $tree_title 440 * 441 * @return Tree 442 */ 443 public static function create($tree_name, $tree_title) { 444 try { 445 // Create a new tree 446 Database::prepare( 447 "INSERT INTO `##gedcom` (gedcom_name) VALUES (?)" 448 )->execute(array($tree_name)); 449 $tree_id = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne(); 450 } catch (PDOException $ex) { 451 // A tree with that name already exists? 452 return self::findById(self::getIdFromName($tree_name)); 453 } 454 455 // Update the list of trees - to include this new one 456 self::$trees = null; 457 $tree = self::findById($tree_id); 458 459 $tree->setPreference('imported', '0'); 460 $tree->setPreference('title', $tree_title); 461 462 // Module privacy 463 Module::setDefaultAccess($tree_id); 464 465 // Gedcom and privacy settings 466 $tree->setPreference('ADVANCED_NAME_FACTS', 'NICK,_AKA'); 467 $tree->setPreference('ADVANCED_PLAC_FACTS', ''); 468 $tree->setPreference('ALLOW_THEME_DROPDOWN', '1'); 469 $tree->setPreference('CALENDAR_FORMAT', 'gregorian'); 470 $tree->setPreference('CHART_BOX_TAGS', ''); 471 $tree->setPreference('COMMON_NAMES_ADD', ''); 472 $tree->setPreference('COMMON_NAMES_REMOVE', ''); 473 $tree->setPreference('COMMON_NAMES_THRESHOLD', '40'); 474 $tree->setPreference('CONTACT_USER_ID', Auth::id()); 475 $tree->setPreference('DEFAULT_PEDIGREE_GENERATIONS', '4'); 476 $tree->setPreference('EXPAND_RELATIVES_EVENTS', '0'); 477 $tree->setPreference('EXPAND_SOURCES', '0'); 478 $tree->setPreference('FAM_FACTS_ADD', 'CENS,MARR,RESI,SLGS,MARR_CIVIL,MARR_RELIGIOUS,MARR_PARTNERS,RESN'); 479 $tree->setPreference('FAM_FACTS_QUICK', 'MARR,DIV,_NMR'); 480 $tree->setPreference('FAM_FACTS_UNIQUE', 'NCHI,MARL,DIV,ANUL,DIVF,ENGA,MARB,MARC,MARS'); 481 $tree->setPreference('FAM_ID_PREFIX', 'F'); 482 $tree->setPreference('FORMAT_TEXT', 'markdown'); 483 $tree->setPreference('FULL_SOURCES', '0'); 484 $tree->setPreference('GEDCOM_ID_PREFIX', 'I'); 485 $tree->setPreference('GEDCOM_MEDIA_PATH', ''); 486 $tree->setPreference('GENERATE_UIDS', '0'); 487 $tree->setPreference('HIDE_GEDCOM_ERRORS', '1'); 488 $tree->setPreference('HIDE_LIVE_PEOPLE', '1'); 489 $tree->setPreference('INDI_FACTS_ADD', 'AFN,BIRT,DEAT,BURI,CREM,ADOP,BAPM,BARM,BASM,BLES,CHRA,CONF,FCOM,ORDN,NATU,EMIG,IMMI,CENS,PROB,WILL,GRAD,RETI,DSCR,EDUC,IDNO,NATI,NCHI,NMR,OCCU,PROP,RELI,RESI,SSN,TITL,BAPL,CONL,ENDL,SLGC,_MILI,ASSO,RESN'); 490 $tree->setPreference('INDI_FACTS_QUICK', 'BIRT,BURI,BAPM,CENS,DEAT,OCCU,RESI'); 491 $tree->setPreference('INDI_FACTS_UNIQUE', ''); 492 $tree->setPreference('KEEP_ALIVE_YEARS_BIRTH', ''); 493 $tree->setPreference('KEEP_ALIVE_YEARS_DEATH', ''); 494 $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language 495 $tree->setPreference('MAX_ALIVE_AGE', 120); 496 $tree->setPreference('MAX_DESCENDANCY_GENERATIONS', '15'); 497 $tree->setPreference('MAX_PEDIGREE_GENERATIONS', '10'); 498 $tree->setPreference('MEDIA_DIRECTORY', 'media/'); 499 $tree->setPreference('MEDIA_ID_PREFIX', 'M'); 500 $tree->setPreference('MEDIA_UPLOAD', WT_PRIV_USER); 501 $tree->setPreference('META_DESCRIPTION', ''); 502 $tree->setPreference('META_TITLE', WT_WEBTREES); 503 $tree->setPreference('NOTE_FACTS_ADD', 'SOUR,RESN'); 504 $tree->setPreference('NOTE_FACTS_QUICK', ''); 505 $tree->setPreference('NOTE_FACTS_UNIQUE', ''); 506 $tree->setPreference('NOTE_ID_PREFIX', 'N'); 507 $tree->setPreference('NO_UPDATE_CHAN', '0'); 508 $tree->setPreference('PEDIGREE_FULL_DETAILS', '1'); 509 $tree->setPreference('PEDIGREE_LAYOUT', '1'); 510 $tree->setPreference('PEDIGREE_ROOT_ID', ''); 511 $tree->setPreference('PEDIGREE_SHOW_GENDER', '0'); 512 $tree->setPreference('PREFER_LEVEL2_SOURCES', '1'); 513 $tree->setPreference('QUICK_REQUIRED_FACTS', 'BIRT,DEAT'); 514 $tree->setPreference('QUICK_REQUIRED_FAMFACTS', 'MARR'); 515 $tree->setPreference('REPO_FACTS_ADD', 'PHON,EMAIL,FAX,WWW,RESN'); 516 $tree->setPreference('REPO_FACTS_QUICK', ''); 517 $tree->setPreference('REPO_FACTS_UNIQUE', 'NAME,ADDR'); 518 $tree->setPreference('REPO_ID_PREFIX', 'R'); 519 $tree->setPreference('REQUIRE_AUTHENTICATION', '0'); 520 $tree->setPreference('SAVE_WATERMARK_IMAGE', '0'); 521 $tree->setPreference('SAVE_WATERMARK_THUMB', '0'); 522 $tree->setPreference('SHOW_AGE_DIFF', '0'); 523 $tree->setPreference('SHOW_COUNTER', '1'); 524 $tree->setPreference('SHOW_DEAD_PEOPLE', WT_PRIV_PUBLIC); 525 $tree->setPreference('SHOW_EST_LIST_DATES', '0'); 526 $tree->setPreference('SHOW_FACT_ICONS', '1'); 527 $tree->setPreference('SHOW_GEDCOM_RECORD', '0'); 528 $tree->setPreference('SHOW_HIGHLIGHT_IMAGES', '1'); 529 $tree->setPreference('SHOW_LDS_AT_GLANCE', '0'); 530 $tree->setPreference('SHOW_LEVEL2_NOTES', '1'); 531 $tree->setPreference('SHOW_LIVING_NAMES', WT_PRIV_USER); 532 $tree->setPreference('SHOW_MEDIA_DOWNLOAD', '0'); 533 $tree->setPreference('SHOW_NO_WATERMARK', WT_PRIV_USER); 534 $tree->setPreference('SHOW_PARENTS_AGE', '1'); 535 $tree->setPreference('SHOW_PEDIGREE_PLACES', '9'); 536 $tree->setPreference('SHOW_PEDIGREE_PLACES_SUFFIX', '0'); 537 $tree->setPreference('SHOW_PRIVATE_RELATIONSHIPS', '1'); 538 $tree->setPreference('SHOW_RELATIVES_EVENTS', '_BIRT_CHIL,_BIRT_SIBL,_MARR_CHIL,_MARR_PARE,_DEAT_CHIL,_DEAT_PARE,_DEAT_GPAR,_DEAT_SIBL,_DEAT_SPOU'); 539 $tree->setPreference('SHOW_STATS', '0'); 540 $tree->setPreference('SOURCE_ID_PREFIX', 'S'); 541 $tree->setPreference('SOUR_FACTS_ADD', 'NOTE,REPO,SHARED_NOTE,RESN'); 542 $tree->setPreference('SOUR_FACTS_QUICK', 'TEXT,NOTE,REPO'); 543 $tree->setPreference('SOUR_FACTS_UNIQUE', 'AUTH,ABBR,TITL,PUBL,TEXT'); 544 $tree->setPreference('SUBLIST_TRIGGER_I', '200'); 545 $tree->setPreference('SURNAME_LIST_STYLE', 'style2'); 546 switch (WT_LOCALE) { 547 case 'es': 548 $tree->setPreference('SURNAME_TRADITION', 'spanish'); 549 break; 550 case 'is': 551 $tree->setPreference('SURNAME_TRADITION', 'icelandic'); 552 break; 553 case 'lt': 554 $tree->setPreference('SURNAME_TRADITION', 'lithuanian'); 555 break; 556 case 'pl': 557 $tree->setPreference('SURNAME_TRADITION', 'polish'); 558 break; 559 case 'pt': 560 case 'pt-BR': 561 $tree->setPreference('SURNAME_TRADITION', 'portuguese'); 562 break; 563 default: 564 $tree->setPreference('SURNAME_TRADITION', 'paternal'); 565 break; 566 } 567 $tree->setPreference('THUMBNAIL_WIDTH', '100'); 568 $tree->setPreference('USE_RIN', '0'); 569 $tree->setPreference('USE_SILHOUETTE', '1'); 570 $tree->setPreference('WATERMARK_THUMB', '0'); 571 $tree->setPreference('WEBMASTER_USER_ID', Auth::id()); 572 $tree->setPreference('WEBTREES_EMAIL', ''); 573 $tree->setPreference('WORD_WRAPPED_NOTES', '0'); 574 575 // Default restriction settings 576 $statement = Database::prepare( 577 "INSERT INTO `##default_resn` (gedcom_id, xref, tag_type, resn) VALUES (?, NULL, ?, ?)" 578 ); 579 $statement->execute(array($tree_id, 'SSN', 'confidential')); 580 $statement->execute(array($tree_id, 'SOUR', 'privacy')); 581 $statement->execute(array($tree_id, 'REPO', 'privacy')); 582 $statement->execute(array($tree_id, 'SUBM', 'confidential')); 583 $statement->execute(array($tree_id, 'SUBN', 'confidential')); 584 585 // Genealogy data 586 // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables... 587 $john_doe = /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */ 588 I18N::translate('John /DOE/'); 589 $note = I18N::translate('Edit this individual and replace their details with your own'); 590 Database::prepare("INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)")->execute(array( 591 $tree_id, 592 "0 HEAD\n1 CHAR UTF-8\n0 @I1@ INDI\n1 NAME {$john_doe}\n1 SEX M\n1 BIRT\n2 DATE 01 JAN 1850\n2 NOTE {$note}\n0 TRLR\n" 593 )); 594 595 // Set the initial blocks 596 Database::prepare( 597 "INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" . 598 " SELECT ?, location, block_order, module_name" . 599 " FROM `##block`" . 600 " WHERE gedcom_id = -1" 601 )->execute(array($tree_id)); 602 603 // Update our cache 604 self::$trees[$tree->tree_id] = $tree; 605 606 return $tree; 607 } 608 609 /** 610 * Delete all the genealogy data from a tree - in preparation for importing 611 * new data. Optionally retain the media data, for when the user has been 612 * editing their data offline using an application which deletes (or does not 613 * support) media data. 614 * 615 * @param bool $keep_media 616 */ 617 public function deleteGenealogyData($keep_media) { 618 Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 619 Database::prepare("DELETE FROM `##individuals` WHERE i_file = ?")->execute(array($this->tree_id)); 620 Database::prepare("DELETE FROM `##families` WHERE f_file = ?")->execute(array($this->tree_id)); 621 Database::prepare("DELETE FROM `##sources` WHERE s_file = ?")->execute(array($this->tree_id)); 622 Database::prepare("DELETE FROM `##other` WHERE o_file = ?")->execute(array($this->tree_id)); 623 Database::prepare("DELETE FROM `##places` WHERE p_file = ?")->execute(array($this->tree_id)); 624 Database::prepare("DELETE FROM `##placelinks` WHERE pl_file = ?")->execute(array($this->tree_id)); 625 Database::prepare("DELETE FROM `##name` WHERE n_file = ?")->execute(array($this->tree_id)); 626 Database::prepare("DELETE FROM `##dates` WHERE d_file = ?")->execute(array($this->tree_id)); 627 Database::prepare("DELETE FROM `##change` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 628 629 if ($keep_media) { 630 Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute(array($this->tree_id)); 631 } else { 632 Database::prepare("DELETE FROM `##link` WHERE l_file =?")->execute(array($this->tree_id)); 633 Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute(array($this->tree_id)); 634 } 635 } 636 637 /** 638 * Delete everything relating to a tree 639 */ 640 public function delete() { 641 // If this is the default tree, then unset it 642 if (Site::getPreference('DEFAULT_GEDCOM') === self::getNameFromId($this->tree_id)) { 643 Site::setPreference('DEFAULT_GEDCOM', ''); 644 } 645 646 $this->deleteGenealogyData(false); 647 648 Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute(array($this->tree_id)); 649 Database::prepare("DELETE FROM `##block` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 650 Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 651 Database::prepare("DELETE FROM `##gedcom_setting` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 652 Database::prepare("DELETE FROM `##module_privacy` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 653 Database::prepare("DELETE FROM `##next_id` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 654 Database::prepare("DELETE FROM `##hit_counter` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 655 Database::prepare("DELETE FROM `##default_resn` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 656 Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 657 Database::prepare("DELETE FROM `##log` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 658 Database::prepare("DELETE FROM `##gedcom` WHERE gedcom_id = ?")->execute(array($this->tree_id)); 659 660 // After updating the database, we need to fetch a new (sorted) copy 661 self::$trees = null; 662 } 663 664 /** 665 * Export the tree to a GEDCOM file 666 * 667 * @param resource $stream 668 */ 669 public function exportGedcom($stream) { 670 $stmt = Database::prepare( 671 "SELECT i_gedcom AS gedcom FROM `##individuals` WHERE i_file = :tree_id_1" . 672 " UNION ALL " . 673 "SELECT f_gedcom AS gedcom FROM `##families` WHERE f_file = :tree_id_2" . 674 " UNION ALL " . 675 "SELECT s_gedcom AS gedcom FROM `##sources` WHERE s_file = :tree_id_3" . 676 " UNION ALL " . 677 "SELECT o_gedcom AS gedcom FROM `##other` WHERE o_file = :tree_id_4 AND o_type NOT IN ('HEAD', 'TRLR')" . 678 " UNION ALL " . 679 "SELECT m_gedcom AS gedcom FROM `##media` WHERE m_file = :tree_id_5" 680 )->execute(array( 681 'tree_id_1' => $this->tree_id, 682 'tree_id_2' => $this->tree_id, 683 'tree_id_3' => $this->tree_id, 684 'tree_id_4' => $this->tree_id, 685 'tree_id_5' => $this->tree_id 686 )); 687 688 $buffer = reformat_record_export(gedcom_header($this->name)); 689 while ($row = $stmt->fetch()) { 690 $buffer .= reformat_record_export($row->gedcom); 691 if (strlen($buffer) > 65535) { 692 fwrite($stream, $buffer); 693 $buffer = ''; 694 } 695 } 696 fwrite($stream, $buffer . '0 TRLR' . WT_EOL); 697 } 698 699 /** 700 * Import data from a gedcom file into this tree. 701 * 702 * @param string $path The full path to the (possibly temporary) file. 703 * @param string $filename The preferred filename, for export/download. 704 * 705 * @throws \Exception 706 */ 707 public function importGedcomFile($path, $filename) { 708 // Read the file in blocks of roughly 64K. Ensure that each block 709 // contains complete gedcom records. This will ensure we don’t split 710 // multi-byte characters, as well as simplifying the code to import 711 // each block. 712 713 $file_data = ''; 714 $fp = fopen($path, 'rb'); 715 716 // Don’t allow the user to cancel the request. We do not want to be left with an incomplete transaction. 717 ignore_user_abort(true); 718 719 Database::beginTransaction(); 720 $this->deleteGenealogyData($this->getPreference('keep_media')); 721 $this->setPreference('gedcom_filename', $filename); 722 $this->setPreference('imported', '0'); 723 724 while (!feof($fp)) { 725 $file_data .= fread($fp, 65536); 726 // There is no strrpos() function that searches for substrings :-( 727 for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) { 728 if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) { 729 // We’ve found the last record boundary in this chunk of data 730 break; 731 } 732 } 733 if ($pos) { 734 Database::prepare( 735 "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)" 736 )->execute(array($this->tree_id, substr($file_data, 0, $pos))); 737 $file_data = substr($file_data, $pos); 738 } 739 } 740 Database::prepare( 741 "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)" 742 )->execute(array($this->tree_id, $file_data)); 743 744 Database::commit(); 745 fclose($fp); 746 } 747 748 /** 749 * Generate a new XREF, unique across all family trees 750 * 751 * @param string $type 752 * 753 * @return string 754 */ 755 public function getNewXref($type = 'INDI') { 756 /** @var string[] Which tree preference is used for which record type */ 757 static $type_to_preference = array( 758 'INDI' => 'GEDCOM_ID_PREFIX', 759 'FAM' => 'FAM_ID_PREFIX', 760 'OBJE' => 'MEDIA_ID_PREFIX', 761 'NOTE' => 'NOTE_ID_PREFIX', 762 'SOUR' => 'SOURCE_ID_PREFIX', 763 'REPO' => 'REPO_ID_PREFIX', 764 ); 765 766 if (array_key_exists($type, $type_to_preference)) { 767 $prefix = $this->getPreference($type_to_preference[$type]); 768 } else { 769 // Use the first non-underscore character 770 $prefix = substr(trim($type, '_'), 0, 1); 771 } 772 773 do { 774 // Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See 775 // http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id 776 $statement = Database::prepare( 777 "UPDATE `##next_id` SET next_id = LAST_INSERT_ID(next_id + 1) WHERE record_type = :record_type AND gedcom_id = :tree_id" 778 ); 779 $statement->execute(array( 780 'record_type' => $type, 781 'tree_id' => $this->tree_id, 782 )); 783 784 if ($statement->rowCount() === 0) { 785 // First time we've used this record type. 786 Database::prepare( 787 "INSERT INTO `##next_id` (gedcom_id, record_type, next_id) VALUES(:tree_id, :record_type, 1)" 788 )->execute(array( 789 'record_type' => $type, 790 'tree_id' => $this->tree_id, 791 )); 792 $num = 1; 793 } else { 794 $num = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne(); 795 } 796 797 // Records may already exist with this sequence number. 798 $already_used = Database::prepare( 799 "SELECT i_id FROM `##individuals` WHERE i_id = :i_id" . 800 " UNION ALL " . 801 "SELECT f_id FROM `##families` WHERE f_id = :f_id" . 802 " UNION ALL " . 803 "SELECT s_id FROM `##sources` WHERE s_id = :s_id" . 804 " UNION ALL " . 805 "SELECT m_id FROM `##media` WHERE m_id = :m_id" . 806 " UNION ALL " . 807 "SELECT o_id FROM `##other` WHERE o_id = :o_id" . 808 " UNION ALL " . 809 "SELECT xref FROM `##change` WHERE xref = :xref" 810 )->execute(array( 811 'i_id' => $prefix . $num, 812 'f_id' => $prefix . $num, 813 's_id' => $prefix . $num, 814 'm_id' => $prefix . $num, 815 'o_id' => $prefix . $num, 816 'xref' => $prefix . $num, 817 ))->fetchOne(); 818 } while ($already_used); 819 820 return $prefix . $num; 821 } 822 823 /** 824 * Create a new record from GEDCOM data. 825 * 826 * @param string $gedcom 827 * 828 * @return GedcomRecord 829 * @throws \Exception 830 */ 831 public function createRecord($gedcom) { 832 if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom, $match)) { 833 $xref = $match[1]; 834 $type = $match[2]; 835 } else { 836 throw new \Exception('Invalid argument to GedcomRecord::createRecord(' . $gedcom . ')'); 837 } 838 if (strpos("\r", $gedcom) !== false) { 839 // MSDOS line endings will break things in horrible ways 840 throw new \Exception('Evil line endings found in GedcomRecord::createRecord(' . $gedcom . ')'); 841 } 842 843 // webtrees creates XREFs containing digits. Anything else (e.g. “new”) is just a placeholder. 844 if (!preg_match('/\d/', $xref)) { 845 $xref = $this->getNewXref($type); 846 $gedcom = preg_replace('/^0 @(' . WT_REGEX_XREF . ')@/', '0 @' . $xref . '@', $gedcom); 847 } 848 849 // Create a change record, if not already present 850 if (!preg_match('/\n1 CHAN/', $gedcom)) { 851 $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName(); 852 } 853 854 // Create a pending change 855 Database::prepare( 856 "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)" 857 )->execute(array( 858 $this->tree_id, 859 $xref, 860 $gedcom, 861 Auth::id() 862 )); 863 864 Log::addEditLog('Create: ' . $type . ' ' . $xref); 865 866 // Accept this pending change 867 if (Auth::user()->getPreference('auto_accept')) { 868 accept_all_changes($xref, $this->tree_id); 869 } 870 // Return the newly created record. Note that since GedcomRecord 871 // has a cache of pending changes, we cannot use it to create a 872 // record with a newly created pending change. 873 return GedcomRecord::getInstance($xref, $this->tree_id, $gedcom); 874 } 875} 876