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