xref: /webtrees/app/Tree.php (revision e7f56f2af615447ab1a7646851f88b465ace9e04)
1a25f0a04SGreg Roach<?php
2a25f0a04SGreg Roach/**
3a25f0a04SGreg Roach * webtrees: online genealogy
41062a142SGreg Roach * Copyright (C) 2018 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 */
16*e7f56f2aSGreg Roachdeclare(strict_types=1);
17*e7f56f2aSGreg Roach
1876692c8bSGreg Roachnamespace Fisharebest\Webtrees;
19a25f0a04SGreg Roach
20b7e60af1SGreg Roachuse Exception;
213d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsExport;
223d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
23a25f0a04SGreg Roachuse PDOException;
24a25f0a04SGreg Roach
25a25f0a04SGreg Roach/**
2676692c8bSGreg Roach * Provide an interface to the wt_gedcom table.
27a25f0a04SGreg Roach */
28c1010edaSGreg Roachclass Tree
29c1010edaSGreg Roach{
30cbc1590aSGreg Roach    /** @var int The tree's ID number */
31518bbdc1SGreg Roach    private $tree_id;
32518bbdc1SGreg Roach
33a25f0a04SGreg Roach    /** @var string The tree's name */
34a25f0a04SGreg Roach    private $name;
35518bbdc1SGreg Roach
36a25f0a04SGreg Roach    /** @var string The tree's title */
37a25f0a04SGreg Roach    private $title;
38a25f0a04SGreg Roach
39e2052359SGreg Roach    /** @var int[] Default access rules for facts in this tree */
40518bbdc1SGreg Roach    private $fact_privacy;
41518bbdc1SGreg Roach
42e2052359SGreg Roach    /** @var int[] Default access rules for individuals in this tree */
43518bbdc1SGreg Roach    private $individual_privacy;
44518bbdc1SGreg Roach
45518bbdc1SGreg Roach    /** @var integer[][] Default access rules for individual facts in this tree */
46518bbdc1SGreg Roach    private $individual_fact_privacy;
47518bbdc1SGreg Roach
48a25f0a04SGreg Roach    /** @var Tree[] All trees that we have permission to see. */
4975a9f908SGreg Roach    private static $trees = [];
50a25f0a04SGreg Roach
51a25f0a04SGreg Roach    /** @var string[] Cached copy of the wt_gedcom_setting table. */
5215d603e7SGreg Roach    private $preferences = [];
53a25f0a04SGreg Roach
54a25f0a04SGreg Roach    /** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
5513abd6f3SGreg Roach    private $user_preferences = [];
56a25f0a04SGreg Roach
57a25f0a04SGreg Roach    /**
58a25f0a04SGreg Roach     * Create a tree object. This is a private constructor - it can only
59a25f0a04SGreg Roach     * be called from Tree::getAll() to ensure proper initialisation.
60a25f0a04SGreg Roach     *
61cbc1590aSGreg Roach     * @param int    $tree_id
62a25f0a04SGreg Roach     * @param string $tree_name
63a25f0a04SGreg Roach     * @param string $tree_title
64a25f0a04SGreg Roach     */
65c1010edaSGreg Roach    private function __construct($tree_id, $tree_name, $tree_title)
66c1010edaSGreg Roach    {
67518bbdc1SGreg Roach        $this->tree_id                 = $tree_id;
68a25f0a04SGreg Roach        $this->name                    = $tree_name;
69a25f0a04SGreg Roach        $this->title                   = $tree_title;
7013abd6f3SGreg Roach        $this->fact_privacy            = [];
7113abd6f3SGreg Roach        $this->individual_privacy      = [];
7213abd6f3SGreg Roach        $this->individual_fact_privacy = [];
73518bbdc1SGreg Roach
74518bbdc1SGreg Roach        // Load the privacy settings for this tree
75518bbdc1SGreg Roach        $rows = Database::prepare(
76e5588fb0SGreg Roach            "SELECT xref, tag_type, CASE resn WHEN 'none' THEN :priv_public WHEN 'privacy' THEN :priv_user WHEN 'confidential' THEN :priv_none WHEN 'hidden' THEN :priv_hide END AS resn" .
77518bbdc1SGreg Roach            " FROM `##default_resn` WHERE gedcom_id = :tree_id"
7813abd6f3SGreg Roach        )->execute([
794b9ff166SGreg Roach            'priv_public' => Auth::PRIV_PRIVATE,
804b9ff166SGreg Roach            'priv_user'   => Auth::PRIV_USER,
814b9ff166SGreg Roach            'priv_none'   => Auth::PRIV_NONE,
824b9ff166SGreg Roach            'priv_hide'   => Auth::PRIV_HIDE,
83cbc1590aSGreg Roach            'tree_id'     => $this->tree_id,
8413abd6f3SGreg Roach        ])->fetchAll();
85518bbdc1SGreg Roach
86518bbdc1SGreg Roach        foreach ($rows as $row) {
87518bbdc1SGreg Roach            if ($row->xref !== null) {
88518bbdc1SGreg Roach                if ($row->tag_type !== null) {
89518bbdc1SGreg Roach                    $this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
90518bbdc1SGreg Roach                } else {
91518bbdc1SGreg Roach                    $this->individual_privacy[$row->xref] = (int) $row->resn;
92518bbdc1SGreg Roach                }
93518bbdc1SGreg Roach            } else {
94518bbdc1SGreg Roach                $this->fact_privacy[$row->tag_type] = (int) $row->resn;
95518bbdc1SGreg Roach            }
96518bbdc1SGreg Roach        }
97a25f0a04SGreg Roach    }
98a25f0a04SGreg Roach
99a25f0a04SGreg Roach    /**
100a25f0a04SGreg Roach     * The ID of this tree
101a25f0a04SGreg Roach     *
102cbc1590aSGreg Roach     * @return int
103a25f0a04SGreg Roach     */
1048f53f488SRico Sonntag    public function getTreeId(): int
105c1010edaSGreg Roach    {
106518bbdc1SGreg Roach        return $this->tree_id;
107a25f0a04SGreg Roach    }
108a25f0a04SGreg Roach
109a25f0a04SGreg Roach    /**
110a25f0a04SGreg Roach     * The name of this tree
111a25f0a04SGreg Roach     *
112a25f0a04SGreg Roach     * @return string
113a25f0a04SGreg Roach     */
1148f53f488SRico Sonntag    public function getName(): string
115c1010edaSGreg Roach    {
116a25f0a04SGreg Roach        return $this->name;
117a25f0a04SGreg Roach    }
118a25f0a04SGreg Roach
119a25f0a04SGreg Roach    /**
120a25f0a04SGreg Roach     * The title of this tree
121a25f0a04SGreg Roach     *
122a25f0a04SGreg Roach     * @return string
123a25f0a04SGreg Roach     */
1248f53f488SRico Sonntag    public function getTitle(): string
125c1010edaSGreg Roach    {
126a25f0a04SGreg Roach        return $this->title;
127a25f0a04SGreg Roach    }
128a25f0a04SGreg Roach
129a25f0a04SGreg Roach    /**
130518bbdc1SGreg Roach     * The fact-level privacy for this tree.
131518bbdc1SGreg Roach     *
132e2052359SGreg Roach     * @return int[]
133518bbdc1SGreg Roach     */
1348f53f488SRico Sonntag    public function getFactPrivacy(): array
135c1010edaSGreg Roach    {
136518bbdc1SGreg Roach        return $this->fact_privacy;
137518bbdc1SGreg Roach    }
138518bbdc1SGreg Roach
139518bbdc1SGreg Roach    /**
140518bbdc1SGreg Roach     * The individual-level privacy for this tree.
141518bbdc1SGreg Roach     *
142e2052359SGreg Roach     * @return int[]
143518bbdc1SGreg Roach     */
1448f53f488SRico Sonntag    public function getIndividualPrivacy(): array
145c1010edaSGreg Roach    {
146518bbdc1SGreg Roach        return $this->individual_privacy;
147518bbdc1SGreg Roach    }
148518bbdc1SGreg Roach
149518bbdc1SGreg Roach    /**
150518bbdc1SGreg Roach     * The individual-fact-level privacy for this tree.
151518bbdc1SGreg Roach     *
152adac8af1SGreg Roach     * @return int[][]
153518bbdc1SGreg Roach     */
1548f53f488SRico Sonntag    public function getIndividualFactPrivacy(): array
155c1010edaSGreg Roach    {
156518bbdc1SGreg Roach        return $this->individual_fact_privacy;
157518bbdc1SGreg Roach    }
158518bbdc1SGreg Roach
159518bbdc1SGreg Roach    /**
160a25f0a04SGreg Roach     * Get the tree’s configuration settings.
161a25f0a04SGreg Roach     *
162a25f0a04SGreg Roach     * @param string $setting_name
16315d603e7SGreg Roach     * @param string $default
164a25f0a04SGreg Roach     *
16515d603e7SGreg Roach     * @return string
166a25f0a04SGreg Roach     */
167771ae10aSGreg Roach    public function getPreference(string $setting_name, string $default = ''): string
168c1010edaSGreg Roach    {
16915d603e7SGreg Roach        if (empty($this->preferences)) {
170a25f0a04SGreg Roach            $this->preferences = Database::prepare(
171e5588fb0SGreg Roach                "SELECT setting_name, setting_value FROM `##gedcom_setting` WHERE gedcom_id = ?"
17213abd6f3SGreg Roach            )->execute([$this->tree_id])->fetchAssoc();
173a25f0a04SGreg Roach        }
174a25f0a04SGreg Roach
175b2ce94c6SRico Sonntag        return $this->preferences[$setting_name] ?? $default;
176a25f0a04SGreg Roach    }
177a25f0a04SGreg Roach
178a25f0a04SGreg Roach    /**
179a25f0a04SGreg Roach     * Set the tree’s configuration settings.
180a25f0a04SGreg Roach     *
181a25f0a04SGreg Roach     * @param string $setting_name
182a25f0a04SGreg Roach     * @param string $setting_value
183a25f0a04SGreg Roach     *
184a25f0a04SGreg Roach     * @return $this
185a25f0a04SGreg Roach     */
186771ae10aSGreg Roach    public function setPreference(string $setting_name, string $setting_value): Tree
187c1010edaSGreg Roach    {
188a25f0a04SGreg Roach        if ($setting_value !== $this->getPreference($setting_name)) {
189a25f0a04SGreg Roach            Database::prepare(
190a25f0a04SGreg Roach                "REPLACE INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
191a25f0a04SGreg Roach                " VALUES (:tree_id, :setting_name, LEFT(:setting_value, 255))"
19213abd6f3SGreg Roach            )->execute([
193518bbdc1SGreg Roach                'tree_id'       => $this->tree_id,
194a25f0a04SGreg Roach                'setting_name'  => $setting_name,
195a25f0a04SGreg Roach                'setting_value' => $setting_value,
19613abd6f3SGreg Roach            ]);
19715d603e7SGreg Roach
198a25f0a04SGreg Roach            $this->preferences[$setting_name] = $setting_value;
19915d603e7SGreg Roach
20072292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
201a25f0a04SGreg Roach        }
202a25f0a04SGreg Roach
203a25f0a04SGreg Roach        return $this;
204a25f0a04SGreg Roach    }
205a25f0a04SGreg Roach
206a25f0a04SGreg Roach    /**
207a25f0a04SGreg Roach     * Get the tree’s user-configuration settings.
208a25f0a04SGreg Roach     *
209a25f0a04SGreg Roach     * @param User   $user
210a25f0a04SGreg Roach     * @param string $setting_name
2117015ba1fSGreg Roach     * @param string $default
212a25f0a04SGreg Roach     *
213a25f0a04SGreg Roach     * @return string
214a25f0a04SGreg Roach     */
215771ae10aSGreg Roach    public function getUserPreference(User $user, string $setting_name, string $default = ''): string
216c1010edaSGreg Roach    {
217a25f0a04SGreg Roach        // There are lots of settings, and we need to fetch lots of them on every page
218a25f0a04SGreg Roach        // so it is quicker to fetch them all in one go.
219a25f0a04SGreg Roach        if (!array_key_exists($user->getUserId(), $this->user_preferences)) {
220a25f0a04SGreg Roach            $this->user_preferences[$user->getUserId()] = Database::prepare(
221e5588fb0SGreg Roach                "SELECT setting_name, setting_value FROM `##user_gedcom_setting` WHERE user_id = ? AND gedcom_id = ?"
222c1010edaSGreg Roach            )->execute([
223c1010edaSGreg Roach                $user->getUserId(),
224c1010edaSGreg Roach                $this->tree_id,
225c1010edaSGreg Roach            ])->fetchAssoc();
226a25f0a04SGreg Roach        }
227a25f0a04SGreg Roach
228b2ce94c6SRico Sonntag        return $this->user_preferences[$user->getUserId()][$setting_name] ?? $default;
229a25f0a04SGreg Roach    }
230a25f0a04SGreg Roach
231a25f0a04SGreg Roach    /**
232a25f0a04SGreg Roach     * Set the tree’s user-configuration settings.
233a25f0a04SGreg Roach     *
234a25f0a04SGreg Roach     * @param User   $user
235a25f0a04SGreg Roach     * @param string $setting_name
236a25f0a04SGreg Roach     * @param string $setting_value
237a25f0a04SGreg Roach     *
238a25f0a04SGreg Roach     * @return $this
239a25f0a04SGreg Roach     */
240771ae10aSGreg Roach    public function setUserPreference(User $user, string $setting_name, string $setting_value): Tree
241c1010edaSGreg Roach    {
242a25f0a04SGreg Roach        if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
243a25f0a04SGreg Roach            // Update the database
2447015ba1fSGreg Roach            if ($setting_value === '') {
245a25f0a04SGreg Roach                Database::prepare(
246a25f0a04SGreg Roach                    "DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = :tree_id AND user_id = :user_id AND setting_name = :setting_name"
24713abd6f3SGreg Roach                )->execute([
248518bbdc1SGreg Roach                    'tree_id'      => $this->tree_id,
249a25f0a04SGreg Roach                    'user_id'      => $user->getUserId(),
250a25f0a04SGreg Roach                    'setting_name' => $setting_name,
25113abd6f3SGreg Roach                ]);
252a25f0a04SGreg Roach            } else {
253a25f0a04SGreg Roach                Database::prepare(
254a25f0a04SGreg 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))"
25513abd6f3SGreg Roach                )->execute([
256a25f0a04SGreg Roach                    'user_id'       => $user->getUserId(),
257518bbdc1SGreg Roach                    'tree_id'       => $this->tree_id,
258a25f0a04SGreg Roach                    'setting_name'  => $setting_name,
259cbc1590aSGreg Roach                    'setting_value' => $setting_value,
26013abd6f3SGreg Roach                ]);
261a25f0a04SGreg Roach            }
262a25f0a04SGreg Roach            // Update our cache
263a25f0a04SGreg Roach            $this->user_preferences[$user->getUserId()][$setting_name] = $setting_value;
264a25f0a04SGreg Roach            // Audit log of changes
26572292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this);
266a25f0a04SGreg Roach        }
267a25f0a04SGreg Roach
268a25f0a04SGreg Roach        return $this;
269a25f0a04SGreg Roach    }
270a25f0a04SGreg Roach
271a25f0a04SGreg Roach    /**
272a25f0a04SGreg Roach     * Can a user accept changes for this tree?
273a25f0a04SGreg Roach     *
274a25f0a04SGreg Roach     * @param User $user
275a25f0a04SGreg Roach     *
276cbc1590aSGreg Roach     * @return bool
277a25f0a04SGreg Roach     */
278771ae10aSGreg Roach    public function canAcceptChanges(User $user): bool
279c1010edaSGreg Roach    {
280a25f0a04SGreg Roach        return Auth::isModerator($this, $user);
281a25f0a04SGreg Roach    }
282a25f0a04SGreg Roach
283a25f0a04SGreg Roach    /**
284a25f0a04SGreg Roach     * Fetch all the trees that we have permission to access.
285a25f0a04SGreg Roach     *
286a25f0a04SGreg Roach     * @return Tree[]
287a25f0a04SGreg Roach     */
288771ae10aSGreg Roach    public static function getAll(): array
289c1010edaSGreg Roach    {
29075a9f908SGreg Roach        if (empty(self::$trees)) {
291a25f0a04SGreg Roach            $rows = Database::prepare(
292e5588fb0SGreg Roach                "SELECT g.gedcom_id AS tree_id, g.gedcom_name AS tree_name, gs1.setting_value AS tree_title" .
293a25f0a04SGreg Roach                " FROM `##gedcom` g" .
294a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs1 ON (g.gedcom_id=gs1.gedcom_id AND gs1.setting_name='title')" .
295a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs2 ON (g.gedcom_id=gs2.gedcom_id AND gs2.setting_name='imported')" .
296a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs3 ON (g.gedcom_id=gs3.gedcom_id AND gs3.setting_name='REQUIRE_AUTHENTICATION')" .
297a25f0a04SGreg Roach                " LEFT JOIN `##user_gedcom_setting` ugs ON (g.gedcom_id=ugs.gedcom_id AND ugs.setting_name='canedit' AND ugs.user_id=?)" .
298a25f0a04SGreg Roach                " WHERE " .
299a25f0a04SGreg Roach                "  g.gedcom_id>0 AND (" . // exclude the "template" tree
300a25f0a04SGreg Roach                "    EXISTS (SELECT 1 FROM `##user_setting` WHERE user_id=? AND setting_name='canadmin' AND setting_value=1)" . // Admin sees all
301a25f0a04SGreg Roach                "   ) OR (" .
3028cca4ddeSGreg Roach                "    (gs2.setting_value = 1 OR ugs.setting_value = 'admin') AND (" . // Allow imported trees, with either:
303a25f0a04SGreg Roach                "     gs3.setting_value <> 1 OR" . // visitor access
304a25f0a04SGreg Roach                "     IFNULL(ugs.setting_value, 'none')<>'none'" . // explicit access
305a25f0a04SGreg Roach                "   )" .
306a25f0a04SGreg Roach                "  )" .
307a25f0a04SGreg Roach                " ORDER BY g.sort_order, 3"
308c1010edaSGreg Roach            )->execute([
309c1010edaSGreg Roach                Auth::id(),
310c1010edaSGreg Roach                Auth::id(),
311c1010edaSGreg Roach            ])->fetchAll();
31275a9f908SGreg Roach
313a25f0a04SGreg Roach            foreach ($rows as $row) {
3143f7ece23SGreg Roach                self::$trees[$row->tree_name] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
315a25f0a04SGreg Roach            }
316a25f0a04SGreg Roach        }
317a25f0a04SGreg Roach
318a25f0a04SGreg Roach        return self::$trees;
319a25f0a04SGreg Roach    }
320a25f0a04SGreg Roach
321a25f0a04SGreg Roach    /**
322d2cdeb3fSGreg Roach     * Find the tree with a specific ID.
323a25f0a04SGreg Roach     *
324cbc1590aSGreg Roach     * @param int $tree_id
325cbc1590aSGreg Roach     *
326cbc1590aSGreg Roach     * @throws \DomainException
327a25f0a04SGreg Roach     * @return Tree
328a25f0a04SGreg Roach     */
329771ae10aSGreg Roach    public static function findById($tree_id): Tree
330c1010edaSGreg Roach    {
33151d0f842SGreg Roach        foreach (self::getAll() as $tree) {
332e568acceSGreg Roach            if ($tree->tree_id == $tree_id) {
33351d0f842SGreg Roach                return $tree;
33451d0f842SGreg Roach            }
33551d0f842SGreg Roach        }
33659f2f229SGreg Roach        throw new \DomainException();
337a25f0a04SGreg Roach    }
338a25f0a04SGreg Roach
339a25f0a04SGreg Roach    /**
340d2cdeb3fSGreg Roach     * Find the tree with a specific name.
341cf4bcc09SGreg Roach     *
342cf4bcc09SGreg Roach     * @param string $tree_name
343cf4bcc09SGreg Roach     *
344cf4bcc09SGreg Roach     * @return Tree|null
345cf4bcc09SGreg Roach     */
346c1010edaSGreg Roach    public static function findByName($tree_name)
347c1010edaSGreg Roach    {
348cf4bcc09SGreg Roach        foreach (self::getAll() as $tree) {
34951d0f842SGreg Roach            if ($tree->name === $tree_name) {
350cf4bcc09SGreg Roach                return $tree;
351cf4bcc09SGreg Roach            }
352cf4bcc09SGreg Roach        }
353cf4bcc09SGreg Roach
354cf4bcc09SGreg Roach        return null;
355cf4bcc09SGreg Roach    }
356cf4bcc09SGreg Roach
357cf4bcc09SGreg Roach    /**
358a25f0a04SGreg Roach     * Create arguments to select_edit_control()
359a25f0a04SGreg Roach     * Note - these will be escaped later
360a25f0a04SGreg Roach     *
361a25f0a04SGreg Roach     * @return string[]
362a25f0a04SGreg Roach     */
363771ae10aSGreg Roach    public static function getIdList(): array
364c1010edaSGreg Roach    {
36513abd6f3SGreg Roach        $list = [];
366a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
367518bbdc1SGreg Roach            $list[$tree->tree_id] = $tree->title;
368a25f0a04SGreg Roach        }
369a25f0a04SGreg Roach
370a25f0a04SGreg Roach        return $list;
371a25f0a04SGreg Roach    }
372a25f0a04SGreg Roach
373a25f0a04SGreg Roach    /**
374a25f0a04SGreg Roach     * Create arguments to select_edit_control()
375a25f0a04SGreg Roach     * Note - these will be escaped later
376a25f0a04SGreg Roach     *
377a25f0a04SGreg Roach     * @return string[]
378a25f0a04SGreg Roach     */
379771ae10aSGreg Roach    public static function getNameList(): array
380c1010edaSGreg Roach    {
38113abd6f3SGreg Roach        $list = [];
382a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
383a25f0a04SGreg Roach            $list[$tree->name] = $tree->title;
384a25f0a04SGreg Roach        }
385a25f0a04SGreg Roach
386a25f0a04SGreg Roach        return $list;
387a25f0a04SGreg Roach    }
388a25f0a04SGreg Roach
389a25f0a04SGreg Roach    /**
390a25f0a04SGreg Roach     * Create a new tree
391a25f0a04SGreg Roach     *
392a25f0a04SGreg Roach     * @param string $tree_name
393a25f0a04SGreg Roach     * @param string $tree_title
394a25f0a04SGreg Roach     *
395a25f0a04SGreg Roach     * @return Tree
396a25f0a04SGreg Roach     */
397771ae10aSGreg Roach    public static function create(string $tree_name, string $tree_title): Tree
398c1010edaSGreg Roach    {
399a25f0a04SGreg Roach        try {
400a25f0a04SGreg Roach            // Create a new tree
401a25f0a04SGreg Roach            Database::prepare(
402a25f0a04SGreg Roach                "INSERT INTO `##gedcom` (gedcom_name) VALUES (?)"
40313abd6f3SGreg Roach            )->execute([$tree_name]);
4044a86d714SGreg Roach
4054a86d714SGreg Roach            $tree_id = (int) Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
406a25f0a04SGreg Roach        } catch (PDOException $ex) {
407bd52fa32SGreg Roach            DebugBar::addThrowable($ex);
408bd52fa32SGreg Roach
409a25f0a04SGreg Roach            // A tree with that name already exists?
410ef2fd529SGreg Roach            return self::findByName($tree_name);
411a25f0a04SGreg Roach        }
412a25f0a04SGreg Roach
413a25f0a04SGreg Roach        // Update the list of trees - to include this new one
41475a9f908SGreg Roach        self::$trees = [];
415d2cdeb3fSGreg Roach        $tree        = self::findById($tree_id);
416a25f0a04SGreg Roach
417a25f0a04SGreg Roach        $tree->setPreference('imported', '0');
418a25f0a04SGreg Roach        $tree->setPreference('title', $tree_title);
419a25f0a04SGreg Roach
420a25f0a04SGreg Roach        // Module privacy
421a25f0a04SGreg Roach        Module::setDefaultAccess($tree_id);
422a25f0a04SGreg Roach
4231507cbcaSGreg Roach        // Set preferences from default tree
4241507cbcaSGreg Roach        Database::prepare(
4251507cbcaSGreg Roach            "INSERT INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
4261507cbcaSGreg Roach            " SELECT :tree_id, setting_name, setting_value" .
4271507cbcaSGreg Roach            " FROM `##gedcom_setting` WHERE gedcom_id = -1"
42813abd6f3SGreg Roach        )->execute([
4291507cbcaSGreg Roach            'tree_id' => $tree_id,
43013abd6f3SGreg Roach        ]);
4311507cbcaSGreg Roach
4321507cbcaSGreg Roach        Database::prepare(
4331507cbcaSGreg Roach            "INSERT INTO `##default_resn` (gedcom_id, tag_type, resn)" .
4341507cbcaSGreg Roach            " SELECT :tree_id, tag_type, resn" .
4351507cbcaSGreg Roach            " FROM `##default_resn` WHERE gedcom_id = -1"
43613abd6f3SGreg Roach        )->execute([
4371507cbcaSGreg Roach            'tree_id' => $tree_id,
43813abd6f3SGreg Roach        ]);
4391507cbcaSGreg Roach
4401507cbcaSGreg Roach        Database::prepare(
4411507cbcaSGreg Roach            "INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" .
4421507cbcaSGreg Roach            " SELECT :tree_id, location, block_order, module_name" .
4431507cbcaSGreg Roach            " FROM `##block` WHERE gedcom_id = -1"
44413abd6f3SGreg Roach        )->execute([
4451507cbcaSGreg Roach            'tree_id' => $tree_id,
44613abd6f3SGreg Roach        ]);
4471507cbcaSGreg Roach
448a25f0a04SGreg Roach        // Gedcom and privacy settings
44976f666f4SGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
45076f666f4SGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
451a25f0a04SGreg Roach        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
452a25f0a04SGreg Roach        switch (WT_LOCALE) {
453a25f0a04SGreg Roach            case 'es':
454a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'spanish');
455a25f0a04SGreg Roach                break;
456a25f0a04SGreg Roach            case 'is':
457a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
458a25f0a04SGreg Roach                break;
459a25f0a04SGreg Roach            case 'lt':
460a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
461a25f0a04SGreg Roach                break;
462a25f0a04SGreg Roach            case 'pl':
463a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'polish');
464a25f0a04SGreg Roach                break;
465a25f0a04SGreg Roach            case 'pt':
466a25f0a04SGreg Roach            case 'pt-BR':
467a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
468a25f0a04SGreg Roach                break;
469a25f0a04SGreg Roach            default:
470a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'paternal');
471a25f0a04SGreg Roach                break;
472a25f0a04SGreg Roach        }
473a25f0a04SGreg Roach
474a25f0a04SGreg Roach        // Genealogy data
475a25f0a04SGreg Roach        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
476bbb76c12SGreg Roach        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
477bbb76c12SGreg Roach        $john_doe = I18N::translate('John /DOE/');
47877e70a22SGreg Roach        $note     = I18N::translate('Edit this individual and replace their details with your own.');
47913abd6f3SGreg Roach        Database::prepare("INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)")->execute([
480a25f0a04SGreg Roach            $tree_id,
481cbc1590aSGreg 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",
48213abd6f3SGreg Roach        ]);
483a25f0a04SGreg Roach
484a25f0a04SGreg Roach        // Update our cache
485518bbdc1SGreg Roach        self::$trees[$tree->tree_id] = $tree;
486a25f0a04SGreg Roach
487a25f0a04SGreg Roach        return $tree;
488a25f0a04SGreg Roach    }
489a25f0a04SGreg Roach
490a25f0a04SGreg Roach    /**
491b78374c5SGreg Roach     * Are there any pending edits for this tree, than need reviewing by a moderator.
492b78374c5SGreg Roach     *
493b78374c5SGreg Roach     * @return bool
494b78374c5SGreg Roach     */
495771ae10aSGreg Roach    public function hasPendingEdit(): bool
496c1010edaSGreg Roach    {
497b78374c5SGreg Roach        return (bool) Database::prepare(
498b78374c5SGreg Roach            "SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
49913abd6f3SGreg Roach        )->execute([
500cbc1590aSGreg Roach            'tree_id' => $this->tree_id,
50113abd6f3SGreg Roach        ])->fetchOne();
502b78374c5SGreg Roach    }
503b78374c5SGreg Roach
504b78374c5SGreg Roach    /**
505a25f0a04SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
506a25f0a04SGreg Roach     * new data. Optionally retain the media data, for when the user has been
507a25f0a04SGreg Roach     * editing their data offline using an application which deletes (or does not
508a25f0a04SGreg Roach     * support) media data.
509a25f0a04SGreg Roach     *
510a25f0a04SGreg Roach     * @param bool $keep_media
511b7e60af1SGreg Roach     *
512b7e60af1SGreg Roach     * @return void
513a25f0a04SGreg Roach     */
514b7e60af1SGreg Roach    public function deleteGenealogyData(bool $keep_media)
515c1010edaSGreg Roach    {
51613abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute([$this->tree_id]);
51713abd6f3SGreg Roach        Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute([$this->tree_id]);
51813abd6f3SGreg Roach        Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute([$this->tree_id]);
51913abd6f3SGreg Roach        Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute([$this->tree_id]);
52013abd6f3SGreg Roach        Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute([$this->tree_id]);
52113abd6f3SGreg Roach        Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute([$this->tree_id]);
52213abd6f3SGreg Roach        Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute([$this->tree_id]);
52313abd6f3SGreg Roach        Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute([$this->tree_id]);
52413abd6f3SGreg Roach        Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute([$this->tree_id]);
52513abd6f3SGreg Roach        Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute([$this->tree_id]);
526a25f0a04SGreg Roach
527a25f0a04SGreg Roach        if ($keep_media) {
52813abd6f3SGreg Roach            Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute([$this->tree_id]);
529a25f0a04SGreg Roach        } else {
53013abd6f3SGreg Roach            Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute([$this->tree_id]);
53113abd6f3SGreg Roach            Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute([$this->tree_id]);
53223ed9d24SGreg Roach            Database::prepare("DELETE FROM `##media_file` WHERE m_file =?")->execute([$this->tree_id]);
533a25f0a04SGreg Roach        }
534a25f0a04SGreg Roach    }
535a25f0a04SGreg Roach
536a25f0a04SGreg Roach    /**
537a25f0a04SGreg Roach     * Delete everything relating to a tree
538b7e60af1SGreg Roach     *
539b7e60af1SGreg Roach     * @return void
540a25f0a04SGreg Roach     */
541c1010edaSGreg Roach    public function delete()
542c1010edaSGreg Roach    {
543a25f0a04SGreg Roach        // If this is the default tree, then unset it
544ef2fd529SGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
545a25f0a04SGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
546a25f0a04SGreg Roach        }
547a25f0a04SGreg Roach
548a25f0a04SGreg Roach        $this->deleteGenealogyData(false);
549a25f0a04SGreg Roach
55013abd6f3SGreg Roach        Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute([$this->tree_id]);
55113abd6f3SGreg Roach        Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute([$this->tree_id]);
55213abd6f3SGreg Roach        Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute([$this->tree_id]);
55313abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
55413abd6f3SGreg Roach        Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
55513abd6f3SGreg Roach        Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute([$this->tree_id]);
55613abd6f3SGreg Roach        Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
55713abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
55813abd6f3SGreg Roach        Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute([$this->tree_id]);
55913abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute([$this->tree_id]);
560a25f0a04SGreg Roach
561a25f0a04SGreg Roach        // After updating the database, we need to fetch a new (sorted) copy
56275a9f908SGreg Roach        self::$trees = [];
563a25f0a04SGreg Roach    }
564a25f0a04SGreg Roach
565a25f0a04SGreg Roach    /**
566a25f0a04SGreg Roach     * Export the tree to a GEDCOM file
567a25f0a04SGreg Roach     *
5685792757eSGreg Roach     * @param resource $stream
569b7e60af1SGreg Roach     *
570b7e60af1SGreg Roach     * @return void
571a25f0a04SGreg Roach     */
572c1010edaSGreg Roach    public function exportGedcom($stream)
573c1010edaSGreg Roach    {
5745792757eSGreg Roach        $stmt = Database::prepare(
575e56ef01aSGreg Roach            "SELECT i_gedcom AS gedcom, i_id AS xref, 1 AS n FROM `##individuals` WHERE i_file = :tree_id_1" .
5765792757eSGreg Roach            " UNION ALL " .
577e56ef01aSGreg Roach            "SELECT f_gedcom AS gedcom, f_id AS xref, 2 AS n FROM `##families`    WHERE f_file = :tree_id_2" .
5785792757eSGreg Roach            " UNION ALL " .
579e56ef01aSGreg Roach            "SELECT s_gedcom AS gedcom, s_id AS xref, 3 AS n FROM `##sources`     WHERE s_file = :tree_id_3" .
5805792757eSGreg Roach            " UNION ALL " .
581e56ef01aSGreg 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')" .
5825792757eSGreg Roach            " UNION ALL " .
583e56ef01aSGreg Roach            "SELECT m_gedcom AS gedcom, m_id AS xref, 5 AS n FROM `##media`       WHERE m_file = :tree_id_5" .
584e56ef01aSGreg Roach            " ORDER BY n, LENGTH(xref), xref"
58513abd6f3SGreg Roach        )->execute([
5865792757eSGreg Roach            'tree_id_1' => $this->tree_id,
5875792757eSGreg Roach            'tree_id_2' => $this->tree_id,
5885792757eSGreg Roach            'tree_id_3' => $this->tree_id,
5895792757eSGreg Roach            'tree_id_4' => $this->tree_id,
590cbc1590aSGreg Roach            'tree_id_5' => $this->tree_id,
59113abd6f3SGreg Roach        ]);
592a25f0a04SGreg Roach
5933d7a8a4cSGreg Roach        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this));
594a214e186SGreg Roach        while (($row = $stmt->fetch()) !== false) {
5953d7a8a4cSGreg Roach            $buffer .= FunctionsExport::reformatRecord($row->gedcom);
596a25f0a04SGreg Roach            if (strlen($buffer) > 65535) {
5975792757eSGreg Roach                fwrite($stream, $buffer);
598a25f0a04SGreg Roach                $buffer = '';
599a25f0a04SGreg Roach            }
600a25f0a04SGreg Roach        }
6010f471f91SGreg Roach        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
602195d09d8SGreg Roach        $stmt->closeCursor();
603a25f0a04SGreg Roach    }
604a25f0a04SGreg Roach
605a25f0a04SGreg Roach    /**
606a25f0a04SGreg Roach     * Import data from a gedcom file into this tree.
607a25f0a04SGreg Roach     *
608a25f0a04SGreg Roach     * @param string $path     The full path to the (possibly temporary) file.
609a25f0a04SGreg Roach     * @param string $filename The preferred filename, for export/download.
610a25f0a04SGreg Roach     *
611b7e60af1SGreg Roach     * @return void
612b7e60af1SGreg Roach     * @throws Exception
613a25f0a04SGreg Roach     */
614771ae10aSGreg Roach    public function importGedcomFile(string $path, string $filename)
615c1010edaSGreg Roach    {
616a25f0a04SGreg Roach        // Read the file in blocks of roughly 64K. Ensure that each block
617a25f0a04SGreg Roach        // contains complete gedcom records. This will ensure we don’t split
618a25f0a04SGreg Roach        // multi-byte characters, as well as simplifying the code to import
619a25f0a04SGreg Roach        // each block.
620a25f0a04SGreg Roach
621a25f0a04SGreg Roach        $file_data = '';
622a25f0a04SGreg Roach        $fp        = fopen($path, 'rb');
623a25f0a04SGreg Roach
624a25f0a04SGreg Roach        // Don’t allow the user to cancel the request. We do not want to be left with an incomplete transaction.
625a25f0a04SGreg Roach        ignore_user_abort(true);
626a25f0a04SGreg Roach
627b7e60af1SGreg Roach        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
628a25f0a04SGreg Roach        $this->setPreference('gedcom_filename', $filename);
629a25f0a04SGreg Roach        $this->setPreference('imported', '0');
630a25f0a04SGreg Roach
631a25f0a04SGreg Roach        while (!feof($fp)) {
632a25f0a04SGreg Roach            $file_data .= fread($fp, 65536);
633a25f0a04SGreg Roach            // There is no strrpos() function that searches for substrings :-(
634a25f0a04SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
635a25f0a04SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
636a25f0a04SGreg Roach                    // We’ve found the last record boundary in this chunk of data
637a25f0a04SGreg Roach                    break;
638a25f0a04SGreg Roach                }
639a25f0a04SGreg Roach            }
640a25f0a04SGreg Roach            if ($pos) {
641a25f0a04SGreg Roach                Database::prepare(
642a25f0a04SGreg Roach                    "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
643c1010edaSGreg Roach                )->execute([
644c1010edaSGreg Roach                    $this->tree_id,
645c1010edaSGreg Roach                    substr($file_data, 0, $pos),
646c1010edaSGreg Roach                ]);
647a25f0a04SGreg Roach                $file_data = substr($file_data, $pos);
648a25f0a04SGreg Roach            }
649a25f0a04SGreg Roach        }
650a25f0a04SGreg Roach        Database::prepare(
651a25f0a04SGreg Roach            "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
652c1010edaSGreg Roach        )->execute([
653c1010edaSGreg Roach            $this->tree_id,
654c1010edaSGreg Roach            $file_data,
655c1010edaSGreg Roach        ]);
656a25f0a04SGreg Roach
657a25f0a04SGreg Roach        fclose($fp);
658a25f0a04SGreg Roach    }
659304f20d5SGreg Roach
660304f20d5SGreg Roach    /**
661b90d8accSGreg Roach     * Generate a new XREF, unique across all family trees
662b90d8accSGreg Roach     *
663b90d8accSGreg Roach     * @return string
664b90d8accSGreg Roach     */
665771ae10aSGreg Roach    public function getNewXref(): string
666c1010edaSGreg Roach    {
667a214e186SGreg Roach        $prefix = 'X';
668b90d8accSGreg Roach
669971d66c8SGreg Roach        $increment = 1.0;
670b90d8accSGreg Roach        do {
671b90d8accSGreg Roach            // Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See
672b90d8accSGreg Roach            // http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
673b90d8accSGreg Roach            $statement = Database::prepare(
674a214e186SGreg Roach                "UPDATE `##site_setting` SET setting_value = LAST_INSERT_ID(setting_value + :increment) WHERE setting_name = 'next_xref'"
675b90d8accSGreg Roach            );
67613abd6f3SGreg Roach            $statement->execute([
677971d66c8SGreg Roach                'increment' => (int) $increment,
67813abd6f3SGreg Roach            ]);
679b90d8accSGreg Roach
680b90d8accSGreg Roach            if ($statement->rowCount() === 0) {
681b90d8accSGreg Roach                // First time we've used this record type.
682a214e186SGreg Roach                Site::setPreference('next_xref', '1');
683b90d8accSGreg Roach                $num = 1;
684b90d8accSGreg Roach            } else {
685b90d8accSGreg Roach                $num = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
686b90d8accSGreg Roach            }
687b90d8accSGreg Roach
688a214e186SGreg Roach            $xref = $prefix . $num;
689a214e186SGreg Roach
690b90d8accSGreg Roach            // Records may already exist with this sequence number.
691b90d8accSGreg Roach            $already_used = Database::prepare(
692a214e186SGreg Roach                "SELECT" .
693a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##individuals` WHERE i_id = :i_id) OR" .
694a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##families` WHERE f_id = :f_id) OR" .
695a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##sources` WHERE s_id = :s_id) OR" .
696a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##media` WHERE m_id = :m_id) OR" .
697a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##other` WHERE o_id = :o_id) OR" .
698a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##change` WHERE xref = :xref)"
69913abd6f3SGreg Roach            )->execute([
700a214e186SGreg Roach                'i_id' => $xref,
701a214e186SGreg Roach                'f_id' => $xref,
702a214e186SGreg Roach                's_id' => $xref,
703a214e186SGreg Roach                'm_id' => $xref,
704a214e186SGreg Roach                'o_id' => $xref,
705a214e186SGreg Roach                'xref' => $xref,
70613abd6f3SGreg Roach            ])->fetchOne();
707971d66c8SGreg Roach
708971d66c8SGreg Roach            // This exponential increment allows us to scan over large blocks of
709971d66c8SGreg Roach            // existing data in a reasonable time.
710971d66c8SGreg Roach            $increment *= 1.01;
711a214e186SGreg Roach        } while ($already_used !== '0');
712b90d8accSGreg Roach
713a214e186SGreg Roach        return $xref;
714b90d8accSGreg Roach    }
715b90d8accSGreg Roach
716b90d8accSGreg Roach    /**
717304f20d5SGreg Roach     * Create a new record from GEDCOM data.
718304f20d5SGreg Roach     *
719304f20d5SGreg Roach     * @param string $gedcom
720304f20d5SGreg Roach     *
72115d603e7SGreg Roach     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
722b7e60af1SGreg Roach     * @throws Exception
723304f20d5SGreg Roach     */
724771ae10aSGreg Roach    public function createRecord(string $gedcom): GedcomRecord
725c1010edaSGreg Roach    {
726304f20d5SGreg Roach        if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom, $match)) {
727304f20d5SGreg Roach            $xref = $match[1];
728304f20d5SGreg Roach            $type = $match[2];
729304f20d5SGreg Roach        } else {
730b7e60af1SGreg Roach            throw new Exception('Invalid argument to GedcomRecord::createRecord(' . $gedcom . ')');
731304f20d5SGreg Roach        }
7329f2d0ff7SGreg Roach        if (strpos($gedcom, "\r") !== false) {
733304f20d5SGreg Roach            // MSDOS line endings will break things in horrible ways
734b7e60af1SGreg Roach            throw new Exception('Evil line endings found in GedcomRecord::createRecord(' . $gedcom . ')');
735304f20d5SGreg Roach        }
736304f20d5SGreg Roach
737304f20d5SGreg Roach        // webtrees creates XREFs containing digits. Anything else (e.g. “new”) is just a placeholder.
738304f20d5SGreg Roach        if (!preg_match('/\d/', $xref)) {
739a214e186SGreg Roach            $xref   = $this->getNewXref();
740304f20d5SGreg Roach            $gedcom = preg_replace('/^0 @(' . WT_REGEX_XREF . ')@/', '0 @' . $xref . '@', $gedcom);
741304f20d5SGreg Roach        }
742304f20d5SGreg Roach
743304f20d5SGreg Roach        // Create a change record, if not already present
744304f20d5SGreg Roach        if (!preg_match('/\n1 CHAN/', $gedcom)) {
745304f20d5SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
746304f20d5SGreg Roach        }
747304f20d5SGreg Roach
748304f20d5SGreg Roach        // Create a pending change
749304f20d5SGreg Roach        Database::prepare(
750304f20d5SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
75113abd6f3SGreg Roach        )->execute([
752bb7c2cdcSGreg Roach            $this->tree_id,
753304f20d5SGreg Roach            $xref,
754304f20d5SGreg Roach            $gedcom,
755cbc1590aSGreg Roach            Auth::id(),
75613abd6f3SGreg Roach        ]);
757304f20d5SGreg Roach
758847d5489SGreg Roach        Log::addEditLog('Create: ' . $type . ' ' . $xref, $this);
759304f20d5SGreg Roach
760304f20d5SGreg Roach        // Accept this pending change
761304f20d5SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
762cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
763304f20d5SGreg Roach        }
764bb7c2cdcSGreg Roach        // Return the newly created record. Note that since GedcomRecord
765bb7c2cdcSGreg Roach        // has a cache of pending changes, we cannot use it to create a
766bb7c2cdcSGreg Roach        // record with a newly created pending change.
76724ec66ceSGreg Roach        return GedcomRecord::getInstance($xref, $this, $gedcom);
768304f20d5SGreg Roach    }
7698586983fSGreg Roach
7708586983fSGreg Roach    /**
7718586983fSGreg Roach     * What is the most significant individual in this tree.
7728586983fSGreg Roach     *
7738586983fSGreg Roach     * @param User $user
7748586983fSGreg Roach     *
7758586983fSGreg Roach     * @return Individual
7768586983fSGreg Roach     */
777c1010edaSGreg Roach    public function significantIndividual(User $user): Individual
778c1010edaSGreg Roach    {
7798586983fSGreg Roach        static $individual; // Only query the DB once.
7808586983fSGreg Roach
7817015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'rootid') !== '') {
7828586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
7838586983fSGreg Roach        }
7847015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'gedcomid') !== '') {
7858586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
7868586983fSGreg Roach        }
7878586983fSGreg Roach        if (!$individual) {
7888586983fSGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
7898586983fSGreg Roach        }
7908586983fSGreg Roach        if (!$individual) {
7918586983fSGreg Roach            $individual = Individual::getInstance(
7928586983fSGreg Roach                Database::prepare(
7935fe1add5SGreg Roach                    "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
7945fe1add5SGreg Roach                )->execute([
7955fe1add5SGreg Roach                    'tree_id' => $this->getTreeId(),
7965fe1add5SGreg Roach                ])->fetchOne(),
7975fe1add5SGreg Roach                $this
7985fe1add5SGreg Roach            );
7995fe1add5SGreg Roach        }
8005fe1add5SGreg Roach        if (!$individual) {
8015fe1add5SGreg Roach            // always return a record
8025fe1add5SGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
8035fe1add5SGreg Roach        }
8045fe1add5SGreg Roach
8055fe1add5SGreg Roach        return $individual;
8065fe1add5SGreg Roach    }
8075fe1add5SGreg Roach
8085fe1add5SGreg Roach    /**
8095fe1add5SGreg Roach     * Get significant information from this page, to allow other pages such as
8105fe1add5SGreg Roach     * charts and reports to initialise with the same records
8115fe1add5SGreg Roach     *
8125fe1add5SGreg Roach     * @return Individual
8135fe1add5SGreg Roach     */
814771ae10aSGreg Roach    public function getSignificantIndividual(): Individual
815c1010edaSGreg Roach    {
8165fe1add5SGreg Roach        static $individual; // Only query the DB once.
8175fe1add5SGreg Roach
8187015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'rootid') !== '') {
8195fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'rootid'), $this);
8205fe1add5SGreg Roach        }
8217015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'gedcomid') !== '') {
8225fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'gedcomid'), $this);
8235fe1add5SGreg Roach        }
8245fe1add5SGreg Roach        if (!$individual) {
8255fe1add5SGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
8265fe1add5SGreg Roach        }
8275fe1add5SGreg Roach        if (!$individual) {
8285fe1add5SGreg Roach            $individual = Individual::getInstance(
8295fe1add5SGreg Roach                Database::prepare(
8308586983fSGreg Roach                    "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = ?"
8318586983fSGreg Roach                )->execute([$this->getTreeId()])->fetchOne(),
8328586983fSGreg Roach                $this
8338586983fSGreg Roach            );
8348586983fSGreg Roach        }
8358586983fSGreg Roach        if (!$individual) {
8368586983fSGreg Roach            // always return a record
8378586983fSGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
8388586983fSGreg Roach        }
8398586983fSGreg Roach
8408586983fSGreg Roach        return $individual;
8418586983fSGreg Roach    }
842a25f0a04SGreg Roach}
843