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