xref: /webtrees/app/Tree.php (revision 323788f4145f5a5554b028e0581a6e2063364968)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2015 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16namespace Fisharebest\Webtrees;
17
18use Fisharebest\Webtrees\Functions\FunctionsExport;
19use Fisharebest\Webtrees\Functions\FunctionsImport;
20use PDOException;
21
22/**
23 * Provide an interface to the wt_gedcom table.
24 */
25class Tree {
26	/** @var int The tree's ID number */
27	private $tree_id;
28
29	/** @var string The tree's name */
30	private $name;
31
32	/** @var string The tree's title */
33	private $title;
34
35	/** @var integer[] Default access rules for facts in this tree */
36	private $fact_privacy;
37
38	/** @var integer[] Default access rules for individuals in this tree */
39	private $individual_privacy;
40
41	/** @var integer[][] Default access rules for individual facts in this tree */
42	private $individual_fact_privacy;
43
44	/** @var Tree[] All trees that we have permission to see. */
45	private static $trees;
46
47	/** @var string[] Cached copy of the wt_gedcom_setting table. */
48	private $preferences;
49
50	/** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
51	private $user_preferences = array();
52
53	/**
54	 * Create a tree object.  This is a private constructor - it can only
55	 * be called from Tree::getAll() to ensure proper initialisation.
56	 *
57	 * @param int    $tree_id
58	 * @param string $tree_name
59	 * @param string $tree_title
60	 */
61	private function __construct($tree_id, $tree_name, $tree_title) {
62		$this->tree_id                 = $tree_id;
63		$this->name                    = $tree_name;
64		$this->title                   = $tree_title;
65		$this->fact_privacy            = array();
66		$this->individual_privacy      = array();
67		$this->individual_fact_privacy = array();
68
69		// Load the privacy settings for this tree
70		$rows = Database::prepare(
71			"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" .
72			" FROM `##default_resn` WHERE gedcom_id = :tree_id"
73		)->execute(array(
74			'priv_public' => Auth::PRIV_PRIVATE,
75			'priv_user'   => Auth::PRIV_USER,
76			'priv_none'   => Auth::PRIV_NONE,
77			'priv_hide'   => Auth::PRIV_HIDE,
78			'tree_id'     => $this->tree_id,
79		))->fetchAll();
80
81		foreach ($rows as $row) {
82			if ($row->xref !== null) {
83				if ($row->tag_type !== null) {
84					$this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
85				} else {
86					$this->individual_privacy[$row->xref] = (int) $row->resn;
87				}
88			} else {
89				$this->fact_privacy[$row->tag_type] = (int) $row->resn;
90			}
91		}
92
93	}
94
95	/**
96	 * The ID of this tree
97	 *
98	 * @return int
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 '<span dir="auto">' . Filter::escapeHtml($this->title) . '</span>';
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 bool
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 int $tree_id
348	 *
349	 * @throws \DomainException
350	 *
351	 * @return Tree
352	 */
353	public static function findById($tree_id) {
354		foreach (self::getAll() as $tree) {
355			if ($tree->tree_id == $tree_id) {
356				return $tree;
357			}
358		}
359		throw new \DomainException;
360	}
361
362	/**
363	 * Find the tree with a specific name.
364	 *
365	 * @param string $tree_name
366	 *
367	 * @return Tree|null
368	 */
369	public static function findByName($tree_name) {
370		foreach (self::getAll() as $tree) {
371			if ($tree->name === $tree_name) {
372				return $tree;
373			}
374		}
375
376		return null;
377	}
378
379	/**
380	 * Create arguments to select_edit_control()
381	 * Note - these will be escaped later
382	 *
383	 * @return string[]
384	 */
385	public static function getIdList() {
386		$list = array();
387		foreach (self::getAll() as $tree) {
388			$list[$tree->tree_id] = $tree->title;
389		}
390
391		return $list;
392	}
393
394	/**
395	 * Create arguments to select_edit_control()
396	 * Note - these will be escaped later
397	 *
398	 * @return string[]
399	 */
400	public static function getNameList() {
401		$list = array();
402		foreach (self::getAll() as $tree) {
403			$list[$tree->name] = $tree->title;
404		}
405
406		return $list;
407	}
408
409	/**
410	 * Create a new tree
411	 *
412	 * @param string $tree_name
413	 * @param string $tree_title
414	 *
415	 * @return Tree
416	 */
417	public static function create($tree_name, $tree_title) {
418		try {
419			// Create a new tree
420			Database::prepare(
421				"INSERT INTO `##gedcom` (gedcom_name) VALUES (?)"
422			)->execute(array($tree_name));
423			$tree_id = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
424		} catch (PDOException $ex) {
425			// A tree with that name already exists?
426			return self::findByName($tree_name);
427		}
428
429		// Update the list of trees - to include this new one
430		self::$trees = null;
431		$tree        = self::findById($tree_id);
432
433		$tree->setPreference('imported', '0');
434		$tree->setPreference('title', $tree_title);
435
436		// Module privacy
437		Module::setDefaultAccess($tree_id);
438
439		// Set preferences from default tree
440		Database::prepare(
441			"INSERT INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
442			" SELECT :tree_id, setting_name, setting_value" .
443			" FROM `##gedcom_setting` WHERE gedcom_id = -1"
444		)->execute(array(
445			'tree_id' => $tree_id,
446		));
447
448		Database::prepare(
449			"INSERT INTO `##default_resn` (gedcom_id, tag_type, resn)" .
450			" SELECT :tree_id, tag_type, resn" .
451			" FROM `##default_resn` WHERE gedcom_id = -1"
452		)->execute(array(
453			'tree_id' => $tree_id,
454		));
455
456		Database::prepare(
457			"INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" .
458			" SELECT :tree_id, location, block_order, module_name" .
459			" FROM `##block` WHERE gedcom_id = -1"
460		)->execute(array(
461			'tree_id' => $tree_id,
462		));
463
464
465
466
467		// Gedcom and privacy settings
468		$tree->setPreference('CONTACT_USER_ID', Auth::id());
469		$tree->setPreference('WEBMASTER_USER_ID', Auth::id());
470		$tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
471		switch (WT_LOCALE) {
472		case 'es':
473			$tree->setPreference('SURNAME_TRADITION', 'spanish');
474			break;
475		case 'is':
476			$tree->setPreference('SURNAME_TRADITION', 'icelandic');
477			break;
478		case 'lt':
479			$tree->setPreference('SURNAME_TRADITION', 'lithuanian');
480			break;
481		case 'pl':
482			$tree->setPreference('SURNAME_TRADITION', 'polish');
483			break;
484		case 'pt':
485		case 'pt-BR':
486			$tree->setPreference('SURNAME_TRADITION', 'portuguese');
487			break;
488		default:
489			$tree->setPreference('SURNAME_TRADITION', 'paternal');
490			break;
491		}
492
493		// Genealogy data
494		// It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
495		$john_doe = /* I18N: This should be a common/default/placeholder name of an individual.  Put slashes around the surname. */
496			I18N::translate('John /DOE/');
497		$note     = I18N::translate('Edit this individual and replace their details with your own.');
498		Database::prepare("INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)")->execute(array(
499			$tree_id,
500			"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",
501		));
502
503		// Update our cache
504		self::$trees[$tree->tree_id] = $tree;
505
506		return $tree;
507	}
508
509	/**
510	 * Are there any pending edits for this tree, than need reviewing by a moderator.
511	 *
512	 * @return bool
513	 */
514	public function hasPendingEdit() {
515		return (bool) Database::prepare(
516			"SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
517		)->execute(array(
518			'tree_id' => $this->tree_id,
519		))->fetchOne();
520	}
521
522	/**
523	 * Delete all the genealogy data from a tree - in preparation for importing
524	 * new data.  Optionally retain the media data, for when the user has been
525	 * editing their data offline using an application which deletes (or does not
526	 * support) media data.
527	 *
528	 * @param bool $keep_media
529	 */
530	public function deleteGenealogyData($keep_media) {
531		Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute(array($this->tree_id));
532		Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute(array($this->tree_id));
533		Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute(array($this->tree_id));
534		Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute(array($this->tree_id));
535		Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute(array($this->tree_id));
536		Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute(array($this->tree_id));
537		Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute(array($this->tree_id));
538		Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute(array($this->tree_id));
539		Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute(array($this->tree_id));
540		Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute(array($this->tree_id));
541
542		if ($keep_media) {
543			Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute(array($this->tree_id));
544		} else {
545			Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute(array($this->tree_id));
546			Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute(array($this->tree_id));
547		}
548	}
549
550	/**
551	 * Delete everything relating to a tree
552	 */
553	public function delete() {
554		// If this is the default tree, then unset it
555		if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
556			Site::setPreference('DEFAULT_GEDCOM', '');
557		}
558
559		$this->deleteGenealogyData(false);
560
561		Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute(array($this->tree_id));
562		Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute(array($this->tree_id));
563		Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute(array($this->tree_id));
564		Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute(array($this->tree_id));
565		Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute(array($this->tree_id));
566		Database::prepare("DELETE FROM `##next_id`             WHERE gedcom_id = ?")->execute(array($this->tree_id));
567		Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute(array($this->tree_id));
568		Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute(array($this->tree_id));
569		Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute(array($this->tree_id));
570		Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute(array($this->tree_id));
571		Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute(array($this->tree_id));
572
573		// After updating the database, we need to fetch a new (sorted) copy
574		self::$trees = null;
575	}
576
577	/**
578	 * Export the tree to a GEDCOM file
579	 *
580	 * @param resource $stream
581	 */
582	public function exportGedcom($stream) {
583		$stmt = Database::prepare(
584			"SELECT i_gedcom AS gedcom FROM `##individuals` WHERE i_file = :tree_id_1" .
585			" UNION ALL " .
586			"SELECT f_gedcom AS gedcom FROM `##families`    WHERE f_file = :tree_id_2" .
587			" UNION ALL " .
588			"SELECT s_gedcom AS gedcom FROM `##sources`     WHERE s_file = :tree_id_3" .
589			" UNION ALL " .
590			"SELECT o_gedcom AS gedcom FROM `##other`       WHERE o_file = :tree_id_4 AND o_type NOT IN ('HEAD', 'TRLR')" .
591			" UNION ALL " .
592			"SELECT m_gedcom AS gedcom FROM `##media`       WHERE m_file = :tree_id_5"
593		)->execute(array(
594			'tree_id_1' => $this->tree_id,
595			'tree_id_2' => $this->tree_id,
596			'tree_id_3' => $this->tree_id,
597			'tree_id_4' => $this->tree_id,
598			'tree_id_5' => $this->tree_id,
599		));
600
601		$buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this));
602		while ($row = $stmt->fetch()) {
603			$buffer .= FunctionsExport::reformatRecord($row->gedcom);
604			if (strlen($buffer) > 65535) {
605				fwrite($stream, $buffer);
606				$buffer = '';
607			}
608		}
609		fwrite($stream, $buffer . '0 TRLR' . WT_EOL);
610	}
611
612	/**
613	 * Import data from a gedcom file into this tree.
614	 *
615	 * @param string  $path       The full path to the (possibly temporary) file.
616	 * @param string  $filename   The preferred filename, for export/download.
617	 *
618	 * @throws \Exception
619	 */
620	public function importGedcomFile($path, $filename) {
621		// Read the file in blocks of roughly 64K.  Ensure that each block
622		// contains complete gedcom records.  This will ensure we don’t split
623		// multi-byte characters, as well as simplifying the code to import
624		// each block.
625
626		$file_data = '';
627		$fp        = fopen($path, 'rb');
628
629		// Don’t allow the user to cancel the request.  We do not want to be left with an incomplete transaction.
630		ignore_user_abort(true);
631
632		Database::beginTransaction();
633		$this->deleteGenealogyData($this->getPreference('keep_media'));
634		$this->setPreference('gedcom_filename', $filename);
635		$this->setPreference('imported', '0');
636
637		while (!feof($fp)) {
638			$file_data .= fread($fp, 65536);
639			// There is no strrpos() function that searches for substrings :-(
640			for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
641				if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
642					// We’ve found the last record boundary in this chunk of data
643					break;
644				}
645			}
646			if ($pos) {
647				Database::prepare(
648					"INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
649				)->execute(array($this->tree_id, substr($file_data, 0, $pos)));
650				$file_data = substr($file_data, $pos);
651			}
652		}
653		Database::prepare(
654			"INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
655		)->execute(array($this->tree_id, $file_data));
656
657		Database::commit();
658		fclose($fp);
659	}
660
661	/**
662	 * Generate a new XREF, unique across all family trees
663	 *
664	 * @param string $type
665	 *
666	 * @return string
667	 */
668	public function getNewXref($type = 'INDI') {
669		/** @var string[] Which tree preference is used for which record type */
670		static $type_to_preference = array(
671			'INDI' => 'GEDCOM_ID_PREFIX',
672			'FAM'  => 'FAM_ID_PREFIX',
673			'OBJE' => 'MEDIA_ID_PREFIX',
674			'NOTE' => 'NOTE_ID_PREFIX',
675			'SOUR' => 'SOURCE_ID_PREFIX',
676			'REPO' => 'REPO_ID_PREFIX',
677		);
678
679		if (array_key_exists($type, $type_to_preference)) {
680			$prefix = $this->getPreference($type_to_preference[$type]);
681		} else {
682			// Use the first non-underscore character
683			$prefix = substr(trim($type, '_'), 0, 1);
684		}
685
686		do {
687			// Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence.  See
688			// http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
689			$statement = Database::prepare(
690				"UPDATE `##next_id` SET next_id = LAST_INSERT_ID(next_id + 1) WHERE record_type = :record_type AND gedcom_id = :tree_id"
691			);
692			$statement->execute(array(
693				'record_type' => $type,
694				'tree_id'     => $this->tree_id,
695			));
696
697			if ($statement->rowCount() === 0) {
698				// First time we've used this record type.
699				Database::prepare(
700					"INSERT INTO `##next_id` (gedcom_id, record_type, next_id) VALUES(:tree_id, :record_type, 1)"
701				)->execute(array(
702					'record_type' => $type,
703					'tree_id'     => $this->tree_id,
704				));
705				$num = 1;
706			} else {
707				$num = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
708			}
709
710			// Records may already exist with this sequence number.
711			$already_used = Database::prepare(
712				"SELECT i_id FROM `##individuals` WHERE i_id = :i_id" .
713				" UNION ALL " .
714				"SELECT f_id FROM `##families` WHERE f_id = :f_id" .
715				" UNION ALL " .
716				"SELECT s_id FROM `##sources` WHERE s_id = :s_id" .
717				" UNION ALL " .
718				"SELECT m_id FROM `##media` WHERE m_id = :m_id" .
719				" UNION ALL " .
720				"SELECT o_id FROM `##other` WHERE o_id = :o_id" .
721				" UNION ALL " .
722				"SELECT xref FROM `##change` WHERE xref = :xref"
723			)->execute(array(
724				'i_id' => $prefix . $num,
725				'f_id' => $prefix . $num,
726				's_id' => $prefix . $num,
727				'm_id' => $prefix . $num,
728				'o_id' => $prefix . $num,
729				'xref' => $prefix . $num,
730			))->fetchOne();
731		} while ($already_used);
732
733		return $prefix . $num;
734	}
735
736	/**
737	 * Create a new record from GEDCOM data.
738	 *
739	 * @param string $gedcom
740	 *
741	 * @throws \Exception
742	 *
743	 * @return GedcomRecord
744	 */
745	public function createRecord($gedcom) {
746		if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom, $match)) {
747			$xref = $match[1];
748			$type = $match[2];
749		} else {
750			throw new \Exception('Invalid argument to GedcomRecord::createRecord(' . $gedcom . ')');
751		}
752		if (strpos("\r", $gedcom) !== false) {
753			// MSDOS line endings will break things in horrible ways
754			throw new \Exception('Evil line endings found in GedcomRecord::createRecord(' . $gedcom . ')');
755		}
756
757		// webtrees creates XREFs containing digits.  Anything else (e.g. “new”) is just a placeholder.
758		if (!preg_match('/\d/', $xref)) {
759			$xref   = $this->getNewXref($type);
760			$gedcom = preg_replace('/^0 @(' . WT_REGEX_XREF . ')@/', '0 @' . $xref . '@', $gedcom);
761		}
762
763		// Create a change record, if not already present
764		if (!preg_match('/\n1 CHAN/', $gedcom)) {
765			$gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
766		}
767
768		// Create a pending change
769		Database::prepare(
770			"INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
771		)->execute(array(
772			$this->tree_id,
773			$xref,
774			$gedcom,
775			Auth::id(),
776		));
777
778		Log::addEditLog('Create: ' . $type . ' ' . $xref);
779
780		// Accept this pending change
781		if (Auth::user()->getPreference('auto_accept')) {
782			FunctionsImport::acceptAllChanges($xref, $this->tree_id);
783		}
784		// Return the newly created record.  Note that since GedcomRecord
785		// has a cache of pending changes, we cannot use it to create a
786		// record with a newly created pending change.
787		return GedcomRecord::getInstance($xref, $this, $gedcom);
788	}
789}
790