xref: /webtrees/app/Tree.php (revision 32f20c14b2839ce85ae9a14fd182d48b6c1989a6)
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;
2301461f86SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
2401461f86SGreg Roachuse Illuminate\Database\Query\Builder;
2501461f86SGreg Roachuse Illuminate\Database\Query\JoinClause;
26afb591d7SGreg Roachuse InvalidArgumentException;
27a25f0a04SGreg Roachuse PDOException;
28afb591d7SGreg Roachuse function substr_compare;
29a25f0a04SGreg Roach
30a25f0a04SGreg Roach/**
3176692c8bSGreg Roach * Provide an interface to the wt_gedcom table.
32a25f0a04SGreg Roach */
33c1010edaSGreg Roachclass Tree
34c1010edaSGreg Roach{
35cbc1590aSGreg Roach    /** @var int The tree's ID number */
3672cf66d4SGreg Roach    private $id;
37518bbdc1SGreg Roach
38a25f0a04SGreg Roach    /** @var string The tree's name */
39a25f0a04SGreg Roach    private $name;
40518bbdc1SGreg Roach
41a25f0a04SGreg Roach    /** @var string The tree's title */
42a25f0a04SGreg Roach    private $title;
43a25f0a04SGreg Roach
44e2052359SGreg Roach    /** @var int[] Default access rules for facts in this tree */
45518bbdc1SGreg Roach    private $fact_privacy;
46518bbdc1SGreg Roach
47e2052359SGreg Roach    /** @var int[] Default access rules for individuals in this tree */
48518bbdc1SGreg Roach    private $individual_privacy;
49518bbdc1SGreg Roach
50518bbdc1SGreg Roach    /** @var integer[][] Default access rules for individual facts in this tree */
51518bbdc1SGreg Roach    private $individual_fact_privacy;
52518bbdc1SGreg Roach
53a25f0a04SGreg Roach    /** @var Tree[] All trees that we have permission to see. */
54*32f20c14SGreg Roach    public static $trees = [];
55a25f0a04SGreg Roach
56a25f0a04SGreg Roach    /** @var string[] Cached copy of the wt_gedcom_setting table. */
5715d603e7SGreg Roach    private $preferences = [];
58a25f0a04SGreg Roach
59a25f0a04SGreg Roach    /** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
6013abd6f3SGreg Roach    private $user_preferences = [];
61a25f0a04SGreg Roach
62061b43d7SGreg Roach    private const RESN_PRIVACY = [
63061b43d7SGreg Roach        'none'         => Auth::PRIV_PRIVATE,
64061b43d7SGreg Roach        'privacy'      => Auth::PRIV_USER,
65061b43d7SGreg Roach        'confidential' => Auth::PRIV_NONE,
66061b43d7SGreg Roach        'hidden'       => Auth::PRIV_HIDE,
67061b43d7SGreg Roach    ];
68061b43d7SGreg Roach
69a25f0a04SGreg Roach    /**
70a25f0a04SGreg Roach     * Create a tree object. This is a private constructor - it can only
71a25f0a04SGreg Roach     * be called from Tree::getAll() to ensure proper initialisation.
72a25f0a04SGreg Roach     *
7372cf66d4SGreg Roach     * @param int    $id
74aa6f03bbSGreg Roach     * @param string $name
75cc13d6d8SGreg Roach     * @param string $title
76a25f0a04SGreg Roach     */
77cc13d6d8SGreg Roach    private function __construct($id, $name, $title)
78c1010edaSGreg Roach    {
7972cf66d4SGreg Roach        $this->id                      = $id;
80aa6f03bbSGreg Roach        $this->name                    = $name;
81cc13d6d8SGreg Roach        $this->title                   = $title;
8213abd6f3SGreg Roach        $this->fact_privacy            = [];
8313abd6f3SGreg Roach        $this->individual_privacy      = [];
8413abd6f3SGreg Roach        $this->individual_fact_privacy = [];
85518bbdc1SGreg Roach
86518bbdc1SGreg Roach        // Load the privacy settings for this tree
87061b43d7SGreg Roach        $rows = DB::table('default_resn')
88061b43d7SGreg Roach            ->where('gedcom_id', '=', $this->id)
89061b43d7SGreg Roach            ->get();
90518bbdc1SGreg Roach
91518bbdc1SGreg Roach        foreach ($rows as $row) {
92061b43d7SGreg Roach            // Convert GEDCOM privacy restriction to a webtrees access level.
93061b43d7SGreg Roach            $row->resn = self::RESN_PRIVACY[$row->resn];
94061b43d7SGreg Roach
95518bbdc1SGreg Roach            if ($row->xref !== null) {
96518bbdc1SGreg Roach                if ($row->tag_type !== null) {
97518bbdc1SGreg Roach                    $this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
98518bbdc1SGreg Roach                } else {
99518bbdc1SGreg Roach                    $this->individual_privacy[$row->xref] = (int) $row->resn;
100518bbdc1SGreg Roach                }
101518bbdc1SGreg Roach            } else {
102518bbdc1SGreg Roach                $this->fact_privacy[$row->tag_type] = (int) $row->resn;
103518bbdc1SGreg Roach            }
104518bbdc1SGreg Roach        }
105a25f0a04SGreg Roach    }
106a25f0a04SGreg Roach
107a25f0a04SGreg Roach    /**
108a25f0a04SGreg Roach     * The ID of this tree
109a25f0a04SGreg Roach     *
110cbc1590aSGreg Roach     * @return int
111a25f0a04SGreg Roach     */
11272cf66d4SGreg Roach    public function id(): int
113c1010edaSGreg Roach    {
11472cf66d4SGreg Roach        return $this->id;
115a25f0a04SGreg Roach    }
116a25f0a04SGreg Roach
117a25f0a04SGreg Roach    /**
118a25f0a04SGreg Roach     * The name of this tree
119a25f0a04SGreg Roach     *
120a25f0a04SGreg Roach     * @return string
121a25f0a04SGreg Roach     */
122aa6f03bbSGreg Roach    public function name(): string
123c1010edaSGreg Roach    {
124a25f0a04SGreg Roach        return $this->name;
125a25f0a04SGreg Roach    }
126a25f0a04SGreg Roach
127a25f0a04SGreg Roach    /**
128a25f0a04SGreg Roach     * The title of this tree
129a25f0a04SGreg Roach     *
130a25f0a04SGreg Roach     * @return string
131a25f0a04SGreg Roach     */
132cc13d6d8SGreg Roach    public function title(): string
133c1010edaSGreg Roach    {
134a25f0a04SGreg Roach        return $this->title;
135a25f0a04SGreg Roach    }
136a25f0a04SGreg Roach
137a25f0a04SGreg Roach    /**
138518bbdc1SGreg Roach     * The fact-level privacy for this tree.
139518bbdc1SGreg Roach     *
140e2052359SGreg Roach     * @return int[]
141518bbdc1SGreg Roach     */
1428f53f488SRico Sonntag    public function getFactPrivacy(): array
143c1010edaSGreg Roach    {
144518bbdc1SGreg Roach        return $this->fact_privacy;
145518bbdc1SGreg Roach    }
146518bbdc1SGreg Roach
147518bbdc1SGreg Roach    /**
148518bbdc1SGreg Roach     * The individual-level privacy for this tree.
149518bbdc1SGreg Roach     *
150e2052359SGreg Roach     * @return int[]
151518bbdc1SGreg Roach     */
1528f53f488SRico Sonntag    public function getIndividualPrivacy(): array
153c1010edaSGreg Roach    {
154518bbdc1SGreg Roach        return $this->individual_privacy;
155518bbdc1SGreg Roach    }
156518bbdc1SGreg Roach
157518bbdc1SGreg Roach    /**
158518bbdc1SGreg Roach     * The individual-fact-level privacy for this tree.
159518bbdc1SGreg Roach     *
160adac8af1SGreg Roach     * @return int[][]
161518bbdc1SGreg Roach     */
1628f53f488SRico Sonntag    public function getIndividualFactPrivacy(): array
163c1010edaSGreg Roach    {
164518bbdc1SGreg Roach        return $this->individual_fact_privacy;
165518bbdc1SGreg Roach    }
166518bbdc1SGreg Roach
167518bbdc1SGreg Roach    /**
168a25f0a04SGreg Roach     * Get the tree’s configuration settings.
169a25f0a04SGreg Roach     *
170a25f0a04SGreg Roach     * @param string $setting_name
17115d603e7SGreg Roach     * @param string $default
172a25f0a04SGreg Roach     *
17315d603e7SGreg Roach     * @return string
174a25f0a04SGreg Roach     */
175771ae10aSGreg Roach    public function getPreference(string $setting_name, string $default = ''): string
176c1010edaSGreg Roach    {
17715d603e7SGreg Roach        if (empty($this->preferences)) {
178061b43d7SGreg Roach            $this->preferences = DB::table('gedcom_setting')
179061b43d7SGreg Roach                ->where('gedcom_id', '=', $this->id)
180061b43d7SGreg Roach                ->pluck('setting_value', 'setting_name')
181061b43d7SGreg Roach                ->all();
182a25f0a04SGreg Roach        }
183a25f0a04SGreg Roach
184b2ce94c6SRico Sonntag        return $this->preferences[$setting_name] ?? $default;
185a25f0a04SGreg Roach    }
186a25f0a04SGreg Roach
187a25f0a04SGreg Roach    /**
188a25f0a04SGreg Roach     * Set the tree’s configuration settings.
189a25f0a04SGreg Roach     *
190a25f0a04SGreg Roach     * @param string $setting_name
191a25f0a04SGreg Roach     * @param string $setting_value
192a25f0a04SGreg Roach     *
193a25f0a04SGreg Roach     * @return $this
194a25f0a04SGreg Roach     */
195771ae10aSGreg Roach    public function setPreference(string $setting_name, string $setting_value): Tree
196c1010edaSGreg Roach    {
197a25f0a04SGreg Roach        if ($setting_value !== $this->getPreference($setting_name)) {
198061b43d7SGreg Roach            DB::table('gedcom_setting')->updateOrInsert([
199061b43d7SGreg Roach                'gedcom_id' =>$this->id,
200a25f0a04SGreg Roach                'setting_name' => $setting_name,
201061b43d7SGreg Roach            ], [
202a25f0a04SGreg Roach                'setting_value' => $setting_value,
20313abd6f3SGreg Roach            ]);
20415d603e7SGreg Roach
205a25f0a04SGreg Roach            $this->preferences[$setting_name] = $setting_value;
20615d603e7SGreg Roach
20772292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
208a25f0a04SGreg Roach        }
209a25f0a04SGreg Roach
210a25f0a04SGreg Roach        return $this;
211a25f0a04SGreg Roach    }
212a25f0a04SGreg Roach
213a25f0a04SGreg Roach    /**
214a25f0a04SGreg Roach     * Get the tree’s user-configuration settings.
215a25f0a04SGreg Roach     *
216a25f0a04SGreg Roach     * @param User   $user
217a25f0a04SGreg Roach     * @param string $setting_name
2187015ba1fSGreg Roach     * @param string $default
219a25f0a04SGreg Roach     *
220a25f0a04SGreg Roach     * @return string
221a25f0a04SGreg Roach     */
222771ae10aSGreg Roach    public function getUserPreference(User $user, string $setting_name, string $default = ''): string
223c1010edaSGreg Roach    {
224a25f0a04SGreg Roach        // There are lots of settings, and we need to fetch lots of them on every page
225a25f0a04SGreg Roach        // so it is quicker to fetch them all in one go.
226a25f0a04SGreg Roach        if (!array_key_exists($user->getUserId(), $this->user_preferences)) {
227061b43d7SGreg Roach            $this->user_preferences[$user->getUserId()] = DB::table('user_gedcom_setting')
228061b43d7SGreg Roach                ->where('user_id', '=', $user->getUserId())
229061b43d7SGreg Roach                ->where('gedcom_id', '=', $this->id)
230061b43d7SGreg Roach                ->pluck('setting_value', 'setting_name')
231061b43d7SGreg Roach                ->all();
232a25f0a04SGreg Roach        }
233a25f0a04SGreg Roach
234b2ce94c6SRico Sonntag        return $this->user_preferences[$user->getUserId()][$setting_name] ?? $default;
235a25f0a04SGreg Roach    }
236a25f0a04SGreg Roach
237a25f0a04SGreg Roach    /**
238a25f0a04SGreg Roach     * Set the tree’s user-configuration settings.
239a25f0a04SGreg Roach     *
240a25f0a04SGreg Roach     * @param User   $user
241a25f0a04SGreg Roach     * @param string $setting_name
242a25f0a04SGreg Roach     * @param string $setting_value
243a25f0a04SGreg Roach     *
244a25f0a04SGreg Roach     * @return $this
245a25f0a04SGreg Roach     */
246771ae10aSGreg Roach    public function setUserPreference(User $user, string $setting_name, string $setting_value): Tree
247c1010edaSGreg Roach    {
248a25f0a04SGreg Roach        if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
249a25f0a04SGreg Roach            // Update the database
250061b43d7SGreg Roach            DB::table('user_gedcom_setting')->updateOrInsert([
251061b43d7SGreg Roach                'gedcom_id' => $this->id(),
252a25f0a04SGreg Roach                'user_id' =>$user->getUserId(),
253a25f0a04SGreg Roach                'setting_name' => $setting_name,
254061b43d7SGreg Roach            ], [
255cbc1590aSGreg Roach                'setting_value' => $setting_value,
25613abd6f3SGreg Roach            ]);
257061b43d7SGreg Roach
258061b43d7SGreg Roach            // Update the cache
259a25f0a04SGreg Roach            $this->user_preferences[$user->getUserId()][$setting_name] = $setting_value;
260a25f0a04SGreg Roach            // Audit log of changes
26172292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this);
262a25f0a04SGreg Roach        }
263a25f0a04SGreg Roach
264a25f0a04SGreg Roach        return $this;
265a25f0a04SGreg Roach    }
266a25f0a04SGreg Roach
267a25f0a04SGreg Roach    /**
268a25f0a04SGreg Roach     * Can a user accept changes for this tree?
269a25f0a04SGreg Roach     *
270a25f0a04SGreg Roach     * @param User $user
271a25f0a04SGreg Roach     *
272cbc1590aSGreg Roach     * @return bool
273a25f0a04SGreg Roach     */
274771ae10aSGreg Roach    public function canAcceptChanges(User $user): bool
275c1010edaSGreg Roach    {
276a25f0a04SGreg Roach        return Auth::isModerator($this, $user);
277a25f0a04SGreg Roach    }
278a25f0a04SGreg Roach
279a25f0a04SGreg Roach    /**
280a25f0a04SGreg Roach     * Fetch all the trees that we have permission to access.
281a25f0a04SGreg Roach     *
282a25f0a04SGreg Roach     * @return Tree[]
283a25f0a04SGreg Roach     */
284771ae10aSGreg Roach    public static function getAll(): array
285c1010edaSGreg Roach    {
28675a9f908SGreg Roach        if (empty(self::$trees)) {
287061b43d7SGreg Roach            /*
288a25f0a04SGreg Roach            $rows = Database::prepare(
289e5588fb0SGreg Roach                "SELECT g.gedcom_id AS tree_id, g.gedcom_name AS tree_name, gs1.setting_value AS tree_title" .
290a25f0a04SGreg Roach                " FROM `##gedcom` g" .
291a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs1 ON (g.gedcom_id=gs1.gedcom_id AND gs1.setting_name='title')" .
292a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs2 ON (g.gedcom_id=gs2.gedcom_id AND gs2.setting_name='imported')" .
293a25f0a04SGreg Roach                " LEFT JOIN `##gedcom_setting`      gs3 ON (g.gedcom_id=gs3.gedcom_id AND gs3.setting_name='REQUIRE_AUTHENTICATION')" .
294a25f0a04SGreg Roach                " LEFT JOIN `##user_gedcom_setting` ugs ON (g.gedcom_id=ugs.gedcom_id AND ugs.setting_name='canedit' AND ugs.user_id=?)" .
295a25f0a04SGreg Roach                " WHERE " .
296a25f0a04SGreg Roach                "  g.gedcom_id>0 AND (" . // exclude the "template" tree
297a25f0a04SGreg Roach                "    EXISTS (SELECT 1 FROM `##user_setting` WHERE user_id=? AND setting_name='canadmin' AND setting_value=1)" . // Admin sees all
298a25f0a04SGreg Roach                "   ) OR (" .
2998cca4ddeSGreg Roach                "    (gs2.setting_value = 1 OR ugs.setting_value = 'admin') AND (" . // Allow imported trees, with either:
300a25f0a04SGreg Roach                "     gs3.setting_value <> 1 OR" . // visitor access
301a25f0a04SGreg Roach                "     IFNULL(ugs.setting_value, 'none')<>'none'" . // explicit access
302a25f0a04SGreg Roach                "   )" .
303a25f0a04SGreg Roach                "  )" .
304a25f0a04SGreg Roach                " ORDER BY g.sort_order, 3"
305c1010edaSGreg Roach            )->execute([
306c1010edaSGreg Roach                Auth::id(),
307c1010edaSGreg Roach                Auth::id(),
308c1010edaSGreg Roach            ])->fetchAll();
309061b43d7SGreg Roach            */
31075a9f908SGreg Roach
31101461f86SGreg Roach            // Admins see all trees
31201461f86SGreg Roach            $query = DB::table('gedcom')
31301461f86SGreg Roach                ->leftJoin('gedcom_setting', function (JoinClause $join): void {
31401461f86SGreg Roach                    $join->on('gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
31501461f86SGreg Roach                        ->where('gedcom_setting.setting_name', '=', 'title');
31601461f86SGreg Roach                })
31701461f86SGreg Roach                ->where('gedcom.gedcom_id', '>', 0)
31801461f86SGreg Roach                ->select([
31901461f86SGreg Roach                    'gedcom.gedcom_id AS tree_id',
32001461f86SGreg Roach                    'gedcom.gedcom_name AS tree_name',
32101461f86SGreg Roach                    'gedcom_setting.setting_value AS tree_title',
32201461f86SGreg Roach                ])
32301461f86SGreg Roach                ->orderBy('gedcom.sort_order')
32401461f86SGreg Roach                ->orderBy('gedcom_setting.setting_value');
32501461f86SGreg Roach
326*32f20c14SGreg Roach            // Non-admins may not see all trees
327*32f20c14SGreg Roach            if (!Auth::isAdmin()) {
32801461f86SGreg Roach                $query
32901461f86SGreg Roach                    ->join('gedcom_setting AS gs2', 'gs2.gedcom_id', '=', 'gedcom.gedcom_id')
33001461f86SGreg Roach                    ->where('gs2.setting_name', '=', 'imported');
33101461f86SGreg Roach
33201461f86SGreg Roach                // Some trees are private
33301461f86SGreg Roach                $query
33401461f86SGreg Roach                    ->leftJoin('gedcom_setting AS gs3', function (JoinClause $join): void {
33501461f86SGreg Roach                        $join->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
33601461f86SGreg Roach                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
33701461f86SGreg Roach                    })
33801461f86SGreg Roach                    ->leftJoin('user_gedcom_setting', function (JoinClause $join): void {
33901461f86SGreg Roach                        $join->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
34001461f86SGreg Roach                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
34101461f86SGreg Roach                            ->where('user_gedcom_setting.setting_name', '=', 'canedit');
34201461f86SGreg Roach                    })
34301461f86SGreg Roach                    ->where(function (Builder $query): void {
34401461f86SGreg Roach                        $query
34501461f86SGreg Roach                            // Managers
34601461f86SGreg Roach                            ->where('user_gedcom_setting.setting_value', '=', 'admin')
34701461f86SGreg Roach                            // Members
34801461f86SGreg Roach                            ->orWhere(function (Builder $query): void {
34901461f86SGreg Roach                                $query
35001461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
35101461f86SGreg Roach                                    ->where('gs3.setting_value', '=', '1')
35201461f86SGreg Roach                                    ->where('user_gedcom_setting.setting_value', '<>', 'none');
35301461f86SGreg Roach                            })
35401461f86SGreg Roach                            // Visitors
35501461f86SGreg Roach                            ->orWhere(function (Builder $query): void {
35601461f86SGreg Roach                                $query
35701461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
35801461f86SGreg Roach                                    ->where(DB::raw("COALESCE(gs3.setting_value ,'0')"), '=', 0);
35901461f86SGreg Roach                            });
36001461f86SGreg Roach                    });
36101461f86SGreg Roach            }
36201461f86SGreg Roach
36301461f86SGreg Roach            $rows = $query->get();
36401461f86SGreg Roach
365a25f0a04SGreg Roach            foreach ($rows as $row) {
3663f7ece23SGreg Roach                self::$trees[$row->tree_name] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
367a25f0a04SGreg Roach            }
368a25f0a04SGreg Roach        }
369a25f0a04SGreg Roach
370a25f0a04SGreg Roach        return self::$trees;
371a25f0a04SGreg Roach    }
372a25f0a04SGreg Roach
373a25f0a04SGreg Roach    /**
374d2cdeb3fSGreg Roach     * Find the tree with a specific ID.
375a25f0a04SGreg Roach     *
376cbc1590aSGreg Roach     * @param int $tree_id
377cbc1590aSGreg Roach     *
378cbc1590aSGreg Roach     * @throws \DomainException
379a25f0a04SGreg Roach     * @return Tree
380a25f0a04SGreg Roach     */
381771ae10aSGreg Roach    public static function findById($tree_id): Tree
382c1010edaSGreg Roach    {
38351d0f842SGreg Roach        foreach (self::getAll() as $tree) {
38472cf66d4SGreg Roach            if ($tree->id == $tree_id) {
38551d0f842SGreg Roach                return $tree;
38651d0f842SGreg Roach            }
38751d0f842SGreg Roach        }
38859f2f229SGreg Roach        throw new \DomainException();
389a25f0a04SGreg Roach    }
390a25f0a04SGreg Roach
391a25f0a04SGreg Roach    /**
392d2cdeb3fSGreg Roach     * Find the tree with a specific name.
393cf4bcc09SGreg Roach     *
394cf4bcc09SGreg Roach     * @param string $tree_name
395cf4bcc09SGreg Roach     *
396cf4bcc09SGreg Roach     * @return Tree|null
397cf4bcc09SGreg Roach     */
398c1010edaSGreg Roach    public static function findByName($tree_name)
399c1010edaSGreg Roach    {
400cf4bcc09SGreg Roach        foreach (self::getAll() as $tree) {
40151d0f842SGreg Roach            if ($tree->name === $tree_name) {
402cf4bcc09SGreg Roach                return $tree;
403cf4bcc09SGreg Roach            }
404cf4bcc09SGreg Roach        }
405cf4bcc09SGreg Roach
406cf4bcc09SGreg Roach        return null;
407cf4bcc09SGreg Roach    }
408cf4bcc09SGreg Roach
409cf4bcc09SGreg Roach    /**
410a25f0a04SGreg Roach     * Create arguments to select_edit_control()
411a25f0a04SGreg Roach     * Note - these will be escaped later
412a25f0a04SGreg Roach     *
413a25f0a04SGreg Roach     * @return string[]
414a25f0a04SGreg Roach     */
415771ae10aSGreg Roach    public static function getIdList(): array
416c1010edaSGreg Roach    {
41713abd6f3SGreg Roach        $list = [];
418a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
41972cf66d4SGreg Roach            $list[$tree->id] = $tree->title;
420a25f0a04SGreg Roach        }
421a25f0a04SGreg Roach
422a25f0a04SGreg Roach        return $list;
423a25f0a04SGreg Roach    }
424a25f0a04SGreg Roach
425a25f0a04SGreg Roach    /**
426a25f0a04SGreg Roach     * Create arguments to select_edit_control()
427a25f0a04SGreg Roach     * Note - these will be escaped later
428a25f0a04SGreg Roach     *
429a25f0a04SGreg Roach     * @return string[]
430a25f0a04SGreg Roach     */
431771ae10aSGreg Roach    public static function getNameList(): array
432c1010edaSGreg Roach    {
43313abd6f3SGreg Roach        $list = [];
434a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
435a25f0a04SGreg Roach            $list[$tree->name] = $tree->title;
436a25f0a04SGreg Roach        }
437a25f0a04SGreg Roach
438a25f0a04SGreg Roach        return $list;
439a25f0a04SGreg Roach    }
440a25f0a04SGreg Roach
441a25f0a04SGreg Roach    /**
442a25f0a04SGreg Roach     * Create a new tree
443a25f0a04SGreg Roach     *
444a25f0a04SGreg Roach     * @param string $tree_name
445a25f0a04SGreg Roach     * @param string $tree_title
446a25f0a04SGreg Roach     *
447a25f0a04SGreg Roach     * @return Tree
448a25f0a04SGreg Roach     */
449771ae10aSGreg Roach    public static function create(string $tree_name, string $tree_title): Tree
450c1010edaSGreg Roach    {
451a25f0a04SGreg Roach        try {
452a25f0a04SGreg Roach            // Create a new tree
45301461f86SGreg Roach            DB::table('gedcom')->insert([
45401461f86SGreg Roach                'gedcom_name' => $tree_name,
45501461f86SGreg Roach            ]);
4564a86d714SGreg Roach
457061b43d7SGreg Roach            $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
458*32f20c14SGreg Roach
459*32f20c14SGreg Roach            $tree = new self($tree_id, $tree_name, $tree_title);
460a25f0a04SGreg Roach        } catch (PDOException $ex) {
461a25f0a04SGreg Roach            // A tree with that name already exists?
462ef2fd529SGreg Roach            return self::findByName($tree_name);
463a25f0a04SGreg Roach        }
464a25f0a04SGreg Roach
465a25f0a04SGreg Roach        // Update the list of trees - to include this new one
466*32f20c14SGreg Roach        self::$trees[$tree_name] = $tree;
467a25f0a04SGreg Roach
468a25f0a04SGreg Roach        $tree->setPreference('imported', '0');
469a25f0a04SGreg Roach        $tree->setPreference('title', $tree_title);
470a25f0a04SGreg Roach
471a25f0a04SGreg Roach        // Module privacy
472a25f0a04SGreg Roach        Module::setDefaultAccess($tree_id);
473a25f0a04SGreg Roach
4741507cbcaSGreg Roach        // Set preferences from default tree
475061b43d7SGreg Roach        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
476061b43d7SGreg Roach            ['gedcom_id', 'setting_name', 'setting_value'],
477061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
478061b43d7SGreg Roach                $query
479061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'setting_name', 'setting_value'])
480061b43d7SGreg Roach                    ->from('gedcom_setting')
481061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
482061b43d7SGreg Roach            }
483061b43d7SGreg Roach        );
4841507cbcaSGreg Roach
485061b43d7SGreg Roach        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
486061b43d7SGreg Roach            ['gedcom_id', 'tag_type', 'resn'],
487061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
488061b43d7SGreg Roach                $query
489061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'tag_type', 'resn'])
490061b43d7SGreg Roach                    ->from('default_resn')
491061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
492061b43d7SGreg Roach            }
493061b43d7SGreg Roach        );
4941507cbcaSGreg Roach
495061b43d7SGreg Roach        (new Builder(DB::connection()))->from('block')->insertUsing(
496061b43d7SGreg Roach            ['gedcom_id', 'location', 'block_order', 'module_name'],
497061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
498061b43d7SGreg Roach                $query
499061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'location', 'block_order', 'module_name'])
500061b43d7SGreg Roach                    ->from('block')
501061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
502061b43d7SGreg Roach            }
503061b43d7SGreg Roach        );
5041507cbcaSGreg Roach
505a25f0a04SGreg Roach        // Gedcom and privacy settings
50676f666f4SGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
50776f666f4SGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
508a25f0a04SGreg Roach        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
509a25f0a04SGreg Roach        switch (WT_LOCALE) {
510a25f0a04SGreg Roach            case 'es':
511a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'spanish');
512a25f0a04SGreg Roach                break;
513a25f0a04SGreg Roach            case 'is':
514a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
515a25f0a04SGreg Roach                break;
516a25f0a04SGreg Roach            case 'lt':
517a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
518a25f0a04SGreg Roach                break;
519a25f0a04SGreg Roach            case 'pl':
520a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'polish');
521a25f0a04SGreg Roach                break;
522a25f0a04SGreg Roach            case 'pt':
523a25f0a04SGreg Roach            case 'pt-BR':
524a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
525a25f0a04SGreg Roach                break;
526a25f0a04SGreg Roach            default:
527a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'paternal');
528a25f0a04SGreg Roach                break;
529a25f0a04SGreg Roach        }
530a25f0a04SGreg Roach
531a25f0a04SGreg Roach        // Genealogy data
532a25f0a04SGreg Roach        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
533bbb76c12SGreg Roach        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
534bbb76c12SGreg Roach        $john_doe = I18N::translate('John /DOE/');
53577e70a22SGreg Roach        $note     = I18N::translate('Edit this individual and replace their details with your own.');
536061b43d7SGreg Roach        $gedcom   = "0 HEAD\n1 CHAR UTF-8\n0 @X1@ INDI\n1 NAME {$john_doe}\n1 SEX M\n1 BIRT\n2 DATE 01 JAN 1850\n2 NOTE {$note}\n0 TRLR\n";
537061b43d7SGreg Roach
538061b43d7SGreg Roach        DB::table('gedcom_chunk')->insert([
539061b43d7SGreg Roach            'gedcom_id'  => $tree_id,
540061b43d7SGreg Roach            'chunk_data' => $gedcom,
54113abd6f3SGreg Roach        ]);
542a25f0a04SGreg Roach
543a25f0a04SGreg Roach        // Update our cache
54472cf66d4SGreg Roach        self::$trees[$tree->id] = $tree;
545a25f0a04SGreg Roach
546a25f0a04SGreg Roach        return $tree;
547a25f0a04SGreg Roach    }
548a25f0a04SGreg Roach
549a25f0a04SGreg Roach    /**
550b78374c5SGreg Roach     * Are there any pending edits for this tree, than need reviewing by a moderator.
551b78374c5SGreg Roach     *
552b78374c5SGreg Roach     * @return bool
553b78374c5SGreg Roach     */
554771ae10aSGreg Roach    public function hasPendingEdit(): bool
555c1010edaSGreg Roach    {
556b78374c5SGreg Roach        return (bool) Database::prepare(
557b78374c5SGreg Roach            "SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
55813abd6f3SGreg Roach        )->execute([
55972cf66d4SGreg Roach            'tree_id' => $this->id,
56013abd6f3SGreg Roach        ])->fetchOne();
561b78374c5SGreg Roach    }
562b78374c5SGreg Roach
563b78374c5SGreg Roach    /**
564a25f0a04SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
565a25f0a04SGreg Roach     * new data. Optionally retain the media data, for when the user has been
566a25f0a04SGreg Roach     * editing their data offline using an application which deletes (or does not
567a25f0a04SGreg Roach     * support) media data.
568a25f0a04SGreg Roach     *
569a25f0a04SGreg Roach     * @param bool $keep_media
570b7e60af1SGreg Roach     *
571b7e60af1SGreg Roach     * @return void
572a25f0a04SGreg Roach     */
573b7e60af1SGreg Roach    public function deleteGenealogyData(bool $keep_media)
574c1010edaSGreg Roach    {
57572cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute([$this->id]);
57672cf66d4SGreg Roach        Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute([$this->id]);
57772cf66d4SGreg Roach        Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute([$this->id]);
57872cf66d4SGreg Roach        Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute([$this->id]);
57972cf66d4SGreg Roach        Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute([$this->id]);
58072cf66d4SGreg Roach        Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute([$this->id]);
58172cf66d4SGreg Roach        Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute([$this->id]);
58272cf66d4SGreg Roach        Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute([$this->id]);
58372cf66d4SGreg Roach        Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute([$this->id]);
58472cf66d4SGreg Roach        Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute([$this->id]);
585a25f0a04SGreg Roach
586a25f0a04SGreg Roach        if ($keep_media) {
58772cf66d4SGreg Roach            Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute([$this->id]);
588a25f0a04SGreg Roach        } else {
58972cf66d4SGreg Roach            Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute([$this->id]);
59072cf66d4SGreg Roach            Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute([$this->id]);
59172cf66d4SGreg Roach            Database::prepare("DELETE FROM `##media_file` WHERE m_file =?")->execute([$this->id]);
592a25f0a04SGreg Roach        }
593a25f0a04SGreg Roach    }
594a25f0a04SGreg Roach
595a25f0a04SGreg Roach    /**
596a25f0a04SGreg Roach     * Delete everything relating to a tree
597b7e60af1SGreg Roach     *
598b7e60af1SGreg Roach     * @return void
599a25f0a04SGreg Roach     */
600c1010edaSGreg Roach    public function delete()
601c1010edaSGreg Roach    {
602a25f0a04SGreg Roach        // If this is the default tree, then unset it
603ef2fd529SGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
604a25f0a04SGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
605a25f0a04SGreg Roach        }
606a25f0a04SGreg Roach
607a25f0a04SGreg Roach        $this->deleteGenealogyData(false);
608a25f0a04SGreg Roach
60972cf66d4SGreg Roach        Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute([$this->id]);
61072cf66d4SGreg Roach        Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute([$this->id]);
61172cf66d4SGreg Roach        Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute([$this->id]);
61272cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute([$this->id]);
61372cf66d4SGreg Roach        Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute([$this->id]);
61472cf66d4SGreg Roach        Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute([$this->id]);
61572cf66d4SGreg Roach        Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute([$this->id]);
61672cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute([$this->id]);
61772cf66d4SGreg Roach        Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute([$this->id]);
61872cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute([$this->id]);
619a25f0a04SGreg Roach
620a25f0a04SGreg Roach        // After updating the database, we need to fetch a new (sorted) copy
62175a9f908SGreg Roach        self::$trees = [];
622a25f0a04SGreg Roach    }
623a25f0a04SGreg Roach
624a25f0a04SGreg Roach    /**
625a25f0a04SGreg Roach     * Export the tree to a GEDCOM file
626a25f0a04SGreg Roach     *
6275792757eSGreg Roach     * @param resource $stream
628b7e60af1SGreg Roach     *
629b7e60af1SGreg Roach     * @return void
630a25f0a04SGreg Roach     */
631c1010edaSGreg Roach    public function exportGedcom($stream)
632c1010edaSGreg Roach    {
6335792757eSGreg Roach        $stmt = Database::prepare(
634e56ef01aSGreg Roach            "SELECT i_gedcom AS gedcom, i_id AS xref, 1 AS n FROM `##individuals` WHERE i_file = :tree_id_1" .
6355792757eSGreg Roach            " UNION ALL " .
636e56ef01aSGreg Roach            "SELECT f_gedcom AS gedcom, f_id AS xref, 2 AS n FROM `##families`    WHERE f_file = :tree_id_2" .
6375792757eSGreg Roach            " UNION ALL " .
638e56ef01aSGreg Roach            "SELECT s_gedcom AS gedcom, s_id AS xref, 3 AS n FROM `##sources`     WHERE s_file = :tree_id_3" .
6395792757eSGreg Roach            " UNION ALL " .
640e56ef01aSGreg 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')" .
6415792757eSGreg Roach            " UNION ALL " .
642e56ef01aSGreg Roach            "SELECT m_gedcom AS gedcom, m_id AS xref, 5 AS n FROM `##media`       WHERE m_file = :tree_id_5" .
643e56ef01aSGreg Roach            " ORDER BY n, LENGTH(xref), xref"
64413abd6f3SGreg Roach        )->execute([
64572cf66d4SGreg Roach            'tree_id_1' => $this->id,
64672cf66d4SGreg Roach            'tree_id_2' => $this->id,
64772cf66d4SGreg Roach            'tree_id_3' => $this->id,
64872cf66d4SGreg Roach            'tree_id_4' => $this->id,
64972cf66d4SGreg Roach            'tree_id_5' => $this->id,
65013abd6f3SGreg Roach        ]);
651a25f0a04SGreg Roach
652a3d8780cSGreg Roach        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this, 'UTF-8'));
653a214e186SGreg Roach        while (($row = $stmt->fetch()) !== false) {
6543d7a8a4cSGreg Roach            $buffer .= FunctionsExport::reformatRecord($row->gedcom);
655a25f0a04SGreg Roach            if (strlen($buffer) > 65535) {
6565792757eSGreg Roach                fwrite($stream, $buffer);
657a25f0a04SGreg Roach                $buffer = '';
658a25f0a04SGreg Roach            }
659a25f0a04SGreg Roach        }
6600f471f91SGreg Roach        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
661195d09d8SGreg Roach        $stmt->closeCursor();
662a25f0a04SGreg Roach    }
663a25f0a04SGreg Roach
664a25f0a04SGreg Roach    /**
665a25f0a04SGreg Roach     * Import data from a gedcom file into this tree.
666a25f0a04SGreg Roach     *
667a25f0a04SGreg Roach     * @param string $path     The full path to the (possibly temporary) file.
668a25f0a04SGreg Roach     * @param string $filename The preferred filename, for export/download.
669a25f0a04SGreg Roach     *
670b7e60af1SGreg Roach     * @return void
671b7e60af1SGreg Roach     * @throws Exception
672a25f0a04SGreg Roach     */
673771ae10aSGreg Roach    public function importGedcomFile(string $path, string $filename)
674c1010edaSGreg Roach    {
675a25f0a04SGreg Roach        // Read the file in blocks of roughly 64K. Ensure that each block
676a25f0a04SGreg Roach        // contains complete gedcom records. This will ensure we don’t split
677a25f0a04SGreg Roach        // multi-byte characters, as well as simplifying the code to import
678a25f0a04SGreg Roach        // each block.
679a25f0a04SGreg Roach
680a25f0a04SGreg Roach        $file_data = '';
681a25f0a04SGreg Roach        $fp        = fopen($path, 'rb');
682a25f0a04SGreg Roach
6832e897bf2SGreg Roach        if ($fp === false) {
6842e897bf2SGreg Roach            throw new Exception('Cannot write file: ' . $path);
6852e897bf2SGreg Roach        }
686a25f0a04SGreg Roach
687b7e60af1SGreg Roach        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
688a25f0a04SGreg Roach        $this->setPreference('gedcom_filename', $filename);
689a25f0a04SGreg Roach        $this->setPreference('imported', '0');
690a25f0a04SGreg Roach
691a25f0a04SGreg Roach        while (!feof($fp)) {
692a25f0a04SGreg Roach            $file_data .= fread($fp, 65536);
693a25f0a04SGreg Roach            // There is no strrpos() function that searches for substrings :-(
694a25f0a04SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
695a25f0a04SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
696a25f0a04SGreg Roach                    // We’ve found the last record boundary in this chunk of data
697a25f0a04SGreg Roach                    break;
698a25f0a04SGreg Roach                }
699a25f0a04SGreg Roach            }
700a25f0a04SGreg Roach            if ($pos) {
701a25f0a04SGreg Roach                Database::prepare(
702a25f0a04SGreg Roach                    "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
703c1010edaSGreg Roach                )->execute([
70472cf66d4SGreg Roach                    $this->id,
705c1010edaSGreg Roach                    substr($file_data, 0, $pos),
706c1010edaSGreg Roach                ]);
707a25f0a04SGreg Roach                $file_data = substr($file_data, $pos);
708a25f0a04SGreg Roach            }
709a25f0a04SGreg Roach        }
710a25f0a04SGreg Roach        Database::prepare(
711a25f0a04SGreg Roach            "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
712c1010edaSGreg Roach        )->execute([
71372cf66d4SGreg Roach            $this->id,
714c1010edaSGreg Roach            $file_data,
715c1010edaSGreg Roach        ]);
716a25f0a04SGreg Roach
717a25f0a04SGreg Roach        fclose($fp);
718a25f0a04SGreg Roach    }
719304f20d5SGreg Roach
720304f20d5SGreg Roach    /**
721b90d8accSGreg Roach     * Generate a new XREF, unique across all family trees
722b90d8accSGreg Roach     *
723b90d8accSGreg Roach     * @return string
724b90d8accSGreg Roach     */
725771ae10aSGreg Roach    public function getNewXref(): string
726c1010edaSGreg Roach    {
727a214e186SGreg Roach        $prefix = 'X';
728b90d8accSGreg Roach
729971d66c8SGreg Roach        $increment = 1.0;
730b90d8accSGreg Roach        do {
731b90d8accSGreg Roach            // Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See
732b90d8accSGreg Roach            // http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
733b90d8accSGreg Roach            $statement = Database::prepare(
734a214e186SGreg Roach                "UPDATE `##site_setting` SET setting_value = LAST_INSERT_ID(setting_value + :increment) WHERE setting_name = 'next_xref'"
735b90d8accSGreg Roach            );
73613abd6f3SGreg Roach            $statement->execute([
737971d66c8SGreg Roach                'increment' => (int) $increment,
73813abd6f3SGreg Roach            ]);
739b90d8accSGreg Roach
740b90d8accSGreg Roach            if ($statement->rowCount() === 0) {
741769d7d6eSGreg Roach                $num = '1';
742bbd8bd1bSGreg Roach                Site::setPreference('next_xref', $num);
743b90d8accSGreg Roach            } else {
744bbd8bd1bSGreg Roach                $num = (string) Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
745b90d8accSGreg Roach            }
746b90d8accSGreg Roach
747a214e186SGreg Roach            $xref = $prefix . $num;
748a214e186SGreg Roach
749b90d8accSGreg Roach            // Records may already exist with this sequence number.
750b90d8accSGreg Roach            $already_used = Database::prepare(
751a214e186SGreg Roach                "SELECT" .
752a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##individuals` WHERE i_id = :i_id) OR" .
753a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##families` WHERE f_id = :f_id) OR" .
754a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##sources` WHERE s_id = :s_id) OR" .
755a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##media` WHERE m_id = :m_id) OR" .
756a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##other` WHERE o_id = :o_id) OR" .
757a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##change` WHERE xref = :xref)"
75813abd6f3SGreg Roach            )->execute([
759a214e186SGreg Roach                'i_id' => $xref,
760a214e186SGreg Roach                'f_id' => $xref,
761a214e186SGreg Roach                's_id' => $xref,
762a214e186SGreg Roach                'm_id' => $xref,
763a214e186SGreg Roach                'o_id' => $xref,
764a214e186SGreg Roach                'xref' => $xref,
76513abd6f3SGreg Roach            ])->fetchOne();
766971d66c8SGreg Roach
767971d66c8SGreg Roach            // This exponential increment allows us to scan over large blocks of
768971d66c8SGreg Roach            // existing data in a reasonable time.
769971d66c8SGreg Roach            $increment *= 1.01;
770a214e186SGreg Roach        } while ($already_used !== '0');
771b90d8accSGreg Roach
772a214e186SGreg Roach        return $xref;
773b90d8accSGreg Roach    }
774b90d8accSGreg Roach
775b90d8accSGreg Roach    /**
776304f20d5SGreg Roach     * Create a new record from GEDCOM data.
777304f20d5SGreg Roach     *
778304f20d5SGreg Roach     * @param string $gedcom
779304f20d5SGreg Roach     *
78015d603e7SGreg Roach     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
781afb591d7SGreg Roach     * @throws InvalidArgumentException
782304f20d5SGreg Roach     */
783771ae10aSGreg Roach    public function createRecord(string $gedcom): GedcomRecord
784c1010edaSGreg Roach    {
785afb591d7SGreg Roach        if (substr_compare($gedcom, '0 @@', 0, 4) !== 0) {
786afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createRecord(' . $gedcom . ') does not begin 0 @@');
787304f20d5SGreg Roach        }
788304f20d5SGreg Roach
789a214e186SGreg Roach        $xref   = $this->getNewXref();
790afb591d7SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
791304f20d5SGreg Roach
792afb591d7SGreg Roach        // Create a change record
793304f20d5SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
794304f20d5SGreg Roach
795304f20d5SGreg Roach        // Create a pending change
796304f20d5SGreg Roach        Database::prepare(
797304f20d5SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
79813abd6f3SGreg Roach        )->execute([
79972cf66d4SGreg Roach            $this->id,
800304f20d5SGreg Roach            $xref,
801304f20d5SGreg Roach            $gedcom,
802cbc1590aSGreg Roach            Auth::id(),
80313abd6f3SGreg Roach        ]);
804304f20d5SGreg Roach
805afb591d7SGreg Roach        // Accept this pending change
806afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
807afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
808afb591d7SGreg Roach
809afb591d7SGreg Roach            return new GedcomRecord($xref, $gedcom, null, $this);
810afb591d7SGreg Roach        }
811afb591d7SGreg Roach
812313e72b3SGreg Roach        return GedcomRecord::getInstance($xref, $this, $gedcom);
813afb591d7SGreg Roach    }
814afb591d7SGreg Roach
815afb591d7SGreg Roach    /**
816afb591d7SGreg Roach     * Create a new family from GEDCOM data.
817afb591d7SGreg Roach     *
818afb591d7SGreg Roach     * @param string $gedcom
819afb591d7SGreg Roach     *
820afb591d7SGreg Roach     * @return Family
821afb591d7SGreg Roach     * @throws InvalidArgumentException
822afb591d7SGreg Roach     */
823afb591d7SGreg Roach    public function createFamily(string $gedcom): GedcomRecord
824afb591d7SGreg Roach    {
825afb591d7SGreg Roach        if (substr_compare($gedcom, '0 @@ FAM', 0, 8) !== 0) {
826afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createFamily(' . $gedcom . ') does not begin 0 @@ FAM');
827afb591d7SGreg Roach        }
828afb591d7SGreg Roach
829afb591d7SGreg Roach        $xref   = $this->getNewXref();
830afb591d7SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
831afb591d7SGreg Roach
832afb591d7SGreg Roach        // Create a change record
833afb591d7SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
834afb591d7SGreg Roach
835afb591d7SGreg Roach        // Create a pending change
836afb591d7SGreg Roach        Database::prepare(
837afb591d7SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
838afb591d7SGreg Roach        )->execute([
83972cf66d4SGreg Roach            $this->id,
840afb591d7SGreg Roach            $xref,
841afb591d7SGreg Roach            $gedcom,
842afb591d7SGreg Roach            Auth::id(),
843afb591d7SGreg Roach        ]);
844304f20d5SGreg Roach
845304f20d5SGreg Roach        // Accept this pending change
846304f20d5SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
847cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
848afb591d7SGreg Roach
849afb591d7SGreg Roach            return new Family($xref, $gedcom, null, $this);
850304f20d5SGreg Roach        }
851afb591d7SGreg Roach
852afb591d7SGreg Roach        return new Family($xref, '', $gedcom, $this);
853afb591d7SGreg Roach    }
854afb591d7SGreg Roach
855afb591d7SGreg Roach    /**
856afb591d7SGreg Roach     * Create a new individual from GEDCOM data.
857afb591d7SGreg Roach     *
858afb591d7SGreg Roach     * @param string $gedcom
859afb591d7SGreg Roach     *
860afb591d7SGreg Roach     * @return Individual
861afb591d7SGreg Roach     * @throws InvalidArgumentException
862afb591d7SGreg Roach     */
863afb591d7SGreg Roach    public function createIndividual(string $gedcom): GedcomRecord
864afb591d7SGreg Roach    {
865afb591d7SGreg Roach        if (substr_compare($gedcom, '0 @@ INDI', 0, 9) !== 0) {
866afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ INDI');
867afb591d7SGreg Roach        }
868afb591d7SGreg Roach
869afb591d7SGreg Roach        $xref   = $this->getNewXref();
870afb591d7SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
871afb591d7SGreg Roach
872afb591d7SGreg Roach        // Create a change record
873afb591d7SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
874afb591d7SGreg Roach
875afb591d7SGreg Roach        // Create a pending change
876afb591d7SGreg Roach        Database::prepare(
877afb591d7SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
878afb591d7SGreg Roach        )->execute([
87972cf66d4SGreg Roach            $this->id,
880afb591d7SGreg Roach            $xref,
881afb591d7SGreg Roach            $gedcom,
882afb591d7SGreg Roach            Auth::id(),
883afb591d7SGreg Roach        ]);
884afb591d7SGreg Roach
885afb591d7SGreg Roach        // Accept this pending change
886afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
887afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
888afb591d7SGreg Roach
889afb591d7SGreg Roach            return new Individual($xref, $gedcom, null, $this);
890afb591d7SGreg Roach        }
891afb591d7SGreg Roach
892afb591d7SGreg Roach        return new Individual($xref, '', $gedcom, $this);
893304f20d5SGreg Roach    }
8948586983fSGreg Roach
8958586983fSGreg Roach    /**
89620b58d20SGreg Roach     * Create a new media object from GEDCOM data.
89720b58d20SGreg Roach     *
89820b58d20SGreg Roach     * @param string $gedcom
89920b58d20SGreg Roach     *
90020b58d20SGreg Roach     * @return Media
90120b58d20SGreg Roach     * @throws InvalidArgumentException
90220b58d20SGreg Roach     */
90320b58d20SGreg Roach    public function createMediaObject(string $gedcom): Media
90420b58d20SGreg Roach    {
90520b58d20SGreg Roach        if (substr_compare($gedcom, '0 @@ OBJE', 0, 9) !== 0) {
90620b58d20SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ OBJE');
90720b58d20SGreg Roach        }
90820b58d20SGreg Roach
90920b58d20SGreg Roach        $xref   = $this->getNewXref();
91020b58d20SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
91120b58d20SGreg Roach
91220b58d20SGreg Roach        // Create a change record
91320b58d20SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
91420b58d20SGreg Roach
91520b58d20SGreg Roach        // Create a pending change
91620b58d20SGreg Roach        Database::prepare(
91720b58d20SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
91820b58d20SGreg Roach        )->execute([
91920b58d20SGreg Roach            $this->id,
92020b58d20SGreg Roach            $xref,
92120b58d20SGreg Roach            $gedcom,
92220b58d20SGreg Roach            Auth::id(),
92320b58d20SGreg Roach        ]);
92420b58d20SGreg Roach
92520b58d20SGreg Roach        // Accept this pending change
92620b58d20SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
92720b58d20SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
92820b58d20SGreg Roach
92920b58d20SGreg Roach            return new Media($xref, $gedcom, null, $this);
93020b58d20SGreg Roach        }
93120b58d20SGreg Roach
93220b58d20SGreg Roach        return new Media($xref, '', $gedcom, $this);
93320b58d20SGreg Roach    }
93420b58d20SGreg Roach
93520b58d20SGreg Roach    /**
9368586983fSGreg Roach     * What is the most significant individual in this tree.
9378586983fSGreg Roach     *
9388586983fSGreg Roach     * @param User $user
9398586983fSGreg Roach     *
9408586983fSGreg Roach     * @return Individual
9418586983fSGreg Roach     */
942c1010edaSGreg Roach    public function significantIndividual(User $user): Individual
943c1010edaSGreg Roach    {
9448586983fSGreg Roach        static $individual; // Only query the DB once.
9458586983fSGreg Roach
9467015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'rootid') !== '') {
9478586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
9488586983fSGreg Roach        }
9497015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'gedcomid') !== '') {
9508586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
9518586983fSGreg Roach        }
9528586983fSGreg Roach        if (!$individual) {
9538586983fSGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
9548586983fSGreg Roach        }
9558586983fSGreg Roach        if (!$individual) {
956769d7d6eSGreg Roach            $xref = (string) Database::prepare(
9575fe1add5SGreg Roach                "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
9585fe1add5SGreg Roach            )->execute([
95972cf66d4SGreg Roach                'tree_id' => $this->id(),
960769d7d6eSGreg Roach            ])->fetchOne();
961769d7d6eSGreg Roach
962769d7d6eSGreg Roach            $individual = Individual::getInstance($xref, $this);
9635fe1add5SGreg Roach        }
9645fe1add5SGreg Roach        if (!$individual) {
9655fe1add5SGreg Roach            // always return a record
9665fe1add5SGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
9675fe1add5SGreg Roach        }
9685fe1add5SGreg Roach
9695fe1add5SGreg Roach        return $individual;
9705fe1add5SGreg Roach    }
9715fe1add5SGreg Roach
9725fe1add5SGreg Roach    /**
9735fe1add5SGreg Roach     * Get significant information from this page, to allow other pages such as
9745fe1add5SGreg Roach     * charts and reports to initialise with the same records
9755fe1add5SGreg Roach     *
9765fe1add5SGreg Roach     * @return Individual
9775fe1add5SGreg Roach     */
978771ae10aSGreg Roach    public function getSignificantIndividual(): Individual
979c1010edaSGreg Roach    {
9805fe1add5SGreg Roach        static $individual; // Only query the DB once.
9815fe1add5SGreg Roach
9827015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'rootid') !== '') {
9835fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'rootid'), $this);
9845fe1add5SGreg Roach        }
9857015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'gedcomid') !== '') {
9865fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'gedcomid'), $this);
9875fe1add5SGreg Roach        }
9885fe1add5SGreg Roach        if (!$individual) {
9895fe1add5SGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
9905fe1add5SGreg Roach        }
9915fe1add5SGreg Roach        if (!$individual) {
992769d7d6eSGreg Roach            $xref = (string) Database::prepare(
993769d7d6eSGreg Roach                "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
994769d7d6eSGreg Roach            )->execute([
99572cf66d4SGreg Roach                'tree_id' => $this->id(),
996769d7d6eSGreg Roach            ])->fetchOne();
997769d7d6eSGreg Roach
998769d7d6eSGreg Roach            $individual = Individual::getInstance($xref, $this);
9998586983fSGreg Roach        }
10008586983fSGreg Roach        if (!$individual) {
10018586983fSGreg Roach            // always return a record
10028586983fSGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
10038586983fSGreg Roach        }
10048586983fSGreg Roach
10058586983fSGreg Roach        return $individual;
10068586983fSGreg Roach    }
1007a25f0a04SGreg Roach}
1008