xref: /webtrees/app/Tree.php (revision e364afe4ae4e316fc4ebd53eccbaff2d29e419a5)
1a25f0a04SGreg Roach<?php
2a25f0a04SGreg Roach/**
3a25f0a04SGreg Roach * webtrees: online genealogy
48fcd0d32SGreg Roach * Copyright (C) 2019 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
20e5a6b4d4SGreg Roachuse Fisharebest\Webtrees\Contracts\UserInterface;
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;
2694026f20SGreg Roachuse Illuminate\Support\Collection;
27bec87e94SGreg Roachuse Illuminate\Support\Str;
28afb591d7SGreg Roachuse InvalidArgumentException;
29a25f0a04SGreg Roachuse PDOException;
308b67c11aSGreg Roachuse stdClass;
31a25f0a04SGreg Roach
32a25f0a04SGreg Roach/**
3376692c8bSGreg Roach * Provide an interface to the wt_gedcom table.
34a25f0a04SGreg Roach */
35c1010edaSGreg Roachclass Tree
36c1010edaSGreg Roach{
37cbc1590aSGreg Roach    /** @var int The tree's ID number */
3872cf66d4SGreg Roach    private $id;
39518bbdc1SGreg Roach
40a25f0a04SGreg Roach    /** @var string The tree's name */
41a25f0a04SGreg Roach    private $name;
42518bbdc1SGreg Roach
43a25f0a04SGreg Roach    /** @var string The tree's title */
44a25f0a04SGreg Roach    private $title;
45a25f0a04SGreg Roach
46e2052359SGreg Roach    /** @var int[] Default access rules for facts in this tree */
47518bbdc1SGreg Roach    private $fact_privacy;
48518bbdc1SGreg Roach
49e2052359SGreg Roach    /** @var int[] Default access rules for individuals in this tree */
50518bbdc1SGreg Roach    private $individual_privacy;
51518bbdc1SGreg Roach
52518bbdc1SGreg Roach    /** @var integer[][] Default access rules for individual facts in this tree */
53518bbdc1SGreg Roach    private $individual_fact_privacy;
54518bbdc1SGreg Roach
55c0804649SGreg Roach    /** @var Tree[] All trees that we have permission to see, indexed by ID. */
5632f20c14SGreg Roach    public static $trees = [];
57a25f0a04SGreg Roach
58a25f0a04SGreg Roach    /** @var string[] Cached copy of the wt_gedcom_setting table. */
5915d603e7SGreg Roach    private $preferences = [];
60a25f0a04SGreg Roach
61a25f0a04SGreg Roach    /** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
6213abd6f3SGreg Roach    private $user_preferences = [];
63a25f0a04SGreg Roach
64061b43d7SGreg Roach    private const RESN_PRIVACY = [
65061b43d7SGreg Roach        'none'         => Auth::PRIV_PRIVATE,
66061b43d7SGreg Roach        'privacy'      => Auth::PRIV_USER,
67061b43d7SGreg Roach        'confidential' => Auth::PRIV_NONE,
68061b43d7SGreg Roach        'hidden'       => Auth::PRIV_HIDE,
69061b43d7SGreg Roach    ];
70061b43d7SGreg Roach
71a25f0a04SGreg Roach    /**
72a25f0a04SGreg Roach     * Create a tree object. This is a private constructor - it can only
73a25f0a04SGreg Roach     * be called from Tree::getAll() to ensure proper initialisation.
74a25f0a04SGreg Roach     *
7572cf66d4SGreg Roach     * @param int    $id
76aa6f03bbSGreg Roach     * @param string $name
77cc13d6d8SGreg Roach     * @param string $title
78a25f0a04SGreg Roach     */
79cc13d6d8SGreg Roach    private function __construct($id, $name, $title)
80c1010edaSGreg Roach    {
8172cf66d4SGreg Roach        $this->id                      = $id;
82aa6f03bbSGreg Roach        $this->name                    = $name;
83cc13d6d8SGreg Roach        $this->title                   = $title;
8413abd6f3SGreg Roach        $this->fact_privacy            = [];
8513abd6f3SGreg Roach        $this->individual_privacy      = [];
8613abd6f3SGreg Roach        $this->individual_fact_privacy = [];
87518bbdc1SGreg Roach
88518bbdc1SGreg Roach        // Load the privacy settings for this tree
89061b43d7SGreg Roach        $rows = DB::table('default_resn')
90061b43d7SGreg Roach            ->where('gedcom_id', '=', $this->id)
91061b43d7SGreg Roach            ->get();
92518bbdc1SGreg Roach
93518bbdc1SGreg Roach        foreach ($rows as $row) {
94061b43d7SGreg Roach            // Convert GEDCOM privacy restriction to a webtrees access level.
95061b43d7SGreg Roach            $row->resn = self::RESN_PRIVACY[$row->resn];
96061b43d7SGreg Roach
97518bbdc1SGreg Roach            if ($row->xref !== null) {
98518bbdc1SGreg Roach                if ($row->tag_type !== null) {
99518bbdc1SGreg Roach                    $this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
100518bbdc1SGreg Roach                } else {
101518bbdc1SGreg Roach                    $this->individual_privacy[$row->xref] = (int) $row->resn;
102518bbdc1SGreg Roach                }
103518bbdc1SGreg Roach            } else {
104518bbdc1SGreg Roach                $this->fact_privacy[$row->tag_type] = (int) $row->resn;
105518bbdc1SGreg Roach            }
106518bbdc1SGreg Roach        }
107a25f0a04SGreg Roach    }
108a25f0a04SGreg Roach
109a25f0a04SGreg Roach    /**
110a25f0a04SGreg Roach     * The ID of this tree
111a25f0a04SGreg Roach     *
112cbc1590aSGreg Roach     * @return int
113a25f0a04SGreg Roach     */
11472cf66d4SGreg Roach    public function id(): int
115c1010edaSGreg Roach    {
11672cf66d4SGreg Roach        return $this->id;
117a25f0a04SGreg Roach    }
118a25f0a04SGreg Roach
119a25f0a04SGreg Roach    /**
120a25f0a04SGreg Roach     * The name of this tree
121a25f0a04SGreg Roach     *
122a25f0a04SGreg Roach     * @return string
123a25f0a04SGreg Roach     */
124aa6f03bbSGreg Roach    public function name(): string
125c1010edaSGreg Roach    {
126a25f0a04SGreg Roach        return $this->name;
127a25f0a04SGreg Roach    }
128a25f0a04SGreg Roach
129a25f0a04SGreg Roach    /**
130a25f0a04SGreg Roach     * The title of this tree
131a25f0a04SGreg Roach     *
132a25f0a04SGreg Roach     * @return string
133a25f0a04SGreg Roach     */
134cc13d6d8SGreg Roach    public function title(): string
135c1010edaSGreg Roach    {
136a25f0a04SGreg Roach        return $this->title;
137a25f0a04SGreg Roach    }
138a25f0a04SGreg Roach
139a25f0a04SGreg Roach    /**
140518bbdc1SGreg Roach     * The fact-level privacy for this tree.
141518bbdc1SGreg Roach     *
142e2052359SGreg Roach     * @return int[]
143518bbdc1SGreg Roach     */
1448f53f488SRico Sonntag    public function getFactPrivacy(): array
145c1010edaSGreg Roach    {
146518bbdc1SGreg Roach        return $this->fact_privacy;
147518bbdc1SGreg Roach    }
148518bbdc1SGreg Roach
149518bbdc1SGreg Roach    /**
150518bbdc1SGreg Roach     * The individual-level privacy for this tree.
151518bbdc1SGreg Roach     *
152e2052359SGreg Roach     * @return int[]
153518bbdc1SGreg Roach     */
1548f53f488SRico Sonntag    public function getIndividualPrivacy(): array
155c1010edaSGreg Roach    {
156518bbdc1SGreg Roach        return $this->individual_privacy;
157518bbdc1SGreg Roach    }
158518bbdc1SGreg Roach
159518bbdc1SGreg Roach    /**
160518bbdc1SGreg Roach     * The individual-fact-level privacy for this tree.
161518bbdc1SGreg Roach     *
162adac8af1SGreg Roach     * @return int[][]
163518bbdc1SGreg Roach     */
1648f53f488SRico Sonntag    public function getIndividualFactPrivacy(): array
165c1010edaSGreg Roach    {
166518bbdc1SGreg Roach        return $this->individual_fact_privacy;
167518bbdc1SGreg Roach    }
168518bbdc1SGreg Roach
169518bbdc1SGreg Roach    /**
170a25f0a04SGreg Roach     * Get the tree’s configuration settings.
171a25f0a04SGreg Roach     *
172a25f0a04SGreg Roach     * @param string $setting_name
17315d603e7SGreg Roach     * @param string $default
174a25f0a04SGreg Roach     *
17515d603e7SGreg Roach     * @return string
176a25f0a04SGreg Roach     */
177771ae10aSGreg Roach    public function getPreference(string $setting_name, string $default = ''): string
178c1010edaSGreg Roach    {
17915d603e7SGreg Roach        if (empty($this->preferences)) {
180061b43d7SGreg Roach            $this->preferences = DB::table('gedcom_setting')
181061b43d7SGreg Roach                ->where('gedcom_id', '=', $this->id)
182061b43d7SGreg Roach                ->pluck('setting_value', 'setting_name')
183061b43d7SGreg Roach                ->all();
184a25f0a04SGreg Roach        }
185a25f0a04SGreg Roach
186b2ce94c6SRico Sonntag        return $this->preferences[$setting_name] ?? $default;
187a25f0a04SGreg Roach    }
188a25f0a04SGreg Roach
189a25f0a04SGreg Roach    /**
190a25f0a04SGreg Roach     * Set the tree’s configuration settings.
191a25f0a04SGreg Roach     *
192a25f0a04SGreg Roach     * @param string $setting_name
193a25f0a04SGreg Roach     * @param string $setting_value
194a25f0a04SGreg Roach     *
195a25f0a04SGreg Roach     * @return $this
196a25f0a04SGreg Roach     */
197771ae10aSGreg Roach    public function setPreference(string $setting_name, string $setting_value): Tree
198c1010edaSGreg Roach    {
199a25f0a04SGreg Roach        if ($setting_value !== $this->getPreference($setting_name)) {
200061b43d7SGreg Roach            DB::table('gedcom_setting')->updateOrInsert([
201061b43d7SGreg Roach                'gedcom_id'    => $this->id,
202a25f0a04SGreg Roach                'setting_name' => $setting_name,
203061b43d7SGreg Roach            ], [
204a25f0a04SGreg Roach                'setting_value' => $setting_value,
20513abd6f3SGreg Roach            ]);
20615d603e7SGreg Roach
207a25f0a04SGreg Roach            $this->preferences[$setting_name] = $setting_value;
20815d603e7SGreg Roach
20972292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
210a25f0a04SGreg Roach        }
211a25f0a04SGreg Roach
212a25f0a04SGreg Roach        return $this;
213a25f0a04SGreg Roach    }
214a25f0a04SGreg Roach
215a25f0a04SGreg Roach    /**
216a25f0a04SGreg Roach     * Get the tree’s user-configuration settings.
217a25f0a04SGreg Roach     *
218e5a6b4d4SGreg Roach     * @param UserInterface   $user
219a25f0a04SGreg Roach     * @param string $setting_name
2207015ba1fSGreg Roach     * @param string $default
221a25f0a04SGreg Roach     *
222a25f0a04SGreg Roach     * @return string
223a25f0a04SGreg Roach     */
224e5a6b4d4SGreg Roach    public function getUserPreference(UserInterface $user, string $setting_name, string $default = ''): string
225c1010edaSGreg Roach    {
226a25f0a04SGreg Roach        // There are lots of settings, and we need to fetch lots of them on every page
227a25f0a04SGreg Roach        // so it is quicker to fetch them all in one go.
228895230eeSGreg Roach        if (!array_key_exists($user->id(), $this->user_preferences)) {
229895230eeSGreg Roach            $this->user_preferences[$user->id()] = DB::table('user_gedcom_setting')
230895230eeSGreg Roach                ->where('user_id', '=', $user->id())
231061b43d7SGreg Roach                ->where('gedcom_id', '=', $this->id)
232061b43d7SGreg Roach                ->pluck('setting_value', 'setting_name')
233061b43d7SGreg Roach                ->all();
234a25f0a04SGreg Roach        }
235a25f0a04SGreg Roach
236895230eeSGreg Roach        return $this->user_preferences[$user->id()][$setting_name] ?? $default;
237a25f0a04SGreg Roach    }
238a25f0a04SGreg Roach
239a25f0a04SGreg Roach    /**
240a25f0a04SGreg Roach     * Set the tree’s user-configuration settings.
241a25f0a04SGreg Roach     *
242*e364afe4SGreg Roach     * @param UserInterface $user
243a25f0a04SGreg Roach     * @param string        $setting_name
244a25f0a04SGreg Roach     * @param string        $setting_value
245a25f0a04SGreg Roach     *
246a25f0a04SGreg Roach     * @return $this
247a25f0a04SGreg Roach     */
248*e364afe4SGreg Roach    public function setUserPreference(UserInterface $user, string $setting_name, string $setting_value): Tree
249c1010edaSGreg Roach    {
250a25f0a04SGreg Roach        if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
251a25f0a04SGreg Roach            // Update the database
252061b43d7SGreg Roach            DB::table('user_gedcom_setting')->updateOrInsert([
253061b43d7SGreg Roach                'gedcom_id'    => $this->id(),
254895230eeSGreg Roach                'user_id'      => $user->id(),
255a25f0a04SGreg Roach                'setting_name' => $setting_name,
256061b43d7SGreg Roach            ], [
257cbc1590aSGreg Roach                'setting_value' => $setting_value,
25813abd6f3SGreg Roach            ]);
259061b43d7SGreg Roach
260061b43d7SGreg Roach            // Update the cache
261895230eeSGreg Roach            $this->user_preferences[$user->id()][$setting_name] = $setting_value;
262a25f0a04SGreg Roach            // Audit log of changes
263e5a6b4d4SGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->userName() . '"', $this);
264a25f0a04SGreg Roach        }
265a25f0a04SGreg Roach
266a25f0a04SGreg Roach        return $this;
267a25f0a04SGreg Roach    }
268a25f0a04SGreg Roach
269a25f0a04SGreg Roach    /**
270a25f0a04SGreg Roach     * Can a user accept changes for this tree?
271a25f0a04SGreg Roach     *
272e5a6b4d4SGreg Roach     * @param UserInterface $user
273a25f0a04SGreg Roach     *
274cbc1590aSGreg Roach     * @return bool
275a25f0a04SGreg Roach     */
276e5a6b4d4SGreg Roach    public function canAcceptChanges(UserInterface $user): bool
277c1010edaSGreg Roach    {
278a25f0a04SGreg Roach        return Auth::isModerator($this, $user);
279a25f0a04SGreg Roach    }
280a25f0a04SGreg Roach
281a25f0a04SGreg Roach    /**
2828b67c11aSGreg Roach     * All the trees that we have permission to access.
283a25f0a04SGreg Roach     *
28454c7f8dfSGreg Roach     * @return Collection
28554c7f8dfSGreg Roach     * @return Tree[]
286a25f0a04SGreg Roach     */
2878b67c11aSGreg Roach    public static function all(): Collection
288c1010edaSGreg Roach    {
28925d7fe95SGreg Roach        return app('cache.array')->rememberForever(__CLASS__, function (): Collection {
29001461f86SGreg Roach            // Admins see all trees
29101461f86SGreg Roach            $query = DB::table('gedcom')
29201461f86SGreg Roach                ->leftJoin('gedcom_setting', function (JoinClause $join): void {
29301461f86SGreg Roach                    $join->on('gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
29401461f86SGreg Roach                        ->where('gedcom_setting.setting_name', '=', 'title');
29501461f86SGreg Roach                })
29601461f86SGreg Roach                ->where('gedcom.gedcom_id', '>', 0)
29701461f86SGreg Roach                ->select([
29801461f86SGreg Roach                    'gedcom.gedcom_id AS tree_id',
29901461f86SGreg Roach                    'gedcom.gedcom_name AS tree_name',
30001461f86SGreg Roach                    'gedcom_setting.setting_value AS tree_title',
30101461f86SGreg Roach                ])
30201461f86SGreg Roach                ->orderBy('gedcom.sort_order')
30301461f86SGreg Roach                ->orderBy('gedcom_setting.setting_value');
30401461f86SGreg Roach
30532f20c14SGreg Roach            // Non-admins may not see all trees
30632f20c14SGreg Roach            if (!Auth::isAdmin()) {
30701461f86SGreg Roach                $query
30836357577SGreg Roach                    ->join('gedcom_setting AS gs2', function (JoinClause $join): void {
30936357577SGreg Roach                        $join->on('gs2.gedcom_id', '=', 'gedcom.gedcom_id')
31001461f86SGreg Roach                            ->where('gs2.setting_name', '=', 'imported');
31136357577SGreg Roach                    })
31236357577SGreg Roach                    ->join('gedcom_setting AS gs3', function (JoinClause $join): void {
31301461f86SGreg Roach                        $join->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
31401461f86SGreg Roach                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
31501461f86SGreg Roach                    })
31601461f86SGreg Roach                    ->leftJoin('user_gedcom_setting', function (JoinClause $join): void {
31701461f86SGreg Roach                        $join->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
31801461f86SGreg Roach                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
31901461f86SGreg Roach                            ->where('user_gedcom_setting.setting_name', '=', 'canedit');
32001461f86SGreg Roach                    })
32101461f86SGreg Roach                    ->where(function (Builder $query): void {
32201461f86SGreg Roach                        $query
32301461f86SGreg Roach                            // Managers
32401461f86SGreg Roach                            ->where('user_gedcom_setting.setting_value', '=', 'admin')
32501461f86SGreg Roach                            // Members
32601461f86SGreg Roach                            ->orWhere(function (Builder $query): void {
32701461f86SGreg Roach                                $query
32801461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
32901461f86SGreg Roach                                    ->where('gs3.setting_value', '=', '1')
33001461f86SGreg Roach                                    ->where('user_gedcom_setting.setting_value', '<>', 'none');
33101461f86SGreg Roach                            })
3328b67c11aSGreg Roach                            // Public trees
33301461f86SGreg Roach                            ->orWhere(function (Builder $query): void {
33401461f86SGreg Roach                                $query
33501461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
33636357577SGreg Roach                                    ->where('gs3.setting_value', '<>', '1');
33701461f86SGreg Roach                            });
33801461f86SGreg Roach                    });
33901461f86SGreg Roach            }
34001461f86SGreg Roach
3418b67c11aSGreg Roach            return $query
3428b67c11aSGreg Roach                ->get()
3438b67c11aSGreg Roach                ->mapWithKeys(function (stdClass $row): array {
3448b67c11aSGreg Roach                    return [$row->tree_id => new self((int) $row->tree_id, $row->tree_name, $row->tree_title)];
3458b67c11aSGreg Roach                });
3468b67c11aSGreg Roach        });
347a25f0a04SGreg Roach    }
3488b67c11aSGreg Roach
3498b67c11aSGreg Roach    /**
3508b67c11aSGreg Roach     * Fetch all the trees that we have permission to access.
3518b67c11aSGreg Roach     *
3528b67c11aSGreg Roach     * @return Tree[]
3538b67c11aSGreg Roach     */
3548b67c11aSGreg Roach    public static function getAll(): array
3558b67c11aSGreg Roach    {
3568b67c11aSGreg Roach        if (empty(self::$trees)) {
3578b67c11aSGreg Roach            self::$trees = self::all()->all();
358a25f0a04SGreg Roach        }
359a25f0a04SGreg Roach
360a25f0a04SGreg Roach        return self::$trees;
361a25f0a04SGreg Roach    }
362a25f0a04SGreg Roach
363a25f0a04SGreg Roach    /**
364d2cdeb3fSGreg Roach     * Find the tree with a specific ID.
365a25f0a04SGreg Roach     *
366cbc1590aSGreg Roach     * @param int $tree_id
367cbc1590aSGreg Roach     *
368a25f0a04SGreg Roach     * @return Tree
369a25f0a04SGreg Roach     */
370c0804649SGreg Roach    public static function findById(int $tree_id): Tree
371c1010edaSGreg Roach    {
372c0804649SGreg Roach        return self::getAll()[$tree_id];
373a25f0a04SGreg Roach    }
374a25f0a04SGreg Roach
375a25f0a04SGreg Roach    /**
376d2cdeb3fSGreg Roach     * Find the tree with a specific name.
377cf4bcc09SGreg Roach     *
378cf4bcc09SGreg Roach     * @param string $tree_name
379cf4bcc09SGreg Roach     *
380cf4bcc09SGreg Roach     * @return Tree|null
381cf4bcc09SGreg Roach     */
382*e364afe4SGreg Roach    public static function findByName($tree_name): ?Tree
383c1010edaSGreg Roach    {
384cf4bcc09SGreg Roach        foreach (self::getAll() as $tree) {
38551d0f842SGreg Roach            if ($tree->name === $tree_name) {
386cf4bcc09SGreg Roach                return $tree;
387cf4bcc09SGreg Roach            }
388cf4bcc09SGreg Roach        }
389cf4bcc09SGreg Roach
390cf4bcc09SGreg Roach        return null;
391cf4bcc09SGreg Roach    }
392cf4bcc09SGreg Roach
393cf4bcc09SGreg Roach    /**
394a25f0a04SGreg Roach     * Create arguments to select_edit_control()
395a25f0a04SGreg Roach     * Note - these will be escaped later
396a25f0a04SGreg Roach     *
397a25f0a04SGreg Roach     * @return string[]
398a25f0a04SGreg Roach     */
399771ae10aSGreg Roach    public static function getIdList(): array
400c1010edaSGreg Roach    {
40113abd6f3SGreg Roach        $list = [];
402a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
40372cf66d4SGreg Roach            $list[$tree->id] = $tree->title;
404a25f0a04SGreg Roach        }
405a25f0a04SGreg Roach
406a25f0a04SGreg Roach        return $list;
407a25f0a04SGreg Roach    }
408a25f0a04SGreg Roach
409a25f0a04SGreg 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 getNameList(): array
416c1010edaSGreg Roach    {
41713abd6f3SGreg Roach        $list = [];
418a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
419a25f0a04SGreg Roach            $list[$tree->name] = $tree->title;
420a25f0a04SGreg Roach        }
421a25f0a04SGreg Roach
422a25f0a04SGreg Roach        return $list;
423a25f0a04SGreg Roach    }
424a25f0a04SGreg Roach
425a25f0a04SGreg Roach    /**
426a25f0a04SGreg Roach     * Create a new tree
427a25f0a04SGreg Roach     *
428a25f0a04SGreg Roach     * @param string $tree_name
429a25f0a04SGreg Roach     * @param string $tree_title
430a25f0a04SGreg Roach     *
431a25f0a04SGreg Roach     * @return Tree
432a25f0a04SGreg Roach     */
433771ae10aSGreg Roach    public static function create(string $tree_name, string $tree_title): Tree
434c1010edaSGreg Roach    {
435a25f0a04SGreg Roach        try {
436a25f0a04SGreg Roach            // Create a new tree
43701461f86SGreg Roach            DB::table('gedcom')->insert([
43801461f86SGreg Roach                'gedcom_name' => $tree_name,
43901461f86SGreg Roach            ]);
4404a86d714SGreg Roach
441061b43d7SGreg Roach            $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
44232f20c14SGreg Roach
44332f20c14SGreg Roach            $tree = new self($tree_id, $tree_name, $tree_title);
444a25f0a04SGreg Roach        } catch (PDOException $ex) {
445a25f0a04SGreg Roach            // A tree with that name already exists?
446ef2fd529SGreg Roach            return self::findByName($tree_name);
447a25f0a04SGreg Roach        }
448a25f0a04SGreg Roach
449a25f0a04SGreg Roach        $tree->setPreference('imported', '0');
450a25f0a04SGreg Roach        $tree->setPreference('title', $tree_title);
451a25f0a04SGreg Roach
4521507cbcaSGreg Roach        // Set preferences from default tree
453061b43d7SGreg Roach        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
454061b43d7SGreg Roach            ['gedcom_id', 'setting_name', 'setting_value'],
455061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
456061b43d7SGreg Roach                $query
457061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'setting_name', 'setting_value'])
458061b43d7SGreg Roach                    ->from('gedcom_setting')
459061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
460061b43d7SGreg Roach            }
461061b43d7SGreg Roach        );
4621507cbcaSGreg Roach
463061b43d7SGreg Roach        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
464061b43d7SGreg Roach            ['gedcom_id', 'tag_type', 'resn'],
465061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
466061b43d7SGreg Roach                $query
467061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'tag_type', 'resn'])
468061b43d7SGreg Roach                    ->from('default_resn')
469061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
470061b43d7SGreg Roach            }
471061b43d7SGreg Roach        );
4721507cbcaSGreg Roach
473a25f0a04SGreg Roach        // Gedcom and privacy settings
47476f666f4SGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
47576f666f4SGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
476a25f0a04SGreg Roach        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
477*e364afe4SGreg Roach
478a25f0a04SGreg Roach        switch (WT_LOCALE) {
479a25f0a04SGreg Roach            case 'es':
480a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'spanish');
481a25f0a04SGreg Roach                break;
482a25f0a04SGreg Roach            case 'is':
483a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
484a25f0a04SGreg Roach                break;
485a25f0a04SGreg Roach            case 'lt':
486a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
487a25f0a04SGreg Roach                break;
488a25f0a04SGreg Roach            case 'pl':
489a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'polish');
490a25f0a04SGreg Roach                break;
491a25f0a04SGreg Roach            case 'pt':
492a25f0a04SGreg Roach            case 'pt-BR':
493a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
494a25f0a04SGreg Roach                break;
495a25f0a04SGreg Roach            default:
496a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'paternal');
497a25f0a04SGreg Roach                break;
498a25f0a04SGreg Roach        }
499a25f0a04SGreg Roach
500a25f0a04SGreg Roach        // Genealogy data
501a25f0a04SGreg Roach        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
502bbb76c12SGreg Roach        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
503bbb76c12SGreg Roach        $john_doe = I18N::translate('John /DOE/');
50477e70a22SGreg Roach        $note     = I18N::translate('Edit this individual and replace their details with your own.');
505061b43d7SGreg 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";
506061b43d7SGreg Roach
507061b43d7SGreg Roach        DB::table('gedcom_chunk')->insert([
508061b43d7SGreg Roach            'gedcom_id'  => $tree_id,
509061b43d7SGreg Roach            'chunk_data' => $gedcom,
51013abd6f3SGreg Roach        ]);
511a25f0a04SGreg Roach
512a25f0a04SGreg Roach        // Update our cache
51372cf66d4SGreg Roach        self::$trees[$tree->id] = $tree;
514a25f0a04SGreg Roach
515a25f0a04SGreg Roach        return $tree;
516a25f0a04SGreg Roach    }
517a25f0a04SGreg Roach
518a25f0a04SGreg Roach    /**
519b78374c5SGreg Roach     * Are there any pending edits for this tree, than need reviewing by a moderator.
520b78374c5SGreg Roach     *
521b78374c5SGreg Roach     * @return bool
522b78374c5SGreg Roach     */
523771ae10aSGreg Roach    public function hasPendingEdit(): bool
524c1010edaSGreg Roach    {
52515a3f100SGreg Roach        return DB::table('change')
52615a3f100SGreg Roach            ->where('gedcom_id', '=', $this->id)
52715a3f100SGreg Roach            ->where('status', '=', 'pending')
52815a3f100SGreg Roach            ->exists();
529b78374c5SGreg Roach    }
530b78374c5SGreg Roach
531b78374c5SGreg Roach    /**
532a25f0a04SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
533a25f0a04SGreg Roach     * new data. Optionally retain the media data, for when the user has been
534a25f0a04SGreg Roach     * editing their data offline using an application which deletes (or does not
535a25f0a04SGreg Roach     * support) media data.
536a25f0a04SGreg Roach     *
537a25f0a04SGreg Roach     * @param bool $keep_media
538b7e60af1SGreg Roach     *
539b7e60af1SGreg Roach     * @return void
540a25f0a04SGreg Roach     */
541*e364afe4SGreg Roach    public function deleteGenealogyData(bool $keep_media): void
542c1010edaSGreg Roach    {
5431ad2dde6SGreg Roach        DB::table('gedcom_chunk')->where('gedcom_id', '=', $this->id)->delete();
5441ad2dde6SGreg Roach        DB::table('individuals')->where('i_file', '=', $this->id)->delete();
5451ad2dde6SGreg Roach        DB::table('families')->where('f_file', '=', $this->id)->delete();
5461ad2dde6SGreg Roach        DB::table('sources')->where('s_file', '=', $this->id)->delete();
5471ad2dde6SGreg Roach        DB::table('other')->where('o_file', '=', $this->id)->delete();
5481ad2dde6SGreg Roach        DB::table('places')->where('p_file', '=', $this->id)->delete();
5491ad2dde6SGreg Roach        DB::table('placelinks')->where('pl_file', '=', $this->id)->delete();
5501ad2dde6SGreg Roach        DB::table('name')->where('n_file', '=', $this->id)->delete();
5511ad2dde6SGreg Roach        DB::table('dates')->where('d_file', '=', $this->id)->delete();
5521ad2dde6SGreg Roach        DB::table('change')->where('gedcom_id', '=', $this->id)->delete();
553a25f0a04SGreg Roach
554a25f0a04SGreg Roach        if ($keep_media) {
5551ad2dde6SGreg Roach            DB::table('link')->where('l_file', '=', $this->id)
5561ad2dde6SGreg Roach                ->where('l_type', '<>', 'OBJE')
5571ad2dde6SGreg Roach                ->delete();
558a25f0a04SGreg Roach        } else {
5591ad2dde6SGreg Roach            DB::table('link')->where('l_file', '=', $this->id)->delete();
5601ad2dde6SGreg Roach            DB::table('media_file')->where('m_file', '=', $this->id)->delete();
5611ad2dde6SGreg Roach            DB::table('media')->where('m_file', '=', $this->id)->delete();
562a25f0a04SGreg Roach        }
563a25f0a04SGreg Roach    }
564a25f0a04SGreg Roach
565a25f0a04SGreg Roach    /**
566a25f0a04SGreg Roach     * Delete everything relating to a tree
567b7e60af1SGreg Roach     *
568b7e60af1SGreg Roach     * @return void
569a25f0a04SGreg Roach     */
570*e364afe4SGreg Roach    public function delete(): void
571c1010edaSGreg Roach    {
572a25f0a04SGreg Roach        // If this is the default tree, then unset it
573ef2fd529SGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
574a25f0a04SGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
575a25f0a04SGreg Roach        }
576a25f0a04SGreg Roach
577a25f0a04SGreg Roach        $this->deleteGenealogyData(false);
578a25f0a04SGreg Roach
579a7890280SGreg Roach        DB::table('block_setting')
580a7890280SGreg Roach            ->join('block', 'block.block_id', '=', 'block_setting.block_id')
581a7890280SGreg Roach            ->where('gedcom_id', '=', $this->id)
582a7890280SGreg Roach            ->delete();
583a7890280SGreg Roach        DB::table('block')->where('gedcom_id', '=', $this->id)->delete();
584a7890280SGreg Roach        DB::table('user_gedcom_setting')->where('gedcom_id', '=', $this->id)->delete();
585a7890280SGreg Roach        DB::table('gedcom_setting')->where('gedcom_id', '=', $this->id)->delete();
586a7890280SGreg Roach        DB::table('module_privacy')->where('gedcom_id', '=', $this->id)->delete();
587a7890280SGreg Roach        DB::table('hit_counter')->where('gedcom_id', '=', $this->id)->delete();
588a7890280SGreg Roach        DB::table('default_resn')->where('gedcom_id', '=', $this->id)->delete();
589a7890280SGreg Roach        DB::table('gedcom_chunk')->where('gedcom_id', '=', $this->id)->delete();
590a7890280SGreg Roach        DB::table('log')->where('gedcom_id', '=', $this->id)->delete();
591a7890280SGreg Roach        DB::table('gedcom')->where('gedcom_id', '=', $this->id)->delete();
592a25f0a04SGreg Roach
593a25f0a04SGreg Roach        // After updating the database, we need to fetch a new (sorted) copy
59475a9f908SGreg Roach        self::$trees = [];
595a25f0a04SGreg Roach    }
596a25f0a04SGreg Roach
597a25f0a04SGreg Roach    /**
598a25f0a04SGreg Roach     * Export the tree to a GEDCOM file
599a25f0a04SGreg Roach     *
6005792757eSGreg Roach     * @param resource $stream
601b7e60af1SGreg Roach     *
602b7e60af1SGreg Roach     * @return void
603a25f0a04SGreg Roach     */
604425af8b9SGreg Roach    public function exportGedcom($stream): void
605c1010edaSGreg Roach    {
606a3d8780cSGreg Roach        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this, 'UTF-8'));
60794026f20SGreg Roach
60894026f20SGreg Roach        $union_families = DB::table('families')
60994026f20SGreg Roach            ->where('f_file', '=', $this->id)
61094026f20SGreg Roach            ->select(['f_gedcom AS gedcom', 'f_id AS xref', DB::raw('LENGTH(f_id) AS len'), DB::raw('2 AS n')]);
61194026f20SGreg Roach
61294026f20SGreg Roach        $union_sources = DB::table('sources')
61394026f20SGreg Roach            ->where('s_file', '=', $this->id)
61494026f20SGreg Roach            ->select(['s_gedcom AS gedcom', 's_id AS xref', DB::raw('LENGTH(s_id) AS len'), DB::raw('3 AS n')]);
61594026f20SGreg Roach
61694026f20SGreg Roach        $union_other = DB::table('other')
61794026f20SGreg Roach            ->where('o_file', '=', $this->id)
61894026f20SGreg Roach            ->whereNotIn('o_type', ['HEAD', 'TRLR'])
61994026f20SGreg Roach            ->select(['o_gedcom AS gedcom', 'o_id AS xref', DB::raw('LENGTH(o_id) AS len'), DB::raw('4 AS n')]);
62094026f20SGreg Roach
62194026f20SGreg Roach        $union_media = DB::table('media')
62294026f20SGreg Roach            ->where('m_file', '=', $this->id)
62394026f20SGreg Roach            ->select(['m_gedcom AS gedcom', 'm_id AS xref', DB::raw('LENGTH(m_id) AS len'), DB::raw('5 AS n')]);
62494026f20SGreg Roach
625e5a6b4d4SGreg Roach        DB::table('individuals')
62694026f20SGreg Roach            ->where('i_file', '=', $this->id)
62794026f20SGreg Roach            ->select(['i_gedcom AS gedcom', 'i_id AS xref', DB::raw('LENGTH(i_id) AS len'), DB::raw('1 AS n')])
62894026f20SGreg Roach            ->union($union_families)
62994026f20SGreg Roach            ->union($union_sources)
63094026f20SGreg Roach            ->union($union_other)
63194026f20SGreg Roach            ->union($union_media)
63294026f20SGreg Roach            ->orderBy('n')
63394026f20SGreg Roach            ->orderBy('len')
63494026f20SGreg Roach            ->orderBy('xref')
63594026f20SGreg Roach            ->chunk(100, function (Collection $rows) use ($stream, &$buffer): void {
63694026f20SGreg Roach                foreach ($rows as $row) {
6373d7a8a4cSGreg Roach                    $buffer .= FunctionsExport::reformatRecord($row->gedcom);
638a25f0a04SGreg Roach                    if (strlen($buffer) > 65535) {
6395792757eSGreg Roach                        fwrite($stream, $buffer);
640a25f0a04SGreg Roach                        $buffer = '';
641a25f0a04SGreg Roach                    }
642a25f0a04SGreg Roach                }
64394026f20SGreg Roach            });
64494026f20SGreg Roach
6450f471f91SGreg Roach        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
646a25f0a04SGreg Roach    }
647a25f0a04SGreg Roach
648a25f0a04SGreg Roach    /**
649a25f0a04SGreg Roach     * Import data from a gedcom file into this tree.
650a25f0a04SGreg Roach     *
651a25f0a04SGreg Roach     * @param string $path     The full path to the (possibly temporary) file.
652a25f0a04SGreg Roach     * @param string $filename The preferred filename, for export/download.
653a25f0a04SGreg Roach     *
654b7e60af1SGreg Roach     * @return void
655a25f0a04SGreg Roach     */
656425af8b9SGreg Roach    public function importGedcomFile(string $path, string $filename): void
657c1010edaSGreg Roach    {
658a25f0a04SGreg Roach        // Read the file in blocks of roughly 64K. Ensure that each block
659a25f0a04SGreg Roach        // contains complete gedcom records. This will ensure we don’t split
660a25f0a04SGreg Roach        // multi-byte characters, as well as simplifying the code to import
661a25f0a04SGreg Roach        // each block.
662a25f0a04SGreg Roach
663a25f0a04SGreg Roach        $file_data = '';
664a25f0a04SGreg Roach        $fp        = fopen($path, 'rb');
665a25f0a04SGreg Roach
666b7e60af1SGreg Roach        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
667a25f0a04SGreg Roach        $this->setPreference('gedcom_filename', $filename);
668a25f0a04SGreg Roach        $this->setPreference('imported', '0');
669a25f0a04SGreg Roach
670a25f0a04SGreg Roach        while (!feof($fp)) {
671a25f0a04SGreg Roach            $file_data .= fread($fp, 65536);
672a25f0a04SGreg Roach            // There is no strrpos() function that searches for substrings :-(
673a25f0a04SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
674a25f0a04SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
675a25f0a04SGreg Roach                    // We’ve found the last record boundary in this chunk of data
676a25f0a04SGreg Roach                    break;
677a25f0a04SGreg Roach                }
678a25f0a04SGreg Roach            }
679a25f0a04SGreg Roach            if ($pos) {
6801ad2dde6SGreg Roach                DB::table('gedcom_chunk')->insert([
6811ad2dde6SGreg Roach                    'gedcom_id'  => $this->id,
6821ad2dde6SGreg Roach                    'chunk_data' => substr($file_data, 0, $pos),
683c1010edaSGreg Roach                ]);
6841ad2dde6SGreg Roach
685a25f0a04SGreg Roach                $file_data = substr($file_data, $pos);
686a25f0a04SGreg Roach            }
687a25f0a04SGreg Roach        }
6881ad2dde6SGreg Roach        DB::table('gedcom_chunk')->insert([
6891ad2dde6SGreg Roach            'gedcom_id'  => $this->id,
6901ad2dde6SGreg Roach            'chunk_data' => $file_data,
691c1010edaSGreg Roach        ]);
692a25f0a04SGreg Roach
693a25f0a04SGreg Roach        fclose($fp);
694a25f0a04SGreg Roach    }
695304f20d5SGreg Roach
696304f20d5SGreg Roach    /**
697b90d8accSGreg Roach     * Generate a new XREF, unique across all family trees
698b90d8accSGreg Roach     *
699b90d8accSGreg Roach     * @return string
700b90d8accSGreg Roach     */
701771ae10aSGreg Roach    public function getNewXref(): string
702c1010edaSGreg Roach    {
703963fbaeeSGreg Roach        // Lock the row, so that only one new XREF may be generated at a time.
704963fbaeeSGreg Roach        DB::table('site_setting')
705963fbaeeSGreg Roach            ->where('setting_name', '=', 'next_xref')
706963fbaeeSGreg Roach            ->lockForUpdate()
707963fbaeeSGreg Roach            ->get();
708963fbaeeSGreg Roach
709a214e186SGreg Roach        $prefix = 'X';
710b90d8accSGreg Roach
711971d66c8SGreg Roach        $increment = 1.0;
712b90d8accSGreg Roach        do {
713963fbaeeSGreg Roach            $num = (int) Site::getPreference('next_xref') + (int) $increment;
714971d66c8SGreg Roach
715971d66c8SGreg Roach            // This exponential increment allows us to scan over large blocks of
716971d66c8SGreg Roach            // existing data in a reasonable time.
717971d66c8SGreg Roach            $increment *= 1.01;
718963fbaeeSGreg Roach
719963fbaeeSGreg Roach            $xref = $prefix . $num;
720963fbaeeSGreg Roach
721963fbaeeSGreg Roach            // Records may already exist with this sequence number.
722963fbaeeSGreg Roach            $already_used =
723963fbaeeSGreg Roach                DB::table('individuals')->where('i_id', '=', $xref)->exists() ||
724963fbaeeSGreg Roach                DB::table('families')->where('f_id', '=', $xref)->exists() ||
725963fbaeeSGreg Roach                DB::table('sources')->where('s_id', '=', $xref)->exists() ||
726963fbaeeSGreg Roach                DB::table('media')->where('m_id', '=', $xref)->exists() ||
727963fbaeeSGreg Roach                DB::table('other')->where('o_id', '=', $xref)->exists() ||
728963fbaeeSGreg Roach                DB::table('change')->where('xref', '=', $xref)->exists();
729963fbaeeSGreg Roach        } while ($already_used);
730963fbaeeSGreg Roach
731963fbaeeSGreg Roach        Site::setPreference('next_xref', (string) $num);
732b90d8accSGreg Roach
733a214e186SGreg Roach        return $xref;
734b90d8accSGreg Roach    }
735b90d8accSGreg Roach
736b90d8accSGreg Roach    /**
737304f20d5SGreg Roach     * Create a new record from GEDCOM data.
738304f20d5SGreg Roach     *
739304f20d5SGreg Roach     * @param string $gedcom
740304f20d5SGreg Roach     *
74115d603e7SGreg Roach     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
742afb591d7SGreg Roach     * @throws InvalidArgumentException
743304f20d5SGreg Roach     */
744771ae10aSGreg Roach    public function createRecord(string $gedcom): GedcomRecord
745c1010edaSGreg Roach    {
746bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ ')) {
747afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createRecord(' . $gedcom . ') does not begin 0 @@');
748304f20d5SGreg Roach        }
749304f20d5SGreg Roach
750a214e186SGreg Roach        $xref   = $this->getNewXref();
751bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ ' . Str::after($gedcom, '0 @@ ');
752304f20d5SGreg Roach
753afb591d7SGreg Roach        // Create a change record
754e5a6b4d4SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
755304f20d5SGreg Roach
756304f20d5SGreg Roach        // Create a pending change
757963fbaeeSGreg Roach        DB::table('change')->insert([
758963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
759963fbaeeSGreg Roach            'xref'       => $xref,
760963fbaeeSGreg Roach            'old_gedcom' => '',
761963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
762963fbaeeSGreg Roach            'user_id'    => Auth::id(),
76313abd6f3SGreg Roach        ]);
764304f20d5SGreg Roach
765afb591d7SGreg Roach        // Accept this pending change
766afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
767afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
768afb591d7SGreg Roach
769afb591d7SGreg Roach            return new GedcomRecord($xref, $gedcom, null, $this);
770afb591d7SGreg Roach        }
771afb591d7SGreg Roach
772313e72b3SGreg Roach        return GedcomRecord::getInstance($xref, $this, $gedcom);
773afb591d7SGreg Roach    }
774afb591d7SGreg Roach
775afb591d7SGreg Roach    /**
776afb591d7SGreg Roach     * Create a new family from GEDCOM data.
777afb591d7SGreg Roach     *
778afb591d7SGreg Roach     * @param string $gedcom
779afb591d7SGreg Roach     *
780afb591d7SGreg Roach     * @return Family
781afb591d7SGreg Roach     * @throws InvalidArgumentException
782afb591d7SGreg Roach     */
783afb591d7SGreg Roach    public function createFamily(string $gedcom): GedcomRecord
784afb591d7SGreg Roach    {
785bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ FAM')) {
786afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createFamily(' . $gedcom . ') does not begin 0 @@ FAM');
787afb591d7SGreg Roach        }
788afb591d7SGreg Roach
789afb591d7SGreg Roach        $xref   = $this->getNewXref();
790bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ FAM' . Str::after($gedcom, '0 @@ FAM');
791afb591d7SGreg Roach
792afb591d7SGreg Roach        // Create a change record
793e5a6b4d4SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
794afb591d7SGreg Roach
795afb591d7SGreg Roach        // Create a pending change
796963fbaeeSGreg Roach        DB::table('change')->insert([
797963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
798963fbaeeSGreg Roach            'xref'       => $xref,
799963fbaeeSGreg Roach            'old_gedcom' => '',
800963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
801963fbaeeSGreg Roach            'user_id'    => Auth::id(),
802afb591d7SGreg Roach        ]);
803304f20d5SGreg Roach
804304f20d5SGreg Roach        // Accept this pending change
805304f20d5SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
806cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
807afb591d7SGreg Roach
808afb591d7SGreg Roach            return new Family($xref, $gedcom, null, $this);
809304f20d5SGreg Roach        }
810afb591d7SGreg Roach
811afb591d7SGreg Roach        return new Family($xref, '', $gedcom, $this);
812afb591d7SGreg Roach    }
813afb591d7SGreg Roach
814afb591d7SGreg Roach    /**
815afb591d7SGreg Roach     * Create a new individual from GEDCOM data.
816afb591d7SGreg Roach     *
817afb591d7SGreg Roach     * @param string $gedcom
818afb591d7SGreg Roach     *
819afb591d7SGreg Roach     * @return Individual
820afb591d7SGreg Roach     * @throws InvalidArgumentException
821afb591d7SGreg Roach     */
822afb591d7SGreg Roach    public function createIndividual(string $gedcom): GedcomRecord
823afb591d7SGreg Roach    {
824bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ INDI')) {
825afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ INDI');
826afb591d7SGreg Roach        }
827afb591d7SGreg Roach
828afb591d7SGreg Roach        $xref   = $this->getNewXref();
829bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ INDI' . Str::after($gedcom, '0 @@ INDI');
830afb591d7SGreg Roach
831afb591d7SGreg Roach        // Create a change record
832e5a6b4d4SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
833afb591d7SGreg Roach
834afb591d7SGreg Roach        // Create a pending change
835963fbaeeSGreg Roach        DB::table('change')->insert([
836963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
837963fbaeeSGreg Roach            'xref'       => $xref,
838963fbaeeSGreg Roach            'old_gedcom' => '',
839963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
840963fbaeeSGreg Roach            'user_id'    => Auth::id(),
841afb591d7SGreg Roach        ]);
842afb591d7SGreg Roach
843afb591d7SGreg Roach        // Accept this pending change
844afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
845afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
846afb591d7SGreg Roach
847afb591d7SGreg Roach            return new Individual($xref, $gedcom, null, $this);
848afb591d7SGreg Roach        }
849afb591d7SGreg Roach
850afb591d7SGreg Roach        return new Individual($xref, '', $gedcom, $this);
851304f20d5SGreg Roach    }
8528586983fSGreg Roach
8538586983fSGreg Roach    /**
85420b58d20SGreg Roach     * Create a new media object from GEDCOM data.
85520b58d20SGreg Roach     *
85620b58d20SGreg Roach     * @param string $gedcom
85720b58d20SGreg Roach     *
85820b58d20SGreg Roach     * @return Media
85920b58d20SGreg Roach     * @throws InvalidArgumentException
86020b58d20SGreg Roach     */
86120b58d20SGreg Roach    public function createMediaObject(string $gedcom): Media
86220b58d20SGreg Roach    {
863bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ OBJE')) {
86420b58d20SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ OBJE');
86520b58d20SGreg Roach        }
86620b58d20SGreg Roach
86720b58d20SGreg Roach        $xref   = $this->getNewXref();
868bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ OBJE' . Str::after($gedcom, '0 @@ OBJE');
86920b58d20SGreg Roach
87020b58d20SGreg Roach        // Create a change record
871e5a6b4d4SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
87220b58d20SGreg Roach
87320b58d20SGreg Roach        // Create a pending change
874963fbaeeSGreg Roach        DB::table('change')->insert([
875963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
876963fbaeeSGreg Roach            'xref'       => $xref,
877963fbaeeSGreg Roach            'old_gedcom' => '',
878963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
879963fbaeeSGreg Roach            'user_id'    => Auth::id(),
88020b58d20SGreg Roach        ]);
88120b58d20SGreg Roach
88220b58d20SGreg Roach        // Accept this pending change
88320b58d20SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
88420b58d20SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
88520b58d20SGreg Roach
88620b58d20SGreg Roach            return new Media($xref, $gedcom, null, $this);
88720b58d20SGreg Roach        }
88820b58d20SGreg Roach
88920b58d20SGreg Roach        return new Media($xref, '', $gedcom, $this);
89020b58d20SGreg Roach    }
89120b58d20SGreg Roach
89220b58d20SGreg Roach    /**
8938586983fSGreg Roach     * What is the most significant individual in this tree.
8948586983fSGreg Roach     *
895e5a6b4d4SGreg Roach     * @param UserInterface $user
8968586983fSGreg Roach     *
8978586983fSGreg Roach     * @return Individual
8988586983fSGreg Roach     */
899e5a6b4d4SGreg Roach    public function significantIndividual(UserInterface $user): Individual
900c1010edaSGreg Roach    {
9018f9b0fb2SGreg Roach        $individual = null;
9028586983fSGreg Roach
9038f9b0fb2SGreg Roach        if ($this->getUserPreference($user, 'rootid') !== '') {
9048586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
9058586983fSGreg Roach        }
9068f9b0fb2SGreg Roach
9078f9b0fb2SGreg Roach        if ($individual === null && $this->getUserPreference($user, 'gedcomid') !== '') {
9088586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
9098586983fSGreg Roach        }
9108f9b0fb2SGreg Roach
911bec87e94SGreg Roach        if ($individual === null && $this->getPreference('PEDIGREE_ROOT_ID') !== '') {
9128586983fSGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
9138586983fSGreg Roach        }
9148f9b0fb2SGreg Roach        if ($individual === null) {
9158f9b0fb2SGreg Roach            $xref = (string) DB::table('individuals')
9168f9b0fb2SGreg Roach                ->where('i_file', '=', $this->id())
9178f9b0fb2SGreg Roach                ->min('i_id');
918769d7d6eSGreg Roach
919769d7d6eSGreg Roach            $individual = Individual::getInstance($xref, $this);
9205fe1add5SGreg Roach        }
9218f9b0fb2SGreg Roach        if ($individual === null) {
9225fe1add5SGreg Roach            // always return a record
9235fe1add5SGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
9245fe1add5SGreg Roach        }
9255fe1add5SGreg Roach
9265fe1add5SGreg Roach        return $individual;
9275fe1add5SGreg Roach    }
928a25f0a04SGreg Roach}
929