xref: /webtrees/app/Tree.php (revision 3d7a8a4ca809135634f38216b734b15acff479f7)
1a25f0a04SGreg Roach<?php
2dd04c183SGreg Roachnamespace Fisharebest\Webtrees;
3a25f0a04SGreg Roach
4a25f0a04SGreg Roach/**
5a25f0a04SGreg Roach * webtrees: online genealogy
6a25f0a04SGreg Roach * Copyright (C) 2015 webtrees development team
7a25f0a04SGreg Roach * This program is free software: you can redistribute it and/or modify
8a25f0a04SGreg Roach * it under the terms of the GNU General Public License as published by
9a25f0a04SGreg Roach * the Free Software Foundation, either version 3 of the License, or
10a25f0a04SGreg Roach * (at your option) any later version.
11a25f0a04SGreg Roach * This program is distributed in the hope that it will be useful,
12a25f0a04SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
13a25f0a04SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14a25f0a04SGreg Roach * GNU General Public License for more details.
15a25f0a04SGreg Roach * You should have received a copy of the GNU General Public License
16a25f0a04SGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
17a25f0a04SGreg Roach */
18a25f0a04SGreg Roach
19*3d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsExport;
20*3d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
21a25f0a04SGreg Roachuse PDOException;
22a25f0a04SGreg Roach
23a25f0a04SGreg Roach/**
24a25f0a04SGreg Roach * Class Tree - Provide an interface to the wt_gedcom table
25a25f0a04SGreg Roach */
26a25f0a04SGreg Roachclass Tree {
27cbc1590aSGreg Roach	/** @var int The tree's ID number */
28518bbdc1SGreg Roach	private $tree_id;
29518bbdc1SGreg Roach
30a25f0a04SGreg Roach	/** @var string The tree's name */
31a25f0a04SGreg Roach	private $name;
32518bbdc1SGreg Roach
33a25f0a04SGreg Roach	/** @var string The tree's title */
34a25f0a04SGreg Roach	private $title;
35a25f0a04SGreg Roach
36518bbdc1SGreg Roach	/** @var integer[] Default access rules for facts in this tree */
37518bbdc1SGreg Roach	private $fact_privacy;
38518bbdc1SGreg Roach
39518bbdc1SGreg Roach	/** @var integer[] Default access rules for individuals in this tree */
40518bbdc1SGreg Roach	private $individual_privacy;
41518bbdc1SGreg Roach
42518bbdc1SGreg Roach	/** @var integer[][] Default access rules for individual facts in this tree */
43518bbdc1SGreg Roach	private $individual_fact_privacy;
44518bbdc1SGreg Roach
45a25f0a04SGreg Roach	/** @var Tree[] All trees that we have permission to see. */
46a25f0a04SGreg Roach	private static $trees;
47a25f0a04SGreg Roach
48a25f0a04SGreg Roach	/** @var string[] Cached copy of the wt_gedcom_setting table. */
49a25f0a04SGreg Roach	private $preferences;
50a25f0a04SGreg Roach
51a25f0a04SGreg Roach	/** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
52a25f0a04SGreg Roach	private $user_preferences = array();
53a25f0a04SGreg Roach
54a25f0a04SGreg Roach	/**
55a25f0a04SGreg Roach	 * Create a tree object.  This is a private constructor - it can only
56a25f0a04SGreg Roach	 * be called from Tree::getAll() to ensure proper initialisation.
57a25f0a04SGreg Roach	 *
58cbc1590aSGreg Roach	 * @param int    $tree_id
59a25f0a04SGreg Roach	 * @param string $tree_name
60a25f0a04SGreg Roach	 * @param string $tree_title
61a25f0a04SGreg Roach	 */
62518bbdc1SGreg Roach	private function __construct($tree_id, $tree_name, $tree_title) {
63518bbdc1SGreg Roach		$this->tree_id                 = $tree_id;
64a25f0a04SGreg Roach		$this->name                    = $tree_name;
65a25f0a04SGreg Roach		$this->title                   = $tree_title;
66518bbdc1SGreg Roach		$this->fact_privacy            = array();
67518bbdc1SGreg Roach		$this->individual_privacy      = array();
68518bbdc1SGreg Roach		$this->individual_fact_privacy = array();
69518bbdc1SGreg Roach
70518bbdc1SGreg Roach		// Load the privacy settings for this tree
71518bbdc1SGreg Roach		$rows = Database::prepare(
72518bbdc1SGreg 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" .
73518bbdc1SGreg Roach			" FROM `##default_resn` WHERE gedcom_id = :tree_id"
74518bbdc1SGreg Roach		)->execute(array(
754b9ff166SGreg Roach			'priv_public' => Auth::PRIV_PRIVATE,
764b9ff166SGreg Roach			'priv_user'   => Auth::PRIV_USER,
774b9ff166SGreg Roach			'priv_none'   => Auth::PRIV_NONE,
784b9ff166SGreg Roach			'priv_hide'   => Auth::PRIV_HIDE,
79cbc1590aSGreg Roach			'tree_id'     => $this->tree_id,
80518bbdc1SGreg Roach		))->fetchAll();
81518bbdc1SGreg Roach
82518bbdc1SGreg Roach		foreach ($rows as $row) {
83518bbdc1SGreg Roach			if ($row->xref !== null) {
84518bbdc1SGreg Roach				if ($row->tag_type !== null) {
85518bbdc1SGreg Roach					$this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
86518bbdc1SGreg Roach				} else {
87518bbdc1SGreg Roach					$this->individual_privacy[$row->xref] = (int) $row->resn;
88518bbdc1SGreg Roach				}
89518bbdc1SGreg Roach			} else {
90518bbdc1SGreg Roach				$this->fact_privacy[$row->tag_type] = (int) $row->resn;
91518bbdc1SGreg Roach			}
92518bbdc1SGreg Roach		}
93518bbdc1SGreg Roach
94a25f0a04SGreg Roach	}
95a25f0a04SGreg Roach
96a25f0a04SGreg Roach	/**
97a25f0a04SGreg Roach	 * The ID of this tree
98a25f0a04SGreg Roach	 *
99cbc1590aSGreg Roach	 * @return int
100a25f0a04SGreg Roach	 */
101518bbdc1SGreg Roach	public function getTreeId() {
102518bbdc1SGreg Roach		return $this->tree_id;
103a25f0a04SGreg Roach	}
104a25f0a04SGreg Roach
105a25f0a04SGreg Roach	/**
106a25f0a04SGreg Roach	 * The name of this tree
107a25f0a04SGreg Roach	 *
108a25f0a04SGreg Roach	 * @return string
109a25f0a04SGreg Roach	 */
110000959d9SGreg Roach	public function getName() {
111a25f0a04SGreg Roach		return $this->name;
112a25f0a04SGreg Roach	}
113a25f0a04SGreg Roach
114a25f0a04SGreg Roach	/**
115a25f0a04SGreg Roach	 * The name of this tree
116a25f0a04SGreg Roach	 *
117a25f0a04SGreg Roach	 * @return string
118a25f0a04SGreg Roach	 */
119000959d9SGreg Roach	public function getNameHtml() {
120a25f0a04SGreg Roach		return Filter::escapeHtml($this->name);
121a25f0a04SGreg Roach	}
122a25f0a04SGreg Roach
123a25f0a04SGreg Roach	/**
124a25f0a04SGreg Roach	 * The name of this tree
125a25f0a04SGreg Roach	 *
126a25f0a04SGreg Roach	 * @return string
127a25f0a04SGreg Roach	 */
128000959d9SGreg Roach	public function getNameUrl() {
129a25f0a04SGreg Roach		return Filter::escapeUrl($this->name);
130a25f0a04SGreg Roach	}
131a25f0a04SGreg Roach
132a25f0a04SGreg Roach	/**
133a25f0a04SGreg Roach	 * The title of this tree
134a25f0a04SGreg Roach	 *
135a25f0a04SGreg Roach	 * @return string
136a25f0a04SGreg Roach	 */
137000959d9SGreg Roach	public function getTitle() {
138a25f0a04SGreg Roach		return $this->title;
139a25f0a04SGreg Roach	}
140a25f0a04SGreg Roach
141a25f0a04SGreg Roach	/**
142a25f0a04SGreg Roach	 * The title of this tree, with HTML markup
143a25f0a04SGreg Roach	 *
144a25f0a04SGreg Roach	 * @return string
145a25f0a04SGreg Roach	 */
146000959d9SGreg Roach	public function getTitleHtml() {
147a77340e1SGreg Roach		return '<span dir="auto">' . Filter::escapeHtml($this->title) . '</span>';
148a25f0a04SGreg Roach	}
149a25f0a04SGreg Roach
150a25f0a04SGreg Roach	/**
151518bbdc1SGreg Roach	 * The fact-level privacy for this tree.
152518bbdc1SGreg Roach	 *
1534f381cf1SGreg Roach	 * @return integer[]
154518bbdc1SGreg Roach	 */
155518bbdc1SGreg Roach	public function getFactPrivacy() {
156518bbdc1SGreg Roach		return $this->fact_privacy;
157518bbdc1SGreg Roach	}
158518bbdc1SGreg Roach
159518bbdc1SGreg Roach	/**
160518bbdc1SGreg Roach	 * The individual-level privacy for this tree.
161518bbdc1SGreg Roach	 *
1624f381cf1SGreg Roach	 * @return integer[]
163518bbdc1SGreg Roach	 */
164518bbdc1SGreg Roach	public function getIndividualPrivacy() {
165518bbdc1SGreg Roach		return $this->individual_privacy;
166518bbdc1SGreg Roach	}
167518bbdc1SGreg Roach
168518bbdc1SGreg Roach	/**
169518bbdc1SGreg Roach	 * The individual-fact-level privacy for this tree.
170518bbdc1SGreg Roach	 *
1714f381cf1SGreg Roach	 * @return integer[][]
172518bbdc1SGreg Roach	 */
173518bbdc1SGreg Roach	public function getIndividualFactPrivacy() {
174518bbdc1SGreg Roach		return $this->individual_fact_privacy;
175518bbdc1SGreg Roach	}
176518bbdc1SGreg Roach
177518bbdc1SGreg Roach	/**
178a25f0a04SGreg Roach	 * Get the tree’s configuration settings.
179a25f0a04SGreg Roach	 *
180a25f0a04SGreg Roach	 * @param string      $setting_name
181a25f0a04SGreg Roach	 * @param string|null $default
182a25f0a04SGreg Roach	 *
183a25f0a04SGreg Roach	 * @return string|null
184a25f0a04SGreg Roach	 */
185a25f0a04SGreg Roach	public function getPreference($setting_name, $default = null) {
186a25f0a04SGreg Roach		if ($this->preferences === null) {
187a25f0a04SGreg Roach			$this->preferences = Database::prepare(
188a25f0a04SGreg Roach				"SELECT SQL_CACHE setting_name, setting_value FROM `##gedcom_setting` WHERE gedcom_id = ?"
189518bbdc1SGreg Roach			)->execute(array($this->tree_id))->fetchAssoc();
190a25f0a04SGreg Roach		}
191a25f0a04SGreg Roach
192a25f0a04SGreg Roach		if (array_key_exists($setting_name, $this->preferences)) {
193a25f0a04SGreg Roach			return $this->preferences[$setting_name];
194a25f0a04SGreg Roach		} else {
195a25f0a04SGreg Roach			return $default;
196a25f0a04SGreg Roach		}
197a25f0a04SGreg Roach	}
198a25f0a04SGreg Roach
199a25f0a04SGreg Roach	/**
200a25f0a04SGreg Roach	 * Set the tree’s configuration settings.
201a25f0a04SGreg Roach	 *
202a25f0a04SGreg Roach	 * @param string $setting_name
203a25f0a04SGreg Roach	 * @param string $setting_value
204a25f0a04SGreg Roach	 *
205a25f0a04SGreg Roach	 * @return $this
206a25f0a04SGreg Roach	 */
207a25f0a04SGreg Roach	public function setPreference($setting_name, $setting_value) {
208a25f0a04SGreg Roach		if ($setting_value !== $this->getPreference($setting_name)) {
209a25f0a04SGreg Roach			// Update the database
210a25f0a04SGreg Roach			if ($setting_value === null) {
211a25f0a04SGreg Roach				Database::prepare(
212a25f0a04SGreg Roach					"DELETE FROM `##gedcom_setting` WHERE gedcom_id = :tree_id AND setting_name = :setting_name"
213a25f0a04SGreg Roach				)->execute(array(
214518bbdc1SGreg Roach					'tree_id'      => $this->tree_id,
215a25f0a04SGreg Roach					'setting_name' => $setting_name,
216a25f0a04SGreg Roach				));
217a25f0a04SGreg Roach			} else {
218a25f0a04SGreg Roach				Database::prepare(
219a25f0a04SGreg Roach					"REPLACE INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
220a25f0a04SGreg Roach					" VALUES (:tree_id, :setting_name, LEFT(:setting_value, 255))"
221a25f0a04SGreg Roach				)->execute(array(
222518bbdc1SGreg Roach					'tree_id'       => $this->tree_id,
223a25f0a04SGreg Roach					'setting_name'  => $setting_name,
224a25f0a04SGreg Roach					'setting_value' => $setting_value,
225a25f0a04SGreg Roach				));
226a25f0a04SGreg Roach			}
227a25f0a04SGreg Roach			// Update our cache
228a25f0a04SGreg Roach			$this->preferences[$setting_name] = $setting_value;
229a25f0a04SGreg Roach			// Audit log of changes
230a25f0a04SGreg Roach			Log::addConfigurationLog('Tree setting "' . $setting_name . '" set to "' . $setting_value . '"', $this);
231a25f0a04SGreg Roach		}
232a25f0a04SGreg Roach
233a25f0a04SGreg Roach		return $this;
234a25f0a04SGreg Roach	}
235a25f0a04SGreg Roach
236a25f0a04SGreg Roach	/**
237a25f0a04SGreg Roach	 * Get the tree’s user-configuration settings.
238a25f0a04SGreg Roach	 *
239a25f0a04SGreg Roach	 * @param User        $user
240a25f0a04SGreg Roach	 * @param string      $setting_name
241a25f0a04SGreg Roach	 * @param string|null $default
242a25f0a04SGreg Roach	 *
243a25f0a04SGreg Roach	 * @return string
244a25f0a04SGreg Roach	 */
245a25f0a04SGreg Roach	public function getUserPreference(User $user, $setting_name, $default = null) {
246a25f0a04SGreg Roach		// There are lots of settings, and we need to fetch lots of them on every page
247a25f0a04SGreg Roach		// so it is quicker to fetch them all in one go.
248a25f0a04SGreg Roach		if (!array_key_exists($user->getUserId(), $this->user_preferences)) {
249a25f0a04SGreg Roach			$this->user_preferences[$user->getUserId()] = Database::prepare(
250a25f0a04SGreg Roach				"SELECT SQL_CACHE setting_name, setting_value FROM `##user_gedcom_setting` WHERE user_id = ? AND gedcom_id = ?"
251518bbdc1SGreg Roach			)->execute(array($user->getUserId(), $this->tree_id))->fetchAssoc();
252a25f0a04SGreg Roach		}
253a25f0a04SGreg Roach
254a25f0a04SGreg Roach		if (array_key_exists($setting_name, $this->user_preferences[$user->getUserId()])) {
255a25f0a04SGreg Roach			return $this->user_preferences[$user->getUserId()][$setting_name];
256a25f0a04SGreg Roach		} else {
257a25f0a04SGreg Roach			return $default;
258a25f0a04SGreg Roach		}
259a25f0a04SGreg Roach	}
260a25f0a04SGreg Roach
261a25f0a04SGreg Roach	/**
262a25f0a04SGreg Roach	 * Set the tree’s user-configuration settings.
263a25f0a04SGreg Roach	 *
264a25f0a04SGreg Roach	 * @param User    $user
265a25f0a04SGreg Roach	 * @param string  $setting_name
266a25f0a04SGreg Roach	 * @param string  $setting_value
267a25f0a04SGreg Roach	 *
268a25f0a04SGreg Roach	 * @return $this
269a25f0a04SGreg Roach	 */
270a25f0a04SGreg Roach	public function setUserPreference(User $user, $setting_name, $setting_value) {
271a25f0a04SGreg Roach		if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
272a25f0a04SGreg Roach			// Update the database
273a25f0a04SGreg Roach			if ($setting_value === null) {
274a25f0a04SGreg Roach				Database::prepare(
275a25f0a04SGreg Roach					"DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = :tree_id AND user_id = :user_id AND setting_name = :setting_name"
276a25f0a04SGreg Roach				)->execute(array(
277518bbdc1SGreg Roach					'tree_id'      => $this->tree_id,
278a25f0a04SGreg Roach					'user_id'      => $user->getUserId(),
279a25f0a04SGreg Roach					'setting_name' => $setting_name,
280a25f0a04SGreg Roach				));
281a25f0a04SGreg Roach			} else {
282a25f0a04SGreg Roach				Database::prepare(
283a25f0a04SGreg 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))"
284a25f0a04SGreg Roach				)->execute(array(
285a25f0a04SGreg Roach					'user_id'       => $user->getUserId(),
286518bbdc1SGreg Roach					'tree_id'       => $this->tree_id,
287a25f0a04SGreg Roach					'setting_name'  => $setting_name,
288cbc1590aSGreg Roach					'setting_value' => $setting_value,
289a25f0a04SGreg Roach				));
290a25f0a04SGreg Roach			}
291a25f0a04SGreg Roach			// Update our cache
292a25f0a04SGreg Roach			$this->user_preferences[$user->getUserId()][$setting_name] = $setting_value;
293a25f0a04SGreg Roach			// Audit log of changes
294a25f0a04SGreg Roach			Log::addConfigurationLog('Tree setting "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this);
295a25f0a04SGreg Roach		}
296a25f0a04SGreg Roach
297a25f0a04SGreg Roach		return $this;
298a25f0a04SGreg Roach	}
299a25f0a04SGreg Roach
300a25f0a04SGreg Roach	/**
301a25f0a04SGreg Roach	 * Can a user accept changes for this tree?
302a25f0a04SGreg Roach	 *
303a25f0a04SGreg Roach	 * @param User $user
304a25f0a04SGreg Roach	 *
305cbc1590aSGreg Roach	 * @return bool
306a25f0a04SGreg Roach	 */
307a25f0a04SGreg Roach	public function canAcceptChanges(User $user) {
308a25f0a04SGreg Roach		return Auth::isModerator($this, $user);
309a25f0a04SGreg Roach	}
310a25f0a04SGreg Roach
311a25f0a04SGreg Roach	/**
312a25f0a04SGreg Roach	 * Fetch all the trees that we have permission to access.
313a25f0a04SGreg Roach	 *
314a25f0a04SGreg Roach	 * @return Tree[]
315a25f0a04SGreg Roach	 */
316a25f0a04SGreg Roach	public static function getAll() {
317a25f0a04SGreg Roach		if (self::$trees === null) {
318a25f0a04SGreg Roach			self::$trees = array();
319a25f0a04SGreg Roach			$rows        = Database::prepare(
320a25f0a04SGreg Roach				"SELECT SQL_CACHE g.gedcom_id AS tree_id, g.gedcom_name AS tree_name, gs1.setting_value AS tree_title" .
321a25f0a04SGreg Roach				" FROM `##gedcom` g" .
322a25f0a04SGreg Roach				" LEFT JOIN `##gedcom_setting`      gs1 ON (g.gedcom_id=gs1.gedcom_id AND gs1.setting_name='title')" .
323a25f0a04SGreg Roach				" LEFT JOIN `##gedcom_setting`      gs2 ON (g.gedcom_id=gs2.gedcom_id AND gs2.setting_name='imported')" .
324a25f0a04SGreg Roach				" LEFT JOIN `##gedcom_setting`      gs3 ON (g.gedcom_id=gs3.gedcom_id AND gs3.setting_name='REQUIRE_AUTHENTICATION')" .
325a25f0a04SGreg Roach				" LEFT JOIN `##user_gedcom_setting` ugs ON (g.gedcom_id=ugs.gedcom_id AND ugs.setting_name='canedit' AND ugs.user_id=?)" .
326a25f0a04SGreg Roach				" WHERE " .
327a25f0a04SGreg Roach				"  g.gedcom_id>0 AND (" . // exclude the "template" tree
328a25f0a04SGreg Roach				"    EXISTS (SELECT 1 FROM `##user_setting` WHERE user_id=? AND setting_name='canadmin' AND setting_value=1)" . // Admin sees all
329a25f0a04SGreg Roach				"   ) OR (" .
330a25f0a04SGreg Roach				"    gs2.setting_value = 1 AND (" . // Allow imported trees, with either:
331a25f0a04SGreg Roach				"     gs3.setting_value <> 1 OR" . // visitor access
332a25f0a04SGreg Roach				"     IFNULL(ugs.setting_value, 'none')<>'none'" . // explicit access
333a25f0a04SGreg Roach				"   )" .
334a25f0a04SGreg Roach				"  )" .
335a25f0a04SGreg Roach				" ORDER BY g.sort_order, 3"
336a25f0a04SGreg Roach			)->execute(array(Auth::id(), Auth::id()))->fetchAll();
337a25f0a04SGreg Roach			foreach ($rows as $row) {
33809c6c661SGreg Roach				self::$trees[] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
339a25f0a04SGreg Roach			}
340a25f0a04SGreg Roach		}
341a25f0a04SGreg Roach
342a25f0a04SGreg Roach		return self::$trees;
343a25f0a04SGreg Roach	}
344a25f0a04SGreg Roach
345a25f0a04SGreg Roach	/**
346d2cdeb3fSGreg Roach	 * Find the tree with a specific ID.
347a25f0a04SGreg Roach	 *
348cbc1590aSGreg Roach	 * @param int $tree_id
349cbc1590aSGreg Roach	 *
350cbc1590aSGreg Roach	 * @throws \DomainException
351a25f0a04SGreg Roach	 *
352a25f0a04SGreg Roach	 * @return Tree
353a25f0a04SGreg Roach	 */
354d2cdeb3fSGreg Roach	public static function findById($tree_id) {
35551d0f842SGreg Roach		foreach (self::getAll() as $tree) {
356e568acceSGreg Roach			if ($tree->tree_id == $tree_id) {
35751d0f842SGreg Roach				return $tree;
35851d0f842SGreg Roach			}
35951d0f842SGreg Roach		}
36051d0f842SGreg Roach		throw new \DomainException;
361a25f0a04SGreg Roach	}
362a25f0a04SGreg Roach
363a25f0a04SGreg Roach	/**
364d2cdeb3fSGreg Roach	 * Find the tree with a specific name.
365cf4bcc09SGreg Roach	 *
366cf4bcc09SGreg Roach	 * @param string $tree_name
367cf4bcc09SGreg Roach	 *
368cf4bcc09SGreg Roach	 * @return Tree|null
369cf4bcc09SGreg Roach	 */
370cf4bcc09SGreg Roach	public static function findByName($tree_name) {
371cf4bcc09SGreg Roach		foreach (self::getAll() as $tree) {
37251d0f842SGreg Roach			if ($tree->name === $tree_name) {
373cf4bcc09SGreg Roach				return $tree;
374cf4bcc09SGreg Roach			}
375cf4bcc09SGreg Roach		}
376cf4bcc09SGreg Roach
377cf4bcc09SGreg Roach		return null;
378cf4bcc09SGreg Roach	}
379cf4bcc09SGreg Roach
380cf4bcc09SGreg Roach	/**
381a25f0a04SGreg Roach	 * Create arguments to select_edit_control()
382a25f0a04SGreg Roach	 * Note - these will be escaped later
383a25f0a04SGreg Roach	 *
384a25f0a04SGreg Roach	 * @return string[]
385a25f0a04SGreg Roach	 */
386a25f0a04SGreg Roach	public static function getIdList() {
387a25f0a04SGreg Roach		$list = array();
388a25f0a04SGreg Roach		foreach (self::getAll() as $tree) {
389518bbdc1SGreg Roach			$list[$tree->tree_id] = $tree->title;
390a25f0a04SGreg Roach		}
391a25f0a04SGreg Roach
392a25f0a04SGreg Roach		return $list;
393a25f0a04SGreg Roach	}
394a25f0a04SGreg Roach
395a25f0a04SGreg Roach	/**
396a25f0a04SGreg Roach	 * Create arguments to select_edit_control()
397a25f0a04SGreg Roach	 * Note - these will be escaped later
398a25f0a04SGreg Roach	 *
399a25f0a04SGreg Roach	 * @return string[]
400a25f0a04SGreg Roach	 */
401a25f0a04SGreg Roach	public static function getNameList() {
402a25f0a04SGreg Roach		$list = array();
403a25f0a04SGreg Roach		foreach (self::getAll() as $tree) {
404a25f0a04SGreg Roach			$list[$tree->name] = $tree->title;
405a25f0a04SGreg Roach		}
406a25f0a04SGreg Roach
407a25f0a04SGreg Roach		return $list;
408a25f0a04SGreg Roach	}
409a25f0a04SGreg Roach
410a25f0a04SGreg Roach	/**
411a25f0a04SGreg Roach	 * Create a new tree
412a25f0a04SGreg Roach	 *
413a25f0a04SGreg Roach	 * @param string $tree_name
414a25f0a04SGreg Roach	 * @param string $tree_title
415a25f0a04SGreg Roach	 *
416a25f0a04SGreg Roach	 * @return Tree
417a25f0a04SGreg Roach	 */
418a25f0a04SGreg Roach	public static function create($tree_name, $tree_title) {
419a25f0a04SGreg Roach		try {
420a25f0a04SGreg Roach			// Create a new tree
421a25f0a04SGreg Roach			Database::prepare(
422a25f0a04SGreg Roach				"INSERT INTO `##gedcom` (gedcom_name) VALUES (?)"
423a25f0a04SGreg Roach			)->execute(array($tree_name));
424a25f0a04SGreg Roach			$tree_id = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
425a25f0a04SGreg Roach		} catch (PDOException $ex) {
426a25f0a04SGreg Roach			// A tree with that name already exists?
427ef2fd529SGreg Roach			return self::findByName($tree_name);
428a25f0a04SGreg Roach		}
429a25f0a04SGreg Roach
430a25f0a04SGreg Roach		// Update the list of trees - to include this new one
431a25f0a04SGreg Roach		self::$trees = null;
432d2cdeb3fSGreg Roach		$tree        = self::findById($tree_id);
433a25f0a04SGreg Roach
434a25f0a04SGreg Roach		$tree->setPreference('imported', '0');
435a25f0a04SGreg Roach		$tree->setPreference('title', $tree_title);
436a25f0a04SGreg Roach
437a25f0a04SGreg Roach		// Module privacy
438a25f0a04SGreg Roach		Module::setDefaultAccess($tree_id);
439a25f0a04SGreg Roach
440a25f0a04SGreg Roach		// Gedcom and privacy settings
441a25f0a04SGreg Roach		$tree->setPreference('ADVANCED_NAME_FACTS', 'NICK,_AKA');
442a25f0a04SGreg Roach		$tree->setPreference('ADVANCED_PLAC_FACTS', '');
443a25f0a04SGreg Roach		$tree->setPreference('ALLOW_THEME_DROPDOWN', '1');
444a25f0a04SGreg Roach		$tree->setPreference('CALENDAR_FORMAT', 'gregorian');
445a25f0a04SGreg Roach		$tree->setPreference('CHART_BOX_TAGS', '');
446a25f0a04SGreg Roach		$tree->setPreference('COMMON_NAMES_ADD', '');
447a25f0a04SGreg Roach		$tree->setPreference('COMMON_NAMES_REMOVE', '');
448a25f0a04SGreg Roach		$tree->setPreference('COMMON_NAMES_THRESHOLD', '40');
449a25f0a04SGreg Roach		$tree->setPreference('CONTACT_USER_ID', Auth::id());
450a25f0a04SGreg Roach		$tree->setPreference('DEFAULT_PEDIGREE_GENERATIONS', '4');
451a25f0a04SGreg Roach		$tree->setPreference('EXPAND_RELATIVES_EVENTS', '0');
452a25f0a04SGreg Roach		$tree->setPreference('EXPAND_SOURCES', '0');
453a25f0a04SGreg Roach		$tree->setPreference('FAM_FACTS_ADD', 'CENS,MARR,RESI,SLGS,MARR_CIVIL,MARR_RELIGIOUS,MARR_PARTNERS,RESN');
454a25f0a04SGreg Roach		$tree->setPreference('FAM_FACTS_QUICK', 'MARR,DIV,_NMR');
455a25f0a04SGreg Roach		$tree->setPreference('FAM_FACTS_UNIQUE', 'NCHI,MARL,DIV,ANUL,DIVF,ENGA,MARB,MARC,MARS');
456a25f0a04SGreg Roach		$tree->setPreference('FAM_ID_PREFIX', 'F');
457a25f0a04SGreg Roach		$tree->setPreference('FORMAT_TEXT', 'markdown');
458a25f0a04SGreg Roach		$tree->setPreference('FULL_SOURCES', '0');
459a25f0a04SGreg Roach		$tree->setPreference('GEDCOM_ID_PREFIX', 'I');
460a25f0a04SGreg Roach		$tree->setPreference('GEDCOM_MEDIA_PATH', '');
461a25f0a04SGreg Roach		$tree->setPreference('GENERATE_UIDS', '0');
462a25f0a04SGreg Roach		$tree->setPreference('HIDE_GEDCOM_ERRORS', '1');
463a25f0a04SGreg Roach		$tree->setPreference('HIDE_LIVE_PEOPLE', '1');
464a25f0a04SGreg Roach		$tree->setPreference('INDI_FACTS_ADD', 'AFN,BIRT,DEAT,BURI,CREM,ADOP,BAPM,BARM,BASM,BLES,CHRA,CONF,FCOM,ORDN,NATU,EMIG,IMMI,CENS,PROB,WILL,GRAD,RETI,DSCR,EDUC,IDNO,NATI,NCHI,NMR,OCCU,PROP,RELI,RESI,SSN,TITL,BAPL,CONL,ENDL,SLGC,_MILI,ASSO,RESN');
465a25f0a04SGreg Roach		$tree->setPreference('INDI_FACTS_QUICK', 'BIRT,BURI,BAPM,CENS,DEAT,OCCU,RESI');
466a25f0a04SGreg Roach		$tree->setPreference('INDI_FACTS_UNIQUE', '');
467a25f0a04SGreg Roach		$tree->setPreference('KEEP_ALIVE_YEARS_BIRTH', '');
468a25f0a04SGreg Roach		$tree->setPreference('KEEP_ALIVE_YEARS_DEATH', '');
469a25f0a04SGreg Roach		$tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
470a25f0a04SGreg Roach		$tree->setPreference('MAX_ALIVE_AGE', 120);
471a25f0a04SGreg Roach		$tree->setPreference('MAX_DESCENDANCY_GENERATIONS', '15');
472a25f0a04SGreg Roach		$tree->setPreference('MAX_PEDIGREE_GENERATIONS', '10');
473a25f0a04SGreg Roach		$tree->setPreference('MEDIA_DIRECTORY', 'media/');
474a25f0a04SGreg Roach		$tree->setPreference('MEDIA_ID_PREFIX', 'M');
4754b9ff166SGreg Roach		$tree->setPreference('MEDIA_UPLOAD', Auth::PRIV_USER);
476a25f0a04SGreg Roach		$tree->setPreference('META_DESCRIPTION', '');
477a25f0a04SGreg Roach		$tree->setPreference('META_TITLE', WT_WEBTREES);
478a25f0a04SGreg Roach		$tree->setPreference('NOTE_FACTS_ADD', 'SOUR,RESN');
479a25f0a04SGreg Roach		$tree->setPreference('NOTE_FACTS_QUICK', '');
480a25f0a04SGreg Roach		$tree->setPreference('NOTE_FACTS_UNIQUE', '');
481a25f0a04SGreg Roach		$tree->setPreference('NOTE_ID_PREFIX', 'N');
482a25f0a04SGreg Roach		$tree->setPreference('NO_UPDATE_CHAN', '0');
483a25f0a04SGreg Roach		$tree->setPreference('PEDIGREE_FULL_DETAILS', '1');
484a25f0a04SGreg Roach		$tree->setPreference('PEDIGREE_LAYOUT', '1');
485a25f0a04SGreg Roach		$tree->setPreference('PEDIGREE_ROOT_ID', '');
486a25f0a04SGreg Roach		$tree->setPreference('PEDIGREE_SHOW_GENDER', '0');
487a25f0a04SGreg Roach		$tree->setPreference('PREFER_LEVEL2_SOURCES', '1');
488a25f0a04SGreg Roach		$tree->setPreference('QUICK_REQUIRED_FACTS', 'BIRT,DEAT');
489a25f0a04SGreg Roach		$tree->setPreference('QUICK_REQUIRED_FAMFACTS', 'MARR');
490a25f0a04SGreg Roach		$tree->setPreference('REPO_FACTS_ADD', 'PHON,EMAIL,FAX,WWW,RESN');
491a25f0a04SGreg Roach		$tree->setPreference('REPO_FACTS_QUICK', '');
492a25f0a04SGreg Roach		$tree->setPreference('REPO_FACTS_UNIQUE', 'NAME,ADDR');
493a25f0a04SGreg Roach		$tree->setPreference('REPO_ID_PREFIX', 'R');
494a25f0a04SGreg Roach		$tree->setPreference('REQUIRE_AUTHENTICATION', '0');
495a25f0a04SGreg Roach		$tree->setPreference('SAVE_WATERMARK_IMAGE', '0');
496a25f0a04SGreg Roach		$tree->setPreference('SAVE_WATERMARK_THUMB', '0');
497a25f0a04SGreg Roach		$tree->setPreference('SHOW_AGE_DIFF', '0');
498a25f0a04SGreg Roach		$tree->setPreference('SHOW_COUNTER', '1');
4994b9ff166SGreg Roach		$tree->setPreference('SHOW_DEAD_PEOPLE', Auth::PRIV_PRIVATE);
500a25f0a04SGreg Roach		$tree->setPreference('SHOW_EST_LIST_DATES', '0');
501a25f0a04SGreg Roach		$tree->setPreference('SHOW_FACT_ICONS', '1');
502a25f0a04SGreg Roach		$tree->setPreference('SHOW_GEDCOM_RECORD', '0');
503a25f0a04SGreg Roach		$tree->setPreference('SHOW_HIGHLIGHT_IMAGES', '1');
504a25f0a04SGreg Roach		$tree->setPreference('SHOW_LDS_AT_GLANCE', '0');
505a25f0a04SGreg Roach		$tree->setPreference('SHOW_LEVEL2_NOTES', '1');
5064b9ff166SGreg Roach		$tree->setPreference('SHOW_LIVING_NAMES', Auth::PRIV_USER);
507a25f0a04SGreg Roach		$tree->setPreference('SHOW_MEDIA_DOWNLOAD', '0');
5084b9ff166SGreg Roach		$tree->setPreference('SHOW_NO_WATERMARK', Auth::PRIV_USER);
509a25f0a04SGreg Roach		$tree->setPreference('SHOW_PARENTS_AGE', '1');
510a25f0a04SGreg Roach		$tree->setPreference('SHOW_PEDIGREE_PLACES', '9');
511a25f0a04SGreg Roach		$tree->setPreference('SHOW_PEDIGREE_PLACES_SUFFIX', '0');
512a25f0a04SGreg Roach		$tree->setPreference('SHOW_PRIVATE_RELATIONSHIPS', '1');
513a25f0a04SGreg Roach		$tree->setPreference('SHOW_RELATIVES_EVENTS', '_BIRT_CHIL,_BIRT_SIBL,_MARR_CHIL,_MARR_PARE,_DEAT_CHIL,_DEAT_PARE,_DEAT_GPAR,_DEAT_SIBL,_DEAT_SPOU');
514a25f0a04SGreg Roach		$tree->setPreference('SOURCE_ID_PREFIX', 'S');
515a25f0a04SGreg Roach		$tree->setPreference('SOUR_FACTS_ADD', 'NOTE,REPO,SHARED_NOTE,RESN');
516a25f0a04SGreg Roach		$tree->setPreference('SOUR_FACTS_QUICK', 'TEXT,NOTE,REPO');
517a25f0a04SGreg Roach		$tree->setPreference('SOUR_FACTS_UNIQUE', 'AUTH,ABBR,TITL,PUBL,TEXT');
518a25f0a04SGreg Roach		$tree->setPreference('SUBLIST_TRIGGER_I', '200');
519a25f0a04SGreg Roach		$tree->setPreference('SURNAME_LIST_STYLE', 'style2');
520a25f0a04SGreg Roach		switch (WT_LOCALE) {
521a25f0a04SGreg Roach		case 'es':
522a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'spanish');
523a25f0a04SGreg Roach			break;
524a25f0a04SGreg Roach		case 'is':
525a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'icelandic');
526a25f0a04SGreg Roach			break;
527a25f0a04SGreg Roach		case 'lt':
528a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'lithuanian');
529a25f0a04SGreg Roach			break;
530a25f0a04SGreg Roach		case 'pl':
531a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'polish');
532a25f0a04SGreg Roach			break;
533a25f0a04SGreg Roach		case 'pt':
534a25f0a04SGreg Roach		case 'pt-BR':
535a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'portuguese');
536a25f0a04SGreg Roach			break;
537a25f0a04SGreg Roach		default:
538a25f0a04SGreg Roach			$tree->setPreference('SURNAME_TRADITION', 'paternal');
539a25f0a04SGreg Roach			break;
540a25f0a04SGreg Roach		}
541a25f0a04SGreg Roach		$tree->setPreference('THUMBNAIL_WIDTH', '100');
542a25f0a04SGreg Roach		$tree->setPreference('USE_RIN', '0');
543a25f0a04SGreg Roach		$tree->setPreference('USE_SILHOUETTE', '1');
544a25f0a04SGreg Roach		$tree->setPreference('WATERMARK_THUMB', '0');
545a25f0a04SGreg Roach		$tree->setPreference('WEBMASTER_USER_ID', Auth::id());
546a25f0a04SGreg Roach		$tree->setPreference('WEBTREES_EMAIL', '');
547a25f0a04SGreg Roach		$tree->setPreference('WORD_WRAPPED_NOTES', '0');
548a25f0a04SGreg Roach
549a25f0a04SGreg Roach		// Default restriction settings
55064d9078aSGreg Roach		Database::prepare(
55164d9078aSGreg Roach			"INSERT INTO `##default_resn` (gedcom_id, tag_type, resn) VALUES (?, 'SSN', 'confidential')"
55264d9078aSGreg Roach		)->execute(array($tree_id));
55364d9078aSGreg Roach		Database::prepare(
55464d9078aSGreg Roach			"INSERT INTO `##default_resn` (gedcom_id, tag_type, resn) VALUES (?, 'SOUR', 'privacy')"
55564d9078aSGreg Roach		)->execute(array($tree_id));
55664d9078aSGreg Roach		Database::prepare(
55764d9078aSGreg Roach			"INSERT INTO `##default_resn` (gedcom_id, tag_type, resn) VALUES (?, 'REPO', 'privacy')"
55864d9078aSGreg Roach		)->execute(array($tree_id));
55964d9078aSGreg Roach		Database::prepare(
56064d9078aSGreg Roach			"INSERT INTO `##default_resn` (gedcom_id, tag_type, resn) VALUES (?, 'SUBM', 'confidential')"
56164d9078aSGreg Roach		)->execute(array($tree_id));
56264d9078aSGreg Roach		Database::prepare(
56364d9078aSGreg Roach			"INSERT INTO `##default_resn` (gedcom_id, tag_type, resn) VALUES (?, 'SUBN', 'confidential')"
56464d9078aSGreg Roach		)->execute(array($tree_id));
565a25f0a04SGreg Roach
566a25f0a04SGreg Roach		// Genealogy data
567a25f0a04SGreg Roach		// It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
568a25f0a04SGreg Roach		$john_doe = /* I18N: This should be a common/default/placeholder name of an individual.  Put slashes around the surname. */
569a25f0a04SGreg Roach			I18N::translate('John /DOE/');
57077e70a22SGreg Roach		$note     = I18N::translate('Edit this individual and replace their details with your own.');
571a25f0a04SGreg Roach		Database::prepare("INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)")->execute(array(
572a25f0a04SGreg Roach			$tree_id,
573cbc1590aSGreg 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",
574a25f0a04SGreg Roach		));
575a25f0a04SGreg Roach
576a25f0a04SGreg Roach		// Set the initial blocks
577a25f0a04SGreg Roach		Database::prepare(
578a25f0a04SGreg Roach			"INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" .
579a25f0a04SGreg Roach			" SELECT ?, location, block_order, module_name" .
580a25f0a04SGreg Roach			" FROM `##block`" .
581a25f0a04SGreg Roach			" WHERE gedcom_id = -1"
582a25f0a04SGreg Roach		)->execute(array($tree_id));
583a25f0a04SGreg Roach
584a25f0a04SGreg Roach		// Update our cache
585518bbdc1SGreg Roach		self::$trees[$tree->tree_id] = $tree;
586a25f0a04SGreg Roach
587a25f0a04SGreg Roach		return $tree;
588a25f0a04SGreg Roach	}
589a25f0a04SGreg Roach
590a25f0a04SGreg Roach	/**
591b78374c5SGreg Roach	 * Are there any pending edits for this tree, than need reviewing by a moderator.
592b78374c5SGreg Roach	 *
593b78374c5SGreg Roach	 * @return bool
594b78374c5SGreg Roach	 */
595b78374c5SGreg Roach	public function hasPendingEdit() {
596b78374c5SGreg Roach		return (bool) Database::prepare(
597b78374c5SGreg Roach			"SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
598b78374c5SGreg Roach		)->execute(array(
599cbc1590aSGreg Roach			'tree_id' => $this->tree_id,
600b78374c5SGreg Roach		))->fetchOne();
601b78374c5SGreg Roach	}
602b78374c5SGreg Roach
603b78374c5SGreg Roach	/**
604a25f0a04SGreg Roach	 * Delete all the genealogy data from a tree - in preparation for importing
605a25f0a04SGreg Roach	 * new data.  Optionally retain the media data, for when the user has been
606a25f0a04SGreg Roach	 * editing their data offline using an application which deletes (or does not
607a25f0a04SGreg Roach	 * support) media data.
608a25f0a04SGreg Roach	 *
609a25f0a04SGreg Roach	 * @param bool $keep_media
610a25f0a04SGreg Roach	 */
611a25f0a04SGreg Roach	public function deleteGenealogyData($keep_media) {
612518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute(array($this->tree_id));
613518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute(array($this->tree_id));
614518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute(array($this->tree_id));
615518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute(array($this->tree_id));
616518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute(array($this->tree_id));
617518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute(array($this->tree_id));
618518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute(array($this->tree_id));
619518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute(array($this->tree_id));
620518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute(array($this->tree_id));
621518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute(array($this->tree_id));
622a25f0a04SGreg Roach
623a25f0a04SGreg Roach		if ($keep_media) {
624518bbdc1SGreg Roach			Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute(array($this->tree_id));
625a25f0a04SGreg Roach		} else {
626518bbdc1SGreg Roach			Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute(array($this->tree_id));
627518bbdc1SGreg Roach			Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute(array($this->tree_id));
628a25f0a04SGreg Roach		}
629a25f0a04SGreg Roach	}
630a25f0a04SGreg Roach
631a25f0a04SGreg Roach	/**
632a25f0a04SGreg Roach	 * Delete everything relating to a tree
633a25f0a04SGreg Roach	 */
634a25f0a04SGreg Roach	public function delete() {
635a25f0a04SGreg Roach		// If this is the default tree, then unset it
636ef2fd529SGreg Roach		if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
637a25f0a04SGreg Roach			Site::setPreference('DEFAULT_GEDCOM', '');
638a25f0a04SGreg Roach		}
639a25f0a04SGreg Roach
640a25f0a04SGreg Roach		$this->deleteGenealogyData(false);
641a25f0a04SGreg Roach
642518bbdc1SGreg Roach		Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute(array($this->tree_id));
643518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute(array($this->tree_id));
644518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute(array($this->tree_id));
645518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute(array($this->tree_id));
646518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute(array($this->tree_id));
647518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##next_id`             WHERE gedcom_id = ?")->execute(array($this->tree_id));
648518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute(array($this->tree_id));
649518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute(array($this->tree_id));
650518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute(array($this->tree_id));
651518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute(array($this->tree_id));
652518bbdc1SGreg Roach		Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute(array($this->tree_id));
653a25f0a04SGreg Roach
654a25f0a04SGreg Roach		// After updating the database, we need to fetch a new (sorted) copy
655a25f0a04SGreg Roach		self::$trees = null;
656a25f0a04SGreg Roach	}
657a25f0a04SGreg Roach
658a25f0a04SGreg Roach	/**
659a25f0a04SGreg Roach	 * Export the tree to a GEDCOM file
660a25f0a04SGreg Roach	 *
6615792757eSGreg Roach	 * @param resource $stream
662a25f0a04SGreg Roach	 */
6635792757eSGreg Roach	public function exportGedcom($stream) {
6645792757eSGreg Roach		$stmt = Database::prepare(
6655792757eSGreg Roach			"SELECT i_gedcom AS gedcom FROM `##individuals` WHERE i_file = :tree_id_1" .
6665792757eSGreg Roach			" UNION ALL " .
6675792757eSGreg Roach			"SELECT f_gedcom AS gedcom FROM `##families`    WHERE f_file = :tree_id_2" .
6685792757eSGreg Roach			" UNION ALL " .
6695792757eSGreg Roach			"SELECT s_gedcom AS gedcom FROM `##sources`     WHERE s_file = :tree_id_3" .
6705792757eSGreg Roach			" UNION ALL " .
6715792757eSGreg Roach			"SELECT o_gedcom AS gedcom FROM `##other`       WHERE o_file = :tree_id_4 AND o_type NOT IN ('HEAD', 'TRLR')" .
6725792757eSGreg Roach			" UNION ALL " .
6735792757eSGreg Roach			"SELECT m_gedcom AS gedcom FROM `##media`       WHERE m_file = :tree_id_5"
6745792757eSGreg Roach		)->execute(array(
6755792757eSGreg Roach			'tree_id_1' => $this->tree_id,
6765792757eSGreg Roach			'tree_id_2' => $this->tree_id,
6775792757eSGreg Roach			'tree_id_3' => $this->tree_id,
6785792757eSGreg Roach			'tree_id_4' => $this->tree_id,
679cbc1590aSGreg Roach			'tree_id_5' => $this->tree_id,
6805792757eSGreg Roach		));
681a25f0a04SGreg Roach
682*3d7a8a4cSGreg Roach		$buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this));
683a25f0a04SGreg Roach		while ($row = $stmt->fetch()) {
684*3d7a8a4cSGreg Roach			$buffer .= FunctionsExport::reformatRecord($row->gedcom);
685a25f0a04SGreg Roach			if (strlen($buffer) > 65535) {
6865792757eSGreg Roach				fwrite($stream, $buffer);
687a25f0a04SGreg Roach				$buffer = '';
688a25f0a04SGreg Roach			}
689a25f0a04SGreg Roach		}
6905792757eSGreg Roach		fwrite($stream, $buffer . '0 TRLR' . WT_EOL);
691a25f0a04SGreg Roach	}
692a25f0a04SGreg Roach
693a25f0a04SGreg Roach	/**
694a25f0a04SGreg Roach	 * Import data from a gedcom file into this tree.
695a25f0a04SGreg Roach	 *
696a25f0a04SGreg Roach	 * @param string  $path       The full path to the (possibly temporary) file.
697a25f0a04SGreg Roach	 * @param string  $filename   The preferred filename, for export/download.
698a25f0a04SGreg Roach	 *
699a25f0a04SGreg Roach	 * @throws \Exception
700a25f0a04SGreg Roach	 */
701ed1bbedbSGreg Roach	public function importGedcomFile($path, $filename) {
702a25f0a04SGreg Roach		// Read the file in blocks of roughly 64K.  Ensure that each block
703a25f0a04SGreg Roach		// contains complete gedcom records.  This will ensure we don’t split
704a25f0a04SGreg Roach		// multi-byte characters, as well as simplifying the code to import
705a25f0a04SGreg Roach		// each block.
706a25f0a04SGreg Roach
707a25f0a04SGreg Roach		$file_data = '';
708a25f0a04SGreg Roach		$fp        = fopen($path, 'rb');
709a25f0a04SGreg Roach
710a25f0a04SGreg Roach		// Don’t allow the user to cancel the request.  We do not want to be left with an incomplete transaction.
711a25f0a04SGreg Roach		ignore_user_abort(true);
712a25f0a04SGreg Roach
713a25f0a04SGreg Roach		Database::beginTransaction();
714ed1bbedbSGreg Roach		$this->deleteGenealogyData($this->getPreference('keep_media'));
715a25f0a04SGreg Roach		$this->setPreference('gedcom_filename', $filename);
716a25f0a04SGreg Roach		$this->setPreference('imported', '0');
717a25f0a04SGreg Roach
718a25f0a04SGreg Roach		while (!feof($fp)) {
719a25f0a04SGreg Roach			$file_data .= fread($fp, 65536);
720a25f0a04SGreg Roach			// There is no strrpos() function that searches for substrings :-(
721a25f0a04SGreg Roach			for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
722a25f0a04SGreg Roach				if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
723a25f0a04SGreg Roach					// We’ve found the last record boundary in this chunk of data
724a25f0a04SGreg Roach					break;
725a25f0a04SGreg Roach				}
726a25f0a04SGreg Roach			}
727a25f0a04SGreg Roach			if ($pos) {
728a25f0a04SGreg Roach				Database::prepare(
729a25f0a04SGreg Roach					"INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
730518bbdc1SGreg Roach				)->execute(array($this->tree_id, substr($file_data, 0, $pos)));
731a25f0a04SGreg Roach				$file_data = substr($file_data, $pos);
732a25f0a04SGreg Roach			}
733a25f0a04SGreg Roach		}
734a25f0a04SGreg Roach		Database::prepare(
735a25f0a04SGreg Roach			"INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
736518bbdc1SGreg Roach		)->execute(array($this->tree_id, $file_data));
737a25f0a04SGreg Roach
738a25f0a04SGreg Roach		Database::commit();
739a25f0a04SGreg Roach		fclose($fp);
740a25f0a04SGreg Roach	}
741304f20d5SGreg Roach
742304f20d5SGreg Roach	/**
743b90d8accSGreg Roach	 * Generate a new XREF, unique across all family trees
744b90d8accSGreg Roach	 *
745b90d8accSGreg Roach	 * @param string $type
746b90d8accSGreg Roach	 *
747b90d8accSGreg Roach	 * @return string
748b90d8accSGreg Roach	 */
7490fb1a955SGreg Roach	public function getNewXref($type = 'INDI') {
750b90d8accSGreg Roach		/** @var string[] Which tree preference is used for which record type */
751b90d8accSGreg Roach		static $type_to_preference = array(
752b90d8accSGreg Roach			'INDI' => 'GEDCOM_ID_PREFIX',
753b90d8accSGreg Roach			'FAM'  => 'FAM_ID_PREFIX',
754b90d8accSGreg Roach			'OBJE' => 'MEDIA_ID_PREFIX',
755b90d8accSGreg Roach			'NOTE' => 'NOTE_ID_PREFIX',
756b90d8accSGreg Roach			'SOUR' => 'SOURCE_ID_PREFIX',
757b90d8accSGreg Roach			'REPO' => 'REPO_ID_PREFIX',
758b90d8accSGreg Roach		);
759b90d8accSGreg Roach
760b90d8accSGreg Roach		if (array_key_exists($type, $type_to_preference)) {
761b90d8accSGreg Roach			$prefix = $this->getPreference($type_to_preference[$type]);
762b90d8accSGreg Roach		} else {
763b90d8accSGreg Roach			// Use the first non-underscore character
764b90d8accSGreg Roach			$prefix = substr(trim($type, '_'), 0, 1);
765b90d8accSGreg Roach		}
766b90d8accSGreg Roach
767b90d8accSGreg Roach		do {
768b90d8accSGreg Roach			// Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence.  See
769b90d8accSGreg Roach			// http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
770b90d8accSGreg Roach			$statement = Database::prepare(
771b90d8accSGreg Roach				"UPDATE `##next_id` SET next_id = LAST_INSERT_ID(next_id + 1) WHERE record_type = :record_type AND gedcom_id = :tree_id"
772b90d8accSGreg Roach			);
773b90d8accSGreg Roach			$statement->execute(array(
774b90d8accSGreg Roach				'record_type' => $type,
775bb7c2cdcSGreg Roach				'tree_id'     => $this->tree_id,
776b90d8accSGreg Roach			));
777b90d8accSGreg Roach
778b90d8accSGreg Roach			if ($statement->rowCount() === 0) {
779b90d8accSGreg Roach				// First time we've used this record type.
780b90d8accSGreg Roach				Database::prepare(
781b90d8accSGreg Roach					"INSERT INTO `##next_id` (gedcom_id, record_type, next_id) VALUES(:tree_id, :record_type, 1)"
782b90d8accSGreg Roach				)->execute(array(
783b90d8accSGreg Roach					'record_type' => $type,
784bb7c2cdcSGreg Roach					'tree_id'     => $this->tree_id,
785b90d8accSGreg Roach				));
786b90d8accSGreg Roach				$num = 1;
787b90d8accSGreg Roach			} else {
788b90d8accSGreg Roach				$num = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
789b90d8accSGreg Roach			}
790b90d8accSGreg Roach
791b90d8accSGreg Roach			// Records may already exist with this sequence number.
792b90d8accSGreg Roach			$already_used = Database::prepare(
793b90d8accSGreg Roach				"SELECT i_id FROM `##individuals` WHERE i_id = :i_id" .
794b90d8accSGreg Roach				" UNION ALL " .
795b90d8accSGreg Roach				"SELECT f_id FROM `##families` WHERE f_id = :f_id" .
796b90d8accSGreg Roach				" UNION ALL " .
797b90d8accSGreg Roach				"SELECT s_id FROM `##sources` WHERE s_id = :s_id" .
798b90d8accSGreg Roach				" UNION ALL " .
799b90d8accSGreg Roach				"SELECT m_id FROM `##media` WHERE m_id = :m_id" .
800b90d8accSGreg Roach				" UNION ALL " .
801b90d8accSGreg Roach				"SELECT o_id FROM `##other` WHERE o_id = :o_id" .
802b90d8accSGreg Roach				" UNION ALL " .
803b90d8accSGreg Roach				"SELECT xref FROM `##change` WHERE xref = :xref"
804b90d8accSGreg Roach			)->execute(array(
805b90d8accSGreg Roach				'i_id' => $prefix . $num,
806b90d8accSGreg Roach				'f_id' => $prefix . $num,
807b90d8accSGreg Roach				's_id' => $prefix . $num,
808b90d8accSGreg Roach				'm_id' => $prefix . $num,
809b90d8accSGreg Roach				'o_id' => $prefix . $num,
810b90d8accSGreg Roach				'xref' => $prefix . $num,
811b90d8accSGreg Roach			))->fetchOne();
812b90d8accSGreg Roach		} while ($already_used);
813b90d8accSGreg Roach
814b90d8accSGreg Roach		return $prefix . $num;
815b90d8accSGreg Roach	}
816b90d8accSGreg Roach
817b90d8accSGreg Roach	/**
818304f20d5SGreg Roach	 * Create a new record from GEDCOM data.
819304f20d5SGreg Roach	 *
820304f20d5SGreg Roach	 * @param string $gedcom
821304f20d5SGreg Roach	 *
822304f20d5SGreg Roach	 * @throws \Exception
823cbc1590aSGreg Roach	 *
824cbc1590aSGreg Roach	 * @return GedcomRecord
825304f20d5SGreg Roach	 */
826304f20d5SGreg Roach	public function createRecord($gedcom) {
827304f20d5SGreg Roach		if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom, $match)) {
828304f20d5SGreg Roach			$xref = $match[1];
829304f20d5SGreg Roach			$type = $match[2];
830304f20d5SGreg Roach		} else {
831304f20d5SGreg Roach			throw new \Exception('Invalid argument to GedcomRecord::createRecord(' . $gedcom . ')');
832304f20d5SGreg Roach		}
833304f20d5SGreg Roach		if (strpos("\r", $gedcom) !== false) {
834304f20d5SGreg Roach			// MSDOS line endings will break things in horrible ways
835304f20d5SGreg Roach			throw new \Exception('Evil line endings found in GedcomRecord::createRecord(' . $gedcom . ')');
836304f20d5SGreg Roach		}
837304f20d5SGreg Roach
838304f20d5SGreg Roach		// webtrees creates XREFs containing digits.  Anything else (e.g. “new”) is just a placeholder.
839304f20d5SGreg Roach		if (!preg_match('/\d/', $xref)) {
840b90d8accSGreg Roach			$xref   = $this->getNewXref($type);
841304f20d5SGreg Roach			$gedcom = preg_replace('/^0 @(' . WT_REGEX_XREF . ')@/', '0 @' . $xref . '@', $gedcom);
842304f20d5SGreg Roach		}
843304f20d5SGreg Roach
844304f20d5SGreg Roach		// Create a change record, if not already present
845304f20d5SGreg Roach		if (!preg_match('/\n1 CHAN/', $gedcom)) {
846304f20d5SGreg Roach			$gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
847304f20d5SGreg Roach		}
848304f20d5SGreg Roach
849304f20d5SGreg Roach		// Create a pending change
850304f20d5SGreg Roach		Database::prepare(
851304f20d5SGreg Roach			"INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
852304f20d5SGreg Roach		)->execute(array(
853bb7c2cdcSGreg Roach			$this->tree_id,
854304f20d5SGreg Roach			$xref,
855304f20d5SGreg Roach			$gedcom,
856cbc1590aSGreg Roach			Auth::id(),
857304f20d5SGreg Roach		));
858304f20d5SGreg Roach
859304f20d5SGreg Roach		Log::addEditLog('Create: ' . $type . ' ' . $xref);
860304f20d5SGreg Roach
861304f20d5SGreg Roach		// Accept this pending change
862304f20d5SGreg Roach		if (Auth::user()->getPreference('auto_accept')) {
863*3d7a8a4cSGreg Roach			FunctionsImport::acceptAllChanges($xref, $this->tree_id);
864304f20d5SGreg Roach		}
865bb7c2cdcSGreg Roach		// Return the newly created record.  Note that since GedcomRecord
866bb7c2cdcSGreg Roach		// has a cache of pending changes, we cannot use it to create a
867bb7c2cdcSGreg Roach		// record with a newly created pending change.
86824ec66ceSGreg Roach		return GedcomRecord::getInstance($xref, $this, $gedcom);
869304f20d5SGreg Roach	}
870a25f0a04SGreg Roach}
871