xref: /webtrees/app/Tree.php (revision bd52fa32338513b5d44dc6b1b89178c1bbf60b6a)
1a25f0a04SGreg Roach<?php
2a25f0a04SGreg Roach/**
3a25f0a04SGreg Roach * webtrees: online genealogy
46bdf7674SGreg Roach * Copyright (C) 2017 webtrees development team
5a25f0a04SGreg Roach * This program is free software: you can redistribute it and/or modify
6a25f0a04SGreg Roach * it under the terms of the GNU General Public License as published by
7a25f0a04SGreg Roach * the Free Software Foundation, either version 3 of the License, or
8a25f0a04SGreg Roach * (at your option) any later version.
9a25f0a04SGreg Roach * This program is distributed in the hope that it will be useful,
10a25f0a04SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
11a25f0a04SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12a25f0a04SGreg Roach * GNU General Public License for more details.
13a25f0a04SGreg Roach * You should have received a copy of the GNU General Public License
14a25f0a04SGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
15a25f0a04SGreg Roach */
1676692c8bSGreg Roachnamespace Fisharebest\Webtrees;
17a25f0a04SGreg Roach
183d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsExport;
193d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
20a25f0a04SGreg Roachuse PDOException;
21a25f0a04SGreg Roach
22a25f0a04SGreg Roach/**
2376692c8bSGreg Roach * Provide an interface to the wt_gedcom table.
24a25f0a04SGreg Roach */
25a25f0a04SGreg Roachclass Tree {
26cbc1590aSGreg Roach	/** @var int The tree's ID number */
27518bbdc1SGreg Roach	private $tree_id;
28518bbdc1SGreg Roach
29a25f0a04SGreg Roach	/** @var string The tree's name */
30a25f0a04SGreg Roach	private $name;
31518bbdc1SGreg Roach
32a25f0a04SGreg Roach	/** @var string The tree's title */
33a25f0a04SGreg Roach	private $title;
34a25f0a04SGreg Roach
35e2052359SGreg Roach	/** @var int[] Default access rules for facts in this tree */
36518bbdc1SGreg Roach	private $fact_privacy;
37518bbdc1SGreg Roach
38e2052359SGreg Roach	/** @var int[] Default access rules for individuals in this tree */
39518bbdc1SGreg Roach	private $individual_privacy;
40518bbdc1SGreg Roach
41518bbdc1SGreg Roach	/** @var integer[][] Default access rules for individual facts in this tree */
42518bbdc1SGreg Roach	private $individual_fact_privacy;
43518bbdc1SGreg Roach
44a25f0a04SGreg Roach	/** @var Tree[] All trees that we have permission to see. */
45a25f0a04SGreg Roach	private static $trees;
46a25f0a04SGreg Roach
47a25f0a04SGreg Roach	/** @var string[] Cached copy of the wt_gedcom_setting table. */
4815d603e7SGreg Roach	private $preferences = [];
49a25f0a04SGreg Roach
50a25f0a04SGreg Roach	/** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
5113abd6f3SGreg Roach	private $user_preferences = [];
52a25f0a04SGreg Roach
53a25f0a04SGreg Roach	/**
54a25f0a04SGreg Roach	 * Create a tree object. This is a private constructor - it can only
55a25f0a04SGreg Roach	 * be called from Tree::getAll() to ensure proper initialisation.
56a25f0a04SGreg Roach	 *
57cbc1590aSGreg Roach	 * @param int    $tree_id
58a25f0a04SGreg Roach	 * @param string $tree_name
59a25f0a04SGreg Roach	 * @param string $tree_title
60a25f0a04SGreg Roach	 */
61518bbdc1SGreg Roach	private function __construct($tree_id, $tree_name, $tree_title) {
62518bbdc1SGreg Roach		$this->tree_id                 = $tree_id;
63a25f0a04SGreg Roach		$this->name                    = $tree_name;
64a25f0a04SGreg Roach		$this->title                   = $tree_title;
6513abd6f3SGreg Roach		$this->fact_privacy            = [];
6613abd6f3SGreg Roach		$this->individual_privacy      = [];
6713abd6f3SGreg Roach		$this->individual_fact_privacy = [];
68518bbdc1SGreg Roach
69518bbdc1SGreg Roach		// Load the privacy settings for this tree
70518bbdc1SGreg Roach		$rows = Database::prepare(
71518bbdc1SGreg Roach			"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" .
72518bbdc1SGreg Roach			" FROM `##default_resn` WHERE gedcom_id = :tree_id"
7313abd6f3SGreg Roach		)->execute([
744b9ff166SGreg Roach			'priv_public' => Auth::PRIV_PRIVATE,
754b9ff166SGreg Roach			'priv_user'   => Auth::PRIV_USER,
764b9ff166SGreg Roach			'priv_none'   => Auth::PRIV_NONE,
774b9ff166SGreg Roach			'priv_hide'   => Auth::PRIV_HIDE,
78cbc1590aSGreg Roach			'tree_id'     => $this->tree_id,
7913abd6f3SGreg Roach		])->fetchAll();
80518bbdc1SGreg Roach
81518bbdc1SGreg Roach		foreach ($rows as $row) {
82518bbdc1SGreg Roach			if ($row->xref !== null) {
83518bbdc1SGreg Roach				if ($row->tag_type !== null) {
84518bbdc1SGreg Roach					$this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
85518bbdc1SGreg Roach				} else {
86518bbdc1SGreg Roach					$this->individual_privacy[$row->xref] = (int) $row->resn;
87518bbdc1SGreg Roach				}
88518bbdc1SGreg Roach			} else {
89518bbdc1SGreg Roach				$this->fact_privacy[$row->tag_type] = (int) $row->resn;
90518bbdc1SGreg Roach			}
91518bbdc1SGreg Roach		}
92a25f0a04SGreg Roach	}
93a25f0a04SGreg Roach
94a25f0a04SGreg Roach	/**
95a25f0a04SGreg Roach	 * The ID of this tree
96a25f0a04SGreg Roach	 *
97cbc1590aSGreg Roach	 * @return int
98a25f0a04SGreg Roach	 */
99518bbdc1SGreg Roach	public function getTreeId() {
100518bbdc1SGreg Roach		return $this->tree_id;
101a25f0a04SGreg Roach	}
102a25f0a04SGreg Roach
103a25f0a04SGreg Roach	/**
104a25f0a04SGreg Roach	 * The name of this tree
105a25f0a04SGreg Roach	 *
106a25f0a04SGreg Roach	 * @return string
107a25f0a04SGreg Roach	 */
108000959d9SGreg Roach	public function getName() {
109a25f0a04SGreg Roach		return $this->name;
110a25f0a04SGreg Roach	}
111a25f0a04SGreg Roach
112a25f0a04SGreg Roach	/**
113a25f0a04SGreg Roach	 * The name of this tree
114a25f0a04SGreg Roach	 *
115a25f0a04SGreg Roach	 * @return string
116a25f0a04SGreg Roach	 */
117000959d9SGreg Roach	public function getNameHtml() {
118cc5ab399SGreg Roach		return Html::escape($this->name);
119a25f0a04SGreg Roach	}
120a25f0a04SGreg Roach
121a25f0a04SGreg Roach	/**
122a25f0a04SGreg Roach	 * The name of this tree
123a25f0a04SGreg Roach	 *
124a25f0a04SGreg Roach	 * @return string
125a25f0a04SGreg Roach	 */
126000959d9SGreg Roach	public function getNameUrl() {
12785ccaa18SGreg Roach		return rawurlencode($this->name);
128a25f0a04SGreg Roach	}
129a25f0a04SGreg Roach
130a25f0a04SGreg Roach	/**
131a25f0a04SGreg Roach	 * The title of this tree
132a25f0a04SGreg Roach	 *
133a25f0a04SGreg Roach	 * @return string
134a25f0a04SGreg Roach	 */
135000959d9SGreg Roach	public function getTitle() {
136a25f0a04SGreg Roach		return $this->title;
137a25f0a04SGreg Roach	}
138a25f0a04SGreg Roach
139a25f0a04SGreg Roach	/**
140a25f0a04SGreg Roach	 * The title of this tree, with HTML markup
141a25f0a04SGreg Roach	 *
142a25f0a04SGreg Roach	 * @return string
143a25f0a04SGreg Roach	 */
144000959d9SGreg Roach	public function getTitleHtml() {
145cc5ab399SGreg Roach		return '<span dir="auto">' . Html::escape($this->title) . '</span>';
146a25f0a04SGreg Roach	}
147a25f0a04SGreg Roach
148a25f0a04SGreg Roach	/**
149518bbdc1SGreg Roach	 * The fact-level privacy for this tree.
150518bbdc1SGreg Roach	 *
151e2052359SGreg Roach	 * @return int[]
152518bbdc1SGreg Roach	 */
153518bbdc1SGreg Roach	public function getFactPrivacy() {
154518bbdc1SGreg Roach		return $this->fact_privacy;
155518bbdc1SGreg Roach	}
156518bbdc1SGreg Roach
157518bbdc1SGreg Roach	/**
158518bbdc1SGreg Roach	 * The individual-level privacy for this tree.
159518bbdc1SGreg Roach	 *
160e2052359SGreg Roach	 * @return int[]
161518bbdc1SGreg Roach	 */
162518bbdc1SGreg Roach	public function getIndividualPrivacy() {
163518bbdc1SGreg Roach		return $this->individual_privacy;
164518bbdc1SGreg Roach	}
165518bbdc1SGreg Roach
166518bbdc1SGreg Roach	/**
167518bbdc1SGreg Roach	 * The individual-fact-level privacy for this tree.
168518bbdc1SGreg Roach	 *
1694f381cf1SGreg Roach	 * @return integer[][]
170518bbdc1SGreg Roach	 */
171518bbdc1SGreg Roach	public function getIndividualFactPrivacy() {
172518bbdc1SGreg Roach		return $this->individual_fact_privacy;
173518bbdc1SGreg Roach	}
174518bbdc1SGreg Roach
175518bbdc1SGreg Roach	/**
176a25f0a04SGreg Roach	 * Get the tree’s configuration settings.
177a25f0a04SGreg Roach	 *
178a25f0a04SGreg Roach	 * @param string $setting_name
17915d603e7SGreg Roach	 * @param string $default
180a25f0a04SGreg Roach	 *
18115d603e7SGreg Roach	 * @return string
182a25f0a04SGreg Roach	 */
18315d603e7SGreg Roach	public function getPreference($setting_name, $default = '') {
18415d603e7SGreg Roach		if (empty($this->preferences)) {
185a25f0a04SGreg Roach			$this->preferences = Database::prepare(
186a25f0a04SGreg Roach				"SELECT SQL_CACHE setting_name, setting_value FROM `##gedcom_setting` WHERE gedcom_id = ?"
18713abd6f3SGreg Roach			)->execute([$this->tree_id])->fetchAssoc();
188a25f0a04SGreg Roach		}
189a25f0a04SGreg Roach
190a25f0a04SGreg Roach		if (array_key_exists($setting_name, $this->preferences)) {
191a25f0a04SGreg Roach			return $this->preferences[$setting_name];
192a25f0a04SGreg Roach		} else {
193a25f0a04SGreg Roach			return $default;
194a25f0a04SGreg Roach		}
195a25f0a04SGreg Roach	}
196a25f0a04SGreg Roach
197a25f0a04SGreg Roach	/**
198a25f0a04SGreg Roach	 * Set the tree’s configuration settings.
199a25f0a04SGreg Roach	 *
200a25f0a04SGreg Roach	 * @param string $setting_name
201a25f0a04SGreg Roach	 * @param string $setting_value
202a25f0a04SGreg Roach	 *
203a25f0a04SGreg Roach	 * @return $this
204a25f0a04SGreg Roach	 */
205a25f0a04SGreg Roach	public function setPreference($setting_name, $setting_value) {
206a25f0a04SGreg Roach		if ($setting_value !== $this->getPreference($setting_name)) {
207a25f0a04SGreg Roach			Database::prepare(
208a25f0a04SGreg Roach				"REPLACE INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
209a25f0a04SGreg Roach				" VALUES (:tree_id, :setting_name, LEFT(:setting_value, 255))"
21013abd6f3SGreg Roach			)->execute([
211518bbdc1SGreg Roach				'tree_id'       => $this->tree_id,
212a25f0a04SGreg Roach				'setting_name'  => $setting_name,
213a25f0a04SGreg Roach				'setting_value' => $setting_value,
21413abd6f3SGreg Roach			]);
21515d603e7SGreg Roach
216a25f0a04SGreg Roach			$this->preferences[$setting_name] = $setting_value;
21715d603e7SGreg Roach
21872292b7dSGreg Roach			Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
219a25f0a04SGreg Roach		}
220a25f0a04SGreg Roach
221a25f0a04SGreg Roach		return $this;
222a25f0a04SGreg Roach	}
223a25f0a04SGreg Roach
224a25f0a04SGreg Roach	/**
225a25f0a04SGreg Roach	 * Get the tree’s user-configuration settings.
226a25f0a04SGreg Roach	 *
227a25f0a04SGreg Roach	 * @param User        $user
228a25f0a04SGreg Roach	 * @param string      $setting_name
229a25f0a04SGreg Roach	 * @param string|null $default
230a25f0a04SGreg Roach	 *
231a25f0a04SGreg Roach	 * @return string
232a25f0a04SGreg Roach	 */
233a25f0a04SGreg Roach	public function getUserPreference(User $user, $setting_name, $default = null) {
234a25f0a04SGreg Roach		// There are lots of settings, and we need to fetch lots of them on every page
235a25f0a04SGreg Roach		// so it is quicker to fetch them all in one go.
236a25f0a04SGreg Roach		if (!array_key_exists($user->getUserId(), $this->user_preferences)) {
237a25f0a04SGreg Roach			$this->user_preferences[$user->getUserId()] = Database::prepare(
238a25f0a04SGreg Roach				"SELECT SQL_CACHE setting_name, setting_value FROM `##user_gedcom_setting` WHERE user_id = ? AND gedcom_id = ?"
23913abd6f3SGreg Roach			)->execute([$user->getUserId(), $this->tree_id])->fetchAssoc();
240a25f0a04SGreg Roach		}
241a25f0a04SGreg Roach
242a25f0a04SGreg Roach		if (array_key_exists($setting_name, $this->user_preferences[$user->getUserId()])) {
243a25f0a04SGreg Roach			return $this->user_preferences[$user->getUserId()][$setting_name];
244a25f0a04SGreg Roach		} else {
245a25f0a04SGreg Roach			return $default;
246a25f0a04SGreg Roach		}
247a25f0a04SGreg Roach	}
248a25f0a04SGreg Roach
249a25f0a04SGreg Roach	/**
250a25f0a04SGreg Roach	 * Set the tree’s user-configuration settings.
251a25f0a04SGreg Roach	 *
252a25f0a04SGreg Roach	 * @param User    $user
253a25f0a04SGreg Roach	 * @param string  $setting_name
254a25f0a04SGreg Roach	 * @param string  $setting_value
255a25f0a04SGreg Roach	 *
256a25f0a04SGreg Roach	 * @return $this
257a25f0a04SGreg Roach	 */
258a25f0a04SGreg Roach	public function setUserPreference(User $user, $setting_name, $setting_value) {
259a25f0a04SGreg Roach		if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
260a25f0a04SGreg Roach			// Update the database
261a25f0a04SGreg Roach			if ($setting_value === null) {
262a25f0a04SGreg Roach				Database::prepare(
263a25f0a04SGreg Roach					"DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = :tree_id AND user_id = :user_id AND setting_name = :setting_name"
26413abd6f3SGreg Roach				)->execute([
265518bbdc1SGreg Roach					'tree_id'      => $this->tree_id,
266a25f0a04SGreg Roach					'user_id'      => $user->getUserId(),
267a25f0a04SGreg Roach					'setting_name' => $setting_name,
26813abd6f3SGreg Roach				]);
269a25f0a04SGreg Roach			} else {
270a25f0a04SGreg Roach				Database::prepare(
271a25f0a04SGreg Roach					"REPLACE INTO `##user_gedcom_setting` (user_id, gedcom_id, setting_name, setting_value) VALUES (:user_id, :tree_id, :setting_name, LEFT(:setting_value, 255))"
27213abd6f3SGreg Roach				)->execute([
273a25f0a04SGreg Roach					'user_id'       => $user->getUserId(),
274518bbdc1SGreg Roach					'tree_id'       => $this->tree_id,
275a25f0a04SGreg Roach					'setting_name'  => $setting_name,
276cbc1590aSGreg Roach					'setting_value' => $setting_value,
27713abd6f3SGreg Roach				]);
278a25f0a04SGreg Roach			}
279a25f0a04SGreg Roach			// Update our cache
280a25f0a04SGreg Roach			$this->user_preferences[$user->getUserId()][$setting_name] = $setting_value;
281a25f0a04SGreg Roach			// Audit log of changes
28272292b7dSGreg Roach			Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this);
283a25f0a04SGreg Roach		}
284a25f0a04SGreg Roach
285a25f0a04SGreg Roach		return $this;
286a25f0a04SGreg Roach	}
287a25f0a04SGreg Roach
288a25f0a04SGreg Roach	/**
289a25f0a04SGreg Roach	 * Can a user accept changes for this tree?
290a25f0a04SGreg Roach	 *
291a25f0a04SGreg Roach	 * @param User $user
292a25f0a04SGreg Roach	 *
293cbc1590aSGreg Roach	 * @return bool
294a25f0a04SGreg Roach	 */
295a25f0a04SGreg Roach	public function canAcceptChanges(User $user) {
296a25f0a04SGreg Roach		return Auth::isModerator($this, $user);
297a25f0a04SGreg Roach	}
298a25f0a04SGreg Roach
299a25f0a04SGreg Roach	/**
300a25f0a04SGreg Roach	 * Fetch all the trees that we have permission to access.
301a25f0a04SGreg Roach	 *
302a25f0a04SGreg Roach	 * @return Tree[]
303a25f0a04SGreg Roach	 */
304a25f0a04SGreg Roach	public static function getAll() {
305a25f0a04SGreg Roach		if (self::$trees === null) {
30613abd6f3SGreg Roach			self::$trees = [];
307a25f0a04SGreg Roach			$rows        = Database::prepare(
308a25f0a04SGreg Roach				"SELECT SQL_CACHE g.gedcom_id AS tree_id, g.gedcom_name AS tree_name, gs1.setting_value AS tree_title" .
309a25f0a04SGreg Roach				" FROM `##gedcom` g" .
310a25f0a04SGreg Roach				" LEFT JOIN `##gedcom_setting`      gs1 ON (g.gedcom_id=gs1.gedcom_id AND gs1.setting_name='title')" .
311a25f0a04SGreg Roach				" LEFT JOIN `##gedcom_setting`      gs2 ON (g.gedcom_id=gs2.gedcom_id AND gs2.setting_name='imported')" .
312a25f0a04SGreg Roach				" LEFT JOIN `##gedcom_setting`      gs3 ON (g.gedcom_id=gs3.gedcom_id AND gs3.setting_name='REQUIRE_AUTHENTICATION')" .
313a25f0a04SGreg Roach				" LEFT JOIN `##user_gedcom_setting` ugs ON (g.gedcom_id=ugs.gedcom_id AND ugs.setting_name='canedit' AND ugs.user_id=?)" .
314a25f0a04SGreg Roach				" WHERE " .
315a25f0a04SGreg Roach				"  g.gedcom_id>0 AND (" . // exclude the "template" tree
316a25f0a04SGreg Roach				"    EXISTS (SELECT 1 FROM `##user_setting` WHERE user_id=? AND setting_name='canadmin' AND setting_value=1)" . // Admin sees all
317a25f0a04SGreg Roach				"   ) OR (" .
3188cca4ddeSGreg Roach				"    (gs2.setting_value = 1 OR ugs.setting_value = 'admin') AND (" . // Allow imported trees, with either:
319a25f0a04SGreg Roach				"     gs3.setting_value <> 1 OR" . // visitor access
320a25f0a04SGreg Roach				"     IFNULL(ugs.setting_value, 'none')<>'none'" . // explicit access
321a25f0a04SGreg Roach				"   )" .
322a25f0a04SGreg Roach				"  )" .
323a25f0a04SGreg Roach				" ORDER BY g.sort_order, 3"
32413abd6f3SGreg Roach			)->execute([Auth::id(), Auth::id()])->fetchAll();
325a25f0a04SGreg Roach			foreach ($rows as $row) {
32609c6c661SGreg Roach				self::$trees[] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
327a25f0a04SGreg Roach			}
328a25f0a04SGreg Roach		}
329a25f0a04SGreg Roach
330a25f0a04SGreg Roach		return self::$trees;
331a25f0a04SGreg Roach	}
332a25f0a04SGreg Roach
333a25f0a04SGreg Roach	/**
334d2cdeb3fSGreg Roach	 * Find the tree with a specific ID.
335a25f0a04SGreg Roach	 *
336cbc1590aSGreg Roach	 * @param int $tree_id
337cbc1590aSGreg Roach	 *
338cbc1590aSGreg Roach	 * @throws \DomainException
339a25f0a04SGreg Roach	 *
340a25f0a04SGreg Roach	 * @return Tree
341a25f0a04SGreg Roach	 */
342d2cdeb3fSGreg Roach	public static function findById($tree_id) {
34351d0f842SGreg Roach		foreach (self::getAll() as $tree) {
344e568acceSGreg Roach			if ($tree->tree_id == $tree_id) {
34551d0f842SGreg Roach				return $tree;
34651d0f842SGreg Roach			}
34751d0f842SGreg Roach		}
34851d0f842SGreg Roach		throw new \DomainException;
349a25f0a04SGreg Roach	}
350a25f0a04SGreg Roach
351a25f0a04SGreg Roach	/**
352d2cdeb3fSGreg Roach	 * Find the tree with a specific name.
353cf4bcc09SGreg Roach	 *
354cf4bcc09SGreg Roach	 * @param string $tree_name
355cf4bcc09SGreg Roach	 *
356cf4bcc09SGreg Roach	 * @return Tree|null
357cf4bcc09SGreg Roach	 */
358cf4bcc09SGreg Roach	public static function findByName($tree_name) {
359cf4bcc09SGreg Roach		foreach (self::getAll() as $tree) {
36051d0f842SGreg Roach			if ($tree->name === $tree_name) {
361cf4bcc09SGreg Roach				return $tree;
362cf4bcc09SGreg Roach			}
363cf4bcc09SGreg Roach		}
364cf4bcc09SGreg Roach
365cf4bcc09SGreg Roach		return null;
366cf4bcc09SGreg Roach	}
367cf4bcc09SGreg Roach
368cf4bcc09SGreg Roach	/**
369a25f0a04SGreg Roach	 * Create arguments to select_edit_control()
370a25f0a04SGreg Roach	 * Note - these will be escaped later
371a25f0a04SGreg Roach	 *
372a25f0a04SGreg Roach	 * @return string[]
373a25f0a04SGreg Roach	 */
374a25f0a04SGreg Roach	public static function getIdList() {
37513abd6f3SGreg Roach		$list = [];
376a25f0a04SGreg Roach		foreach (self::getAll() as $tree) {
377518bbdc1SGreg Roach			$list[$tree->tree_id] = $tree->title;
378a25f0a04SGreg Roach		}
379a25f0a04SGreg Roach
380a25f0a04SGreg Roach		return $list;
381a25f0a04SGreg Roach	}
382a25f0a04SGreg Roach
383a25f0a04SGreg Roach	/**
384a25f0a04SGreg Roach	 * Create arguments to select_edit_control()
385a25f0a04SGreg Roach	 * Note - these will be escaped later
386a25f0a04SGreg Roach	 *
387a25f0a04SGreg Roach	 * @return string[]
388a25f0a04SGreg Roach	 */
389a25f0a04SGreg Roach	public static function getNameList() {
39013abd6f3SGreg Roach		$list = [];
391a25f0a04SGreg Roach		foreach (self::getAll() as $tree) {
392a25f0a04SGreg Roach			$list[$tree->name] = $tree->title;
393a25f0a04SGreg Roach		}
394a25f0a04SGreg Roach
395a25f0a04SGreg Roach		return $list;
396a25f0a04SGreg Roach	}
397a25f0a04SGreg Roach
398a25f0a04SGreg Roach	/**
399a25f0a04SGreg Roach	 * Create a new tree
400a25f0a04SGreg Roach	 *
401a25f0a04SGreg Roach	 * @param string $tree_name
402a25f0a04SGreg Roach	 * @param string $tree_title
403a25f0a04SGreg Roach	 *
404a25f0a04SGreg Roach	 * @return Tree
405a25f0a04SGreg Roach	 */
406a25f0a04SGreg Roach	public static function create($tree_name, $tree_title) {
407a25f0a04SGreg Roach		try {
408a25f0a04SGreg Roach			// Create a new tree
409a25f0a04SGreg Roach			Database::prepare(
410a25f0a04SGreg Roach				"INSERT INTO `##gedcom` (gedcom_name) VALUES (?)"
41113abd6f3SGreg Roach			)->execute([$tree_name]);
412a25f0a04SGreg Roach			$tree_id = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
413a25f0a04SGreg Roach		} catch (PDOException $ex) {
414*bd52fa32SGreg Roach			DebugBar::addThrowable($ex);
415*bd52fa32SGreg Roach
416a25f0a04SGreg Roach			// A tree with that name already exists?
417ef2fd529SGreg Roach			return self::findByName($tree_name);
418a25f0a04SGreg Roach		}
419a25f0a04SGreg Roach
420a25f0a04SGreg Roach		// Update the list of trees - to include this new one
421a25f0a04SGreg Roach		self::$trees = null;
422d2cdeb3fSGreg Roach		$tree        = self::findById($tree_id);
423a25f0a04SGreg Roach
424a25f0a04SGreg Roach		$tree->setPreference('imported', '0');
425a25f0a04SGreg Roach		$tree->setPreference('title', $tree_title);
426a25f0a04SGreg Roach
427a25f0a04SGreg Roach		// Module privacy
428a25f0a04SGreg Roach		Module::setDefaultAccess($tree_id);
429a25f0a04SGreg Roach
4301507cbcaSGreg Roach		// Set preferences from default tree
4311507cbcaSGreg Roach		Database::prepare(
4321507cbcaSGreg Roach			"INSERT INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
4331507cbcaSGreg Roach			" SELECT :tree_id, setting_name, setting_value" .
4341507cbcaSGreg Roach			" FROM `##gedcom_setting` WHERE gedcom_id = -1"
43513abd6f3SGreg Roach		)->execute([
4361507cbcaSGreg Roach			'tree_id' => $tree_id,
43713abd6f3SGreg Roach		]);
4381507cbcaSGreg Roach
4391507cbcaSGreg Roach		Database::prepare(
4401507cbcaSGreg Roach			"INSERT INTO `##default_resn` (gedcom_id, tag_type, resn)" .
4411507cbcaSGreg Roach			" SELECT :tree_id, tag_type, resn" .
4421507cbcaSGreg Roach			" FROM `##default_resn` WHERE gedcom_id = -1"
44313abd6f3SGreg Roach		)->execute([
4441507cbcaSGreg Roach			'tree_id' => $tree_id,
44513abd6f3SGreg Roach		]);
4461507cbcaSGreg Roach
4471507cbcaSGreg Roach		Database::prepare(
4481507cbcaSGreg Roach			"INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" .
4491507cbcaSGreg Roach			" SELECT :tree_id, location, block_order, module_name" .
4501507cbcaSGreg Roach			" FROM `##block` WHERE gedcom_id = -1"
45113abd6f3SGreg Roach		)->execute([
4521507cbcaSGreg Roach			'tree_id' => $tree_id,
45313abd6f3SGreg Roach		]);
4541507cbcaSGreg Roach
455a25f0a04SGreg Roach		// Gedcom and privacy settings
456a25f0a04SGreg Roach		$tree->setPreference('CONTACT_USER_ID', Auth::id());
4571507cbcaSGreg Roach		$tree->setPreference('WEBMASTER_USER_ID', Auth::id());
458a25f0a04SGreg Roach		$tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
459a25f0a04SGreg Roach		switch (WT_LOCALE) {
460a25f0a04SGreg Roach		case 'es':
461a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'spanish');
462a25f0a04SGreg Roach			break;
463a25f0a04SGreg Roach		case 'is':
464a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'icelandic');
465a25f0a04SGreg Roach			break;
466a25f0a04SGreg Roach		case 'lt':
467a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'lithuanian');
468a25f0a04SGreg Roach			break;
469a25f0a04SGreg Roach		case 'pl':
470a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'polish');
471a25f0a04SGreg Roach			break;
472a25f0a04SGreg Roach		case 'pt':
473a25f0a04SGreg Roach		case 'pt-BR':
474a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'portuguese');
475a25f0a04SGreg Roach			break;
476a25f0a04SGreg Roach		default:
477a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'paternal');
478a25f0a04SGreg Roach			break;
479a25f0a04SGreg Roach		}
480a25f0a04SGreg Roach
481a25f0a04SGreg Roach		// Genealogy data
482a25f0a04SGreg Roach		// It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
4830fd39724SGreg Roach		$john_doe = /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */ I18N::translate('John /DOE/');
48477e70a22SGreg Roach		$note     = I18N::translate('Edit this individual and replace their details with your own.');
48513abd6f3SGreg Roach		Database::prepare("INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)")->execute([
486a25f0a04SGreg Roach			$tree_id,
487cbc1590aSGreg Roach			"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",
48813abd6f3SGreg Roach		]);
489a25f0a04SGreg Roach
490a25f0a04SGreg Roach		// Update our cache
491518bbdc1SGreg Roach		self::$trees[$tree->tree_id] = $tree;
492a25f0a04SGreg Roach
493a25f0a04SGreg Roach		return $tree;
494a25f0a04SGreg Roach	}
495a25f0a04SGreg Roach
496a25f0a04SGreg Roach	/**
497b78374c5SGreg Roach	 * Are there any pending edits for this tree, than need reviewing by a moderator.
498b78374c5SGreg Roach	 *
499b78374c5SGreg Roach	 * @return bool
500b78374c5SGreg Roach	 */
501b78374c5SGreg Roach	public function hasPendingEdit() {
502b78374c5SGreg Roach		return (bool) Database::prepare(
503b78374c5SGreg Roach			"SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
50413abd6f3SGreg Roach		)->execute([
505cbc1590aSGreg Roach			'tree_id' => $this->tree_id,
50613abd6f3SGreg Roach		])->fetchOne();
507b78374c5SGreg Roach	}
508b78374c5SGreg Roach
509b78374c5SGreg Roach	/**
510a25f0a04SGreg Roach	 * Delete all the genealogy data from a tree - in preparation for importing
511a25f0a04SGreg Roach	 * new data. Optionally retain the media data, for when the user has been
512a25f0a04SGreg Roach	 * editing their data offline using an application which deletes (or does not
513a25f0a04SGreg Roach	 * support) media data.
514a25f0a04SGreg Roach	 *
515a25f0a04SGreg Roach	 * @param bool $keep_media
516a25f0a04SGreg Roach	 */
517a25f0a04SGreg Roach	public function deleteGenealogyData($keep_media) {
51813abd6f3SGreg Roach		Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute([$this->tree_id]);
51913abd6f3SGreg Roach		Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute([$this->tree_id]);
52013abd6f3SGreg Roach		Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute([$this->tree_id]);
52113abd6f3SGreg Roach		Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute([$this->tree_id]);
52213abd6f3SGreg Roach		Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute([$this->tree_id]);
52313abd6f3SGreg Roach		Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute([$this->tree_id]);
52413abd6f3SGreg Roach		Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute([$this->tree_id]);
52513abd6f3SGreg Roach		Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute([$this->tree_id]);
52613abd6f3SGreg Roach		Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute([$this->tree_id]);
52713abd6f3SGreg Roach		Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute([$this->tree_id]);
528a25f0a04SGreg Roach
529a25f0a04SGreg Roach		if ($keep_media) {
53013abd6f3SGreg Roach			Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute([$this->tree_id]);
531a25f0a04SGreg Roach		} else {
53213abd6f3SGreg Roach			Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute([$this->tree_id]);
53313abd6f3SGreg Roach			Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute([$this->tree_id]);
534a25f0a04SGreg Roach		}
535a25f0a04SGreg Roach	}
536a25f0a04SGreg Roach
537a25f0a04SGreg Roach	/**
538a25f0a04SGreg Roach	 * Delete everything relating to a tree
539a25f0a04SGreg Roach	 */
540a25f0a04SGreg Roach	public function delete() {
541a25f0a04SGreg Roach		// If this is the default tree, then unset it
542ef2fd529SGreg Roach		if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
543a25f0a04SGreg Roach			Site::setPreference('DEFAULT_GEDCOM', '');
544a25f0a04SGreg Roach		}
545a25f0a04SGreg Roach
546a25f0a04SGreg Roach		$this->deleteGenealogyData(false);
547a25f0a04SGreg Roach
54813abd6f3SGreg Roach		Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute([$this->tree_id]);
54913abd6f3SGreg Roach		Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute([$this->tree_id]);
55013abd6f3SGreg Roach		Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute([$this->tree_id]);
55113abd6f3SGreg Roach		Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
55213abd6f3SGreg Roach		Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
55313abd6f3SGreg Roach		Database::prepare("DELETE FROM `##next_id`             WHERE gedcom_id = ?")->execute([$this->tree_id]);
55413abd6f3SGreg Roach		Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute([$this->tree_id]);
55513abd6f3SGreg Roach		Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
55613abd6f3SGreg Roach		Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
55713abd6f3SGreg Roach		Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute([$this->tree_id]);
55813abd6f3SGreg Roach		Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute([$this->tree_id]);
559a25f0a04SGreg Roach
560a25f0a04SGreg Roach		// After updating the database, we need to fetch a new (sorted) copy
561a25f0a04SGreg Roach		self::$trees = null;
562a25f0a04SGreg Roach	}
563a25f0a04SGreg Roach
564a25f0a04SGreg Roach	/**
565a25f0a04SGreg Roach	 * Export the tree to a GEDCOM file
566a25f0a04SGreg Roach	 *
5675792757eSGreg Roach	 * @param resource $stream
568a25f0a04SGreg Roach	 */
5695792757eSGreg Roach	public function exportGedcom($stream) {
5705792757eSGreg Roach		$stmt = Database::prepare(
571e56ef01aSGreg Roach			"SELECT i_gedcom AS gedcom, i_id AS xref, 1 AS n FROM `##individuals` WHERE i_file = :tree_id_1" .
5725792757eSGreg Roach			" UNION ALL " .
573e56ef01aSGreg Roach			"SELECT f_gedcom AS gedcom, f_id AS xref, 2 AS n FROM `##families`    WHERE f_file = :tree_id_2" .
5745792757eSGreg Roach			" UNION ALL " .
575e56ef01aSGreg Roach			"SELECT s_gedcom AS gedcom, s_id AS xref, 3 AS n FROM `##sources`     WHERE s_file = :tree_id_3" .
5765792757eSGreg Roach			" UNION ALL " .
577e56ef01aSGreg Roach			"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')" .
5785792757eSGreg Roach			" UNION ALL " .
579e56ef01aSGreg Roach			"SELECT m_gedcom AS gedcom, m_id AS xref, 5 AS n FROM `##media`       WHERE m_file = :tree_id_5" .
580e56ef01aSGreg Roach			" ORDER BY n, LENGTH(xref), xref"
58113abd6f3SGreg Roach		)->execute([
5825792757eSGreg Roach			'tree_id_1' => $this->tree_id,
5835792757eSGreg Roach			'tree_id_2' => $this->tree_id,
5845792757eSGreg Roach			'tree_id_3' => $this->tree_id,
5855792757eSGreg Roach			'tree_id_4' => $this->tree_id,
586cbc1590aSGreg Roach			'tree_id_5' => $this->tree_id,
58713abd6f3SGreg Roach		]);
588a25f0a04SGreg Roach
5893d7a8a4cSGreg Roach		$buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this));
590a25f0a04SGreg Roach		while ($row = $stmt->fetch()) {
5913d7a8a4cSGreg Roach			$buffer .= FunctionsExport::reformatRecord($row->gedcom);
592a25f0a04SGreg Roach			if (strlen($buffer) > 65535) {
5935792757eSGreg Roach				fwrite($stream, $buffer);
594a25f0a04SGreg Roach				$buffer = '';
595a25f0a04SGreg Roach			}
596a25f0a04SGreg Roach		}
5975792757eSGreg Roach		fwrite($stream, $buffer . '0 TRLR' . WT_EOL);
598195d09d8SGreg Roach		$stmt->closeCursor();
599a25f0a04SGreg Roach	}
600a25f0a04SGreg Roach
601a25f0a04SGreg Roach	/**
602a25f0a04SGreg Roach	 * Import data from a gedcom file into this tree.
603a25f0a04SGreg Roach	 *
604a25f0a04SGreg Roach	 * @param string  $path       The full path to the (possibly temporary) file.
605a25f0a04SGreg Roach	 * @param string  $filename   The preferred filename, for export/download.
606a25f0a04SGreg Roach	 *
607a25f0a04SGreg Roach	 * @throws \Exception
608a25f0a04SGreg Roach	 */
609ed1bbedbSGreg Roach	public function importGedcomFile($path, $filename) {
610a25f0a04SGreg Roach		// Read the file in blocks of roughly 64K. Ensure that each block
611a25f0a04SGreg Roach		// contains complete gedcom records. This will ensure we don’t split
612a25f0a04SGreg Roach		// multi-byte characters, as well as simplifying the code to import
613a25f0a04SGreg Roach		// each block.
614a25f0a04SGreg Roach
615a25f0a04SGreg Roach		$file_data = '';
616a25f0a04SGreg Roach		$fp        = fopen($path, 'rb');
617a25f0a04SGreg Roach
618a25f0a04SGreg Roach		// Don’t allow the user to cancel the request. We do not want to be left with an incomplete transaction.
619a25f0a04SGreg Roach		ignore_user_abort(true);
620a25f0a04SGreg Roach
621a25f0a04SGreg Roach		Database::beginTransaction();
622ed1bbedbSGreg Roach		$this->deleteGenealogyData($this->getPreference('keep_media'));
623a25f0a04SGreg Roach		$this->setPreference('gedcom_filename', $filename);
624a25f0a04SGreg Roach		$this->setPreference('imported', '0');
625a25f0a04SGreg Roach
626a25f0a04SGreg Roach		while (!feof($fp)) {
627a25f0a04SGreg Roach			$file_data .= fread($fp, 65536);
628a25f0a04SGreg Roach			// There is no strrpos() function that searches for substrings :-(
629a25f0a04SGreg Roach			for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
630a25f0a04SGreg Roach				if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
631a25f0a04SGreg Roach					// We’ve found the last record boundary in this chunk of data
632a25f0a04SGreg Roach					break;
633a25f0a04SGreg Roach				}
634a25f0a04SGreg Roach			}
635a25f0a04SGreg Roach			if ($pos) {
636a25f0a04SGreg Roach				Database::prepare(
637a25f0a04SGreg Roach					"INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
63813abd6f3SGreg Roach				)->execute([$this->tree_id, substr($file_data, 0, $pos)]);
639a25f0a04SGreg Roach				$file_data = substr($file_data, $pos);
640a25f0a04SGreg Roach			}
641a25f0a04SGreg Roach		}
642a25f0a04SGreg Roach		Database::prepare(
643a25f0a04SGreg Roach			"INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
64413abd6f3SGreg Roach		)->execute([$this->tree_id, $file_data]);
645a25f0a04SGreg Roach
646a25f0a04SGreg Roach		Database::commit();
647a25f0a04SGreg Roach		fclose($fp);
648a25f0a04SGreg Roach	}
649304f20d5SGreg Roach
650304f20d5SGreg Roach	/**
651b90d8accSGreg Roach	 * Generate a new XREF, unique across all family trees
652b90d8accSGreg Roach	 *
653b90d8accSGreg Roach	 * @param string $type
654b90d8accSGreg Roach	 *
655b90d8accSGreg Roach	 * @return string
656b90d8accSGreg Roach	 */
6570fb1a955SGreg Roach	public function getNewXref($type = 'INDI') {
658b90d8accSGreg Roach		/** @var string[] Which tree preference is used for which record type */
65913abd6f3SGreg Roach		static $type_to_preference = [
660b90d8accSGreg Roach			'INDI' => 'GEDCOM_ID_PREFIX',
661b90d8accSGreg Roach			'FAM'  => 'FAM_ID_PREFIX',
662b90d8accSGreg Roach			'OBJE' => 'MEDIA_ID_PREFIX',
663b90d8accSGreg Roach			'NOTE' => 'NOTE_ID_PREFIX',
664b90d8accSGreg Roach			'SOUR' => 'SOURCE_ID_PREFIX',
665b90d8accSGreg Roach			'REPO' => 'REPO_ID_PREFIX',
66613abd6f3SGreg Roach		];
667b90d8accSGreg Roach
668b90d8accSGreg Roach		if (array_key_exists($type, $type_to_preference)) {
669b90d8accSGreg Roach			$prefix = $this->getPreference($type_to_preference[$type]);
670b90d8accSGreg Roach		} else {
671b90d8accSGreg Roach			// Use the first non-underscore character
672b90d8accSGreg Roach			$prefix = substr(trim($type, '_'), 0, 1);
673b90d8accSGreg Roach		}
674b90d8accSGreg Roach
675971d66c8SGreg Roach		$increment = 1.0;
676b90d8accSGreg Roach		do {
677b90d8accSGreg Roach			// Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See
678b90d8accSGreg Roach			// http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
679b90d8accSGreg Roach			$statement = Database::prepare(
680971d66c8SGreg Roach				"UPDATE `##next_id` SET next_id = LAST_INSERT_ID(next_id + :increment) WHERE record_type = :record_type AND gedcom_id = :tree_id"
681b90d8accSGreg Roach			);
68213abd6f3SGreg Roach			$statement->execute([
683971d66c8SGreg Roach				'increment'   => (int) $increment,
684b90d8accSGreg Roach				'record_type' => $type,
685bb7c2cdcSGreg Roach				'tree_id'     => $this->tree_id,
68613abd6f3SGreg Roach			]);
687b90d8accSGreg Roach
688b90d8accSGreg Roach			if ($statement->rowCount() === 0) {
689b90d8accSGreg Roach				// First time we've used this record type.
690b90d8accSGreg Roach				Database::prepare(
691b90d8accSGreg Roach					"INSERT INTO `##next_id` (gedcom_id, record_type, next_id) VALUES(:tree_id, :record_type, 1)"
69213abd6f3SGreg Roach				)->execute([
693b90d8accSGreg Roach					'record_type' => $type,
694bb7c2cdcSGreg Roach					'tree_id'     => $this->tree_id,
69513abd6f3SGreg Roach				]);
696b90d8accSGreg Roach				$num = 1;
697b90d8accSGreg Roach			} else {
698b90d8accSGreg Roach				$num = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
699b90d8accSGreg Roach			}
700b90d8accSGreg Roach
701b90d8accSGreg Roach			// Records may already exist with this sequence number.
702b90d8accSGreg Roach			$already_used = Database::prepare(
703b90d8accSGreg Roach				"SELECT i_id FROM `##individuals` WHERE i_id = :i_id" .
704b90d8accSGreg Roach				" UNION ALL " .
705b90d8accSGreg Roach				"SELECT f_id FROM `##families` WHERE f_id = :f_id" .
706b90d8accSGreg Roach				" UNION ALL " .
707b90d8accSGreg Roach				"SELECT s_id FROM `##sources` WHERE s_id = :s_id" .
708b90d8accSGreg Roach				" UNION ALL " .
709b90d8accSGreg Roach				"SELECT m_id FROM `##media` WHERE m_id = :m_id" .
710b90d8accSGreg Roach				" UNION ALL " .
711b90d8accSGreg Roach				"SELECT o_id FROM `##other` WHERE o_id = :o_id" .
712b90d8accSGreg Roach				" UNION ALL " .
713b90d8accSGreg Roach				"SELECT xref FROM `##change` WHERE xref = :xref"
71413abd6f3SGreg Roach			)->execute([
715b90d8accSGreg Roach				'i_id' => $prefix . $num,
716b90d8accSGreg Roach				'f_id' => $prefix . $num,
717b90d8accSGreg Roach				's_id' => $prefix . $num,
718b90d8accSGreg Roach				'm_id' => $prefix . $num,
719b90d8accSGreg Roach				'o_id' => $prefix . $num,
720b90d8accSGreg Roach				'xref' => $prefix . $num,
72113abd6f3SGreg Roach			])->fetchOne();
722971d66c8SGreg Roach
723971d66c8SGreg Roach			// This exponential increment allows us to scan over large blocks of
724971d66c8SGreg Roach			// existing data in a reasonable time.
725971d66c8SGreg Roach			$increment *= 1.01;
726b90d8accSGreg Roach		} while ($already_used);
727b90d8accSGreg Roach
728b90d8accSGreg Roach		return $prefix . $num;
729b90d8accSGreg Roach	}
730b90d8accSGreg Roach
731b90d8accSGreg Roach	/**
732304f20d5SGreg Roach	 * Create a new record from GEDCOM data.
733304f20d5SGreg Roach	 *
734304f20d5SGreg Roach	 * @param string $gedcom
735304f20d5SGreg Roach	 *
736304f20d5SGreg Roach	 * @throws \Exception
737cbc1590aSGreg Roach	 *
73815d603e7SGreg Roach	 * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
739304f20d5SGreg Roach	 */
740304f20d5SGreg Roach	public function createRecord($gedcom) {
741304f20d5SGreg Roach		if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom, $match)) {
742304f20d5SGreg Roach			$xref = $match[1];
743304f20d5SGreg Roach			$type = $match[2];
744304f20d5SGreg Roach		} else {
745304f20d5SGreg Roach			throw new \Exception('Invalid argument to GedcomRecord::createRecord(' . $gedcom . ')');
746304f20d5SGreg Roach		}
747304f20d5SGreg Roach		if (strpos("\r", $gedcom) !== false) {
748304f20d5SGreg Roach			// MSDOS line endings will break things in horrible ways
749304f20d5SGreg Roach			throw new \Exception('Evil line endings found in GedcomRecord::createRecord(' . $gedcom . ')');
750304f20d5SGreg Roach		}
751304f20d5SGreg Roach
752304f20d5SGreg Roach		// webtrees creates XREFs containing digits. Anything else (e.g. “new”) is just a placeholder.
753304f20d5SGreg Roach		if (!preg_match('/\d/', $xref)) {
754b90d8accSGreg Roach			$xref   = $this->getNewXref($type);
755304f20d5SGreg Roach			$gedcom = preg_replace('/^0 @(' . WT_REGEX_XREF . ')@/', '0 @' . $xref . '@', $gedcom);
756304f20d5SGreg Roach		}
757304f20d5SGreg Roach
758304f20d5SGreg Roach		// Create a change record, if not already present
759304f20d5SGreg Roach		if (!preg_match('/\n1 CHAN/', $gedcom)) {
760304f20d5SGreg Roach			$gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
761304f20d5SGreg Roach		}
762304f20d5SGreg Roach
763304f20d5SGreg Roach		// Create a pending change
764304f20d5SGreg Roach		Database::prepare(
765304f20d5SGreg Roach			"INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
76613abd6f3SGreg Roach		)->execute([
767bb7c2cdcSGreg Roach			$this->tree_id,
768304f20d5SGreg Roach			$xref,
769304f20d5SGreg Roach			$gedcom,
770cbc1590aSGreg Roach			Auth::id(),
77113abd6f3SGreg Roach		]);
772304f20d5SGreg Roach
773304f20d5SGreg Roach		Log::addEditLog('Create: ' . $type . ' ' . $xref);
774304f20d5SGreg Roach
775304f20d5SGreg Roach		// Accept this pending change
776304f20d5SGreg Roach		if (Auth::user()->getPreference('auto_accept')) {
7773d7a8a4cSGreg Roach			FunctionsImport::acceptAllChanges($xref, $this->tree_id);
778304f20d5SGreg Roach		}
779bb7c2cdcSGreg Roach		// Return the newly created record. Note that since GedcomRecord
780bb7c2cdcSGreg Roach		// has a cache of pending changes, we cannot use it to create a
781bb7c2cdcSGreg Roach		// record with a newly created pending change.
78224ec66ceSGreg Roach		return GedcomRecord::getInstance($xref, $this, $gedcom);
783304f20d5SGreg Roach	}
784a25f0a04SGreg Roach}
785