xref: /webtrees/app/Tree.php (revision 72cf66d48ef1f917238d9b0939a8aa33f257e274)
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 */
16e7f56f2aSGreg Roachdeclare(strict_types=1);
17e7f56f2aSGreg Roach
1876692c8bSGreg Roachnamespace Fisharebest\Webtrees;
19a25f0a04SGreg Roach
20b7e60af1SGreg Roachuse Exception;
213d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsExport;
223d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
23afb591d7SGreg Roachuse InvalidArgumentException;
24a25f0a04SGreg Roachuse PDOException;
25afb591d7SGreg Roachuse function substr_compare;
26a25f0a04SGreg Roach
27a25f0a04SGreg Roach/**
2876692c8bSGreg Roach * Provide an interface to the wt_gedcom table.
29a25f0a04SGreg Roach */
30c1010edaSGreg Roachclass Tree
31c1010edaSGreg Roach{
32cbc1590aSGreg Roach    /** @var int The tree's ID number */
33*72cf66d4SGreg Roach    private $id;
34518bbdc1SGreg Roach
35a25f0a04SGreg Roach    /** @var string The tree's name */
36a25f0a04SGreg Roach    private $name;
37518bbdc1SGreg Roach
38a25f0a04SGreg Roach    /** @var string The tree's title */
39a25f0a04SGreg Roach    private $title;
40a25f0a04SGreg Roach
41e2052359SGreg Roach    /** @var int[] Default access rules for facts in this tree */
42518bbdc1SGreg Roach    private $fact_privacy;
43518bbdc1SGreg Roach
44e2052359SGreg Roach    /** @var int[] Default access rules for individuals in this tree */
45518bbdc1SGreg Roach    private $individual_privacy;
46518bbdc1SGreg Roach
47518bbdc1SGreg Roach    /** @var integer[][] Default access rules for individual facts in this tree */
48518bbdc1SGreg Roach    private $individual_fact_privacy;
49518bbdc1SGreg Roach
50a25f0a04SGreg Roach    /** @var Tree[] All trees that we have permission to see. */
5175a9f908SGreg Roach    private static $trees = [];
52a25f0a04SGreg Roach
53a25f0a04SGreg Roach    /** @var string[] Cached copy of the wt_gedcom_setting table. */
5415d603e7SGreg Roach    private $preferences = [];
55a25f0a04SGreg Roach
56a25f0a04SGreg Roach    /** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
5713abd6f3SGreg Roach    private $user_preferences = [];
58a25f0a04SGreg Roach
59a25f0a04SGreg Roach    /**
60a25f0a04SGreg Roach     * Create a tree object. This is a private constructor - it can only
61a25f0a04SGreg Roach     * be called from Tree::getAll() to ensure proper initialisation.
62a25f0a04SGreg Roach     *
63*72cf66d4SGreg Roach     * @param int    $id
64a25f0a04SGreg Roach     * @param string $tree_name
65a25f0a04SGreg Roach     * @param string $tree_title
66a25f0a04SGreg Roach     */
67*72cf66d4SGreg Roach    private function __construct($id, $tree_name, $tree_title)
68c1010edaSGreg Roach    {
69*72cf66d4SGreg Roach        $this->id                      = $id;
70a25f0a04SGreg Roach        $this->name                    = $tree_name;
71a25f0a04SGreg Roach        $this->title                   = $tree_title;
7213abd6f3SGreg Roach        $this->fact_privacy            = [];
7313abd6f3SGreg Roach        $this->individual_privacy      = [];
7413abd6f3SGreg Roach        $this->individual_fact_privacy = [];
75518bbdc1SGreg Roach
76518bbdc1SGreg Roach        // Load the privacy settings for this tree
77518bbdc1SGreg Roach        $rows = Database::prepare(
78e5588fb0SGreg 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" .
79518bbdc1SGreg Roach            " FROM `##default_resn` WHERE gedcom_id = :tree_id"
8013abd6f3SGreg Roach        )->execute([
814b9ff166SGreg Roach            'priv_public' => Auth::PRIV_PRIVATE,
824b9ff166SGreg Roach            'priv_user'   => Auth::PRIV_USER,
834b9ff166SGreg Roach            'priv_none'   => Auth::PRIV_NONE,
844b9ff166SGreg Roach            'priv_hide'   => Auth::PRIV_HIDE,
85*72cf66d4SGreg Roach            'tree_id'     => $this->id,
8613abd6f3SGreg Roach        ])->fetchAll();
87518bbdc1SGreg Roach
88518bbdc1SGreg Roach        foreach ($rows as $row) {
89518bbdc1SGreg Roach            if ($row->xref !== null) {
90518bbdc1SGreg Roach                if ($row->tag_type !== null) {
91518bbdc1SGreg Roach                    $this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
92518bbdc1SGreg Roach                } else {
93518bbdc1SGreg Roach                    $this->individual_privacy[$row->xref] = (int) $row->resn;
94518bbdc1SGreg Roach                }
95518bbdc1SGreg Roach            } else {
96518bbdc1SGreg Roach                $this->fact_privacy[$row->tag_type] = (int) $row->resn;
97518bbdc1SGreg Roach            }
98518bbdc1SGreg Roach        }
99a25f0a04SGreg Roach    }
100a25f0a04SGreg Roach
101a25f0a04SGreg Roach    /**
102a25f0a04SGreg Roach     * The ID of this tree
103a25f0a04SGreg Roach     *
104cbc1590aSGreg Roach     * @return int
105a25f0a04SGreg Roach     */
106*72cf66d4SGreg Roach    public function id(): int
107c1010edaSGreg Roach    {
108*72cf66d4SGreg Roach        return $this->id;
109a25f0a04SGreg Roach    }
110a25f0a04SGreg Roach
111a25f0a04SGreg Roach    /**
112a25f0a04SGreg Roach     * The name of this tree
113a25f0a04SGreg Roach     *
114a25f0a04SGreg Roach     * @return string
115a25f0a04SGreg Roach     */
1168f53f488SRico Sonntag    public function getName(): string
117c1010edaSGreg Roach    {
118a25f0a04SGreg Roach        return $this->name;
119a25f0a04SGreg Roach    }
120a25f0a04SGreg Roach
121a25f0a04SGreg Roach    /**
122a25f0a04SGreg Roach     * The title of this tree
123a25f0a04SGreg Roach     *
124a25f0a04SGreg Roach     * @return string
125a25f0a04SGreg Roach     */
1268f53f488SRico Sonntag    public function getTitle(): string
127c1010edaSGreg Roach    {
128a25f0a04SGreg Roach        return $this->title;
129a25f0a04SGreg Roach    }
130a25f0a04SGreg Roach
131a25f0a04SGreg Roach    /**
132518bbdc1SGreg Roach     * The fact-level privacy for this tree.
133518bbdc1SGreg Roach     *
134e2052359SGreg Roach     * @return int[]
135518bbdc1SGreg Roach     */
1368f53f488SRico Sonntag    public function getFactPrivacy(): array
137c1010edaSGreg Roach    {
138518bbdc1SGreg Roach        return $this->fact_privacy;
139518bbdc1SGreg Roach    }
140518bbdc1SGreg Roach
141518bbdc1SGreg Roach    /**
142518bbdc1SGreg Roach     * The individual-level privacy for this tree.
143518bbdc1SGreg Roach     *
144e2052359SGreg Roach     * @return int[]
145518bbdc1SGreg Roach     */
1468f53f488SRico Sonntag    public function getIndividualPrivacy(): array
147c1010edaSGreg Roach    {
148518bbdc1SGreg Roach        return $this->individual_privacy;
149518bbdc1SGreg Roach    }
150518bbdc1SGreg Roach
151518bbdc1SGreg Roach    /**
152518bbdc1SGreg Roach     * The individual-fact-level privacy for this tree.
153518bbdc1SGreg Roach     *
154adac8af1SGreg Roach     * @return int[][]
155518bbdc1SGreg Roach     */
1568f53f488SRico Sonntag    public function getIndividualFactPrivacy(): array
157c1010edaSGreg Roach    {
158518bbdc1SGreg Roach        return $this->individual_fact_privacy;
159518bbdc1SGreg Roach    }
160518bbdc1SGreg Roach
161518bbdc1SGreg Roach    /**
162a25f0a04SGreg Roach     * Get the tree’s configuration settings.
163a25f0a04SGreg Roach     *
164a25f0a04SGreg Roach     * @param string $setting_name
16515d603e7SGreg Roach     * @param string $default
166a25f0a04SGreg Roach     *
16715d603e7SGreg Roach     * @return string
168a25f0a04SGreg Roach     */
169771ae10aSGreg Roach    public function getPreference(string $setting_name, string $default = ''): string
170c1010edaSGreg Roach    {
17115d603e7SGreg Roach        if (empty($this->preferences)) {
172a25f0a04SGreg Roach            $this->preferences = Database::prepare(
173e5588fb0SGreg Roach                "SELECT setting_name, setting_value FROM `##gedcom_setting` WHERE gedcom_id = ?"
174*72cf66d4SGreg Roach            )->execute([$this->id])->fetchAssoc();
175a25f0a04SGreg Roach        }
176a25f0a04SGreg Roach
177b2ce94c6SRico Sonntag        return $this->preferences[$setting_name] ?? $default;
178a25f0a04SGreg Roach    }
179a25f0a04SGreg Roach
180a25f0a04SGreg Roach    /**
181a25f0a04SGreg Roach     * Set the tree’s configuration settings.
182a25f0a04SGreg Roach     *
183a25f0a04SGreg Roach     * @param string $setting_name
184a25f0a04SGreg Roach     * @param string $setting_value
185a25f0a04SGreg Roach     *
186a25f0a04SGreg Roach     * @return $this
187a25f0a04SGreg Roach     */
188771ae10aSGreg Roach    public function setPreference(string $setting_name, string $setting_value): Tree
189c1010edaSGreg Roach    {
190a25f0a04SGreg Roach        if ($setting_value !== $this->getPreference($setting_name)) {
191a25f0a04SGreg Roach            Database::prepare(
192a25f0a04SGreg Roach                "REPLACE INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
193a25f0a04SGreg Roach                " VALUES (:tree_id, :setting_name, LEFT(:setting_value, 255))"
19413abd6f3SGreg Roach            )->execute([
195*72cf66d4SGreg Roach                'tree_id'       => $this->id,
196a25f0a04SGreg Roach                'setting_name'  => $setting_name,
197a25f0a04SGreg Roach                'setting_value' => $setting_value,
19813abd6f3SGreg Roach            ]);
19915d603e7SGreg Roach
200a25f0a04SGreg Roach            $this->preferences[$setting_name] = $setting_value;
20115d603e7SGreg Roach
20272292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
203a25f0a04SGreg Roach        }
204a25f0a04SGreg Roach
205a25f0a04SGreg Roach        return $this;
206a25f0a04SGreg Roach    }
207a25f0a04SGreg Roach
208a25f0a04SGreg Roach    /**
209a25f0a04SGreg Roach     * Get the tree’s user-configuration settings.
210a25f0a04SGreg Roach     *
211a25f0a04SGreg Roach     * @param User   $user
212a25f0a04SGreg Roach     * @param string $setting_name
2137015ba1fSGreg Roach     * @param string $default
214a25f0a04SGreg Roach     *
215a25f0a04SGreg Roach     * @return string
216a25f0a04SGreg Roach     */
217771ae10aSGreg Roach    public function getUserPreference(User $user, string $setting_name, string $default = ''): string
218c1010edaSGreg Roach    {
219a25f0a04SGreg Roach        // There are lots of settings, and we need to fetch lots of them on every page
220a25f0a04SGreg Roach        // so it is quicker to fetch them all in one go.
221a25f0a04SGreg Roach        if (!array_key_exists($user->getUserId(), $this->user_preferences)) {
222a25f0a04SGreg Roach            $this->user_preferences[$user->getUserId()] = Database::prepare(
223e5588fb0SGreg Roach                "SELECT setting_name, setting_value FROM `##user_gedcom_setting` WHERE user_id = ? AND gedcom_id = ?"
224c1010edaSGreg Roach            )->execute([
225c1010edaSGreg Roach                $user->getUserId(),
226*72cf66d4SGreg Roach                $this->id,
227c1010edaSGreg Roach            ])->fetchAssoc();
228a25f0a04SGreg Roach        }
229a25f0a04SGreg Roach
230b2ce94c6SRico Sonntag        return $this->user_preferences[$user->getUserId()][$setting_name] ?? $default;
231a25f0a04SGreg Roach    }
232a25f0a04SGreg Roach
233a25f0a04SGreg Roach    /**
234a25f0a04SGreg Roach     * Set the tree’s user-configuration settings.
235a25f0a04SGreg Roach     *
236a25f0a04SGreg Roach     * @param User   $user
237a25f0a04SGreg Roach     * @param string $setting_name
238a25f0a04SGreg Roach     * @param string $setting_value
239a25f0a04SGreg Roach     *
240a25f0a04SGreg Roach     * @return $this
241a25f0a04SGreg Roach     */
242771ae10aSGreg Roach    public function setUserPreference(User $user, string $setting_name, string $setting_value): Tree
243c1010edaSGreg Roach    {
244a25f0a04SGreg Roach        if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
245a25f0a04SGreg Roach            // Update the database
2467015ba1fSGreg Roach            if ($setting_value === '') {
247a25f0a04SGreg Roach                Database::prepare(
248a25f0a04SGreg Roach                    "DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = :tree_id AND user_id = :user_id AND setting_name = :setting_name"
24913abd6f3SGreg Roach                )->execute([
250*72cf66d4SGreg Roach                    'tree_id'      => $this->id,
251a25f0a04SGreg Roach                    'user_id'      => $user->getUserId(),
252a25f0a04SGreg Roach                    'setting_name' => $setting_name,
25313abd6f3SGreg Roach                ]);
254a25f0a04SGreg Roach            } else {
255a25f0a04SGreg Roach                Database::prepare(
256a25f0a04SGreg 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))"
25713abd6f3SGreg Roach                )->execute([
258a25f0a04SGreg Roach                    'user_id'       => $user->getUserId(),
259*72cf66d4SGreg Roach                    'tree_id'       => $this->id,
260a25f0a04SGreg Roach                    'setting_name'  => $setting_name,
261cbc1590aSGreg Roach                    'setting_value' => $setting_value,
26213abd6f3SGreg Roach                ]);
263a25f0a04SGreg Roach            }
264a25f0a04SGreg Roach            // Update our cache
265a25f0a04SGreg Roach            $this->user_preferences[$user->getUserId()][$setting_name] = $setting_value;
266a25f0a04SGreg Roach            // Audit log of changes
26772292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this);
268a25f0a04SGreg Roach        }
269a25f0a04SGreg Roach
270a25f0a04SGreg Roach        return $this;
271a25f0a04SGreg Roach    }
272a25f0a04SGreg Roach
273a25f0a04SGreg Roach    /**
274a25f0a04SGreg Roach     * Can a user accept changes for this tree?
275a25f0a04SGreg Roach     *
276a25f0a04SGreg Roach     * @param User $user
277a25f0a04SGreg Roach     *
278cbc1590aSGreg Roach     * @return bool
279a25f0a04SGreg Roach     */
280771ae10aSGreg Roach    public function canAcceptChanges(User $user): bool
281c1010edaSGreg Roach    {
282a25f0a04SGreg Roach        return Auth::isModerator($this, $user);
283a25f0a04SGreg Roach    }
284a25f0a04SGreg Roach
285a25f0a04SGreg Roach    /**
286a25f0a04SGreg Roach     * Fetch all the trees that we have permission to access.
287a25f0a04SGreg Roach     *
288a25f0a04SGreg Roach     * @return Tree[]
289a25f0a04SGreg Roach     */
290771ae10aSGreg Roach    public static function getAll(): array
291c1010edaSGreg Roach    {
29275a9f908SGreg Roach        if (empty(self::$trees)) {
293a25f0a04SGreg Roach            $rows = Database::prepare(
294e5588fb0SGreg Roach                "SELECT g.gedcom_id AS tree_id, g.gedcom_name AS tree_name, gs1.setting_value AS tree_title" .
295a25f0a04SGreg Roach                " FROM `##gedcom` g" .
296a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs1 ON (g.gedcom_id=gs1.gedcom_id AND gs1.setting_name='title')" .
297a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs2 ON (g.gedcom_id=gs2.gedcom_id AND gs2.setting_name='imported')" .
298a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs3 ON (g.gedcom_id=gs3.gedcom_id AND gs3.setting_name='REQUIRE_AUTHENTICATION')" .
299a25f0a04SGreg Roach                " LEFT JOIN `##user_gedcom_setting` ugs ON (g.gedcom_id=ugs.gedcom_id AND ugs.setting_name='canedit' AND ugs.user_id=?)" .
300a25f0a04SGreg Roach                " WHERE " .
301a25f0a04SGreg Roach                "  g.gedcom_id>0 AND (" . // exclude the "template" tree
302a25f0a04SGreg Roach                "    EXISTS (SELECT 1 FROM `##user_setting` WHERE user_id=? AND setting_name='canadmin' AND setting_value=1)" . // Admin sees all
303a25f0a04SGreg Roach                "   ) OR (" .
3048cca4ddeSGreg Roach                "    (gs2.setting_value = 1 OR ugs.setting_value = 'admin') AND (" . // Allow imported trees, with either:
305a25f0a04SGreg Roach                "     gs3.setting_value <> 1 OR" . // visitor access
306a25f0a04SGreg Roach                "     IFNULL(ugs.setting_value, 'none')<>'none'" . // explicit access
307a25f0a04SGreg Roach                "   )" .
308a25f0a04SGreg Roach                "  )" .
309a25f0a04SGreg Roach                " ORDER BY g.sort_order, 3"
310c1010edaSGreg Roach            )->execute([
311c1010edaSGreg Roach                Auth::id(),
312c1010edaSGreg Roach                Auth::id(),
313c1010edaSGreg Roach            ])->fetchAll();
31475a9f908SGreg Roach
315a25f0a04SGreg Roach            foreach ($rows as $row) {
3163f7ece23SGreg Roach                self::$trees[$row->tree_name] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
317a25f0a04SGreg Roach            }
318a25f0a04SGreg Roach        }
319a25f0a04SGreg Roach
320a25f0a04SGreg Roach        return self::$trees;
321a25f0a04SGreg Roach    }
322a25f0a04SGreg Roach
323a25f0a04SGreg Roach    /**
324d2cdeb3fSGreg Roach     * Find the tree with a specific ID.
325a25f0a04SGreg Roach     *
326cbc1590aSGreg Roach     * @param int $tree_id
327cbc1590aSGreg Roach     *
328cbc1590aSGreg Roach     * @throws \DomainException
329a25f0a04SGreg Roach     * @return Tree
330a25f0a04SGreg Roach     */
331771ae10aSGreg Roach    public static function findById($tree_id): Tree
332c1010edaSGreg Roach    {
33351d0f842SGreg Roach        foreach (self::getAll() as $tree) {
334*72cf66d4SGreg Roach            if ($tree->id == $tree_id) {
33551d0f842SGreg Roach                return $tree;
33651d0f842SGreg Roach            }
33751d0f842SGreg Roach        }
33859f2f229SGreg Roach        throw new \DomainException();
339a25f0a04SGreg Roach    }
340a25f0a04SGreg Roach
341a25f0a04SGreg Roach    /**
342d2cdeb3fSGreg Roach     * Find the tree with a specific name.
343cf4bcc09SGreg Roach     *
344cf4bcc09SGreg Roach     * @param string $tree_name
345cf4bcc09SGreg Roach     *
346cf4bcc09SGreg Roach     * @return Tree|null
347cf4bcc09SGreg Roach     */
348c1010edaSGreg Roach    public static function findByName($tree_name)
349c1010edaSGreg Roach    {
350cf4bcc09SGreg Roach        foreach (self::getAll() as $tree) {
35151d0f842SGreg Roach            if ($tree->name === $tree_name) {
352cf4bcc09SGreg Roach                return $tree;
353cf4bcc09SGreg Roach            }
354cf4bcc09SGreg Roach        }
355cf4bcc09SGreg Roach
356cf4bcc09SGreg Roach        return null;
357cf4bcc09SGreg Roach    }
358cf4bcc09SGreg Roach
359cf4bcc09SGreg Roach    /**
360a25f0a04SGreg Roach     * Create arguments to select_edit_control()
361a25f0a04SGreg Roach     * Note - these will be escaped later
362a25f0a04SGreg Roach     *
363a25f0a04SGreg Roach     * @return string[]
364a25f0a04SGreg Roach     */
365771ae10aSGreg Roach    public static function getIdList(): array
366c1010edaSGreg Roach    {
36713abd6f3SGreg Roach        $list = [];
368a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
369*72cf66d4SGreg Roach            $list[$tree->id] = $tree->title;
370a25f0a04SGreg Roach        }
371a25f0a04SGreg Roach
372a25f0a04SGreg Roach        return $list;
373a25f0a04SGreg Roach    }
374a25f0a04SGreg Roach
375a25f0a04SGreg Roach    /**
376a25f0a04SGreg Roach     * Create arguments to select_edit_control()
377a25f0a04SGreg Roach     * Note - these will be escaped later
378a25f0a04SGreg Roach     *
379a25f0a04SGreg Roach     * @return string[]
380a25f0a04SGreg Roach     */
381771ae10aSGreg Roach    public static function getNameList(): array
382c1010edaSGreg Roach    {
38313abd6f3SGreg Roach        $list = [];
384a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
385a25f0a04SGreg Roach            $list[$tree->name] = $tree->title;
386a25f0a04SGreg Roach        }
387a25f0a04SGreg Roach
388a25f0a04SGreg Roach        return $list;
389a25f0a04SGreg Roach    }
390a25f0a04SGreg Roach
391a25f0a04SGreg Roach    /**
392a25f0a04SGreg Roach     * Create a new tree
393a25f0a04SGreg Roach     *
394a25f0a04SGreg Roach     * @param string $tree_name
395a25f0a04SGreg Roach     * @param string $tree_title
396a25f0a04SGreg Roach     *
397a25f0a04SGreg Roach     * @return Tree
398a25f0a04SGreg Roach     */
399771ae10aSGreg Roach    public static function create(string $tree_name, string $tree_title): Tree
400c1010edaSGreg Roach    {
401a25f0a04SGreg Roach        try {
402a25f0a04SGreg Roach            // Create a new tree
403a25f0a04SGreg Roach            Database::prepare(
404a25f0a04SGreg Roach                "INSERT INTO `##gedcom` (gedcom_name) VALUES (?)"
40513abd6f3SGreg Roach            )->execute([$tree_name]);
4064a86d714SGreg Roach
4074a86d714SGreg Roach            $tree_id = (int) Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
408a25f0a04SGreg Roach        } catch (PDOException $ex) {
409bd52fa32SGreg Roach            DebugBar::addThrowable($ex);
410bd52fa32SGreg Roach
411a25f0a04SGreg Roach            // A tree with that name already exists?
412ef2fd529SGreg Roach            return self::findByName($tree_name);
413a25f0a04SGreg Roach        }
414a25f0a04SGreg Roach
415a25f0a04SGreg Roach        // Update the list of trees - to include this new one
41675a9f908SGreg Roach        self::$trees = [];
417d2cdeb3fSGreg Roach        $tree        = self::findById($tree_id);
418a25f0a04SGreg Roach
419a25f0a04SGreg Roach        $tree->setPreference('imported', '0');
420a25f0a04SGreg Roach        $tree->setPreference('title', $tree_title);
421a25f0a04SGreg Roach
422a25f0a04SGreg Roach        // Module privacy
423a25f0a04SGreg Roach        Module::setDefaultAccess($tree_id);
424a25f0a04SGreg Roach
4251507cbcaSGreg Roach        // Set preferences from default tree
4261507cbcaSGreg Roach        Database::prepare(
4271507cbcaSGreg Roach            "INSERT INTO `##gedcom_setting` (gedcom_id, setting_name, setting_value)" .
4281507cbcaSGreg Roach            " SELECT :tree_id, setting_name, setting_value" .
4291507cbcaSGreg Roach            " FROM `##gedcom_setting` WHERE gedcom_id = -1"
43013abd6f3SGreg Roach        )->execute([
4311507cbcaSGreg Roach            'tree_id' => $tree_id,
43213abd6f3SGreg Roach        ]);
4331507cbcaSGreg Roach
4341507cbcaSGreg Roach        Database::prepare(
4351507cbcaSGreg Roach            "INSERT INTO `##default_resn` (gedcom_id, tag_type, resn)" .
4361507cbcaSGreg Roach            " SELECT :tree_id, tag_type, resn" .
4371507cbcaSGreg Roach            " FROM `##default_resn` WHERE gedcom_id = -1"
43813abd6f3SGreg Roach        )->execute([
4391507cbcaSGreg Roach            'tree_id' => $tree_id,
44013abd6f3SGreg Roach        ]);
4411507cbcaSGreg Roach
4421507cbcaSGreg Roach        Database::prepare(
4431507cbcaSGreg Roach            "INSERT INTO `##block` (gedcom_id, location, block_order, module_name)" .
4441507cbcaSGreg Roach            " SELECT :tree_id, location, block_order, module_name" .
4451507cbcaSGreg Roach            " FROM `##block` WHERE gedcom_id = -1"
44613abd6f3SGreg Roach        )->execute([
4471507cbcaSGreg Roach            'tree_id' => $tree_id,
44813abd6f3SGreg Roach        ]);
4491507cbcaSGreg Roach
450a25f0a04SGreg Roach        // Gedcom and privacy settings
45176f666f4SGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
45276f666f4SGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
453a25f0a04SGreg Roach        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
454a25f0a04SGreg Roach        switch (WT_LOCALE) {
455a25f0a04SGreg Roach            case 'es':
456a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'spanish');
457a25f0a04SGreg Roach                break;
458a25f0a04SGreg Roach            case 'is':
459a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
460a25f0a04SGreg Roach                break;
461a25f0a04SGreg Roach            case 'lt':
462a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
463a25f0a04SGreg Roach                break;
464a25f0a04SGreg Roach            case 'pl':
465a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'polish');
466a25f0a04SGreg Roach                break;
467a25f0a04SGreg Roach            case 'pt':
468a25f0a04SGreg Roach            case 'pt-BR':
469a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
470a25f0a04SGreg Roach                break;
471a25f0a04SGreg Roach            default:
472a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'paternal');
473a25f0a04SGreg Roach                break;
474a25f0a04SGreg Roach        }
475a25f0a04SGreg Roach
476a25f0a04SGreg Roach        // Genealogy data
477a25f0a04SGreg Roach        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
478bbb76c12SGreg Roach        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
479bbb76c12SGreg Roach        $john_doe = I18N::translate('John /DOE/');
48077e70a22SGreg Roach        $note     = I18N::translate('Edit this individual and replace their details with your own.');
48113abd6f3SGreg Roach        Database::prepare("INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)")->execute([
482a25f0a04SGreg Roach            $tree_id,
483cbc1590aSGreg 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",
48413abd6f3SGreg Roach        ]);
485a25f0a04SGreg Roach
486a25f0a04SGreg Roach        // Update our cache
487*72cf66d4SGreg Roach        self::$trees[$tree->id] = $tree;
488a25f0a04SGreg Roach
489a25f0a04SGreg Roach        return $tree;
490a25f0a04SGreg Roach    }
491a25f0a04SGreg Roach
492a25f0a04SGreg Roach    /**
493b78374c5SGreg Roach     * Are there any pending edits for this tree, than need reviewing by a moderator.
494b78374c5SGreg Roach     *
495b78374c5SGreg Roach     * @return bool
496b78374c5SGreg Roach     */
497771ae10aSGreg Roach    public function hasPendingEdit(): bool
498c1010edaSGreg Roach    {
499b78374c5SGreg Roach        return (bool) Database::prepare(
500b78374c5SGreg Roach            "SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
50113abd6f3SGreg Roach        )->execute([
502*72cf66d4SGreg Roach            'tree_id' => $this->id,
50313abd6f3SGreg Roach        ])->fetchOne();
504b78374c5SGreg Roach    }
505b78374c5SGreg Roach
506b78374c5SGreg Roach    /**
507a25f0a04SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
508a25f0a04SGreg Roach     * new data. Optionally retain the media data, for when the user has been
509a25f0a04SGreg Roach     * editing their data offline using an application which deletes (or does not
510a25f0a04SGreg Roach     * support) media data.
511a25f0a04SGreg Roach     *
512a25f0a04SGreg Roach     * @param bool $keep_media
513b7e60af1SGreg Roach     *
514b7e60af1SGreg Roach     * @return void
515a25f0a04SGreg Roach     */
516b7e60af1SGreg Roach    public function deleteGenealogyData(bool $keep_media)
517c1010edaSGreg Roach    {
518*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute([$this->id]);
519*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute([$this->id]);
520*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute([$this->id]);
521*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute([$this->id]);
522*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute([$this->id]);
523*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute([$this->id]);
524*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute([$this->id]);
525*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute([$this->id]);
526*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute([$this->id]);
527*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute([$this->id]);
528a25f0a04SGreg Roach
529a25f0a04SGreg Roach        if ($keep_media) {
530*72cf66d4SGreg Roach            Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute([$this->id]);
531a25f0a04SGreg Roach        } else {
532*72cf66d4SGreg Roach            Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute([$this->id]);
533*72cf66d4SGreg Roach            Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute([$this->id]);
534*72cf66d4SGreg Roach            Database::prepare("DELETE FROM `##media_file` WHERE m_file =?")->execute([$this->id]);
535a25f0a04SGreg Roach        }
536a25f0a04SGreg Roach    }
537a25f0a04SGreg Roach
538a25f0a04SGreg Roach    /**
539a25f0a04SGreg Roach     * Delete everything relating to a tree
540b7e60af1SGreg Roach     *
541b7e60af1SGreg Roach     * @return void
542a25f0a04SGreg Roach     */
543c1010edaSGreg Roach    public function delete()
544c1010edaSGreg Roach    {
545a25f0a04SGreg Roach        // If this is the default tree, then unset it
546ef2fd529SGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
547a25f0a04SGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
548a25f0a04SGreg Roach        }
549a25f0a04SGreg Roach
550a25f0a04SGreg Roach        $this->deleteGenealogyData(false);
551a25f0a04SGreg Roach
552*72cf66d4SGreg Roach        Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute([$this->id]);
553*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute([$this->id]);
554*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute([$this->id]);
555*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute([$this->id]);
556*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute([$this->id]);
557*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute([$this->id]);
558*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute([$this->id]);
559*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute([$this->id]);
560*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute([$this->id]);
561*72cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute([$this->id]);
562a25f0a04SGreg Roach
563a25f0a04SGreg Roach        // After updating the database, we need to fetch a new (sorted) copy
56475a9f908SGreg Roach        self::$trees = [];
565a25f0a04SGreg Roach    }
566a25f0a04SGreg Roach
567a25f0a04SGreg Roach    /**
568a25f0a04SGreg Roach     * Export the tree to a GEDCOM file
569a25f0a04SGreg Roach     *
5705792757eSGreg Roach     * @param resource $stream
571b7e60af1SGreg Roach     *
572b7e60af1SGreg Roach     * @return void
573a25f0a04SGreg Roach     */
574c1010edaSGreg Roach    public function exportGedcom($stream)
575c1010edaSGreg Roach    {
5765792757eSGreg Roach        $stmt = Database::prepare(
577e56ef01aSGreg Roach            "SELECT i_gedcom AS gedcom, i_id AS xref, 1 AS n FROM `##individuals` WHERE i_file = :tree_id_1" .
5785792757eSGreg Roach            " UNION ALL " .
579e56ef01aSGreg Roach            "SELECT f_gedcom AS gedcom, f_id AS xref, 2 AS n FROM `##families`    WHERE f_file = :tree_id_2" .
5805792757eSGreg Roach            " UNION ALL " .
581e56ef01aSGreg Roach            "SELECT s_gedcom AS gedcom, s_id AS xref, 3 AS n FROM `##sources`     WHERE s_file = :tree_id_3" .
5825792757eSGreg Roach            " UNION ALL " .
583e56ef01aSGreg 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')" .
5845792757eSGreg Roach            " UNION ALL " .
585e56ef01aSGreg Roach            "SELECT m_gedcom AS gedcom, m_id AS xref, 5 AS n FROM `##media`       WHERE m_file = :tree_id_5" .
586e56ef01aSGreg Roach            " ORDER BY n, LENGTH(xref), xref"
58713abd6f3SGreg Roach        )->execute([
588*72cf66d4SGreg Roach            'tree_id_1' => $this->id,
589*72cf66d4SGreg Roach            'tree_id_2' => $this->id,
590*72cf66d4SGreg Roach            'tree_id_3' => $this->id,
591*72cf66d4SGreg Roach            'tree_id_4' => $this->id,
592*72cf66d4SGreg Roach            'tree_id_5' => $this->id,
59313abd6f3SGreg Roach        ]);
594a25f0a04SGreg Roach
595a3d8780cSGreg Roach        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this, 'UTF-8'));
596a214e186SGreg Roach        while (($row = $stmt->fetch()) !== false) {
5973d7a8a4cSGreg Roach            $buffer .= FunctionsExport::reformatRecord($row->gedcom);
598a25f0a04SGreg Roach            if (strlen($buffer) > 65535) {
5995792757eSGreg Roach                fwrite($stream, $buffer);
600a25f0a04SGreg Roach                $buffer = '';
601a25f0a04SGreg Roach            }
602a25f0a04SGreg Roach        }
6030f471f91SGreg Roach        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
604195d09d8SGreg Roach        $stmt->closeCursor();
605a25f0a04SGreg Roach    }
606a25f0a04SGreg Roach
607a25f0a04SGreg Roach    /**
608a25f0a04SGreg Roach     * Import data from a gedcom file into this tree.
609a25f0a04SGreg Roach     *
610a25f0a04SGreg Roach     * @param string $path     The full path to the (possibly temporary) file.
611a25f0a04SGreg Roach     * @param string $filename The preferred filename, for export/download.
612a25f0a04SGreg Roach     *
613b7e60af1SGreg Roach     * @return void
614b7e60af1SGreg Roach     * @throws Exception
615a25f0a04SGreg Roach     */
616771ae10aSGreg Roach    public function importGedcomFile(string $path, string $filename)
617c1010edaSGreg Roach    {
618a25f0a04SGreg Roach        // Read the file in blocks of roughly 64K. Ensure that each block
619a25f0a04SGreg Roach        // contains complete gedcom records. This will ensure we don’t split
620a25f0a04SGreg Roach        // multi-byte characters, as well as simplifying the code to import
621a25f0a04SGreg Roach        // each block.
622a25f0a04SGreg Roach
623a25f0a04SGreg Roach        $file_data = '';
624a25f0a04SGreg Roach        $fp        = fopen($path, 'rb');
625a25f0a04SGreg Roach
6262e897bf2SGreg Roach        if ($fp === false) {
6272e897bf2SGreg Roach            throw new Exception('Cannot write file: ' . $path);
6282e897bf2SGreg Roach        }
629a25f0a04SGreg Roach
630b7e60af1SGreg Roach        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
631a25f0a04SGreg Roach        $this->setPreference('gedcom_filename', $filename);
632a25f0a04SGreg Roach        $this->setPreference('imported', '0');
633a25f0a04SGreg Roach
634a25f0a04SGreg Roach        while (!feof($fp)) {
635a25f0a04SGreg Roach            $file_data .= fread($fp, 65536);
636a25f0a04SGreg Roach            // There is no strrpos() function that searches for substrings :-(
637a25f0a04SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
638a25f0a04SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
639a25f0a04SGreg Roach                    // We’ve found the last record boundary in this chunk of data
640a25f0a04SGreg Roach                    break;
641a25f0a04SGreg Roach                }
642a25f0a04SGreg Roach            }
643a25f0a04SGreg Roach            if ($pos) {
644a25f0a04SGreg Roach                Database::prepare(
645a25f0a04SGreg Roach                    "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
646c1010edaSGreg Roach                )->execute([
647*72cf66d4SGreg Roach                    $this->id,
648c1010edaSGreg Roach                    substr($file_data, 0, $pos),
649c1010edaSGreg Roach                ]);
650a25f0a04SGreg Roach                $file_data = substr($file_data, $pos);
651a25f0a04SGreg Roach            }
652a25f0a04SGreg Roach        }
653a25f0a04SGreg Roach        Database::prepare(
654a25f0a04SGreg Roach            "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
655c1010edaSGreg Roach        )->execute([
656*72cf66d4SGreg Roach            $this->id,
657c1010edaSGreg Roach            $file_data,
658c1010edaSGreg Roach        ]);
659a25f0a04SGreg Roach
660a25f0a04SGreg Roach        fclose($fp);
661a25f0a04SGreg Roach    }
662304f20d5SGreg Roach
663304f20d5SGreg Roach    /**
664b90d8accSGreg Roach     * Generate a new XREF, unique across all family trees
665b90d8accSGreg Roach     *
666b90d8accSGreg Roach     * @return string
667b90d8accSGreg Roach     */
668771ae10aSGreg Roach    public function getNewXref(): string
669c1010edaSGreg Roach    {
670a214e186SGreg Roach        $prefix = 'X';
671b90d8accSGreg Roach
672971d66c8SGreg Roach        $increment = 1.0;
673b90d8accSGreg Roach        do {
674b90d8accSGreg Roach            // Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See
675b90d8accSGreg Roach            // http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
676b90d8accSGreg Roach            $statement = Database::prepare(
677a214e186SGreg Roach                "UPDATE `##site_setting` SET setting_value = LAST_INSERT_ID(setting_value + :increment) WHERE setting_name = 'next_xref'"
678b90d8accSGreg Roach            );
67913abd6f3SGreg Roach            $statement->execute([
680971d66c8SGreg Roach                'increment' => (int) $increment,
68113abd6f3SGreg Roach            ]);
682b90d8accSGreg Roach
683b90d8accSGreg Roach            if ($statement->rowCount() === 0) {
684769d7d6eSGreg Roach                $num = '1';
685bbd8bd1bSGreg Roach                Site::setPreference('next_xref', $num);
686b90d8accSGreg Roach            } else {
687bbd8bd1bSGreg Roach                $num = (string) Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
688b90d8accSGreg Roach            }
689b90d8accSGreg Roach
690a214e186SGreg Roach            $xref = $prefix . $num;
691a214e186SGreg Roach
692b90d8accSGreg Roach            // Records may already exist with this sequence number.
693b90d8accSGreg Roach            $already_used = Database::prepare(
694a214e186SGreg Roach                "SELECT" .
695a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##individuals` WHERE i_id = :i_id) OR" .
696a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##families` WHERE f_id = :f_id) OR" .
697a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##sources` WHERE s_id = :s_id) OR" .
698a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##media` WHERE m_id = :m_id) OR" .
699a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##other` WHERE o_id = :o_id) OR" .
700a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##change` WHERE xref = :xref)"
70113abd6f3SGreg Roach            )->execute([
702a214e186SGreg Roach                'i_id' => $xref,
703a214e186SGreg Roach                'f_id' => $xref,
704a214e186SGreg Roach                's_id' => $xref,
705a214e186SGreg Roach                'm_id' => $xref,
706a214e186SGreg Roach                'o_id' => $xref,
707a214e186SGreg Roach                'xref' => $xref,
70813abd6f3SGreg Roach            ])->fetchOne();
709971d66c8SGreg Roach
710971d66c8SGreg Roach            // This exponential increment allows us to scan over large blocks of
711971d66c8SGreg Roach            // existing data in a reasonable time.
712971d66c8SGreg Roach            $increment *= 1.01;
713a214e186SGreg Roach        } while ($already_used !== '0');
714b90d8accSGreg Roach
715a214e186SGreg Roach        return $xref;
716b90d8accSGreg Roach    }
717b90d8accSGreg Roach
718b90d8accSGreg Roach    /**
719304f20d5SGreg Roach     * Create a new record from GEDCOM data.
720304f20d5SGreg Roach     *
721304f20d5SGreg Roach     * @param string $gedcom
722304f20d5SGreg Roach     *
72315d603e7SGreg Roach     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
724afb591d7SGreg Roach     * @throws InvalidArgumentException
725304f20d5SGreg Roach     */
726771ae10aSGreg Roach    public function createRecord(string $gedcom): GedcomRecord
727c1010edaSGreg Roach    {
728afb591d7SGreg Roach        if (substr_compare($gedcom, '0 @@', 0, 4) !== 0) {
729afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createRecord(' . $gedcom . ') does not begin 0 @@');
730304f20d5SGreg Roach        }
731304f20d5SGreg Roach
732a214e186SGreg Roach        $xref   = $this->getNewXref();
733afb591d7SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
734304f20d5SGreg Roach
735afb591d7SGreg Roach        // Create a change record
736304f20d5SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
737304f20d5SGreg Roach
738304f20d5SGreg Roach        // Create a pending change
739304f20d5SGreg Roach        Database::prepare(
740304f20d5SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
74113abd6f3SGreg Roach        )->execute([
742*72cf66d4SGreg Roach            $this->id,
743304f20d5SGreg Roach            $xref,
744304f20d5SGreg Roach            $gedcom,
745cbc1590aSGreg Roach            Auth::id(),
74613abd6f3SGreg Roach        ]);
747304f20d5SGreg Roach
748afb591d7SGreg Roach        // Accept this pending change
749afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
750afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
751afb591d7SGreg Roach
752afb591d7SGreg Roach            return new GedcomRecord($xref, $gedcom, null, $this);
753afb591d7SGreg Roach        }
754afb591d7SGreg Roach
755313e72b3SGreg Roach        return GedcomRecord::getInstance($xref, $this, $gedcom);
756afb591d7SGreg Roach    }
757afb591d7SGreg Roach
758afb591d7SGreg Roach    /**
759afb591d7SGreg Roach     * Create a new family from GEDCOM data.
760afb591d7SGreg Roach     *
761afb591d7SGreg Roach     * @param string $gedcom
762afb591d7SGreg Roach     *
763afb591d7SGreg Roach     * @return Family
764afb591d7SGreg Roach     * @throws InvalidArgumentException
765afb591d7SGreg Roach     */
766afb591d7SGreg Roach    public function createFamily(string $gedcom): GedcomRecord
767afb591d7SGreg Roach    {
768afb591d7SGreg Roach        if (substr_compare($gedcom, '0 @@ FAM', 0, 8) !== 0) {
769afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createFamily(' . $gedcom . ') does not begin 0 @@ FAM');
770afb591d7SGreg Roach        }
771afb591d7SGreg Roach
772afb591d7SGreg Roach        $xref   = $this->getNewXref();
773afb591d7SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
774afb591d7SGreg Roach
775afb591d7SGreg Roach        // Create a change record
776afb591d7SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
777afb591d7SGreg Roach
778afb591d7SGreg Roach        // Create a pending change
779afb591d7SGreg Roach        Database::prepare(
780afb591d7SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
781afb591d7SGreg Roach        )->execute([
782*72cf66d4SGreg Roach            $this->id,
783afb591d7SGreg Roach            $xref,
784afb591d7SGreg Roach            $gedcom,
785afb591d7SGreg Roach            Auth::id(),
786afb591d7SGreg Roach        ]);
787304f20d5SGreg Roach
788304f20d5SGreg Roach        // Accept this pending change
789304f20d5SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
790cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
791afb591d7SGreg Roach
792afb591d7SGreg Roach            return new Family($xref, $gedcom, null, $this);
793304f20d5SGreg Roach        }
794afb591d7SGreg Roach
795afb591d7SGreg Roach        return new Family($xref, '', $gedcom, $this);
796afb591d7SGreg Roach    }
797afb591d7SGreg Roach
798afb591d7SGreg Roach    /**
799afb591d7SGreg Roach     * Create a new individual from GEDCOM data.
800afb591d7SGreg Roach     *
801afb591d7SGreg Roach     * @param string $gedcom
802afb591d7SGreg Roach     *
803afb591d7SGreg Roach     * @return Individual
804afb591d7SGreg Roach     * @throws InvalidArgumentException
805afb591d7SGreg Roach     */
806afb591d7SGreg Roach    public function createIndividual(string $gedcom): GedcomRecord
807afb591d7SGreg Roach    {
808afb591d7SGreg Roach        if (substr_compare($gedcom, '0 @@ INDI', 0, 9) !== 0) {
809afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ INDI');
810afb591d7SGreg Roach        }
811afb591d7SGreg Roach
812afb591d7SGreg Roach        $xref   = $this->getNewXref();
813afb591d7SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
814afb591d7SGreg Roach
815afb591d7SGreg Roach        // Create a change record
816afb591d7SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
817afb591d7SGreg Roach
818afb591d7SGreg Roach        // Create a pending change
819afb591d7SGreg Roach        Database::prepare(
820afb591d7SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
821afb591d7SGreg Roach        )->execute([
822*72cf66d4SGreg Roach            $this->id,
823afb591d7SGreg Roach            $xref,
824afb591d7SGreg Roach            $gedcom,
825afb591d7SGreg Roach            Auth::id(),
826afb591d7SGreg Roach        ]);
827afb591d7SGreg Roach
828afb591d7SGreg Roach        // Accept this pending change
829afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
830afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
831afb591d7SGreg Roach
832afb591d7SGreg Roach            return new Individual($xref, $gedcom, null, $this);
833afb591d7SGreg Roach        }
834afb591d7SGreg Roach
835afb591d7SGreg Roach        return new Individual($xref, '', $gedcom, $this);
836304f20d5SGreg Roach    }
8378586983fSGreg Roach
8388586983fSGreg Roach    /**
8398586983fSGreg Roach     * What is the most significant individual in this tree.
8408586983fSGreg Roach     *
8418586983fSGreg Roach     * @param User $user
8428586983fSGreg Roach     *
8438586983fSGreg Roach     * @return Individual
8448586983fSGreg Roach     */
845c1010edaSGreg Roach    public function significantIndividual(User $user): Individual
846c1010edaSGreg Roach    {
8478586983fSGreg Roach        static $individual; // Only query the DB once.
8488586983fSGreg Roach
8497015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'rootid') !== '') {
8508586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
8518586983fSGreg Roach        }
8527015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'gedcomid') !== '') {
8538586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
8548586983fSGreg Roach        }
8558586983fSGreg Roach        if (!$individual) {
8568586983fSGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
8578586983fSGreg Roach        }
8588586983fSGreg Roach        if (!$individual) {
859769d7d6eSGreg Roach            $xref = (string) Database::prepare(
8605fe1add5SGreg Roach                "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
8615fe1add5SGreg Roach            )->execute([
862*72cf66d4SGreg Roach                'tree_id' => $this->id(),
863769d7d6eSGreg Roach            ])->fetchOne();
864769d7d6eSGreg Roach
865769d7d6eSGreg Roach            $individual = Individual::getInstance($xref, $this);
8665fe1add5SGreg Roach        }
8675fe1add5SGreg Roach        if (!$individual) {
8685fe1add5SGreg Roach            // always return a record
8695fe1add5SGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
8705fe1add5SGreg Roach        }
8715fe1add5SGreg Roach
8725fe1add5SGreg Roach        return $individual;
8735fe1add5SGreg Roach    }
8745fe1add5SGreg Roach
8755fe1add5SGreg Roach    /**
8765fe1add5SGreg Roach     * Get significant information from this page, to allow other pages such as
8775fe1add5SGreg Roach     * charts and reports to initialise with the same records
8785fe1add5SGreg Roach     *
8795fe1add5SGreg Roach     * @return Individual
8805fe1add5SGreg Roach     */
881771ae10aSGreg Roach    public function getSignificantIndividual(): Individual
882c1010edaSGreg Roach    {
8835fe1add5SGreg Roach        static $individual; // Only query the DB once.
8845fe1add5SGreg Roach
8857015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'rootid') !== '') {
8865fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'rootid'), $this);
8875fe1add5SGreg Roach        }
8887015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'gedcomid') !== '') {
8895fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'gedcomid'), $this);
8905fe1add5SGreg Roach        }
8915fe1add5SGreg Roach        if (!$individual) {
8925fe1add5SGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
8935fe1add5SGreg Roach        }
8945fe1add5SGreg Roach        if (!$individual) {
895769d7d6eSGreg Roach            $xref = (string) Database::prepare(
896769d7d6eSGreg Roach                "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
897769d7d6eSGreg Roach            )->execute([
898*72cf66d4SGreg Roach                'tree_id' => $this->id(),
899769d7d6eSGreg Roach            ])->fetchOne();
900769d7d6eSGreg Roach
901769d7d6eSGreg Roach            $individual = Individual::getInstance($xref, $this);
9028586983fSGreg Roach        }
9038586983fSGreg Roach        if (!$individual) {
9048586983fSGreg Roach            // always return a record
9058586983fSGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
9068586983fSGreg Roach        }
9078586983fSGreg Roach
9088586983fSGreg Roach        return $individual;
9098586983fSGreg Roach    }
910a25f0a04SGreg Roach}
911