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