xref: /webtrees/app/Tree.php (revision b11e001b10de48937bf6f9197fb7d1562b743545)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 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 int[] Default access rules for facts in this tree */
36	private $fact_privacy;
37
38	/** @var int[] 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 = [];
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            = [];
66		$this->individual_privacy      = [];
67		$this->individual_fact_privacy = [];
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([
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	 * 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 getNameUrl() {
118		return rawurlencode($this->name);
119	}
120
121	/**
122	 * The title of this tree
123	 *
124	 * @return string
125	 */
126	public function getTitle() {
127		return $this->title;
128	}
129
130	/**
131	 * The title of this tree, with HTML markup
132	 *
133	 * @return string
134	 */
135	public function getTitleHtml() {
136		return '<span dir="auto">' . e($this->title) . '</span>';
137	}
138
139	/**
140	 * The fact-level privacy for this tree.
141	 *
142	 * @return int[]
143	 */
144	public function getFactPrivacy() {
145		return $this->fact_privacy;
146	}
147
148	/**
149	 * The individual-level privacy for this tree.
150	 *
151	 * @return int[]
152	 */
153	public function getIndividualPrivacy() {
154		return $this->individual_privacy;
155	}
156
157	/**
158	 * The individual-fact-level privacy for this tree.
159	 *
160	 * @return int[][]
161	 */
162	public function getIndividualFactPrivacy() {
163		return $this->individual_fact_privacy;
164	}
165
166	/**
167	 * Get the tree’s configuration settings.
168	 *
169	 * @param string $setting_name
170	 * @param string $default
171	 *
172	 * @return string
173	 */
174	public function getPreference($setting_name, $default = '') {
175		if (empty($this->preferences)) {
176			$this->preferences = Database::prepare(
177				"SELECT SQL_CACHE setting_name, setting_value FROM `##gedcom_setting` WHERE gedcom_id = ?"
178			)->execute([$this->tree_id])->fetchAssoc();
179		}
180
181		if (array_key_exists($setting_name, $this->preferences)) {
182			return $this->preferences[$setting_name];
183		} else {
184			return $default;
185		}
186	}
187
188	/**
189	 * Set the tree’s configuration settings.
190	 *
191	 * @param string $setting_name
192	 * @param string $setting_value
193	 *
194	 * @return $this
195	 */
196	public function setPreference($setting_name, $setting_value) {
197		if ($setting_value !== $this->getPreference($setting_name)) {
198			Database::prepare(
199				"REPLACE INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
200				" VALUES (:tree_id, :setting_name, LEFT(:setting_value, 255))"
201			)->execute([
202				'tree_id'       => $this->tree_id,
203				'setting_name'  => $setting_name,
204				'setting_value' => $setting_value,
205			]);
206
207			$this->preferences[$setting_name] = $setting_value;
208
209			Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
210		}
211
212		return $this;
213	}
214
215	/**
216	 * Get the tree’s user-configuration settings.
217	 *
218	 * @param User        $user
219	 * @param string      $setting_name
220	 * @param string|null $default
221	 *
222	 * @return string
223	 */
224	public function getUserPreference(User $user, $setting_name, $default = null) {
225		// There are lots of settings, and we need to fetch lots of them on every page
226		// so it is quicker to fetch them all in one go.
227		if (!array_key_exists($user->getUserId(), $this->user_preferences)) {
228			$this->user_preferences[$user->getUserId()] = Database::prepare(
229				"SELECT SQL_CACHE setting_name, setting_value FROM `##user_gedcom_setting` WHERE user_id = ? AND gedcom_id = ?"
230			)->execute([$user->getUserId(), $this->tree_id])->fetchAssoc();
231		}
232
233		if (array_key_exists($setting_name, $this->user_preferences[$user->getUserId()])) {
234			return $this->user_preferences[$user->getUserId()][$setting_name];
235		} else {
236			return $default;
237		}
238	}
239
240	/**
241	 * Set the tree’s user-configuration settings.
242	 *
243	 * @param User    $user
244	 * @param string  $setting_name
245	 * @param string  $setting_value
246	 *
247	 * @return $this
248	 */
249	public function setUserPreference(User $user, $setting_name, $setting_value) {
250		if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
251			// Update the database
252			if ($setting_value === null) {
253				Database::prepare(
254					"DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = :tree_id AND user_id = :user_id AND setting_name = :setting_name"
255				)->execute([
256					'tree_id'      => $this->tree_id,
257					'user_id'      => $user->getUserId(),
258					'setting_name' => $setting_name,
259				]);
260			} else {
261				Database::prepare(
262					"REPLACE INTO `##user_gedcom_setting` (user_id, gedcom_id, setting_name, setting_value) VALUES (:user_id, :tree_id, :setting_name, LEFT(:setting_value, 255))"
263				)->execute([
264					'user_id'       => $user->getUserId(),
265					'tree_id'       => $this->tree_id,
266					'setting_name'  => $setting_name,
267					'setting_value' => $setting_value,
268				]);
269			}
270			// Update our cache
271			$this->user_preferences[$user->getUserId()][$setting_name] = $setting_value;
272			// Audit log of changes
273			Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this);
274		}
275
276		return $this;
277	}
278
279	/**
280	 * Can a user accept changes for this tree?
281	 *
282	 * @param User $user
283	 *
284	 * @return bool
285	 */
286	public function canAcceptChanges(User $user) {
287		return Auth::isModerator($this, $user);
288	}
289
290	/**
291	 * Fetch all the trees that we have permission to access.
292	 *
293	 * @return Tree[]
294	 */
295	public static function getAll() {
296		if (self::$trees === null) {
297			self::$trees = [];
298			$rows        = Database::prepare(
299				"SELECT SQL_CACHE g.gedcom_id AS tree_id, g.gedcom_name AS tree_name, gs1.setting_value AS tree_title" .
300				" FROM `##gedcom` g" .
301				" LEFT JOIN `##gedcom_setting`      gs1 ON (g.gedcom_id=gs1.gedcom_id AND gs1.setting_name='title')" .
302				" LEFT JOIN `##gedcom_setting`      gs2 ON (g.gedcom_id=gs2.gedcom_id AND gs2.setting_name='imported')" .
303				" LEFT JOIN `##gedcom_setting`      gs3 ON (g.gedcom_id=gs3.gedcom_id AND gs3.setting_name='REQUIRE_AUTHENTICATION')" .
304				" LEFT JOIN `##user_gedcom_setting` ugs ON (g.gedcom_id=ugs.gedcom_id AND ugs.setting_name='canedit' AND ugs.user_id=?)" .
305				" WHERE " .
306				"  g.gedcom_id>0 AND (" . // exclude the "template" tree
307				"    EXISTS (SELECT 1 FROM `##user_setting` WHERE user_id=? AND setting_name='canadmin' AND setting_value=1)" . // Admin sees all
308				"   ) OR (" .
309				"    (gs2.setting_value = 1 OR ugs.setting_value = 'admin') AND (" . // Allow imported trees, with either:
310				"     gs3.setting_value <> 1 OR" . // visitor access
311				"     IFNULL(ugs.setting_value, 'none')<>'none'" . // explicit access
312				"   )" .
313				"  )" .
314				" ORDER BY g.sort_order, 3"
315			)->execute([Auth::id(), Auth::id()])->fetchAll();
316			foreach ($rows as $row) {
317				self::$trees[$row->tree_name] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
318			}
319		}
320
321		return self::$trees;
322	}
323
324	/**
325	 * Find the tree with a specific ID.
326	 *
327	 * @param int $tree_id
328	 *
329	 * @throws \DomainException
330	 *
331	 * @return Tree
332	 */
333	public static function findById($tree_id) {
334		foreach (self::getAll() as $tree) {
335			if ($tree->tree_id == $tree_id) {
336				return $tree;
337			}
338		}
339		throw new \DomainException;
340	}
341
342	/**
343	 * Find the tree with a specific name.
344	 *
345	 * @param string $tree_name
346	 *
347	 * @return Tree|null
348	 */
349	public static function findByName($tree_name) {
350		foreach (self::getAll() as $tree) {
351			if ($tree->name === $tree_name) {
352				return $tree;
353			}
354		}
355
356		return null;
357	}
358
359	/**
360	 * Create arguments to select_edit_control()
361	 * Note - these will be escaped later
362	 *
363	 * @return string[]
364	 */
365	public static function getIdList() {
366		$list = [];
367		foreach (self::getAll() as $tree) {
368			$list[$tree->tree_id] = $tree->title;
369		}
370
371		return $list;
372	}
373
374	/**
375	 * Create arguments to select_edit_control()
376	 * Note - these will be escaped later
377	 *
378	 * @return string[]
379	 */
380	public static function getNameList() {
381		$list = [];
382		foreach (self::getAll() as $tree) {
383			$list[$tree->name] = $tree->title;
384		}
385
386		return $list;
387	}
388
389	/**
390	 * Create a new tree
391	 *
392	 * @param string $tree_name
393	 * @param string $tree_title
394	 *
395	 * @return Tree
396	 */
397	public static function create($tree_name, $tree_title) {
398		try {
399			// Create a new tree
400			Database::prepare(
401				"INSERT INTO `##gedcom` (gedcom_name) VALUES (?)"
402			)->execute([$tree_name]);
403			$tree_id = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
404		} catch (PDOException $ex) {
405			DebugBar::addThrowable($ex);
406
407			// A tree with that name already exists?
408			return self::findByName($tree_name);
409		}
410
411		// Update the list of trees - to include this new one
412		self::$trees = null;
413		$tree        = self::findById($tree_id);
414
415		$tree->setPreference('imported', '0');
416		$tree->setPreference('title', $tree_title);
417
418		// Module privacy
419		Module::setDefaultAccess($tree_id);
420
421		// Set preferences from default tree
422		Database::prepare(
423			"INSERT INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
424			" SELECT :tree_id, setting_name, setting_value" .
425			" FROM `##gedcom_setting` WHERE gedcom_id = -1"
426		)->execute([
427			'tree_id' => $tree_id,
428		]);
429
430		Database::prepare(
431			"INSERT INTO `##default_resn` (gedcom_id, tag_type, resn)" .
432			" SELECT :tree_id, tag_type, resn" .
433			" FROM `##default_resn` WHERE gedcom_id = -1"
434		)->execute([
435			'tree_id' => $tree_id,
436		]);
437
438		Database::prepare(
439			"INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" .
440			" SELECT :tree_id, location, block_order, module_name" .
441			" FROM `##block` WHERE gedcom_id = -1"
442		)->execute([
443			'tree_id' => $tree_id,
444		]);
445
446		// Gedcom and privacy settings
447		$tree->setPreference('CONTACT_USER_ID', Auth::id());
448		$tree->setPreference('WEBMASTER_USER_ID', Auth::id());
449		$tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
450		switch (WT_LOCALE) {
451			case 'es':
452				$tree->setPreference('SURNAME_TRADITION', 'spanish');
453				break;
454			case 'is':
455				$tree->setPreference('SURNAME_TRADITION', 'icelandic');
456				break;
457			case 'lt':
458				$tree->setPreference('SURNAME_TRADITION', 'lithuanian');
459				break;
460			case 'pl':
461				$tree->setPreference('SURNAME_TRADITION', 'polish');
462				break;
463			case 'pt':
464			case 'pt-BR':
465				$tree->setPreference('SURNAME_TRADITION', 'portuguese');
466				break;
467			default:
468				$tree->setPreference('SURNAME_TRADITION', 'paternal');
469				break;
470		}
471
472		// Genealogy data
473		// It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
474		$john_doe = /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */ I18N::translate('John /DOE/');
475		$note     = I18N::translate('Edit this individual and replace their details with your own.');
476		Database::prepare("INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)")->execute([
477			$tree_id,
478			"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",
479		]);
480
481		// Update our cache
482		self::$trees[$tree->tree_id] = $tree;
483
484		return $tree;
485	}
486
487	/**
488	 * Are there any pending edits for this tree, than need reviewing by a moderator.
489	 *
490	 * @return bool
491	 */
492	public function hasPendingEdit() {
493		return (bool) Database::prepare(
494			"SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
495		)->execute([
496			'tree_id' => $this->tree_id,
497		])->fetchOne();
498	}
499
500	/**
501	 * Delete all the genealogy data from a tree - in preparation for importing
502	 * new data. Optionally retain the media data, for when the user has been
503	 * editing their data offline using an application which deletes (or does not
504	 * support) media data.
505	 *
506	 * @param bool $keep_media
507	 */
508	public function deleteGenealogyData($keep_media) {
509		Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute([$this->tree_id]);
510		Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute([$this->tree_id]);
511		Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute([$this->tree_id]);
512		Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute([$this->tree_id]);
513		Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute([$this->tree_id]);
514		Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute([$this->tree_id]);
515		Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute([$this->tree_id]);
516		Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute([$this->tree_id]);
517		Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute([$this->tree_id]);
518		Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute([$this->tree_id]);
519
520		if ($keep_media) {
521			Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute([$this->tree_id]);
522		} else {
523			Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute([$this->tree_id]);
524			Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute([$this->tree_id]);
525			Database::prepare("DELETE FROM `##media_file` WHERE m_file =?")->execute([$this->tree_id]);
526		}
527	}
528
529	/**
530	 * Delete everything relating to a tree
531	 */
532	public function delete() {
533		// If this is the default tree, then unset it
534		if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
535			Site::setPreference('DEFAULT_GEDCOM', '');
536		}
537
538		$this->deleteGenealogyData(false);
539
540		Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute([$this->tree_id]);
541		Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute([$this->tree_id]);
542		Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute([$this->tree_id]);
543		Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
544		Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
545		Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute([$this->tree_id]);
546		Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
547		Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
548		Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute([$this->tree_id]);
549		Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute([$this->tree_id]);
550
551		// After updating the database, we need to fetch a new (sorted) copy
552		self::$trees = null;
553	}
554
555	/**
556	 * Export the tree to a GEDCOM file
557	 *
558	 * @param resource $stream
559	 */
560	public function exportGedcom($stream) {
561		$stmt = Database::prepare(
562			"SELECT i_gedcom AS gedcom, i_id AS xref, 1 AS n FROM `##individuals` WHERE i_file = :tree_id_1" .
563			" UNION ALL " .
564			"SELECT f_gedcom AS gedcom, f_id AS xref, 2 AS n FROM `##families`    WHERE f_file = :tree_id_2" .
565			" UNION ALL " .
566			"SELECT s_gedcom AS gedcom, s_id AS xref, 3 AS n FROM `##sources`     WHERE s_file = :tree_id_3" .
567			" UNION ALL " .
568			"SELECT o_gedcom AS gedcom, o_id AS xref, 4 AS n FROM `##other`       WHERE o_file = :tree_id_4 AND o_type NOT IN ('HEAD', 'TRLR')" .
569			" UNION ALL " .
570			"SELECT m_gedcom AS gedcom, m_id AS xref, 5 AS n FROM `##media`       WHERE m_file = :tree_id_5" .
571			" ORDER BY n, LENGTH(xref), xref"
572		)->execute([
573			'tree_id_1' => $this->tree_id,
574			'tree_id_2' => $this->tree_id,
575			'tree_id_3' => $this->tree_id,
576			'tree_id_4' => $this->tree_id,
577			'tree_id_5' => $this->tree_id,
578		]);
579
580		$buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this));
581		while (($row = $stmt->fetch()) !== false) {
582			$buffer .= FunctionsExport::reformatRecord($row->gedcom);
583			if (strlen($buffer) > 65535) {
584				fwrite($stream, $buffer);
585				$buffer = '';
586			}
587		}
588		fwrite($stream, $buffer . '0 TRLR' . WT_EOL);
589		$stmt->closeCursor();
590	}
591
592	/**
593	 * Import data from a gedcom file into this tree.
594	 *
595	 * @param string  $path       The full path to the (possibly temporary) file.
596	 * @param string  $filename   The preferred filename, for export/download.
597	 *
598	 * @throws \Exception
599	 */
600	public function importGedcomFile($path, $filename) {
601		// Read the file in blocks of roughly 64K. Ensure that each block
602		// contains complete gedcom records. This will ensure we don’t split
603		// multi-byte characters, as well as simplifying the code to import
604		// each block.
605
606		$file_data = '';
607		$fp        = fopen($path, 'rb');
608
609		// Don’t allow the user to cancel the request. We do not want to be left with an incomplete transaction.
610		ignore_user_abort(true);
611
612		Database::beginTransaction();
613		$this->deleteGenealogyData($this->getPreference('keep_media'));
614		$this->setPreference('gedcom_filename', $filename);
615		$this->setPreference('imported', '0');
616
617		while (!feof($fp)) {
618			$file_data .= fread($fp, 65536);
619			// There is no strrpos() function that searches for substrings :-(
620			for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
621				if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
622					// We’ve found the last record boundary in this chunk of data
623					break;
624				}
625			}
626			if ($pos) {
627				Database::prepare(
628					"INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
629				)->execute([$this->tree_id, substr($file_data, 0, $pos)]);
630				$file_data = substr($file_data, $pos);
631			}
632		}
633		Database::prepare(
634			"INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
635		)->execute([$this->tree_id, $file_data]);
636
637		Database::commit();
638		fclose($fp);
639	}
640
641	/**
642	 * Generate a new XREF, unique across all family trees
643	 *
644	 * @return string
645	 */
646	public function getNewXref() {
647		$prefix = 'X';
648
649		$increment = 1.0;
650		do {
651			// Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See
652			// http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
653			$statement = Database::prepare(
654				"UPDATE `##site_setting` SET setting_value = LAST_INSERT_ID(setting_value + :increment) WHERE setting_name = 'next_xref'"
655			);
656			$statement->execute([
657				'increment'   => (int) $increment,
658			]);
659
660			if ($statement->rowCount() === 0) {
661				// First time we've used this record type.
662				Site::setPreference('next_xref', '1');
663				$num = 1;
664			} else {
665				$num = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
666			}
667
668			$xref = $prefix . $num;
669
670			// Records may already exist with this sequence number.
671			$already_used = Database::prepare(
672				"SELECT" .
673				" EXISTS (SELECT 1 FROM `##individuals` WHERE i_id = :i_id) OR" .
674				" EXISTS (SELECT 1 FROM `##families` WHERE f_id = :f_id) OR" .
675				" EXISTS (SELECT 1 FROM `##sources` WHERE s_id = :s_id) OR" .
676				" EXISTS (SELECT 1 FROM `##media` WHERE m_id = :m_id) OR" .
677				" EXISTS (SELECT 1 FROM `##other` WHERE o_id = :o_id) OR" .
678				" EXISTS (SELECT 1 FROM `##change` WHERE xref = :xref)"
679			)->execute([
680				'i_id' => $xref,
681				'f_id' => $xref,
682				's_id' => $xref,
683				'm_id' => $xref,
684				'o_id' => $xref,
685				'xref' => $xref,
686			])->fetchOne();
687
688			// This exponential increment allows us to scan over large blocks of
689			// existing data in a reasonable time.
690			$increment *= 1.01;
691		} while ($already_used !== '0');
692
693		return $xref;
694	}
695
696	/**
697	 * Create a new record from GEDCOM data.
698	 *
699	 * @param string $gedcom
700	 *
701	 * @throws \Exception
702	 *
703	 * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
704	 */
705	public function createRecord($gedcom) {
706		if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom, $match)) {
707			$xref = $match[1];
708			$type = $match[2];
709		} else {
710			throw new \Exception('Invalid argument to GedcomRecord::createRecord(' . $gedcom . ')');
711		}
712		if (strpos("\r", $gedcom) !== false) {
713			// MSDOS line endings will break things in horrible ways
714			throw new \Exception('Evil line endings found in GedcomRecord::createRecord(' . $gedcom . ')');
715		}
716
717		// webtrees creates XREFs containing digits. Anything else (e.g. “new”) is just a placeholder.
718		if (!preg_match('/\d/', $xref)) {
719			$xref   = $this->getNewXref();
720			$gedcom = preg_replace('/^0 @(' . WT_REGEX_XREF . ')@/', '0 @' . $xref . '@', $gedcom);
721		}
722
723		// Create a change record, if not already present
724		if (!preg_match('/\n1 CHAN/', $gedcom)) {
725			$gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
726		}
727
728		// Create a pending change
729		Database::prepare(
730			"INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
731		)->execute([
732			$this->tree_id,
733			$xref,
734			$gedcom,
735			Auth::id(),
736		]);
737
738		Log::addEditLog('Create: ' . $type . ' ' . $xref);
739
740		// Accept this pending change
741		if (Auth::user()->getPreference('auto_accept')) {
742			FunctionsImport::acceptAllChanges($xref, $this->tree_id);
743		}
744		// Return the newly created record. Note that since GedcomRecord
745		// has a cache of pending changes, we cannot use it to create a
746		// record with a newly created pending change.
747		return GedcomRecord::getInstance($xref, $this, $gedcom);
748	}
749}
750