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