xref: /webtrees/app/Tree.php (revision b2ce94c6833c25934b40a7e6bc15985d50b5f42a)
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 */
1676692c8bSGreg Roachnamespace Fisharebest\Webtrees;
17a25f0a04SGreg Roach
18b7e60af1SGreg Roachuse Exception;
193d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsExport;
203d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
21a25f0a04SGreg Roachuse PDOException;
22a25f0a04SGreg Roach
23a25f0a04SGreg Roach/**
2476692c8bSGreg Roach * Provide an interface to the wt_gedcom table.
25a25f0a04SGreg Roach */
26c1010edaSGreg Roachclass Tree
27c1010edaSGreg Roach{
28cbc1590aSGreg Roach    /** @var int The tree's ID number */
29518bbdc1SGreg Roach    private $tree_id;
30518bbdc1SGreg Roach
31a25f0a04SGreg Roach    /** @var string The tree's name */
32a25f0a04SGreg Roach    private $name;
33518bbdc1SGreg Roach
34a25f0a04SGreg Roach    /** @var string The tree's title */
35a25f0a04SGreg Roach    private $title;
36a25f0a04SGreg Roach
37e2052359SGreg Roach    /** @var int[] Default access rules for facts in this tree */
38518bbdc1SGreg Roach    private $fact_privacy;
39518bbdc1SGreg Roach
40e2052359SGreg Roach    /** @var int[] Default access rules for individuals in this tree */
41518bbdc1SGreg Roach    private $individual_privacy;
42518bbdc1SGreg Roach
43518bbdc1SGreg Roach    /** @var integer[][] Default access rules for individual facts in this tree */
44518bbdc1SGreg Roach    private $individual_fact_privacy;
45518bbdc1SGreg Roach
46a25f0a04SGreg Roach    /** @var Tree[] All trees that we have permission to see. */
4775a9f908SGreg Roach    private static $trees = [];
48a25f0a04SGreg Roach
49a25f0a04SGreg Roach    /** @var string[] Cached copy of the wt_gedcom_setting table. */
5015d603e7SGreg Roach    private $preferences = [];
51a25f0a04SGreg Roach
52a25f0a04SGreg Roach    /** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
5313abd6f3SGreg Roach    private $user_preferences = [];
54a25f0a04SGreg Roach
55a25f0a04SGreg Roach    /**
56a25f0a04SGreg Roach     * Create a tree object. This is a private constructor - it can only
57a25f0a04SGreg Roach     * be called from Tree::getAll() to ensure proper initialisation.
58a25f0a04SGreg Roach     *
59cbc1590aSGreg Roach     * @param int    $tree_id
60a25f0a04SGreg Roach     * @param string $tree_name
61a25f0a04SGreg Roach     * @param string $tree_title
62a25f0a04SGreg Roach     */
63c1010edaSGreg Roach    private function __construct($tree_id, $tree_name, $tree_title)
64c1010edaSGreg Roach    {
65518bbdc1SGreg Roach        $this->tree_id                 = $tree_id;
66a25f0a04SGreg Roach        $this->name                    = $tree_name;
67a25f0a04SGreg Roach        $this->title                   = $tree_title;
6813abd6f3SGreg Roach        $this->fact_privacy            = [];
6913abd6f3SGreg Roach        $this->individual_privacy      = [];
7013abd6f3SGreg Roach        $this->individual_fact_privacy = [];
71518bbdc1SGreg Roach
72518bbdc1SGreg Roach        // Load the privacy settings for this tree
73518bbdc1SGreg Roach        $rows = Database::prepare(
74e5588fb0SGreg 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" .
75518bbdc1SGreg Roach            " FROM `##default_resn` WHERE gedcom_id = :tree_id"
7613abd6f3SGreg Roach        )->execute([
774b9ff166SGreg Roach            'priv_public' => Auth::PRIV_PRIVATE,
784b9ff166SGreg Roach            'priv_user'   => Auth::PRIV_USER,
794b9ff166SGreg Roach            'priv_none'   => Auth::PRIV_NONE,
804b9ff166SGreg Roach            'priv_hide'   => Auth::PRIV_HIDE,
81cbc1590aSGreg Roach            'tree_id'     => $this->tree_id,
8213abd6f3SGreg Roach        ])->fetchAll();
83518bbdc1SGreg Roach
84518bbdc1SGreg Roach        foreach ($rows as $row) {
85518bbdc1SGreg Roach            if ($row->xref !== null) {
86518bbdc1SGreg Roach                if ($row->tag_type !== null) {
87518bbdc1SGreg Roach                    $this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
88518bbdc1SGreg Roach                } else {
89518bbdc1SGreg Roach                    $this->individual_privacy[$row->xref] = (int) $row->resn;
90518bbdc1SGreg Roach                }
91518bbdc1SGreg Roach            } else {
92518bbdc1SGreg Roach                $this->fact_privacy[$row->tag_type] = (int) $row->resn;
93518bbdc1SGreg Roach            }
94518bbdc1SGreg Roach        }
95a25f0a04SGreg Roach    }
96a25f0a04SGreg Roach
97a25f0a04SGreg Roach    /**
98a25f0a04SGreg Roach     * The ID of this tree
99a25f0a04SGreg Roach     *
100cbc1590aSGreg Roach     * @return int
101a25f0a04SGreg Roach     */
1028f53f488SRico Sonntag    public function getTreeId(): int
103c1010edaSGreg Roach    {
104518bbdc1SGreg Roach        return $this->tree_id;
105a25f0a04SGreg Roach    }
106a25f0a04SGreg Roach
107a25f0a04SGreg Roach    /**
108a25f0a04SGreg Roach     * The name of this tree
109a25f0a04SGreg Roach     *
110a25f0a04SGreg Roach     * @return string
111a25f0a04SGreg Roach     */
1128f53f488SRico Sonntag    public function getName(): string
113c1010edaSGreg Roach    {
114a25f0a04SGreg Roach        return $this->name;
115a25f0a04SGreg Roach    }
116a25f0a04SGreg Roach
117a25f0a04SGreg Roach    /**
118a25f0a04SGreg Roach     * The title of this tree
119a25f0a04SGreg Roach     *
120a25f0a04SGreg Roach     * @return string
121a25f0a04SGreg Roach     */
1228f53f488SRico Sonntag    public function getTitle(): string
123c1010edaSGreg Roach    {
124a25f0a04SGreg Roach        return $this->title;
125a25f0a04SGreg Roach    }
126a25f0a04SGreg Roach
127a25f0a04SGreg Roach    /**
128518bbdc1SGreg Roach     * The fact-level privacy for this tree.
129518bbdc1SGreg Roach     *
130e2052359SGreg Roach     * @return int[]
131518bbdc1SGreg Roach     */
1328f53f488SRico Sonntag    public function getFactPrivacy(): array
133c1010edaSGreg Roach    {
134518bbdc1SGreg Roach        return $this->fact_privacy;
135518bbdc1SGreg Roach    }
136518bbdc1SGreg Roach
137518bbdc1SGreg Roach    /**
138518bbdc1SGreg Roach     * The individual-level privacy for this tree.
139518bbdc1SGreg Roach     *
140e2052359SGreg Roach     * @return int[]
141518bbdc1SGreg Roach     */
1428f53f488SRico Sonntag    public function getIndividualPrivacy(): array
143c1010edaSGreg Roach    {
144518bbdc1SGreg Roach        return $this->individual_privacy;
145518bbdc1SGreg Roach    }
146518bbdc1SGreg Roach
147518bbdc1SGreg Roach    /**
148518bbdc1SGreg Roach     * The individual-fact-level privacy for this tree.
149518bbdc1SGreg Roach     *
150adac8af1SGreg Roach     * @return int[][]
151518bbdc1SGreg Roach     */
1528f53f488SRico Sonntag    public function getIndividualFactPrivacy(): array
153c1010edaSGreg Roach    {
154518bbdc1SGreg Roach        return $this->individual_fact_privacy;
155518bbdc1SGreg Roach    }
156518bbdc1SGreg Roach
157518bbdc1SGreg Roach    /**
158a25f0a04SGreg Roach     * Get the tree’s configuration settings.
159a25f0a04SGreg Roach     *
160a25f0a04SGreg Roach     * @param string $setting_name
16115d603e7SGreg Roach     * @param string $default
162a25f0a04SGreg Roach     *
16315d603e7SGreg Roach     * @return string
164a25f0a04SGreg Roach     */
165771ae10aSGreg Roach    public function getPreference(string $setting_name, string $default = ''): string
166c1010edaSGreg Roach    {
16715d603e7SGreg Roach        if (empty($this->preferences)) {
168a25f0a04SGreg Roach            $this->preferences = Database::prepare(
169e5588fb0SGreg Roach                "SELECT setting_name, setting_value FROM `##gedcom_setting` WHERE gedcom_id = ?"
17013abd6f3SGreg Roach            )->execute([$this->tree_id])->fetchAssoc();
171a25f0a04SGreg Roach        }
172a25f0a04SGreg Roach
173*b2ce94c6SRico Sonntag        return $this->preferences[$setting_name] ?? $default;
174a25f0a04SGreg Roach    }
175a25f0a04SGreg Roach
176a25f0a04SGreg Roach    /**
177a25f0a04SGreg Roach     * Set the tree’s configuration settings.
178a25f0a04SGreg Roach     *
179a25f0a04SGreg Roach     * @param string $setting_name
180a25f0a04SGreg Roach     * @param string $setting_value
181a25f0a04SGreg Roach     *
182a25f0a04SGreg Roach     * @return $this
183a25f0a04SGreg Roach     */
184771ae10aSGreg Roach    public function setPreference(string $setting_name, string $setting_value): Tree
185c1010edaSGreg Roach    {
186a25f0a04SGreg Roach        if ($setting_value !== $this->getPreference($setting_name)) {
187a25f0a04SGreg Roach            Database::prepare(
188a25f0a04SGreg Roach                "REPLACE INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
189a25f0a04SGreg Roach                " VALUES (:tree_id, :setting_name, LEFT(:setting_value, 255))"
19013abd6f3SGreg Roach            )->execute([
191518bbdc1SGreg Roach                'tree_id'       => $this->tree_id,
192a25f0a04SGreg Roach                'setting_name'  => $setting_name,
193a25f0a04SGreg Roach                'setting_value' => $setting_value,
19413abd6f3SGreg Roach            ]);
19515d603e7SGreg Roach
196a25f0a04SGreg Roach            $this->preferences[$setting_name] = $setting_value;
19715d603e7SGreg Roach
19872292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
199a25f0a04SGreg Roach        }
200a25f0a04SGreg Roach
201a25f0a04SGreg Roach        return $this;
202a25f0a04SGreg Roach    }
203a25f0a04SGreg Roach
204a25f0a04SGreg Roach    /**
205a25f0a04SGreg Roach     * Get the tree’s user-configuration settings.
206a25f0a04SGreg Roach     *
207a25f0a04SGreg Roach     * @param User   $user
208a25f0a04SGreg Roach     * @param string $setting_name
2097015ba1fSGreg Roach     * @param string $default
210a25f0a04SGreg Roach     *
211a25f0a04SGreg Roach     * @return string
212a25f0a04SGreg Roach     */
213771ae10aSGreg Roach    public function getUserPreference(User $user, string $setting_name, string $default = ''): string
214c1010edaSGreg Roach    {
215a25f0a04SGreg Roach        // There are lots of settings, and we need to fetch lots of them on every page
216a25f0a04SGreg Roach        // so it is quicker to fetch them all in one go.
217a25f0a04SGreg Roach        if (!array_key_exists($user->getUserId(), $this->user_preferences)) {
218a25f0a04SGreg Roach            $this->user_preferences[$user->getUserId()] = Database::prepare(
219e5588fb0SGreg Roach                "SELECT setting_name, setting_value FROM `##user_gedcom_setting` WHERE user_id = ? AND gedcom_id = ?"
220c1010edaSGreg Roach            )->execute([
221c1010edaSGreg Roach                $user->getUserId(),
222c1010edaSGreg Roach                $this->tree_id,
223c1010edaSGreg Roach            ])->fetchAssoc();
224a25f0a04SGreg Roach        }
225a25f0a04SGreg Roach
226*b2ce94c6SRico Sonntag        return $this->user_preferences[$user->getUserId()][$setting_name] ?? $default;
227a25f0a04SGreg Roach    }
228a25f0a04SGreg Roach
229a25f0a04SGreg Roach    /**
230a25f0a04SGreg Roach     * Set the tree’s user-configuration settings.
231a25f0a04SGreg Roach     *
232a25f0a04SGreg Roach     * @param User   $user
233a25f0a04SGreg Roach     * @param string $setting_name
234a25f0a04SGreg Roach     * @param string $setting_value
235a25f0a04SGreg Roach     *
236a25f0a04SGreg Roach     * @return $this
237a25f0a04SGreg Roach     */
238771ae10aSGreg Roach    public function setUserPreference(User $user, string $setting_name, string $setting_value): Tree
239c1010edaSGreg Roach    {
240a25f0a04SGreg Roach        if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
241a25f0a04SGreg Roach            // Update the database
2427015ba1fSGreg Roach            if ($setting_value === '') {
243a25f0a04SGreg Roach                Database::prepare(
244a25f0a04SGreg Roach                    "DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = :tree_id AND user_id = :user_id AND setting_name = :setting_name"
24513abd6f3SGreg Roach                )->execute([
246518bbdc1SGreg Roach                    'tree_id'      => $this->tree_id,
247a25f0a04SGreg Roach                    'user_id'      => $user->getUserId(),
248a25f0a04SGreg Roach                    'setting_name' => $setting_name,
24913abd6f3SGreg Roach                ]);
250a25f0a04SGreg Roach            } else {
251a25f0a04SGreg Roach                Database::prepare(
252a25f0a04SGreg 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))"
25313abd6f3SGreg Roach                )->execute([
254a25f0a04SGreg Roach                    'user_id'       => $user->getUserId(),
255518bbdc1SGreg Roach                    'tree_id'       => $this->tree_id,
256a25f0a04SGreg Roach                    'setting_name'  => $setting_name,
257cbc1590aSGreg Roach                    'setting_value' => $setting_value,
25813abd6f3SGreg Roach                ]);
259a25f0a04SGreg Roach            }
260a25f0a04SGreg Roach            // Update our cache
261a25f0a04SGreg Roach            $this->user_preferences[$user->getUserId()][$setting_name] = $setting_value;
262a25f0a04SGreg Roach            // Audit log of changes
26372292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this);
264a25f0a04SGreg Roach        }
265a25f0a04SGreg Roach
266a25f0a04SGreg Roach        return $this;
267a25f0a04SGreg Roach    }
268a25f0a04SGreg Roach
269a25f0a04SGreg Roach    /**
270a25f0a04SGreg Roach     * Can a user accept changes for this tree?
271a25f0a04SGreg Roach     *
272a25f0a04SGreg Roach     * @param User $user
273a25f0a04SGreg Roach     *
274cbc1590aSGreg Roach     * @return bool
275a25f0a04SGreg Roach     */
276771ae10aSGreg Roach    public function canAcceptChanges(User $user): bool
277c1010edaSGreg Roach    {
278a25f0a04SGreg Roach        return Auth::isModerator($this, $user);
279a25f0a04SGreg Roach    }
280a25f0a04SGreg Roach
281a25f0a04SGreg Roach    /**
282a25f0a04SGreg Roach     * Fetch all the trees that we have permission to access.
283a25f0a04SGreg Roach     *
284a25f0a04SGreg Roach     * @return Tree[]
285a25f0a04SGreg Roach     */
286771ae10aSGreg Roach    public static function getAll(): array
287c1010edaSGreg Roach    {
28875a9f908SGreg Roach        if (empty(self::$trees)) {
289a25f0a04SGreg Roach            $rows        = Database::prepare(
290e5588fb0SGreg Roach                "SELECT g.gedcom_id AS tree_id, g.gedcom_name AS tree_name, gs1.setting_value AS tree_title" .
291a25f0a04SGreg Roach                " FROM `##gedcom` g" .
292a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs1 ON (g.gedcom_id=gs1.gedcom_id AND gs1.setting_name='title')" .
293a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs2 ON (g.gedcom_id=gs2.gedcom_id AND gs2.setting_name='imported')" .
294a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs3 ON (g.gedcom_id=gs3.gedcom_id AND gs3.setting_name='REQUIRE_AUTHENTICATION')" .
295a25f0a04SGreg Roach                " LEFT JOIN `##user_gedcom_setting` ugs ON (g.gedcom_id=ugs.gedcom_id AND ugs.setting_name='canedit' AND ugs.user_id=?)" .
296a25f0a04SGreg Roach                " WHERE " .
297a25f0a04SGreg Roach                "  g.gedcom_id>0 AND (" . // exclude the "template" tree
298a25f0a04SGreg Roach                "    EXISTS (SELECT 1 FROM `##user_setting` WHERE user_id=? AND setting_name='canadmin' AND setting_value=1)" . // Admin sees all
299a25f0a04SGreg Roach                "   ) OR (" .
3008cca4ddeSGreg Roach                "    (gs2.setting_value = 1 OR ugs.setting_value = 'admin') AND (" . // Allow imported trees, with either:
301a25f0a04SGreg Roach                "     gs3.setting_value <> 1 OR" . // visitor access
302a25f0a04SGreg Roach                "     IFNULL(ugs.setting_value, 'none')<>'none'" . // explicit access
303a25f0a04SGreg Roach                "   )" .
304a25f0a04SGreg Roach                "  )" .
305a25f0a04SGreg Roach                " ORDER BY g.sort_order, 3"
306c1010edaSGreg Roach            )->execute([
307c1010edaSGreg Roach                Auth::id(),
308c1010edaSGreg Roach                Auth::id(),
309c1010edaSGreg Roach            ])->fetchAll();
31075a9f908SGreg Roach
311a25f0a04SGreg Roach            foreach ($rows as $row) {
3123f7ece23SGreg Roach                self::$trees[$row->tree_name] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
313a25f0a04SGreg Roach            }
314a25f0a04SGreg Roach        }
315a25f0a04SGreg Roach
316a25f0a04SGreg Roach        return self::$trees;
317a25f0a04SGreg Roach    }
318a25f0a04SGreg Roach
319a25f0a04SGreg Roach    /**
320d2cdeb3fSGreg Roach     * Find the tree with a specific ID.
321a25f0a04SGreg Roach     *
322cbc1590aSGreg Roach     * @param int $tree_id
323cbc1590aSGreg Roach     *
324cbc1590aSGreg Roach     * @throws \DomainException
325a25f0a04SGreg Roach     * @return Tree
326a25f0a04SGreg Roach     */
327771ae10aSGreg Roach    public static function findById($tree_id): Tree
328c1010edaSGreg Roach    {
32951d0f842SGreg Roach        foreach (self::getAll() as $tree) {
330e568acceSGreg Roach            if ($tree->tree_id == $tree_id) {
33151d0f842SGreg Roach                return $tree;
33251d0f842SGreg Roach            }
33351d0f842SGreg Roach        }
33459f2f229SGreg Roach        throw new \DomainException();
335a25f0a04SGreg Roach    }
336a25f0a04SGreg Roach
337a25f0a04SGreg Roach    /**
338d2cdeb3fSGreg Roach     * Find the tree with a specific name.
339cf4bcc09SGreg Roach     *
340cf4bcc09SGreg Roach     * @param string $tree_name
341cf4bcc09SGreg Roach     *
342cf4bcc09SGreg Roach     * @return Tree|null
343cf4bcc09SGreg Roach     */
344c1010edaSGreg Roach    public static function findByName($tree_name)
345c1010edaSGreg Roach    {
346cf4bcc09SGreg Roach        foreach (self::getAll() as $tree) {
34751d0f842SGreg Roach            if ($tree->name === $tree_name) {
348cf4bcc09SGreg Roach                return $tree;
349cf4bcc09SGreg Roach            }
350cf4bcc09SGreg Roach        }
351cf4bcc09SGreg Roach
352cf4bcc09SGreg Roach        return null;
353cf4bcc09SGreg Roach    }
354cf4bcc09SGreg Roach
355cf4bcc09SGreg Roach    /**
356a25f0a04SGreg Roach     * Create arguments to select_edit_control()
357a25f0a04SGreg Roach     * Note - these will be escaped later
358a25f0a04SGreg Roach     *
359a25f0a04SGreg Roach     * @return string[]
360a25f0a04SGreg Roach     */
361771ae10aSGreg Roach    public static function getIdList(): array
362c1010edaSGreg Roach    {
36313abd6f3SGreg Roach        $list = [];
364a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
365518bbdc1SGreg Roach            $list[$tree->tree_id] = $tree->title;
366a25f0a04SGreg Roach        }
367a25f0a04SGreg Roach
368a25f0a04SGreg Roach        return $list;
369a25f0a04SGreg Roach    }
370a25f0a04SGreg Roach
371a25f0a04SGreg Roach    /**
372a25f0a04SGreg Roach     * Create arguments to select_edit_control()
373a25f0a04SGreg Roach     * Note - these will be escaped later
374a25f0a04SGreg Roach     *
375a25f0a04SGreg Roach     * @return string[]
376a25f0a04SGreg Roach     */
377771ae10aSGreg Roach    public static function getNameList(): array
378c1010edaSGreg Roach    {
37913abd6f3SGreg Roach        $list = [];
380a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
381a25f0a04SGreg Roach            $list[$tree->name] = $tree->title;
382a25f0a04SGreg Roach        }
383a25f0a04SGreg Roach
384a25f0a04SGreg Roach        return $list;
385a25f0a04SGreg Roach    }
386a25f0a04SGreg Roach
387a25f0a04SGreg Roach    /**
388a25f0a04SGreg Roach     * Create a new tree
389a25f0a04SGreg Roach     *
390a25f0a04SGreg Roach     * @param string $tree_name
391a25f0a04SGreg Roach     * @param string $tree_title
392a25f0a04SGreg Roach     *
393a25f0a04SGreg Roach     * @return Tree
394a25f0a04SGreg Roach     */
395771ae10aSGreg Roach    public static function create(string $tree_name, string $tree_title): Tree
396c1010edaSGreg Roach    {
397a25f0a04SGreg Roach        try {
398a25f0a04SGreg Roach            // Create a new tree
399a25f0a04SGreg Roach            Database::prepare(
400a25f0a04SGreg Roach                "INSERT INTO `##gedcom` (gedcom_name) VALUES (?)"
40113abd6f3SGreg Roach            )->execute([$tree_name]);
402a25f0a04SGreg Roach            $tree_id = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
403a25f0a04SGreg Roach        } catch (PDOException $ex) {
404bd52fa32SGreg Roach            DebugBar::addThrowable($ex);
405bd52fa32SGreg Roach
406a25f0a04SGreg Roach            // A tree with that name already exists?
407ef2fd529SGreg Roach            return self::findByName($tree_name);
408a25f0a04SGreg Roach        }
409a25f0a04SGreg Roach
410a25f0a04SGreg Roach        // Update the list of trees - to include this new one
41175a9f908SGreg Roach        self::$trees = [];
412d2cdeb3fSGreg Roach        $tree        = self::findById($tree_id);
413a25f0a04SGreg Roach
414a25f0a04SGreg Roach        $tree->setPreference('imported', '0');
415a25f0a04SGreg Roach        $tree->setPreference('title', $tree_title);
416a25f0a04SGreg Roach
417a25f0a04SGreg Roach        // Module privacy
418a25f0a04SGreg Roach        Module::setDefaultAccess($tree_id);
419a25f0a04SGreg Roach
4201507cbcaSGreg Roach        // Set preferences from default tree
4211507cbcaSGreg Roach        Database::prepare(
4221507cbcaSGreg Roach            "INSERT INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
4231507cbcaSGreg Roach            " SELECT :tree_id, setting_name, setting_value" .
4241507cbcaSGreg Roach            " FROM `##gedcom_setting` WHERE gedcom_id = -1"
42513abd6f3SGreg Roach        )->execute([
4261507cbcaSGreg Roach            'tree_id' => $tree_id,
42713abd6f3SGreg Roach        ]);
4281507cbcaSGreg Roach
4291507cbcaSGreg Roach        Database::prepare(
4301507cbcaSGreg Roach            "INSERT INTO `##default_resn` (gedcom_id, tag_type, resn)" .
4311507cbcaSGreg Roach            " SELECT :tree_id, tag_type, resn" .
4321507cbcaSGreg Roach            " FROM `##default_resn` WHERE gedcom_id = -1"
43313abd6f3SGreg Roach        )->execute([
4341507cbcaSGreg Roach            'tree_id' => $tree_id,
43513abd6f3SGreg Roach        ]);
4361507cbcaSGreg Roach
4371507cbcaSGreg Roach        Database::prepare(
4381507cbcaSGreg Roach            "INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" .
4391507cbcaSGreg Roach            " SELECT :tree_id, location, block_order, module_name" .
4401507cbcaSGreg Roach            " FROM `##block` WHERE gedcom_id = -1"
44113abd6f3SGreg Roach        )->execute([
4421507cbcaSGreg Roach            'tree_id' => $tree_id,
44313abd6f3SGreg Roach        ]);
4441507cbcaSGreg Roach
445a25f0a04SGreg Roach        // Gedcom and privacy settings
44676f666f4SGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
44776f666f4SGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
448a25f0a04SGreg Roach        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
449a25f0a04SGreg Roach        switch (WT_LOCALE) {
450a25f0a04SGreg Roach            case 'es':
451a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'spanish');
452a25f0a04SGreg Roach                break;
453a25f0a04SGreg Roach            case 'is':
454a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
455a25f0a04SGreg Roach                break;
456a25f0a04SGreg Roach            case 'lt':
457a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
458a25f0a04SGreg Roach                break;
459a25f0a04SGreg Roach            case 'pl':
460a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'polish');
461a25f0a04SGreg Roach                break;
462a25f0a04SGreg Roach            case 'pt':
463a25f0a04SGreg Roach            case 'pt-BR':
464a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
465a25f0a04SGreg Roach                break;
466a25f0a04SGreg Roach            default:
467a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'paternal');
468a25f0a04SGreg Roach                break;
469a25f0a04SGreg Roach        }
470a25f0a04SGreg Roach
471a25f0a04SGreg Roach        // Genealogy data
472a25f0a04SGreg Roach        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
473bbb76c12SGreg Roach        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
474bbb76c12SGreg Roach        $john_doe = I18N::translate('John /DOE/');
47577e70a22SGreg Roach        $note     = I18N::translate('Edit this individual and replace their details with your own.');
47613abd6f3SGreg Roach        Database::prepare("INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)")->execute([
477a25f0a04SGreg Roach            $tree_id,
478cbc1590aSGreg 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",
47913abd6f3SGreg Roach        ]);
480a25f0a04SGreg Roach
481a25f0a04SGreg Roach        // Update our cache
482518bbdc1SGreg Roach        self::$trees[$tree->tree_id] = $tree;
483a25f0a04SGreg Roach
484a25f0a04SGreg Roach        return $tree;
485a25f0a04SGreg Roach    }
486a25f0a04SGreg Roach
487a25f0a04SGreg Roach    /**
488b78374c5SGreg Roach     * Are there any pending edits for this tree, than need reviewing by a moderator.
489b78374c5SGreg Roach     *
490b78374c5SGreg Roach     * @return bool
491b78374c5SGreg Roach     */
492771ae10aSGreg Roach    public function hasPendingEdit(): bool
493c1010edaSGreg Roach    {
494b78374c5SGreg Roach        return (bool) Database::prepare(
495b78374c5SGreg Roach            "SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
49613abd6f3SGreg Roach        )->execute([
497cbc1590aSGreg Roach            'tree_id' => $this->tree_id,
49813abd6f3SGreg Roach        ])->fetchOne();
499b78374c5SGreg Roach    }
500b78374c5SGreg Roach
501b78374c5SGreg Roach    /**
502a25f0a04SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
503a25f0a04SGreg Roach     * new data. Optionally retain the media data, for when the user has been
504a25f0a04SGreg Roach     * editing their data offline using an application which deletes (or does not
505a25f0a04SGreg Roach     * support) media data.
506a25f0a04SGreg Roach     *
507a25f0a04SGreg Roach     * @param bool $keep_media
508b7e60af1SGreg Roach     *
509b7e60af1SGreg Roach     * @return void
510a25f0a04SGreg Roach     */
511b7e60af1SGreg Roach    public function deleteGenealogyData(bool $keep_media)
512c1010edaSGreg Roach    {
51313abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute([$this->tree_id]);
51413abd6f3SGreg Roach        Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute([$this->tree_id]);
51513abd6f3SGreg Roach        Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute([$this->tree_id]);
51613abd6f3SGreg Roach        Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute([$this->tree_id]);
51713abd6f3SGreg Roach        Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute([$this->tree_id]);
51813abd6f3SGreg Roach        Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute([$this->tree_id]);
51913abd6f3SGreg Roach        Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute([$this->tree_id]);
52013abd6f3SGreg Roach        Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute([$this->tree_id]);
52113abd6f3SGreg Roach        Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute([$this->tree_id]);
52213abd6f3SGreg Roach        Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute([$this->tree_id]);
523a25f0a04SGreg Roach
524a25f0a04SGreg Roach        if ($keep_media) {
52513abd6f3SGreg Roach            Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute([$this->tree_id]);
526a25f0a04SGreg Roach        } else {
52713abd6f3SGreg Roach            Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute([$this->tree_id]);
52813abd6f3SGreg Roach            Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute([$this->tree_id]);
52923ed9d24SGreg Roach            Database::prepare("DELETE FROM `##media_file` WHERE m_file =?")->execute([$this->tree_id]);
530a25f0a04SGreg Roach        }
531a25f0a04SGreg Roach    }
532a25f0a04SGreg Roach
533a25f0a04SGreg Roach    /**
534a25f0a04SGreg Roach     * Delete everything relating to a tree
535b7e60af1SGreg Roach     *
536b7e60af1SGreg Roach     * @return void
537a25f0a04SGreg Roach     */
538c1010edaSGreg Roach    public function delete()
539c1010edaSGreg Roach    {
540a25f0a04SGreg Roach        // If this is the default tree, then unset it
541ef2fd529SGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
542a25f0a04SGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
543a25f0a04SGreg Roach        }
544a25f0a04SGreg Roach
545a25f0a04SGreg Roach        $this->deleteGenealogyData(false);
546a25f0a04SGreg Roach
54713abd6f3SGreg Roach        Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute([$this->tree_id]);
54813abd6f3SGreg Roach        Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute([$this->tree_id]);
54913abd6f3SGreg Roach        Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute([$this->tree_id]);
55013abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
55113abd6f3SGreg Roach        Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
55213abd6f3SGreg Roach        Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute([$this->tree_id]);
55313abd6f3SGreg Roach        Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
55413abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
55513abd6f3SGreg Roach        Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute([$this->tree_id]);
55613abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute([$this->tree_id]);
557a25f0a04SGreg Roach
558a25f0a04SGreg Roach        // After updating the database, we need to fetch a new (sorted) copy
55975a9f908SGreg Roach        self::$trees = [];
560a25f0a04SGreg Roach    }
561a25f0a04SGreg Roach
562a25f0a04SGreg Roach    /**
563a25f0a04SGreg Roach     * Export the tree to a GEDCOM file
564a25f0a04SGreg Roach     *
5655792757eSGreg Roach     * @param resource $stream
566b7e60af1SGreg Roach     *
567b7e60af1SGreg Roach     * @return void
568a25f0a04SGreg Roach     */
569c1010edaSGreg Roach    public function exportGedcom($stream)
570c1010edaSGreg Roach    {
5715792757eSGreg Roach        $stmt = Database::prepare(
572e56ef01aSGreg Roach            "SELECT i_gedcom AS gedcom, i_id AS xref, 1 AS n FROM `##individuals` WHERE i_file = :tree_id_1" .
5735792757eSGreg Roach            " UNION ALL " .
574e56ef01aSGreg Roach            "SELECT f_gedcom AS gedcom, f_id AS xref, 2 AS n FROM `##families`    WHERE f_file = :tree_id_2" .
5755792757eSGreg Roach            " UNION ALL " .
576e56ef01aSGreg Roach            "SELECT s_gedcom AS gedcom, s_id AS xref, 3 AS n FROM `##sources`     WHERE s_file = :tree_id_3" .
5775792757eSGreg Roach            " UNION ALL " .
578e56ef01aSGreg 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')" .
5795792757eSGreg Roach            " UNION ALL " .
580e56ef01aSGreg Roach            "SELECT m_gedcom AS gedcom, m_id AS xref, 5 AS n FROM `##media`       WHERE m_file = :tree_id_5" .
581e56ef01aSGreg Roach            " ORDER BY n, LENGTH(xref), xref"
58213abd6f3SGreg Roach        )->execute([
5835792757eSGreg Roach            'tree_id_1' => $this->tree_id,
5845792757eSGreg Roach            'tree_id_2' => $this->tree_id,
5855792757eSGreg Roach            'tree_id_3' => $this->tree_id,
5865792757eSGreg Roach            'tree_id_4' => $this->tree_id,
587cbc1590aSGreg Roach            'tree_id_5' => $this->tree_id,
58813abd6f3SGreg Roach        ]);
589a25f0a04SGreg Roach
5903d7a8a4cSGreg Roach        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this));
591a214e186SGreg Roach        while (($row = $stmt->fetch()) !== false) {
5923d7a8a4cSGreg Roach            $buffer .= FunctionsExport::reformatRecord($row->gedcom);
593a25f0a04SGreg Roach            if (strlen($buffer) > 65535) {
5945792757eSGreg Roach                fwrite($stream, $buffer);
595a25f0a04SGreg Roach                $buffer = '';
596a25f0a04SGreg Roach            }
597a25f0a04SGreg Roach        }
5980f471f91SGreg Roach        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
599195d09d8SGreg Roach        $stmt->closeCursor();
600a25f0a04SGreg Roach    }
601a25f0a04SGreg Roach
602a25f0a04SGreg Roach    /**
603a25f0a04SGreg Roach     * Import data from a gedcom file into this tree.
604a25f0a04SGreg Roach     *
605a25f0a04SGreg Roach     * @param string $path     The full path to the (possibly temporary) file.
606a25f0a04SGreg Roach     * @param string $filename The preferred filename, for export/download.
607a25f0a04SGreg Roach     *
608b7e60af1SGreg Roach     * @return void
609b7e60af1SGreg Roach     * @throws Exception
610a25f0a04SGreg Roach     */
611771ae10aSGreg Roach    public function importGedcomFile(string $path, string $filename)
612c1010edaSGreg Roach    {
613a25f0a04SGreg Roach        // Read the file in blocks of roughly 64K. Ensure that each block
614a25f0a04SGreg Roach        // contains complete gedcom records. This will ensure we don’t split
615a25f0a04SGreg Roach        // multi-byte characters, as well as simplifying the code to import
616a25f0a04SGreg Roach        // each block.
617a25f0a04SGreg Roach
618a25f0a04SGreg Roach        $file_data = '';
619a25f0a04SGreg Roach        $fp        = fopen($path, 'rb');
620a25f0a04SGreg Roach
621a25f0a04SGreg Roach        // Don’t allow the user to cancel the request. We do not want to be left with an incomplete transaction.
622a25f0a04SGreg Roach        ignore_user_abort(true);
623a25f0a04SGreg Roach
624b7e60af1SGreg Roach        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
625a25f0a04SGreg Roach        $this->setPreference('gedcom_filename', $filename);
626a25f0a04SGreg Roach        $this->setPreference('imported', '0');
627a25f0a04SGreg Roach
628a25f0a04SGreg Roach        while (!feof($fp)) {
629a25f0a04SGreg Roach            $file_data .= fread($fp, 65536);
630a25f0a04SGreg Roach            // There is no strrpos() function that searches for substrings :-(
631a25f0a04SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
632a25f0a04SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
633a25f0a04SGreg Roach                    // We’ve found the last record boundary in this chunk of data
634a25f0a04SGreg Roach                    break;
635a25f0a04SGreg Roach                }
636a25f0a04SGreg Roach            }
637a25f0a04SGreg Roach            if ($pos) {
638a25f0a04SGreg Roach                Database::prepare(
639a25f0a04SGreg Roach                    "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
640c1010edaSGreg Roach                )->execute([
641c1010edaSGreg Roach                    $this->tree_id,
642c1010edaSGreg Roach                    substr($file_data, 0, $pos),
643c1010edaSGreg Roach                ]);
644a25f0a04SGreg Roach                $file_data = substr($file_data, $pos);
645a25f0a04SGreg Roach            }
646a25f0a04SGreg Roach        }
647a25f0a04SGreg Roach        Database::prepare(
648a25f0a04SGreg Roach            "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
649c1010edaSGreg Roach        )->execute([
650c1010edaSGreg Roach            $this->tree_id,
651c1010edaSGreg Roach            $file_data,
652c1010edaSGreg Roach        ]);
653a25f0a04SGreg Roach
654a25f0a04SGreg Roach        fclose($fp);
655a25f0a04SGreg Roach    }
656304f20d5SGreg Roach
657304f20d5SGreg Roach    /**
658b90d8accSGreg Roach     * Generate a new XREF, unique across all family trees
659b90d8accSGreg Roach     *
660b90d8accSGreg Roach     * @return string
661b90d8accSGreg Roach     */
662771ae10aSGreg Roach    public function getNewXref(): string
663c1010edaSGreg Roach    {
664a214e186SGreg Roach        $prefix = 'X';
665b90d8accSGreg Roach
666971d66c8SGreg Roach        $increment = 1.0;
667b90d8accSGreg Roach        do {
668b90d8accSGreg Roach            // Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See
669b90d8accSGreg Roach            // http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
670b90d8accSGreg Roach            $statement = Database::prepare(
671a214e186SGreg Roach                "UPDATE `##site_setting` SET setting_value = LAST_INSERT_ID(setting_value + :increment) WHERE setting_name = 'next_xref'"
672b90d8accSGreg Roach            );
67313abd6f3SGreg Roach            $statement->execute([
674971d66c8SGreg Roach                'increment' => (int) $increment,
67513abd6f3SGreg Roach            ]);
676b90d8accSGreg Roach
677b90d8accSGreg Roach            if ($statement->rowCount() === 0) {
678b90d8accSGreg Roach                // First time we've used this record type.
679a214e186SGreg Roach                Site::setPreference('next_xref', '1');
680b90d8accSGreg Roach                $num = 1;
681b90d8accSGreg Roach            } else {
682b90d8accSGreg Roach                $num = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
683b90d8accSGreg Roach            }
684b90d8accSGreg Roach
685a214e186SGreg Roach            $xref = $prefix . $num;
686a214e186SGreg Roach
687b90d8accSGreg Roach            // Records may already exist with this sequence number.
688b90d8accSGreg Roach            $already_used = Database::prepare(
689a214e186SGreg Roach                "SELECT" .
690a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##individuals` WHERE i_id = :i_id) OR" .
691a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##families` WHERE f_id = :f_id) OR" .
692a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##sources` WHERE s_id = :s_id) OR" .
693a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##media` WHERE m_id = :m_id) OR" .
694a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##other` WHERE o_id = :o_id) OR" .
695a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##change` WHERE xref = :xref)"
69613abd6f3SGreg Roach            )->execute([
697a214e186SGreg Roach                'i_id' => $xref,
698a214e186SGreg Roach                'f_id' => $xref,
699a214e186SGreg Roach                's_id' => $xref,
700a214e186SGreg Roach                'm_id' => $xref,
701a214e186SGreg Roach                'o_id' => $xref,
702a214e186SGreg Roach                'xref' => $xref,
70313abd6f3SGreg Roach            ])->fetchOne();
704971d66c8SGreg Roach
705971d66c8SGreg Roach            // This exponential increment allows us to scan over large blocks of
706971d66c8SGreg Roach            // existing data in a reasonable time.
707971d66c8SGreg Roach            $increment *= 1.01;
708a214e186SGreg Roach        } while ($already_used !== '0');
709b90d8accSGreg Roach
710a214e186SGreg Roach        return $xref;
711b90d8accSGreg Roach    }
712b90d8accSGreg Roach
713b90d8accSGreg Roach    /**
714304f20d5SGreg Roach     * Create a new record from GEDCOM data.
715304f20d5SGreg Roach     *
716304f20d5SGreg Roach     * @param string $gedcom
717304f20d5SGreg Roach     *
71815d603e7SGreg Roach     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
719b7e60af1SGreg Roach     * @throws Exception
720304f20d5SGreg Roach     */
721771ae10aSGreg Roach    public function createRecord(string $gedcom): GedcomRecord
722c1010edaSGreg Roach    {
723304f20d5SGreg Roach        if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom, $match)) {
724304f20d5SGreg Roach            $xref = $match[1];
725304f20d5SGreg Roach            $type = $match[2];
726304f20d5SGreg Roach        } else {
727b7e60af1SGreg Roach            throw new Exception('Invalid argument to GedcomRecord::createRecord(' . $gedcom . ')');
728304f20d5SGreg Roach        }
7299f2d0ff7SGreg Roach        if (strpos($gedcom, "\r") !== false) {
730304f20d5SGreg Roach            // MSDOS line endings will break things in horrible ways
731b7e60af1SGreg Roach            throw new Exception('Evil line endings found in GedcomRecord::createRecord(' . $gedcom . ')');
732304f20d5SGreg Roach        }
733304f20d5SGreg Roach
734304f20d5SGreg Roach        // webtrees creates XREFs containing digits. Anything else (e.g. “new”) is just a placeholder.
735304f20d5SGreg Roach        if (!preg_match('/\d/', $xref)) {
736a214e186SGreg Roach            $xref   = $this->getNewXref();
737304f20d5SGreg Roach            $gedcom = preg_replace('/^0 @(' . WT_REGEX_XREF . ')@/', '0 @' . $xref . '@', $gedcom);
738304f20d5SGreg Roach        }
739304f20d5SGreg Roach
740304f20d5SGreg Roach        // Create a change record, if not already present
741304f20d5SGreg Roach        if (!preg_match('/\n1 CHAN/', $gedcom)) {
742304f20d5SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
743304f20d5SGreg Roach        }
744304f20d5SGreg Roach
745304f20d5SGreg Roach        // Create a pending change
746304f20d5SGreg Roach        Database::prepare(
747304f20d5SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
74813abd6f3SGreg Roach        )->execute([
749bb7c2cdcSGreg Roach            $this->tree_id,
750304f20d5SGreg Roach            $xref,
751304f20d5SGreg Roach            $gedcom,
752cbc1590aSGreg Roach            Auth::id(),
75313abd6f3SGreg Roach        ]);
754304f20d5SGreg Roach
755847d5489SGreg Roach        Log::addEditLog('Create: ' . $type . ' ' . $xref, $this);
756304f20d5SGreg Roach
757304f20d5SGreg Roach        // Accept this pending change
758304f20d5SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
759cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
760304f20d5SGreg Roach        }
761bb7c2cdcSGreg Roach        // Return the newly created record. Note that since GedcomRecord
762bb7c2cdcSGreg Roach        // has a cache of pending changes, we cannot use it to create a
763bb7c2cdcSGreg Roach        // record with a newly created pending change.
76424ec66ceSGreg Roach        return GedcomRecord::getInstance($xref, $this, $gedcom);
765304f20d5SGreg Roach    }
7668586983fSGreg Roach
7678586983fSGreg Roach    /**
7688586983fSGreg Roach     * What is the most significant individual in this tree.
7698586983fSGreg Roach     *
7708586983fSGreg Roach     * @param User $user
7718586983fSGreg Roach     *
7728586983fSGreg Roach     * @return Individual
7738586983fSGreg Roach     */
774c1010edaSGreg Roach    public function significantIndividual(User $user): Individual
775c1010edaSGreg Roach    {
7768586983fSGreg Roach        static $individual; // Only query the DB once.
7778586983fSGreg Roach
7787015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'rootid') !== '') {
7798586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
7808586983fSGreg Roach        }
7817015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'gedcomid') !== '') {
7828586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
7838586983fSGreg Roach        }
7848586983fSGreg Roach        if (!$individual) {
7858586983fSGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
7868586983fSGreg Roach        }
7878586983fSGreg Roach        if (!$individual) {
7888586983fSGreg Roach            $individual = Individual::getInstance(
7898586983fSGreg Roach                Database::prepare(
7905fe1add5SGreg Roach                    "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
7915fe1add5SGreg Roach                )->execute([
7925fe1add5SGreg Roach                    'tree_id' => $this->getTreeId(),
7935fe1add5SGreg Roach                ])->fetchOne(),
7945fe1add5SGreg Roach                $this
7955fe1add5SGreg Roach            );
7965fe1add5SGreg Roach        }
7975fe1add5SGreg Roach        if (!$individual) {
7985fe1add5SGreg Roach            // always return a record
7995fe1add5SGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
8005fe1add5SGreg Roach        }
8015fe1add5SGreg Roach
8025fe1add5SGreg Roach        return $individual;
8035fe1add5SGreg Roach    }
8045fe1add5SGreg Roach
8055fe1add5SGreg Roach    /**
8065fe1add5SGreg Roach     * Get significant information from this page, to allow other pages such as
8075fe1add5SGreg Roach     * charts and reports to initialise with the same records
8085fe1add5SGreg Roach     *
8095fe1add5SGreg Roach     * @return Individual
8105fe1add5SGreg Roach     */
811771ae10aSGreg Roach    public function getSignificantIndividual(): Individual
812c1010edaSGreg Roach    {
8135fe1add5SGreg Roach        static $individual; // Only query the DB once.
8145fe1add5SGreg Roach
8157015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'rootid') !== '') {
8165fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'rootid'), $this);
8175fe1add5SGreg Roach        }
8187015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'gedcomid') !== '') {
8195fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'gedcomid'), $this);
8205fe1add5SGreg Roach        }
8215fe1add5SGreg Roach        if (!$individual) {
8225fe1add5SGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
8235fe1add5SGreg Roach        }
8245fe1add5SGreg Roach        if (!$individual) {
8255fe1add5SGreg Roach            $individual = Individual::getInstance(
8265fe1add5SGreg Roach                Database::prepare(
8278586983fSGreg Roach                    "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = ?"
8288586983fSGreg Roach                )->execute([$this->getTreeId()])->fetchOne(),
8298586983fSGreg Roach                $this
8308586983fSGreg Roach            );
8318586983fSGreg Roach        }
8328586983fSGreg Roach        if (!$individual) {
8338586983fSGreg Roach            // always return a record
8348586983fSGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
8358586983fSGreg Roach        }
8368586983fSGreg Roach
8378586983fSGreg Roach        return $individual;
8388586983fSGreg Roach    }
839a25f0a04SGreg Roach}
840