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