xref: /webtrees/app/Tree.php (revision 4a86d7149e8ef5bb77f9d427c9b91b695138e67b)
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
173b2ce94c6SRico 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
226b2ce94c6SRico 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]);
402*4a86d714SGreg Roach
403*4a86d714SGreg Roach            $tree_id = (int) Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
404a25f0a04SGreg Roach        } catch (PDOException $ex) {
405bd52fa32SGreg Roach            DebugBar::addThrowable($ex);
406bd52fa32SGreg Roach
407a25f0a04SGreg Roach            // A tree with that name already exists?
408ef2fd529SGreg Roach            return self::findByName($tree_name);
409a25f0a04SGreg Roach        }
410a25f0a04SGreg Roach
411a25f0a04SGreg Roach        // Update the list of trees - to include this new one
41275a9f908SGreg Roach        self::$trees = [];
413d2cdeb3fSGreg Roach        $tree        = self::findById($tree_id);
414a25f0a04SGreg Roach
415a25f0a04SGreg Roach        $tree->setPreference('imported', '0');
416a25f0a04SGreg Roach        $tree->setPreference('title', $tree_title);
417a25f0a04SGreg Roach
418a25f0a04SGreg Roach        // Module privacy
419a25f0a04SGreg Roach        Module::setDefaultAccess($tree_id);
420a25f0a04SGreg Roach
4211507cbcaSGreg Roach        // Set preferences from default tree
4221507cbcaSGreg Roach        Database::prepare(
4231507cbcaSGreg Roach            "INSERT INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
4241507cbcaSGreg Roach            " SELECT :tree_id, setting_name, setting_value" .
4251507cbcaSGreg Roach            " FROM `##gedcom_setting` WHERE gedcom_id = -1"
42613abd6f3SGreg Roach        )->execute([
4271507cbcaSGreg Roach            'tree_id' => $tree_id,
42813abd6f3SGreg Roach        ]);
4291507cbcaSGreg Roach
4301507cbcaSGreg Roach        Database::prepare(
4311507cbcaSGreg Roach            "INSERT INTO `##default_resn` (gedcom_id, tag_type, resn)" .
4321507cbcaSGreg Roach            " SELECT :tree_id, tag_type, resn" .
4331507cbcaSGreg Roach            " FROM `##default_resn` WHERE gedcom_id = -1"
43413abd6f3SGreg Roach        )->execute([
4351507cbcaSGreg Roach            'tree_id' => $tree_id,
43613abd6f3SGreg Roach        ]);
4371507cbcaSGreg Roach
4381507cbcaSGreg Roach        Database::prepare(
4391507cbcaSGreg Roach            "INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" .
4401507cbcaSGreg Roach            " SELECT :tree_id, location, block_order, module_name" .
4411507cbcaSGreg Roach            " FROM `##block` WHERE gedcom_id = -1"
44213abd6f3SGreg Roach        )->execute([
4431507cbcaSGreg Roach            'tree_id' => $tree_id,
44413abd6f3SGreg Roach        ]);
4451507cbcaSGreg Roach
446a25f0a04SGreg Roach        // Gedcom and privacy settings
44776f666f4SGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
44876f666f4SGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
449a25f0a04SGreg Roach        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
450a25f0a04SGreg Roach        switch (WT_LOCALE) {
451a25f0a04SGreg Roach            case 'es':
452a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'spanish');
453a25f0a04SGreg Roach                break;
454a25f0a04SGreg Roach            case 'is':
455a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
456a25f0a04SGreg Roach                break;
457a25f0a04SGreg Roach            case 'lt':
458a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
459a25f0a04SGreg Roach                break;
460a25f0a04SGreg Roach            case 'pl':
461a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'polish');
462a25f0a04SGreg Roach                break;
463a25f0a04SGreg Roach            case 'pt':
464a25f0a04SGreg Roach            case 'pt-BR':
465a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
466a25f0a04SGreg Roach                break;
467a25f0a04SGreg Roach            default:
468a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'paternal');
469a25f0a04SGreg Roach                break;
470a25f0a04SGreg Roach        }
471a25f0a04SGreg Roach
472a25f0a04SGreg Roach        // Genealogy data
473a25f0a04SGreg Roach        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
474bbb76c12SGreg Roach        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
475bbb76c12SGreg Roach        $john_doe = I18N::translate('John /DOE/');
47677e70a22SGreg Roach        $note     = I18N::translate('Edit this individual and replace their details with your own.');
47713abd6f3SGreg Roach        Database::prepare("INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)")->execute([
478a25f0a04SGreg Roach            $tree_id,
479cbc1590aSGreg 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",
48013abd6f3SGreg Roach        ]);
481a25f0a04SGreg Roach
482a25f0a04SGreg Roach        // Update our cache
483518bbdc1SGreg Roach        self::$trees[$tree->tree_id] = $tree;
484a25f0a04SGreg Roach
485a25f0a04SGreg Roach        return $tree;
486a25f0a04SGreg Roach    }
487a25f0a04SGreg Roach
488a25f0a04SGreg Roach    /**
489b78374c5SGreg Roach     * Are there any pending edits for this tree, than need reviewing by a moderator.
490b78374c5SGreg Roach     *
491b78374c5SGreg Roach     * @return bool
492b78374c5SGreg Roach     */
493771ae10aSGreg Roach    public function hasPendingEdit(): bool
494c1010edaSGreg Roach    {
495b78374c5SGreg Roach        return (bool) Database::prepare(
496b78374c5SGreg Roach            "SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
49713abd6f3SGreg Roach        )->execute([
498cbc1590aSGreg Roach            'tree_id' => $this->tree_id,
49913abd6f3SGreg Roach        ])->fetchOne();
500b78374c5SGreg Roach    }
501b78374c5SGreg Roach
502b78374c5SGreg Roach    /**
503a25f0a04SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
504a25f0a04SGreg Roach     * new data. Optionally retain the media data, for when the user has been
505a25f0a04SGreg Roach     * editing their data offline using an application which deletes (or does not
506a25f0a04SGreg Roach     * support) media data.
507a25f0a04SGreg Roach     *
508a25f0a04SGreg Roach     * @param bool $keep_media
509b7e60af1SGreg Roach     *
510b7e60af1SGreg Roach     * @return void
511a25f0a04SGreg Roach     */
512b7e60af1SGreg Roach    public function deleteGenealogyData(bool $keep_media)
513c1010edaSGreg Roach    {
51413abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute([$this->tree_id]);
51513abd6f3SGreg Roach        Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute([$this->tree_id]);
51613abd6f3SGreg Roach        Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute([$this->tree_id]);
51713abd6f3SGreg Roach        Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute([$this->tree_id]);
51813abd6f3SGreg Roach        Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute([$this->tree_id]);
51913abd6f3SGreg Roach        Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute([$this->tree_id]);
52013abd6f3SGreg Roach        Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute([$this->tree_id]);
52113abd6f3SGreg Roach        Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute([$this->tree_id]);
52213abd6f3SGreg Roach        Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute([$this->tree_id]);
52313abd6f3SGreg Roach        Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute([$this->tree_id]);
524a25f0a04SGreg Roach
525a25f0a04SGreg Roach        if ($keep_media) {
52613abd6f3SGreg Roach            Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute([$this->tree_id]);
527a25f0a04SGreg Roach        } else {
52813abd6f3SGreg Roach            Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute([$this->tree_id]);
52913abd6f3SGreg Roach            Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute([$this->tree_id]);
53023ed9d24SGreg Roach            Database::prepare("DELETE FROM `##media_file` WHERE m_file =?")->execute([$this->tree_id]);
531a25f0a04SGreg Roach        }
532a25f0a04SGreg Roach    }
533a25f0a04SGreg Roach
534a25f0a04SGreg Roach    /**
535a25f0a04SGreg Roach     * Delete everything relating to a tree
536b7e60af1SGreg Roach     *
537b7e60af1SGreg Roach     * @return void
538a25f0a04SGreg Roach     */
539c1010edaSGreg Roach    public function delete()
540c1010edaSGreg Roach    {
541a25f0a04SGreg Roach        // If this is the default tree, then unset it
542ef2fd529SGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
543a25f0a04SGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
544a25f0a04SGreg Roach        }
545a25f0a04SGreg Roach
546a25f0a04SGreg Roach        $this->deleteGenealogyData(false);
547a25f0a04SGreg Roach
54813abd6f3SGreg Roach        Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute([$this->tree_id]);
54913abd6f3SGreg Roach        Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute([$this->tree_id]);
55013abd6f3SGreg Roach        Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute([$this->tree_id]);
55113abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
55213abd6f3SGreg Roach        Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute([$this->tree_id]);
55313abd6f3SGreg Roach        Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute([$this->tree_id]);
55413abd6f3SGreg Roach        Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
55513abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute([$this->tree_id]);
55613abd6f3SGreg Roach        Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute([$this->tree_id]);
55713abd6f3SGreg Roach        Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute([$this->tree_id]);
558a25f0a04SGreg Roach
559a25f0a04SGreg Roach        // After updating the database, we need to fetch a new (sorted) copy
56075a9f908SGreg Roach        self::$trees = [];
561a25f0a04SGreg Roach    }
562a25f0a04SGreg Roach
563a25f0a04SGreg Roach    /**
564a25f0a04SGreg Roach     * Export the tree to a GEDCOM file
565a25f0a04SGreg Roach     *
5665792757eSGreg Roach     * @param resource $stream
567b7e60af1SGreg Roach     *
568b7e60af1SGreg Roach     * @return void
569a25f0a04SGreg Roach     */
570c1010edaSGreg Roach    public function exportGedcom($stream)
571c1010edaSGreg Roach    {
5725792757eSGreg Roach        $stmt = Database::prepare(
573e56ef01aSGreg Roach            "SELECT i_gedcom AS gedcom, i_id AS xref, 1 AS n FROM `##individuals` WHERE i_file = :tree_id_1" .
5745792757eSGreg Roach            " UNION ALL " .
575e56ef01aSGreg Roach            "SELECT f_gedcom AS gedcom, f_id AS xref, 2 AS n FROM `##families`    WHERE f_file = :tree_id_2" .
5765792757eSGreg Roach            " UNION ALL " .
577e56ef01aSGreg Roach            "SELECT s_gedcom AS gedcom, s_id AS xref, 3 AS n FROM `##sources`     WHERE s_file = :tree_id_3" .
5785792757eSGreg Roach            " UNION ALL " .
579e56ef01aSGreg 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')" .
5805792757eSGreg Roach            " UNION ALL " .
581e56ef01aSGreg Roach            "SELECT m_gedcom AS gedcom, m_id AS xref, 5 AS n FROM `##media`       WHERE m_file = :tree_id_5" .
582e56ef01aSGreg Roach            " ORDER BY n, LENGTH(xref), xref"
58313abd6f3SGreg Roach        )->execute([
5845792757eSGreg Roach            'tree_id_1' => $this->tree_id,
5855792757eSGreg Roach            'tree_id_2' => $this->tree_id,
5865792757eSGreg Roach            'tree_id_3' => $this->tree_id,
5875792757eSGreg Roach            'tree_id_4' => $this->tree_id,
588cbc1590aSGreg Roach            'tree_id_5' => $this->tree_id,
58913abd6f3SGreg Roach        ]);
590a25f0a04SGreg Roach
5913d7a8a4cSGreg Roach        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this));
592a214e186SGreg Roach        while (($row = $stmt->fetch()) !== false) {
5933d7a8a4cSGreg Roach            $buffer .= FunctionsExport::reformatRecord($row->gedcom);
594a25f0a04SGreg Roach            if (strlen($buffer) > 65535) {
5955792757eSGreg Roach                fwrite($stream, $buffer);
596a25f0a04SGreg Roach                $buffer = '';
597a25f0a04SGreg Roach            }
598a25f0a04SGreg Roach        }
5990f471f91SGreg Roach        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
600195d09d8SGreg Roach        $stmt->closeCursor();
601a25f0a04SGreg Roach    }
602a25f0a04SGreg Roach
603a25f0a04SGreg Roach    /**
604a25f0a04SGreg Roach     * Import data from a gedcom file into this tree.
605a25f0a04SGreg Roach     *
606a25f0a04SGreg Roach     * @param string $path     The full path to the (possibly temporary) file.
607a25f0a04SGreg Roach     * @param string $filename The preferred filename, for export/download.
608a25f0a04SGreg Roach     *
609b7e60af1SGreg Roach     * @return void
610b7e60af1SGreg Roach     * @throws Exception
611a25f0a04SGreg Roach     */
612771ae10aSGreg Roach    public function importGedcomFile(string $path, string $filename)
613c1010edaSGreg Roach    {
614a25f0a04SGreg Roach        // Read the file in blocks of roughly 64K. Ensure that each block
615a25f0a04SGreg Roach        // contains complete gedcom records. This will ensure we don’t split
616a25f0a04SGreg Roach        // multi-byte characters, as well as simplifying the code to import
617a25f0a04SGreg Roach        // each block.
618a25f0a04SGreg Roach
619a25f0a04SGreg Roach        $file_data = '';
620a25f0a04SGreg Roach        $fp        = fopen($path, 'rb');
621a25f0a04SGreg Roach
622a25f0a04SGreg Roach        // Don’t allow the user to cancel the request. We do not want to be left with an incomplete transaction.
623a25f0a04SGreg Roach        ignore_user_abort(true);
624a25f0a04SGreg Roach
625b7e60af1SGreg Roach        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
626a25f0a04SGreg Roach        $this->setPreference('gedcom_filename', $filename);
627a25f0a04SGreg Roach        $this->setPreference('imported', '0');
628a25f0a04SGreg Roach
629a25f0a04SGreg Roach        while (!feof($fp)) {
630a25f0a04SGreg Roach            $file_data .= fread($fp, 65536);
631a25f0a04SGreg Roach            // There is no strrpos() function that searches for substrings :-(
632a25f0a04SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
633a25f0a04SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
634a25f0a04SGreg Roach                    // We’ve found the last record boundary in this chunk of data
635a25f0a04SGreg Roach                    break;
636a25f0a04SGreg Roach                }
637a25f0a04SGreg Roach            }
638a25f0a04SGreg Roach            if ($pos) {
639a25f0a04SGreg Roach                Database::prepare(
640a25f0a04SGreg Roach                    "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
641c1010edaSGreg Roach                )->execute([
642c1010edaSGreg Roach                    $this->tree_id,
643c1010edaSGreg Roach                    substr($file_data, 0, $pos),
644c1010edaSGreg Roach                ]);
645a25f0a04SGreg Roach                $file_data = substr($file_data, $pos);
646a25f0a04SGreg Roach            }
647a25f0a04SGreg Roach        }
648a25f0a04SGreg Roach        Database::prepare(
649a25f0a04SGreg Roach            "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
650c1010edaSGreg Roach        )->execute([
651c1010edaSGreg Roach            $this->tree_id,
652c1010edaSGreg Roach            $file_data,
653c1010edaSGreg Roach        ]);
654a25f0a04SGreg Roach
655a25f0a04SGreg Roach        fclose($fp);
656a25f0a04SGreg Roach    }
657304f20d5SGreg Roach
658304f20d5SGreg Roach    /**
659b90d8accSGreg Roach     * Generate a new XREF, unique across all family trees
660b90d8accSGreg Roach     *
661b90d8accSGreg Roach     * @return string
662b90d8accSGreg Roach     */
663771ae10aSGreg Roach    public function getNewXref(): string
664c1010edaSGreg Roach    {
665a214e186SGreg Roach        $prefix = 'X';
666b90d8accSGreg Roach
667971d66c8SGreg Roach        $increment = 1.0;
668b90d8accSGreg Roach        do {
669b90d8accSGreg Roach            // Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See
670b90d8accSGreg Roach            // http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
671b90d8accSGreg Roach            $statement = Database::prepare(
672a214e186SGreg Roach                "UPDATE `##site_setting` SET setting_value = LAST_INSERT_ID(setting_value + :increment) WHERE setting_name = 'next_xref'"
673b90d8accSGreg Roach            );
67413abd6f3SGreg Roach            $statement->execute([
675971d66c8SGreg Roach                'increment' => (int) $increment,
67613abd6f3SGreg Roach            ]);
677b90d8accSGreg Roach
678b90d8accSGreg Roach            if ($statement->rowCount() === 0) {
679b90d8accSGreg Roach                // First time we've used this record type.
680a214e186SGreg Roach                Site::setPreference('next_xref', '1');
681b90d8accSGreg Roach                $num = 1;
682b90d8accSGreg Roach            } else {
683b90d8accSGreg Roach                $num = Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
684b90d8accSGreg Roach            }
685b90d8accSGreg Roach
686a214e186SGreg Roach            $xref = $prefix . $num;
687a214e186SGreg Roach
688b90d8accSGreg Roach            // Records may already exist with this sequence number.
689b90d8accSGreg Roach            $already_used = Database::prepare(
690a214e186SGreg Roach                "SELECT" .
691a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##individuals` WHERE i_id = :i_id) OR" .
692a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##families` WHERE f_id = :f_id) OR" .
693a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##sources` WHERE s_id = :s_id) OR" .
694a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##media` WHERE m_id = :m_id) OR" .
695a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##other` WHERE o_id = :o_id) OR" .
696a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##change` WHERE xref = :xref)"
69713abd6f3SGreg Roach            )->execute([
698a214e186SGreg Roach                'i_id' => $xref,
699a214e186SGreg Roach                'f_id' => $xref,
700a214e186SGreg Roach                's_id' => $xref,
701a214e186SGreg Roach                'm_id' => $xref,
702a214e186SGreg Roach                'o_id' => $xref,
703a214e186SGreg Roach                'xref' => $xref,
70413abd6f3SGreg Roach            ])->fetchOne();
705971d66c8SGreg Roach
706971d66c8SGreg Roach            // This exponential increment allows us to scan over large blocks of
707971d66c8SGreg Roach            // existing data in a reasonable time.
708971d66c8SGreg Roach            $increment *= 1.01;
709a214e186SGreg Roach        } while ($already_used !== '0');
710b90d8accSGreg Roach
711a214e186SGreg Roach        return $xref;
712b90d8accSGreg Roach    }
713b90d8accSGreg Roach
714b90d8accSGreg Roach    /**
715304f20d5SGreg Roach     * Create a new record from GEDCOM data.
716304f20d5SGreg Roach     *
717304f20d5SGreg Roach     * @param string $gedcom
718304f20d5SGreg Roach     *
71915d603e7SGreg Roach     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
720b7e60af1SGreg Roach     * @throws Exception
721304f20d5SGreg Roach     */
722771ae10aSGreg Roach    public function createRecord(string $gedcom): GedcomRecord
723c1010edaSGreg Roach    {
724304f20d5SGreg Roach        if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom, $match)) {
725304f20d5SGreg Roach            $xref = $match[1];
726304f20d5SGreg Roach            $type = $match[2];
727304f20d5SGreg Roach        } else {
728b7e60af1SGreg Roach            throw new Exception('Invalid argument to GedcomRecord::createRecord(' . $gedcom . ')');
729304f20d5SGreg Roach        }
7309f2d0ff7SGreg Roach        if (strpos($gedcom, "\r") !== false) {
731304f20d5SGreg Roach            // MSDOS line endings will break things in horrible ways
732b7e60af1SGreg Roach            throw new Exception('Evil line endings found in GedcomRecord::createRecord(' . $gedcom . ')');
733304f20d5SGreg Roach        }
734304f20d5SGreg Roach
735304f20d5SGreg Roach        // webtrees creates XREFs containing digits. Anything else (e.g. “new”) is just a placeholder.
736304f20d5SGreg Roach        if (!preg_match('/\d/', $xref)) {
737a214e186SGreg Roach            $xref   = $this->getNewXref();
738304f20d5SGreg Roach            $gedcom = preg_replace('/^0 @(' . WT_REGEX_XREF . ')@/', '0 @' . $xref . '@', $gedcom);
739304f20d5SGreg Roach        }
740304f20d5SGreg Roach
741304f20d5SGreg Roach        // Create a change record, if not already present
742304f20d5SGreg Roach        if (!preg_match('/\n1 CHAN/', $gedcom)) {
743304f20d5SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
744304f20d5SGreg Roach        }
745304f20d5SGreg Roach
746304f20d5SGreg Roach        // Create a pending change
747304f20d5SGreg Roach        Database::prepare(
748304f20d5SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
74913abd6f3SGreg Roach        )->execute([
750bb7c2cdcSGreg Roach            $this->tree_id,
751304f20d5SGreg Roach            $xref,
752304f20d5SGreg Roach            $gedcom,
753cbc1590aSGreg Roach            Auth::id(),
75413abd6f3SGreg Roach        ]);
755304f20d5SGreg Roach
756847d5489SGreg Roach        Log::addEditLog('Create: ' . $type . ' ' . $xref, $this);
757304f20d5SGreg Roach
758304f20d5SGreg Roach        // Accept this pending change
759304f20d5SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
760cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
761304f20d5SGreg Roach        }
762bb7c2cdcSGreg Roach        // Return the newly created record. Note that since GedcomRecord
763bb7c2cdcSGreg Roach        // has a cache of pending changes, we cannot use it to create a
764bb7c2cdcSGreg Roach        // record with a newly created pending change.
76524ec66ceSGreg Roach        return GedcomRecord::getInstance($xref, $this, $gedcom);
766304f20d5SGreg Roach    }
7678586983fSGreg Roach
7688586983fSGreg Roach    /**
7698586983fSGreg Roach     * What is the most significant individual in this tree.
7708586983fSGreg Roach     *
7718586983fSGreg Roach     * @param User $user
7728586983fSGreg Roach     *
7738586983fSGreg Roach     * @return Individual
7748586983fSGreg Roach     */
775c1010edaSGreg Roach    public function significantIndividual(User $user): Individual
776c1010edaSGreg Roach    {
7778586983fSGreg Roach        static $individual; // Only query the DB once.
7788586983fSGreg Roach
7797015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'rootid') !== '') {
7808586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
7818586983fSGreg Roach        }
7827015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'gedcomid') !== '') {
7838586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
7848586983fSGreg Roach        }
7858586983fSGreg Roach        if (!$individual) {
7868586983fSGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
7878586983fSGreg Roach        }
7888586983fSGreg Roach        if (!$individual) {
7898586983fSGreg Roach            $individual = Individual::getInstance(
7908586983fSGreg Roach                Database::prepare(
7915fe1add5SGreg Roach                    "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
7925fe1add5SGreg Roach                )->execute([
7935fe1add5SGreg Roach                    'tree_id' => $this->getTreeId(),
7945fe1add5SGreg Roach                ])->fetchOne(),
7955fe1add5SGreg Roach                $this
7965fe1add5SGreg Roach            );
7975fe1add5SGreg Roach        }
7985fe1add5SGreg Roach        if (!$individual) {
7995fe1add5SGreg Roach            // always return a record
8005fe1add5SGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
8015fe1add5SGreg Roach        }
8025fe1add5SGreg Roach
8035fe1add5SGreg Roach        return $individual;
8045fe1add5SGreg Roach    }
8055fe1add5SGreg Roach
8065fe1add5SGreg Roach    /**
8075fe1add5SGreg Roach     * Get significant information from this page, to allow other pages such as
8085fe1add5SGreg Roach     * charts and reports to initialise with the same records
8095fe1add5SGreg Roach     *
8105fe1add5SGreg Roach     * @return Individual
8115fe1add5SGreg Roach     */
812771ae10aSGreg Roach    public function getSignificantIndividual(): Individual
813c1010edaSGreg Roach    {
8145fe1add5SGreg Roach        static $individual; // Only query the DB once.
8155fe1add5SGreg Roach
8167015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'rootid') !== '') {
8175fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'rootid'), $this);
8185fe1add5SGreg Roach        }
8197015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'gedcomid') !== '') {
8205fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'gedcomid'), $this);
8215fe1add5SGreg Roach        }
8225fe1add5SGreg Roach        if (!$individual) {
8235fe1add5SGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
8245fe1add5SGreg Roach        }
8255fe1add5SGreg Roach        if (!$individual) {
8265fe1add5SGreg Roach            $individual = Individual::getInstance(
8275fe1add5SGreg Roach                Database::prepare(
8288586983fSGreg Roach                    "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = ?"
8298586983fSGreg Roach                )->execute([$this->getTreeId()])->fetchOne(),
8308586983fSGreg Roach                $this
8318586983fSGreg Roach            );
8328586983fSGreg Roach        }
8338586983fSGreg Roach        if (!$individual) {
8348586983fSGreg Roach            // always return a record
8358586983fSGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
8368586983fSGreg Roach        }
8378586983fSGreg Roach
8388586983fSGreg Roach        return $individual;
8398586983fSGreg Roach    }
840a25f0a04SGreg Roach}
841