xref: /webtrees/app/Tree.php (revision 061b43d78e753dc0c2b6d7c1767d279b5f5aeee9)
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. */
5475a9f908SGreg Roach    private 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
62*061b43d7SGreg Roach    private const RESN_PRIVACY = [
63*061b43d7SGreg Roach        'none'         => Auth::PRIV_PRIVATE,
64*061b43d7SGreg Roach        'privacy'      => Auth::PRIV_USER,
65*061b43d7SGreg Roach        'confidential' => Auth::PRIV_NONE,
66*061b43d7SGreg Roach        'hidden'       => Auth::PRIV_HIDE,
67*061b43d7SGreg Roach    ];
68*061b43d7SGreg 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
87*061b43d7SGreg Roach        $rows = DB::table('default_resn')
88*061b43d7SGreg Roach            ->where('gedcom_id', '=', $this->id)
89*061b43d7SGreg Roach            ->get();
90518bbdc1SGreg Roach
91518bbdc1SGreg Roach        foreach ($rows as $row) {
92*061b43d7SGreg Roach            // Convert GEDCOM privacy restriction to a webtrees access level.
93*061b43d7SGreg Roach            $row->resn = self::RESN_PRIVACY[$row->resn];
94*061b43d7SGreg 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)) {
178*061b43d7SGreg Roach            $this->preferences = DB::table('gedcom_setting')
179*061b43d7SGreg Roach                ->where('gedcom_id', '=', $this->id)
180*061b43d7SGreg Roach                ->pluck('setting_value', 'setting_name')
181*061b43d7SGreg 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)) {
198*061b43d7SGreg Roach            DB::table('gedcom_setting')->updateOrInsert([
199*061b43d7SGreg Roach                'gedcom_id' =>$this->id,
200a25f0a04SGreg Roach                'setting_name' => $setting_name,
201*061b43d7SGreg 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)) {
227*061b43d7SGreg Roach            $this->user_preferences[$user->getUserId()] = DB::table('user_gedcom_setting')
228*061b43d7SGreg Roach                ->where('user_id', '=', $user->getUserId())
229*061b43d7SGreg Roach                ->where('gedcom_id', '=', $this->id)
230*061b43d7SGreg Roach                ->pluck('setting_value', 'setting_name')
231*061b43d7SGreg 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
250*061b43d7SGreg Roach            DB::table('user_gedcom_setting')->updateOrInsert([
251*061b43d7SGreg Roach                'gedcom_id' => $this->id(),
252a25f0a04SGreg Roach                'user_id' =>$user->getUserId(),
253a25f0a04SGreg Roach                'setting_name' => $setting_name,
254*061b43d7SGreg Roach            ], [
255cbc1590aSGreg Roach                'setting_value' => $setting_value,
25613abd6f3SGreg Roach            ]);
257*061b43d7SGreg Roach
258*061b43d7SGreg 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)) {
287*061b43d7SGreg 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();
309*061b43d7SGreg 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*061b43d7SGreg Roach            if (false && !Auth::isAdmin()) {
32701461f86SGreg Roach                $query
32801461f86SGreg Roach                    ->join('gedcom_setting AS gs2','gs2.gedcom_id', '=', 'gedcom.gedcom_id')
32901461f86SGreg Roach                    ->where('gs2.setting_name', '=', 'imported');
33001461f86SGreg Roach
33101461f86SGreg Roach                // Some trees are private
33201461f86SGreg Roach                $query
33301461f86SGreg Roach                    ->leftJoin('gedcom_setting AS gs3', function (JoinClause $join): void {
33401461f86SGreg Roach                        $join->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
33501461f86SGreg Roach                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
33601461f86SGreg Roach                    })
33701461f86SGreg Roach                    ->leftJoin('user_gedcom_setting', function (JoinClause $join): void {
33801461f86SGreg Roach                        $join->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
33901461f86SGreg Roach                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
34001461f86SGreg Roach                            ->where('user_gedcom_setting.setting_name', '=', 'canedit');
34101461f86SGreg Roach                    })
34201461f86SGreg Roach                    ->where(function (Builder $query): void {
34301461f86SGreg Roach                        $query
34401461f86SGreg Roach                            // Managers
34501461f86SGreg Roach                            ->where('user_gedcom_setting.setting_value', '=', 'admin')
34601461f86SGreg Roach                            // Members
34701461f86SGreg Roach                            ->orWhere(function (Builder $query): void {
34801461f86SGreg Roach                                $query
34901461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
35001461f86SGreg Roach                                    ->where('gs3.setting_value', '=', '1')
35101461f86SGreg Roach                                    ->where('user_gedcom_setting.setting_value', '<>', 'none');
35201461f86SGreg Roach                            })
35301461f86SGreg Roach                            // Visitors
35401461f86SGreg Roach                            ->orWhere(function (Builder $query): void {
35501461f86SGreg Roach                                $query
35601461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
35701461f86SGreg Roach                                    ->where(DB::raw("COALESCE(gs3.setting_value ,'0')"), '=', 0);
35801461f86SGreg Roach                            });
35901461f86SGreg Roach                    });
36001461f86SGreg Roach            }
36101461f86SGreg Roach
36201461f86SGreg Roach            $rows = $query->get();
36301461f86SGreg Roach
364a25f0a04SGreg Roach            foreach ($rows as $row) {
3653f7ece23SGreg Roach                self::$trees[$row->tree_name] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
366a25f0a04SGreg Roach            }
367a25f0a04SGreg Roach        }
368a25f0a04SGreg Roach
369a25f0a04SGreg Roach        return self::$trees;
370a25f0a04SGreg Roach    }
371a25f0a04SGreg Roach
372a25f0a04SGreg Roach    /**
373d2cdeb3fSGreg Roach     * Find the tree with a specific ID.
374a25f0a04SGreg Roach     *
375cbc1590aSGreg Roach     * @param int $tree_id
376cbc1590aSGreg Roach     *
377cbc1590aSGreg Roach     * @throws \DomainException
378a25f0a04SGreg Roach     * @return Tree
379a25f0a04SGreg Roach     */
380771ae10aSGreg Roach    public static function findById($tree_id): Tree
381c1010edaSGreg Roach    {
38251d0f842SGreg Roach        foreach (self::getAll() as $tree) {
38372cf66d4SGreg Roach            if ($tree->id == $tree_id) {
38451d0f842SGreg Roach                return $tree;
38551d0f842SGreg Roach            }
38651d0f842SGreg Roach        }
38759f2f229SGreg Roach        throw new \DomainException();
388a25f0a04SGreg Roach    }
389a25f0a04SGreg Roach
390a25f0a04SGreg Roach    /**
391d2cdeb3fSGreg Roach     * Find the tree with a specific name.
392cf4bcc09SGreg Roach     *
393cf4bcc09SGreg Roach     * @param string $tree_name
394cf4bcc09SGreg Roach     *
395cf4bcc09SGreg Roach     * @return Tree|null
396cf4bcc09SGreg Roach     */
397c1010edaSGreg Roach    public static function findByName($tree_name)
398c1010edaSGreg Roach    {
399cf4bcc09SGreg Roach        foreach (self::getAll() as $tree) {
40051d0f842SGreg Roach            if ($tree->name === $tree_name) {
401cf4bcc09SGreg Roach                return $tree;
402cf4bcc09SGreg Roach            }
403cf4bcc09SGreg Roach        }
404cf4bcc09SGreg Roach
405cf4bcc09SGreg Roach        return null;
406cf4bcc09SGreg Roach    }
407cf4bcc09SGreg Roach
408cf4bcc09SGreg Roach    /**
409a25f0a04SGreg Roach     * Create arguments to select_edit_control()
410a25f0a04SGreg Roach     * Note - these will be escaped later
411a25f0a04SGreg Roach     *
412a25f0a04SGreg Roach     * @return string[]
413a25f0a04SGreg Roach     */
414771ae10aSGreg Roach    public static function getIdList(): array
415c1010edaSGreg Roach    {
41613abd6f3SGreg Roach        $list = [];
417a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
41872cf66d4SGreg Roach            $list[$tree->id] = $tree->title;
419a25f0a04SGreg Roach        }
420a25f0a04SGreg Roach
421a25f0a04SGreg Roach        return $list;
422a25f0a04SGreg Roach    }
423a25f0a04SGreg Roach
424a25f0a04SGreg Roach    /**
425a25f0a04SGreg Roach     * Create arguments to select_edit_control()
426a25f0a04SGreg Roach     * Note - these will be escaped later
427a25f0a04SGreg Roach     *
428a25f0a04SGreg Roach     * @return string[]
429a25f0a04SGreg Roach     */
430771ae10aSGreg Roach    public static function getNameList(): array
431c1010edaSGreg Roach    {
43213abd6f3SGreg Roach        $list = [];
433a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
434a25f0a04SGreg Roach            $list[$tree->name] = $tree->title;
435a25f0a04SGreg Roach        }
436a25f0a04SGreg Roach
437a25f0a04SGreg Roach        return $list;
438a25f0a04SGreg Roach    }
439a25f0a04SGreg Roach
440a25f0a04SGreg Roach    /**
441a25f0a04SGreg Roach     * Create a new tree
442a25f0a04SGreg Roach     *
443a25f0a04SGreg Roach     * @param string $tree_name
444a25f0a04SGreg Roach     * @param string $tree_title
445a25f0a04SGreg Roach     *
446a25f0a04SGreg Roach     * @return Tree
447a25f0a04SGreg Roach     */
448771ae10aSGreg Roach    public static function create(string $tree_name, string $tree_title): Tree
449c1010edaSGreg Roach    {
450a25f0a04SGreg Roach        try {
451a25f0a04SGreg Roach            // Create a new tree
45201461f86SGreg Roach            DB::table('gedcom')->insert([
45301461f86SGreg Roach                'gedcom_name' => $tree_name,
45401461f86SGreg Roach            ]);
4554a86d714SGreg Roach
456*061b43d7SGreg Roach            $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
457a25f0a04SGreg Roach        } catch (PDOException $ex) {
458a25f0a04SGreg Roach            // A tree with that name already exists?
459ef2fd529SGreg Roach            return self::findByName($tree_name);
460a25f0a04SGreg Roach        }
461a25f0a04SGreg Roach
462a25f0a04SGreg Roach        // Update the list of trees - to include this new one
46375a9f908SGreg Roach        self::$trees = [];
464d2cdeb3fSGreg Roach        $tree        = self::findById($tree_id);
465a25f0a04SGreg Roach
466a25f0a04SGreg Roach        $tree->setPreference('imported', '0');
467a25f0a04SGreg Roach        $tree->setPreference('title', $tree_title);
468a25f0a04SGreg Roach
469a25f0a04SGreg Roach        // Module privacy
470a25f0a04SGreg Roach        Module::setDefaultAccess($tree_id);
471a25f0a04SGreg Roach
4721507cbcaSGreg Roach        // Set preferences from default tree
473*061b43d7SGreg Roach        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
474*061b43d7SGreg Roach            ['gedcom_id', 'setting_name', 'setting_value'],
475*061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
476*061b43d7SGreg Roach                $query
477*061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'setting_name', 'setting_value'])
478*061b43d7SGreg Roach                    ->from('gedcom_setting')
479*061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
480*061b43d7SGreg Roach            }
481*061b43d7SGreg Roach        );
4821507cbcaSGreg Roach
483*061b43d7SGreg Roach        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
484*061b43d7SGreg Roach            ['gedcom_id', 'tag_type', 'resn'],
485*061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
486*061b43d7SGreg Roach                $query
487*061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'tag_type', 'resn'])
488*061b43d7SGreg Roach                    ->from('default_resn')
489*061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
490*061b43d7SGreg Roach            }
491*061b43d7SGreg Roach        );
4921507cbcaSGreg Roach
493*061b43d7SGreg Roach        (new Builder(DB::connection()))->from('block')->insertUsing(
494*061b43d7SGreg Roach            ['gedcom_id', 'location', 'block_order', 'module_name'],
495*061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
496*061b43d7SGreg Roach                $query
497*061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'location', 'block_order', 'module_name'])
498*061b43d7SGreg Roach                    ->from('block')
499*061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
500*061b43d7SGreg Roach            }
501*061b43d7SGreg Roach        );
5021507cbcaSGreg Roach
503a25f0a04SGreg Roach        // Gedcom and privacy settings
50476f666f4SGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
50576f666f4SGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
506a25f0a04SGreg Roach        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
507a25f0a04SGreg Roach        switch (WT_LOCALE) {
508a25f0a04SGreg Roach            case 'es':
509a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'spanish');
510a25f0a04SGreg Roach                break;
511a25f0a04SGreg Roach            case 'is':
512a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
513a25f0a04SGreg Roach                break;
514a25f0a04SGreg Roach            case 'lt':
515a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
516a25f0a04SGreg Roach                break;
517a25f0a04SGreg Roach            case 'pl':
518a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'polish');
519a25f0a04SGreg Roach                break;
520a25f0a04SGreg Roach            case 'pt':
521a25f0a04SGreg Roach            case 'pt-BR':
522a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
523a25f0a04SGreg Roach                break;
524a25f0a04SGreg Roach            default:
525a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'paternal');
526a25f0a04SGreg Roach                break;
527a25f0a04SGreg Roach        }
528a25f0a04SGreg Roach
529a25f0a04SGreg Roach        // Genealogy data
530a25f0a04SGreg Roach        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
531bbb76c12SGreg Roach        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
532bbb76c12SGreg Roach        $john_doe = I18N::translate('John /DOE/');
53377e70a22SGreg Roach        $note     = I18N::translate('Edit this individual and replace their details with your own.');
534*061b43d7SGreg 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";
535*061b43d7SGreg Roach
536*061b43d7SGreg Roach        DB::table('gedcom_chunk')->insert([
537*061b43d7SGreg Roach            'gedcom_id'  => $tree_id,
538*061b43d7SGreg Roach            'chunk_data' => $gedcom,
53913abd6f3SGreg Roach        ]);
540a25f0a04SGreg Roach
541a25f0a04SGreg Roach        // Update our cache
54272cf66d4SGreg Roach        self::$trees[$tree->id] = $tree;
543a25f0a04SGreg Roach
544a25f0a04SGreg Roach        return $tree;
545a25f0a04SGreg Roach    }
546a25f0a04SGreg Roach
547a25f0a04SGreg Roach    /**
548b78374c5SGreg Roach     * Are there any pending edits for this tree, than need reviewing by a moderator.
549b78374c5SGreg Roach     *
550b78374c5SGreg Roach     * @return bool
551b78374c5SGreg Roach     */
552771ae10aSGreg Roach    public function hasPendingEdit(): bool
553c1010edaSGreg Roach    {
554b78374c5SGreg Roach        return (bool) Database::prepare(
555b78374c5SGreg Roach            "SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
55613abd6f3SGreg Roach        )->execute([
55772cf66d4SGreg Roach            'tree_id' => $this->id,
55813abd6f3SGreg Roach        ])->fetchOne();
559b78374c5SGreg Roach    }
560b78374c5SGreg Roach
561b78374c5SGreg Roach    /**
562a25f0a04SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
563a25f0a04SGreg Roach     * new data. Optionally retain the media data, for when the user has been
564a25f0a04SGreg Roach     * editing their data offline using an application which deletes (or does not
565a25f0a04SGreg Roach     * support) media data.
566a25f0a04SGreg Roach     *
567a25f0a04SGreg Roach     * @param bool $keep_media
568b7e60af1SGreg Roach     *
569b7e60af1SGreg Roach     * @return void
570a25f0a04SGreg Roach     */
571b7e60af1SGreg Roach    public function deleteGenealogyData(bool $keep_media)
572c1010edaSGreg Roach    {
57372cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute([$this->id]);
57472cf66d4SGreg Roach        Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute([$this->id]);
57572cf66d4SGreg Roach        Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute([$this->id]);
57672cf66d4SGreg Roach        Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute([$this->id]);
57772cf66d4SGreg Roach        Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute([$this->id]);
57872cf66d4SGreg Roach        Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute([$this->id]);
57972cf66d4SGreg Roach        Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute([$this->id]);
58072cf66d4SGreg Roach        Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute([$this->id]);
58172cf66d4SGreg Roach        Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute([$this->id]);
58272cf66d4SGreg Roach        Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute([$this->id]);
583a25f0a04SGreg Roach
584a25f0a04SGreg Roach        if ($keep_media) {
58572cf66d4SGreg Roach            Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute([$this->id]);
586a25f0a04SGreg Roach        } else {
58772cf66d4SGreg Roach            Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute([$this->id]);
58872cf66d4SGreg Roach            Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute([$this->id]);
58972cf66d4SGreg Roach            Database::prepare("DELETE FROM `##media_file` WHERE m_file =?")->execute([$this->id]);
590a25f0a04SGreg Roach        }
591a25f0a04SGreg Roach    }
592a25f0a04SGreg Roach
593a25f0a04SGreg Roach    /**
594a25f0a04SGreg Roach     * Delete everything relating to a tree
595b7e60af1SGreg Roach     *
596b7e60af1SGreg Roach     * @return void
597a25f0a04SGreg Roach     */
598c1010edaSGreg Roach    public function delete()
599c1010edaSGreg Roach    {
600a25f0a04SGreg Roach        // If this is the default tree, then unset it
601ef2fd529SGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
602a25f0a04SGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
603a25f0a04SGreg Roach        }
604a25f0a04SGreg Roach
605a25f0a04SGreg Roach        $this->deleteGenealogyData(false);
606a25f0a04SGreg Roach
60772cf66d4SGreg Roach        Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute([$this->id]);
60872cf66d4SGreg Roach        Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute([$this->id]);
60972cf66d4SGreg Roach        Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute([$this->id]);
61072cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute([$this->id]);
61172cf66d4SGreg Roach        Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute([$this->id]);
61272cf66d4SGreg Roach        Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute([$this->id]);
61372cf66d4SGreg Roach        Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute([$this->id]);
61472cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute([$this->id]);
61572cf66d4SGreg Roach        Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute([$this->id]);
61672cf66d4SGreg Roach        Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute([$this->id]);
617a25f0a04SGreg Roach
618a25f0a04SGreg Roach        // After updating the database, we need to fetch a new (sorted) copy
61975a9f908SGreg Roach        self::$trees = [];
620a25f0a04SGreg Roach    }
621a25f0a04SGreg Roach
622a25f0a04SGreg Roach    /**
623a25f0a04SGreg Roach     * Export the tree to a GEDCOM file
624a25f0a04SGreg Roach     *
6255792757eSGreg Roach     * @param resource $stream
626b7e60af1SGreg Roach     *
627b7e60af1SGreg Roach     * @return void
628a25f0a04SGreg Roach     */
629c1010edaSGreg Roach    public function exportGedcom($stream)
630c1010edaSGreg Roach    {
6315792757eSGreg Roach        $stmt = Database::prepare(
632e56ef01aSGreg Roach            "SELECT i_gedcom AS gedcom, i_id AS xref, 1 AS n FROM `##individuals` WHERE i_file = :tree_id_1" .
6335792757eSGreg Roach            " UNION ALL " .
634e56ef01aSGreg Roach            "SELECT f_gedcom AS gedcom, f_id AS xref, 2 AS n FROM `##families`    WHERE f_file = :tree_id_2" .
6355792757eSGreg Roach            " UNION ALL " .
636e56ef01aSGreg Roach            "SELECT s_gedcom AS gedcom, s_id AS xref, 3 AS n FROM `##sources`     WHERE s_file = :tree_id_3" .
6375792757eSGreg Roach            " UNION ALL " .
638e56ef01aSGreg 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')" .
6395792757eSGreg Roach            " UNION ALL " .
640e56ef01aSGreg Roach            "SELECT m_gedcom AS gedcom, m_id AS xref, 5 AS n FROM `##media`       WHERE m_file = :tree_id_5" .
641e56ef01aSGreg Roach            " ORDER BY n, LENGTH(xref), xref"
64213abd6f3SGreg Roach        )->execute([
64372cf66d4SGreg Roach            'tree_id_1' => $this->id,
64472cf66d4SGreg Roach            'tree_id_2' => $this->id,
64572cf66d4SGreg Roach            'tree_id_3' => $this->id,
64672cf66d4SGreg Roach            'tree_id_4' => $this->id,
64772cf66d4SGreg Roach            'tree_id_5' => $this->id,
64813abd6f3SGreg Roach        ]);
649a25f0a04SGreg Roach
650a3d8780cSGreg Roach        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this, 'UTF-8'));
651a214e186SGreg Roach        while (($row = $stmt->fetch()) !== false) {
6523d7a8a4cSGreg Roach            $buffer .= FunctionsExport::reformatRecord($row->gedcom);
653a25f0a04SGreg Roach            if (strlen($buffer) > 65535) {
6545792757eSGreg Roach                fwrite($stream, $buffer);
655a25f0a04SGreg Roach                $buffer = '';
656a25f0a04SGreg Roach            }
657a25f0a04SGreg Roach        }
6580f471f91SGreg Roach        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
659195d09d8SGreg Roach        $stmt->closeCursor();
660a25f0a04SGreg Roach    }
661a25f0a04SGreg Roach
662a25f0a04SGreg Roach    /**
663a25f0a04SGreg Roach     * Import data from a gedcom file into this tree.
664a25f0a04SGreg Roach     *
665a25f0a04SGreg Roach     * @param string $path     The full path to the (possibly temporary) file.
666a25f0a04SGreg Roach     * @param string $filename The preferred filename, for export/download.
667a25f0a04SGreg Roach     *
668b7e60af1SGreg Roach     * @return void
669b7e60af1SGreg Roach     * @throws Exception
670a25f0a04SGreg Roach     */
671771ae10aSGreg Roach    public function importGedcomFile(string $path, string $filename)
672c1010edaSGreg Roach    {
673a25f0a04SGreg Roach        // Read the file in blocks of roughly 64K. Ensure that each block
674a25f0a04SGreg Roach        // contains complete gedcom records. This will ensure we don’t split
675a25f0a04SGreg Roach        // multi-byte characters, as well as simplifying the code to import
676a25f0a04SGreg Roach        // each block.
677a25f0a04SGreg Roach
678a25f0a04SGreg Roach        $file_data = '';
679a25f0a04SGreg Roach        $fp        = fopen($path, 'rb');
680a25f0a04SGreg Roach
6812e897bf2SGreg Roach        if ($fp === false) {
6822e897bf2SGreg Roach            throw new Exception('Cannot write file: ' . $path);
6832e897bf2SGreg Roach        }
684a25f0a04SGreg Roach
685b7e60af1SGreg Roach        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
686a25f0a04SGreg Roach        $this->setPreference('gedcom_filename', $filename);
687a25f0a04SGreg Roach        $this->setPreference('imported', '0');
688a25f0a04SGreg Roach
689a25f0a04SGreg Roach        while (!feof($fp)) {
690a25f0a04SGreg Roach            $file_data .= fread($fp, 65536);
691a25f0a04SGreg Roach            // There is no strrpos() function that searches for substrings :-(
692a25f0a04SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
693a25f0a04SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
694a25f0a04SGreg Roach                    // We’ve found the last record boundary in this chunk of data
695a25f0a04SGreg Roach                    break;
696a25f0a04SGreg Roach                }
697a25f0a04SGreg Roach            }
698a25f0a04SGreg Roach            if ($pos) {
699a25f0a04SGreg Roach                Database::prepare(
700a25f0a04SGreg Roach                    "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
701c1010edaSGreg Roach                )->execute([
70272cf66d4SGreg Roach                    $this->id,
703c1010edaSGreg Roach                    substr($file_data, 0, $pos),
704c1010edaSGreg Roach                ]);
705a25f0a04SGreg Roach                $file_data = substr($file_data, $pos);
706a25f0a04SGreg Roach            }
707a25f0a04SGreg Roach        }
708a25f0a04SGreg Roach        Database::prepare(
709a25f0a04SGreg Roach            "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
710c1010edaSGreg Roach        )->execute([
71172cf66d4SGreg Roach            $this->id,
712c1010edaSGreg Roach            $file_data,
713c1010edaSGreg Roach        ]);
714a25f0a04SGreg Roach
715a25f0a04SGreg Roach        fclose($fp);
716a25f0a04SGreg Roach    }
717304f20d5SGreg Roach
718304f20d5SGreg Roach    /**
719b90d8accSGreg Roach     * Generate a new XREF, unique across all family trees
720b90d8accSGreg Roach     *
721b90d8accSGreg Roach     * @return string
722b90d8accSGreg Roach     */
723771ae10aSGreg Roach    public function getNewXref(): string
724c1010edaSGreg Roach    {
725a214e186SGreg Roach        $prefix = 'X';
726b90d8accSGreg Roach
727971d66c8SGreg Roach        $increment = 1.0;
728b90d8accSGreg Roach        do {
729b90d8accSGreg Roach            // Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See
730b90d8accSGreg Roach            // http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
731b90d8accSGreg Roach            $statement = Database::prepare(
732a214e186SGreg Roach                "UPDATE `##site_setting` SET setting_value = LAST_INSERT_ID(setting_value + :increment) WHERE setting_name = 'next_xref'"
733b90d8accSGreg Roach            );
73413abd6f3SGreg Roach            $statement->execute([
735971d66c8SGreg Roach                'increment' => (int) $increment,
73613abd6f3SGreg Roach            ]);
737b90d8accSGreg Roach
738b90d8accSGreg Roach            if ($statement->rowCount() === 0) {
739769d7d6eSGreg Roach                $num = '1';
740bbd8bd1bSGreg Roach                Site::setPreference('next_xref', $num);
741b90d8accSGreg Roach            } else {
742bbd8bd1bSGreg Roach                $num = (string) Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
743b90d8accSGreg Roach            }
744b90d8accSGreg Roach
745a214e186SGreg Roach            $xref = $prefix . $num;
746a214e186SGreg Roach
747b90d8accSGreg Roach            // Records may already exist with this sequence number.
748b90d8accSGreg Roach            $already_used = Database::prepare(
749a214e186SGreg Roach                "SELECT" .
750a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##individuals` WHERE i_id = :i_id) OR" .
751a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##families` WHERE f_id = :f_id) OR" .
752a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##sources` WHERE s_id = :s_id) OR" .
753a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##media` WHERE m_id = :m_id) OR" .
754a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##other` WHERE o_id = :o_id) OR" .
755a214e186SGreg Roach                " EXISTS (SELECT 1 FROM `##change` WHERE xref = :xref)"
75613abd6f3SGreg Roach            )->execute([
757a214e186SGreg Roach                'i_id' => $xref,
758a214e186SGreg Roach                'f_id' => $xref,
759a214e186SGreg Roach                's_id' => $xref,
760a214e186SGreg Roach                'm_id' => $xref,
761a214e186SGreg Roach                'o_id' => $xref,
762a214e186SGreg Roach                'xref' => $xref,
76313abd6f3SGreg Roach            ])->fetchOne();
764971d66c8SGreg Roach
765971d66c8SGreg Roach            // This exponential increment allows us to scan over large blocks of
766971d66c8SGreg Roach            // existing data in a reasonable time.
767971d66c8SGreg Roach            $increment *= 1.01;
768a214e186SGreg Roach        } while ($already_used !== '0');
769b90d8accSGreg Roach
770a214e186SGreg Roach        return $xref;
771b90d8accSGreg Roach    }
772b90d8accSGreg Roach
773b90d8accSGreg Roach    /**
774304f20d5SGreg Roach     * Create a new record from GEDCOM data.
775304f20d5SGreg Roach     *
776304f20d5SGreg Roach     * @param string $gedcom
777304f20d5SGreg Roach     *
77815d603e7SGreg Roach     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
779afb591d7SGreg Roach     * @throws InvalidArgumentException
780304f20d5SGreg Roach     */
781771ae10aSGreg Roach    public function createRecord(string $gedcom): GedcomRecord
782c1010edaSGreg Roach    {
783afb591d7SGreg Roach        if (substr_compare($gedcom, '0 @@', 0, 4) !== 0) {
784afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createRecord(' . $gedcom . ') does not begin 0 @@');
785304f20d5SGreg Roach        }
786304f20d5SGreg Roach
787a214e186SGreg Roach        $xref   = $this->getNewXref();
788afb591d7SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
789304f20d5SGreg Roach
790afb591d7SGreg Roach        // Create a change record
791304f20d5SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
792304f20d5SGreg Roach
793304f20d5SGreg Roach        // Create a pending change
794304f20d5SGreg Roach        Database::prepare(
795304f20d5SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
79613abd6f3SGreg Roach        )->execute([
79772cf66d4SGreg Roach            $this->id,
798304f20d5SGreg Roach            $xref,
799304f20d5SGreg Roach            $gedcom,
800cbc1590aSGreg Roach            Auth::id(),
80113abd6f3SGreg Roach        ]);
802304f20d5SGreg Roach
803afb591d7SGreg Roach        // Accept this pending change
804afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
805afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
806afb591d7SGreg Roach
807afb591d7SGreg Roach            return new GedcomRecord($xref, $gedcom, null, $this);
808afb591d7SGreg Roach        }
809afb591d7SGreg Roach
810313e72b3SGreg Roach        return GedcomRecord::getInstance($xref, $this, $gedcom);
811afb591d7SGreg Roach    }
812afb591d7SGreg Roach
813afb591d7SGreg Roach    /**
814afb591d7SGreg Roach     * Create a new family from GEDCOM data.
815afb591d7SGreg Roach     *
816afb591d7SGreg Roach     * @param string $gedcom
817afb591d7SGreg Roach     *
818afb591d7SGreg Roach     * @return Family
819afb591d7SGreg Roach     * @throws InvalidArgumentException
820afb591d7SGreg Roach     */
821afb591d7SGreg Roach    public function createFamily(string $gedcom): GedcomRecord
822afb591d7SGreg Roach    {
823afb591d7SGreg Roach        if (substr_compare($gedcom, '0 @@ FAM', 0, 8) !== 0) {
824afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createFamily(' . $gedcom . ') does not begin 0 @@ FAM');
825afb591d7SGreg Roach        }
826afb591d7SGreg Roach
827afb591d7SGreg Roach        $xref   = $this->getNewXref();
828afb591d7SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
829afb591d7SGreg Roach
830afb591d7SGreg Roach        // Create a change record
831afb591d7SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
832afb591d7SGreg Roach
833afb591d7SGreg Roach        // Create a pending change
834afb591d7SGreg Roach        Database::prepare(
835afb591d7SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
836afb591d7SGreg Roach        )->execute([
83772cf66d4SGreg Roach            $this->id,
838afb591d7SGreg Roach            $xref,
839afb591d7SGreg Roach            $gedcom,
840afb591d7SGreg Roach            Auth::id(),
841afb591d7SGreg Roach        ]);
842304f20d5SGreg Roach
843304f20d5SGreg Roach        // Accept this pending change
844304f20d5SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
845cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
846afb591d7SGreg Roach
847afb591d7SGreg Roach            return new Family($xref, $gedcom, null, $this);
848304f20d5SGreg Roach        }
849afb591d7SGreg Roach
850afb591d7SGreg Roach        return new Family($xref, '', $gedcom, $this);
851afb591d7SGreg Roach    }
852afb591d7SGreg Roach
853afb591d7SGreg Roach    /**
854afb591d7SGreg Roach     * Create a new individual from GEDCOM data.
855afb591d7SGreg Roach     *
856afb591d7SGreg Roach     * @param string $gedcom
857afb591d7SGreg Roach     *
858afb591d7SGreg Roach     * @return Individual
859afb591d7SGreg Roach     * @throws InvalidArgumentException
860afb591d7SGreg Roach     */
861afb591d7SGreg Roach    public function createIndividual(string $gedcom): GedcomRecord
862afb591d7SGreg Roach    {
863afb591d7SGreg Roach        if (substr_compare($gedcom, '0 @@ INDI', 0, 9) !== 0) {
864afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ INDI');
865afb591d7SGreg Roach        }
866afb591d7SGreg Roach
867afb591d7SGreg Roach        $xref   = $this->getNewXref();
868afb591d7SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
869afb591d7SGreg Roach
870afb591d7SGreg Roach        // Create a change record
871afb591d7SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
872afb591d7SGreg Roach
873afb591d7SGreg Roach        // Create a pending change
874afb591d7SGreg Roach        Database::prepare(
875afb591d7SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
876afb591d7SGreg Roach        )->execute([
87772cf66d4SGreg Roach            $this->id,
878afb591d7SGreg Roach            $xref,
879afb591d7SGreg Roach            $gedcom,
880afb591d7SGreg Roach            Auth::id(),
881afb591d7SGreg Roach        ]);
882afb591d7SGreg Roach
883afb591d7SGreg Roach        // Accept this pending change
884afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
885afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
886afb591d7SGreg Roach
887afb591d7SGreg Roach            return new Individual($xref, $gedcom, null, $this);
888afb591d7SGreg Roach        }
889afb591d7SGreg Roach
890afb591d7SGreg Roach        return new Individual($xref, '', $gedcom, $this);
891304f20d5SGreg Roach    }
8928586983fSGreg Roach
8938586983fSGreg Roach    /**
89420b58d20SGreg Roach     * Create a new media object from GEDCOM data.
89520b58d20SGreg Roach     *
89620b58d20SGreg Roach     * @param string $gedcom
89720b58d20SGreg Roach     *
89820b58d20SGreg Roach     * @return Media
89920b58d20SGreg Roach     * @throws InvalidArgumentException
90020b58d20SGreg Roach     */
90120b58d20SGreg Roach    public function createMediaObject(string $gedcom): Media
90220b58d20SGreg Roach    {
90320b58d20SGreg Roach        if (substr_compare($gedcom, '0 @@ OBJE', 0, 9) !== 0) {
90420b58d20SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ OBJE');
90520b58d20SGreg Roach        }
90620b58d20SGreg Roach
90720b58d20SGreg Roach        $xref   = $this->getNewXref();
90820b58d20SGreg Roach        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
90920b58d20SGreg Roach
91020b58d20SGreg Roach        // Create a change record
91120b58d20SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
91220b58d20SGreg Roach
91320b58d20SGreg Roach        // Create a pending change
91420b58d20SGreg Roach        Database::prepare(
91520b58d20SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
91620b58d20SGreg Roach        )->execute([
91720b58d20SGreg Roach            $this->id,
91820b58d20SGreg Roach            $xref,
91920b58d20SGreg Roach            $gedcom,
92020b58d20SGreg Roach            Auth::id(),
92120b58d20SGreg Roach        ]);
92220b58d20SGreg Roach
92320b58d20SGreg Roach        // Accept this pending change
92420b58d20SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
92520b58d20SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
92620b58d20SGreg Roach
92720b58d20SGreg Roach            return new Media($xref, $gedcom, null, $this);
92820b58d20SGreg Roach        }
92920b58d20SGreg Roach
93020b58d20SGreg Roach        return new Media($xref, '', $gedcom, $this);
93120b58d20SGreg Roach    }
93220b58d20SGreg Roach
93320b58d20SGreg Roach    /**
9348586983fSGreg Roach     * What is the most significant individual in this tree.
9358586983fSGreg Roach     *
9368586983fSGreg Roach     * @param User $user
9378586983fSGreg Roach     *
9388586983fSGreg Roach     * @return Individual
9398586983fSGreg Roach     */
940c1010edaSGreg Roach    public function significantIndividual(User $user): Individual
941c1010edaSGreg Roach    {
9428586983fSGreg Roach        static $individual; // Only query the DB once.
9438586983fSGreg Roach
9447015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'rootid') !== '') {
9458586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
9468586983fSGreg Roach        }
9477015ba1fSGreg Roach        if (!$individual && $this->getUserPreference($user, 'gedcomid') !== '') {
9488586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
9498586983fSGreg Roach        }
9508586983fSGreg Roach        if (!$individual) {
9518586983fSGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
9528586983fSGreg Roach        }
9538586983fSGreg Roach        if (!$individual) {
954769d7d6eSGreg Roach            $xref = (string) Database::prepare(
9555fe1add5SGreg Roach                "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
9565fe1add5SGreg Roach            )->execute([
95772cf66d4SGreg Roach                'tree_id' => $this->id(),
958769d7d6eSGreg Roach            ])->fetchOne();
959769d7d6eSGreg Roach
960769d7d6eSGreg Roach            $individual = Individual::getInstance($xref, $this);
9615fe1add5SGreg Roach        }
9625fe1add5SGreg Roach        if (!$individual) {
9635fe1add5SGreg Roach            // always return a record
9645fe1add5SGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
9655fe1add5SGreg Roach        }
9665fe1add5SGreg Roach
9675fe1add5SGreg Roach        return $individual;
9685fe1add5SGreg Roach    }
9695fe1add5SGreg Roach
9705fe1add5SGreg Roach    /**
9715fe1add5SGreg Roach     * Get significant information from this page, to allow other pages such as
9725fe1add5SGreg Roach     * charts and reports to initialise with the same records
9735fe1add5SGreg Roach     *
9745fe1add5SGreg Roach     * @return Individual
9755fe1add5SGreg Roach     */
976771ae10aSGreg Roach    public function getSignificantIndividual(): Individual
977c1010edaSGreg Roach    {
9785fe1add5SGreg Roach        static $individual; // Only query the DB once.
9795fe1add5SGreg Roach
9807015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'rootid') !== '') {
9815fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'rootid'), $this);
9825fe1add5SGreg Roach        }
9837015ba1fSGreg Roach        if (!$individual && $this->getUserPreference(Auth::user(), 'gedcomid') !== '') {
9845fe1add5SGreg Roach            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'gedcomid'), $this);
9855fe1add5SGreg Roach        }
9865fe1add5SGreg Roach        if (!$individual) {
9875fe1add5SGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
9885fe1add5SGreg Roach        }
9895fe1add5SGreg Roach        if (!$individual) {
990769d7d6eSGreg Roach            $xref = (string) Database::prepare(
991769d7d6eSGreg Roach                "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
992769d7d6eSGreg Roach            )->execute([
99372cf66d4SGreg Roach                'tree_id' => $this->id(),
994769d7d6eSGreg Roach            ])->fetchOne();
995769d7d6eSGreg Roach
996769d7d6eSGreg Roach            $individual = Individual::getInstance($xref, $this);
9978586983fSGreg Roach        }
9988586983fSGreg Roach        if (!$individual) {
9998586983fSGreg Roach            // always return a record
10008586983fSGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
10018586983fSGreg Roach        }
10028586983fSGreg Roach
10038586983fSGreg Roach        return $individual;
10048586983fSGreg Roach    }
1005a25f0a04SGreg Roach}
1006