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