xref: /webtrees/app/Tree.php (revision c0804649bf60e006885fb046f075cf3008bf7cb9)
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
203d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsExport;
213d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
2201461f86SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
2301461f86SGreg Roachuse Illuminate\Database\Query\Builder;
2401461f86SGreg Roachuse Illuminate\Database\Query\JoinClause;
2594026f20SGreg Roachuse Illuminate\Support\Collection;
26bec87e94SGreg Roachuse Illuminate\Support\Str;
27afb591d7SGreg Roachuse InvalidArgumentException;
28a25f0a04SGreg Roachuse PDOException;
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
53*c0804649SGreg Roach    /** @var Tree[] All trees that we have permission to see, indexed by ID. */
5432f20c14SGreg Roach    public static $trees = [];
55a25f0a04SGreg Roach
56a25f0a04SGreg Roach    /** @var string[] Cached copy of the wt_gedcom_setting table. */
5715d603e7SGreg Roach    private $preferences = [];
58a25f0a04SGreg Roach
59a25f0a04SGreg Roach    /** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
6013abd6f3SGreg Roach    private $user_preferences = [];
61a25f0a04SGreg Roach
62061b43d7SGreg Roach    private const RESN_PRIVACY = [
63061b43d7SGreg Roach        'none'         => Auth::PRIV_PRIVATE,
64061b43d7SGreg Roach        'privacy'      => Auth::PRIV_USER,
65061b43d7SGreg Roach        'confidential' => Auth::PRIV_NONE,
66061b43d7SGreg Roach        'hidden'       => Auth::PRIV_HIDE,
67061b43d7SGreg Roach    ];
68061b43d7SGreg Roach
69a25f0a04SGreg Roach    /**
70a25f0a04SGreg Roach     * Create a tree object. This is a private constructor - it can only
71a25f0a04SGreg Roach     * be called from Tree::getAll() to ensure proper initialisation.
72a25f0a04SGreg Roach     *
7372cf66d4SGreg Roach     * @param int    $id
74aa6f03bbSGreg Roach     * @param string $name
75cc13d6d8SGreg Roach     * @param string $title
76a25f0a04SGreg Roach     */
77cc13d6d8SGreg Roach    private function __construct($id, $name, $title)
78c1010edaSGreg Roach    {
7972cf66d4SGreg Roach        $this->id                      = $id;
80aa6f03bbSGreg Roach        $this->name                    = $name;
81cc13d6d8SGreg Roach        $this->title                   = $title;
8213abd6f3SGreg Roach        $this->fact_privacy            = [];
8313abd6f3SGreg Roach        $this->individual_privacy      = [];
8413abd6f3SGreg Roach        $this->individual_fact_privacy = [];
85518bbdc1SGreg Roach
86518bbdc1SGreg Roach        // Load the privacy settings for this tree
87061b43d7SGreg Roach        $rows = DB::table('default_resn')
88061b43d7SGreg Roach            ->where('gedcom_id', '=', $this->id)
89061b43d7SGreg Roach            ->get();
90518bbdc1SGreg Roach
91518bbdc1SGreg Roach        foreach ($rows as $row) {
92061b43d7SGreg Roach            // Convert GEDCOM privacy restriction to a webtrees access level.
93061b43d7SGreg Roach            $row->resn = self::RESN_PRIVACY[$row->resn];
94061b43d7SGreg Roach
95518bbdc1SGreg Roach            if ($row->xref !== null) {
96518bbdc1SGreg Roach                if ($row->tag_type !== null) {
97518bbdc1SGreg Roach                    $this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
98518bbdc1SGreg Roach                } else {
99518bbdc1SGreg Roach                    $this->individual_privacy[$row->xref] = (int) $row->resn;
100518bbdc1SGreg Roach                }
101518bbdc1SGreg Roach            } else {
102518bbdc1SGreg Roach                $this->fact_privacy[$row->tag_type] = (int) $row->resn;
103518bbdc1SGreg Roach            }
104518bbdc1SGreg Roach        }
105a25f0a04SGreg Roach    }
106a25f0a04SGreg Roach
107a25f0a04SGreg Roach    /**
108a25f0a04SGreg Roach     * The ID of this tree
109a25f0a04SGreg Roach     *
110cbc1590aSGreg Roach     * @return int
111a25f0a04SGreg Roach     */
11272cf66d4SGreg Roach    public function id(): int
113c1010edaSGreg Roach    {
11472cf66d4SGreg Roach        return $this->id;
115a25f0a04SGreg Roach    }
116a25f0a04SGreg Roach
117a25f0a04SGreg Roach    /**
118a25f0a04SGreg Roach     * The name of this tree
119a25f0a04SGreg Roach     *
120a25f0a04SGreg Roach     * @return string
121a25f0a04SGreg Roach     */
122aa6f03bbSGreg Roach    public function name(): string
123c1010edaSGreg Roach    {
124a25f0a04SGreg Roach        return $this->name;
125a25f0a04SGreg Roach    }
126a25f0a04SGreg Roach
127a25f0a04SGreg Roach    /**
128a25f0a04SGreg Roach     * The title of this tree
129a25f0a04SGreg Roach     *
130a25f0a04SGreg Roach     * @return string
131a25f0a04SGreg Roach     */
132cc13d6d8SGreg Roach    public function title(): string
133c1010edaSGreg Roach    {
134a25f0a04SGreg Roach        return $this->title;
135a25f0a04SGreg Roach    }
136a25f0a04SGreg Roach
137a25f0a04SGreg Roach    /**
138518bbdc1SGreg Roach     * The fact-level privacy for this tree.
139518bbdc1SGreg Roach     *
140e2052359SGreg Roach     * @return int[]
141518bbdc1SGreg Roach     */
1428f53f488SRico Sonntag    public function getFactPrivacy(): array
143c1010edaSGreg Roach    {
144518bbdc1SGreg Roach        return $this->fact_privacy;
145518bbdc1SGreg Roach    }
146518bbdc1SGreg Roach
147518bbdc1SGreg Roach    /**
148518bbdc1SGreg Roach     * The individual-level privacy for this tree.
149518bbdc1SGreg Roach     *
150e2052359SGreg Roach     * @return int[]
151518bbdc1SGreg Roach     */
1528f53f488SRico Sonntag    public function getIndividualPrivacy(): array
153c1010edaSGreg Roach    {
154518bbdc1SGreg Roach        return $this->individual_privacy;
155518bbdc1SGreg Roach    }
156518bbdc1SGreg Roach
157518bbdc1SGreg Roach    /**
158518bbdc1SGreg Roach     * The individual-fact-level privacy for this tree.
159518bbdc1SGreg Roach     *
160adac8af1SGreg Roach     * @return int[][]
161518bbdc1SGreg Roach     */
1628f53f488SRico Sonntag    public function getIndividualFactPrivacy(): array
163c1010edaSGreg Roach    {
164518bbdc1SGreg Roach        return $this->individual_fact_privacy;
165518bbdc1SGreg Roach    }
166518bbdc1SGreg Roach
167518bbdc1SGreg Roach    /**
168a25f0a04SGreg Roach     * Get the tree’s configuration settings.
169a25f0a04SGreg Roach     *
170a25f0a04SGreg Roach     * @param string $setting_name
17115d603e7SGreg Roach     * @param string $default
172a25f0a04SGreg Roach     *
17315d603e7SGreg Roach     * @return string
174a25f0a04SGreg Roach     */
175771ae10aSGreg Roach    public function getPreference(string $setting_name, string $default = ''): string
176c1010edaSGreg Roach    {
17715d603e7SGreg Roach        if (empty($this->preferences)) {
178061b43d7SGreg Roach            $this->preferences = DB::table('gedcom_setting')
179061b43d7SGreg Roach                ->where('gedcom_id', '=', $this->id)
180061b43d7SGreg Roach                ->pluck('setting_value', 'setting_name')
181061b43d7SGreg Roach                ->all();
182a25f0a04SGreg Roach        }
183a25f0a04SGreg Roach
184b2ce94c6SRico Sonntag        return $this->preferences[$setting_name] ?? $default;
185a25f0a04SGreg Roach    }
186a25f0a04SGreg Roach
187a25f0a04SGreg Roach    /**
188a25f0a04SGreg Roach     * Set the tree’s configuration settings.
189a25f0a04SGreg Roach     *
190a25f0a04SGreg Roach     * @param string $setting_name
191a25f0a04SGreg Roach     * @param string $setting_value
192a25f0a04SGreg Roach     *
193a25f0a04SGreg Roach     * @return $this
194a25f0a04SGreg Roach     */
195771ae10aSGreg Roach    public function setPreference(string $setting_name, string $setting_value): Tree
196c1010edaSGreg Roach    {
197a25f0a04SGreg Roach        if ($setting_value !== $this->getPreference($setting_name)) {
198061b43d7SGreg Roach            DB::table('gedcom_setting')->updateOrInsert([
199061b43d7SGreg Roach                'gedcom_id'    => $this->id,
200a25f0a04SGreg Roach                'setting_name' => $setting_name,
201061b43d7SGreg Roach            ], [
202a25f0a04SGreg Roach                'setting_value' => $setting_value,
20313abd6f3SGreg Roach            ]);
20415d603e7SGreg Roach
205a25f0a04SGreg Roach            $this->preferences[$setting_name] = $setting_value;
20615d603e7SGreg Roach
20772292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
208a25f0a04SGreg Roach        }
209a25f0a04SGreg Roach
210a25f0a04SGreg Roach        return $this;
211a25f0a04SGreg Roach    }
212a25f0a04SGreg Roach
213a25f0a04SGreg Roach    /**
214a25f0a04SGreg Roach     * Get the tree’s user-configuration settings.
215a25f0a04SGreg Roach     *
216a25f0a04SGreg Roach     * @param User   $user
217a25f0a04SGreg Roach     * @param string $setting_name
2187015ba1fSGreg Roach     * @param string $default
219a25f0a04SGreg Roach     *
220a25f0a04SGreg Roach     * @return string
221a25f0a04SGreg Roach     */
222771ae10aSGreg Roach    public function getUserPreference(User $user, string $setting_name, string $default = ''): string
223c1010edaSGreg Roach    {
224a25f0a04SGreg Roach        // There are lots of settings, and we need to fetch lots of them on every page
225a25f0a04SGreg Roach        // so it is quicker to fetch them all in one go.
226a25f0a04SGreg Roach        if (!array_key_exists($user->getUserId(), $this->user_preferences)) {
227061b43d7SGreg Roach            $this->user_preferences[$user->getUserId()] = DB::table('user_gedcom_setting')
228061b43d7SGreg Roach                ->where('user_id', '=', $user->getUserId())
229061b43d7SGreg Roach                ->where('gedcom_id', '=', $this->id)
230061b43d7SGreg Roach                ->pluck('setting_value', 'setting_name')
231061b43d7SGreg Roach                ->all();
232a25f0a04SGreg Roach        }
233a25f0a04SGreg Roach
234b2ce94c6SRico Sonntag        return $this->user_preferences[$user->getUserId()][$setting_name] ?? $default;
235a25f0a04SGreg Roach    }
236a25f0a04SGreg Roach
237a25f0a04SGreg Roach    /**
238a25f0a04SGreg Roach     * Set the tree’s user-configuration settings.
239a25f0a04SGreg Roach     *
240a25f0a04SGreg Roach     * @param User   $user
241a25f0a04SGreg Roach     * @param string $setting_name
242a25f0a04SGreg Roach     * @param string $setting_value
243a25f0a04SGreg Roach     *
244a25f0a04SGreg Roach     * @return $this
245a25f0a04SGreg Roach     */
246771ae10aSGreg Roach    public function setUserPreference(User $user, string $setting_name, string $setting_value): Tree
247c1010edaSGreg Roach    {
248a25f0a04SGreg Roach        if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
249a25f0a04SGreg Roach            // Update the database
250061b43d7SGreg Roach            DB::table('user_gedcom_setting')->updateOrInsert([
251061b43d7SGreg Roach                'gedcom_id'    => $this->id(),
252a25f0a04SGreg Roach                'user_id'      => $user->getUserId(),
253a25f0a04SGreg Roach                'setting_name' => $setting_name,
254061b43d7SGreg Roach            ], [
255cbc1590aSGreg Roach                'setting_value' => $setting_value,
25613abd6f3SGreg Roach            ]);
257061b43d7SGreg Roach
258061b43d7SGreg Roach            // Update the cache
259a25f0a04SGreg Roach            $this->user_preferences[$user->getUserId()][$setting_name] = $setting_value;
260a25f0a04SGreg Roach            // Audit log of changes
26172292b7dSGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this);
262a25f0a04SGreg Roach        }
263a25f0a04SGreg Roach
264a25f0a04SGreg Roach        return $this;
265a25f0a04SGreg Roach    }
266a25f0a04SGreg Roach
267a25f0a04SGreg Roach    /**
268a25f0a04SGreg Roach     * Can a user accept changes for this tree?
269a25f0a04SGreg Roach     *
270a25f0a04SGreg Roach     * @param User $user
271a25f0a04SGreg Roach     *
272cbc1590aSGreg Roach     * @return bool
273a25f0a04SGreg Roach     */
274771ae10aSGreg Roach    public function canAcceptChanges(User $user): bool
275c1010edaSGreg Roach    {
276a25f0a04SGreg Roach        return Auth::isModerator($this, $user);
277a25f0a04SGreg Roach    }
278a25f0a04SGreg Roach
279a25f0a04SGreg Roach    /**
280a25f0a04SGreg Roach     * Fetch all the trees that we have permission to access.
281a25f0a04SGreg Roach     *
282a25f0a04SGreg Roach     * @return Tree[]
283a25f0a04SGreg Roach     */
284771ae10aSGreg Roach    public static function getAll(): array
285c1010edaSGreg Roach    {
28675a9f908SGreg Roach        if (empty(self::$trees)) {
28701461f86SGreg Roach            // Admins see all trees
28801461f86SGreg Roach            $query = DB::table('gedcom')
28901461f86SGreg Roach                ->leftJoin('gedcom_setting', function (JoinClause $join): void {
29001461f86SGreg Roach                    $join->on('gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
29101461f86SGreg Roach                        ->where('gedcom_setting.setting_name', '=', 'title');
29201461f86SGreg Roach                })
29301461f86SGreg Roach                ->where('gedcom.gedcom_id', '>', 0)
29401461f86SGreg Roach                ->select([
29501461f86SGreg Roach                    'gedcom.gedcom_id AS tree_id',
29601461f86SGreg Roach                    'gedcom.gedcom_name AS tree_name',
29701461f86SGreg Roach                    'gedcom_setting.setting_value AS tree_title',
29801461f86SGreg Roach                ])
29901461f86SGreg Roach                ->orderBy('gedcom.sort_order')
30001461f86SGreg Roach                ->orderBy('gedcom_setting.setting_value');
30101461f86SGreg Roach
30232f20c14SGreg Roach            // Non-admins may not see all trees
30332f20c14SGreg Roach            if (!Auth::isAdmin()) {
30401461f86SGreg Roach                $query
30536357577SGreg Roach                    ->join('gedcom_setting AS gs2', function (JoinClause $join): void {
30636357577SGreg Roach                        $join->on('gs2.gedcom_id', '=', 'gedcom.gedcom_id')
30701461f86SGreg Roach                            ->where('gs2.setting_name', '=', 'imported');
30836357577SGreg Roach                    })
30936357577SGreg Roach                    ->join('gedcom_setting AS gs3', function (JoinClause $join): void {
31001461f86SGreg Roach                        $join->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
31101461f86SGreg Roach                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
31201461f86SGreg Roach                    })
31301461f86SGreg Roach                    ->leftJoin('user_gedcom_setting', function (JoinClause $join): void {
31401461f86SGreg Roach                        $join->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
31501461f86SGreg Roach                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
31601461f86SGreg Roach                            ->where('user_gedcom_setting.setting_name', '=', 'canedit');
31701461f86SGreg Roach                    })
31801461f86SGreg Roach                    ->where(function (Builder $query): void {
31901461f86SGreg Roach                        $query
32001461f86SGreg Roach                            // Managers
32101461f86SGreg Roach                            ->where('user_gedcom_setting.setting_value', '=', 'admin')
32201461f86SGreg Roach                            // Members
32301461f86SGreg Roach                            ->orWhere(function (Builder $query): void {
32401461f86SGreg Roach                                $query
32501461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
32601461f86SGreg Roach                                    ->where('gs3.setting_value', '=', '1')
32701461f86SGreg Roach                                    ->where('user_gedcom_setting.setting_value', '<>', 'none');
32801461f86SGreg Roach                            })
32936357577SGreg Roach                            // PUblic trees
33001461f86SGreg Roach                            ->orWhere(function (Builder $query): void {
33101461f86SGreg Roach                                $query
33201461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
33336357577SGreg Roach                                    ->where('gs3.setting_value', '<>', '1');
33401461f86SGreg Roach                            });
33501461f86SGreg Roach                    });
33601461f86SGreg Roach            }
33701461f86SGreg Roach
33801461f86SGreg Roach            $rows = $query->get();
33901461f86SGreg Roach
340a25f0a04SGreg Roach            foreach ($rows as $row) {
341*c0804649SGreg Roach                self::$trees[$row->tree_id] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
342a25f0a04SGreg Roach            }
343a25f0a04SGreg Roach        }
344a25f0a04SGreg Roach
345a25f0a04SGreg Roach        return self::$trees;
346a25f0a04SGreg Roach    }
347a25f0a04SGreg Roach
348a25f0a04SGreg Roach    /**
349d2cdeb3fSGreg Roach     * Find the tree with a specific ID.
350a25f0a04SGreg Roach     *
351cbc1590aSGreg Roach     * @param int $tree_id
352cbc1590aSGreg Roach     *
353a25f0a04SGreg Roach     * @return Tree
354a25f0a04SGreg Roach     */
355*c0804649SGreg Roach    public static function findById(int $tree_id): Tree
356c1010edaSGreg Roach    {
357*c0804649SGreg Roach        return self::getAll()[$tree_id];
358a25f0a04SGreg Roach    }
359a25f0a04SGreg Roach
360a25f0a04SGreg Roach    /**
361d2cdeb3fSGreg Roach     * Find the tree with a specific name.
362cf4bcc09SGreg Roach     *
363cf4bcc09SGreg Roach     * @param string $tree_name
364cf4bcc09SGreg Roach     *
365cf4bcc09SGreg Roach     * @return Tree|null
366cf4bcc09SGreg Roach     */
367c1010edaSGreg Roach    public static function findByName($tree_name)
368c1010edaSGreg Roach    {
369cf4bcc09SGreg Roach        foreach (self::getAll() as $tree) {
37051d0f842SGreg Roach            if ($tree->name === $tree_name) {
371cf4bcc09SGreg Roach                return $tree;
372cf4bcc09SGreg Roach            }
373cf4bcc09SGreg Roach        }
374cf4bcc09SGreg Roach
375cf4bcc09SGreg Roach        return null;
376cf4bcc09SGreg Roach    }
377cf4bcc09SGreg Roach
378cf4bcc09SGreg Roach    /**
379a25f0a04SGreg Roach     * Create arguments to select_edit_control()
380a25f0a04SGreg Roach     * Note - these will be escaped later
381a25f0a04SGreg Roach     *
382a25f0a04SGreg Roach     * @return string[]
383a25f0a04SGreg Roach     */
384771ae10aSGreg Roach    public static function getIdList(): array
385c1010edaSGreg Roach    {
38613abd6f3SGreg Roach        $list = [];
387a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
38872cf66d4SGreg Roach            $list[$tree->id] = $tree->title;
389a25f0a04SGreg Roach        }
390a25f0a04SGreg Roach
391a25f0a04SGreg Roach        return $list;
392a25f0a04SGreg Roach    }
393a25f0a04SGreg Roach
394a25f0a04SGreg Roach    /**
395a25f0a04SGreg Roach     * Create arguments to select_edit_control()
396a25f0a04SGreg Roach     * Note - these will be escaped later
397a25f0a04SGreg Roach     *
398a25f0a04SGreg Roach     * @return string[]
399a25f0a04SGreg Roach     */
400771ae10aSGreg Roach    public static function getNameList(): array
401c1010edaSGreg Roach    {
40213abd6f3SGreg Roach        $list = [];
403a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
404a25f0a04SGreg Roach            $list[$tree->name] = $tree->title;
405a25f0a04SGreg Roach        }
406a25f0a04SGreg Roach
407a25f0a04SGreg Roach        return $list;
408a25f0a04SGreg Roach    }
409a25f0a04SGreg Roach
410a25f0a04SGreg Roach    /**
411a25f0a04SGreg Roach     * Create a new tree
412a25f0a04SGreg Roach     *
413a25f0a04SGreg Roach     * @param string $tree_name
414a25f0a04SGreg Roach     * @param string $tree_title
415a25f0a04SGreg Roach     *
416a25f0a04SGreg Roach     * @return Tree
417a25f0a04SGreg Roach     */
418771ae10aSGreg Roach    public static function create(string $tree_name, string $tree_title): Tree
419c1010edaSGreg Roach    {
420a25f0a04SGreg Roach        try {
421a25f0a04SGreg Roach            // Create a new tree
42201461f86SGreg Roach            DB::table('gedcom')->insert([
42301461f86SGreg Roach                'gedcom_name' => $tree_name,
42401461f86SGreg Roach            ]);
4254a86d714SGreg Roach
426061b43d7SGreg Roach            $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
42732f20c14SGreg Roach
42832f20c14SGreg Roach            $tree = new self($tree_id, $tree_name, $tree_title);
429a25f0a04SGreg Roach        } catch (PDOException $ex) {
430a25f0a04SGreg Roach            // A tree with that name already exists?
431ef2fd529SGreg Roach            return self::findByName($tree_name);
432a25f0a04SGreg Roach        }
433a25f0a04SGreg Roach
434a25f0a04SGreg Roach        $tree->setPreference('imported', '0');
435a25f0a04SGreg Roach        $tree->setPreference('title', $tree_title);
436a25f0a04SGreg Roach
437a25f0a04SGreg Roach        // Module privacy
438a25f0a04SGreg Roach        Module::setDefaultAccess($tree_id);
439a25f0a04SGreg Roach
4401507cbcaSGreg Roach        // Set preferences from default tree
441061b43d7SGreg Roach        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
442061b43d7SGreg Roach            ['gedcom_id', 'setting_name', 'setting_value'],
443061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
444061b43d7SGreg Roach                $query
445061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'setting_name', 'setting_value'])
446061b43d7SGreg Roach                    ->from('gedcom_setting')
447061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
448061b43d7SGreg Roach            }
449061b43d7SGreg Roach        );
4501507cbcaSGreg Roach
451061b43d7SGreg Roach        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
452061b43d7SGreg Roach            ['gedcom_id', 'tag_type', 'resn'],
453061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
454061b43d7SGreg Roach                $query
455061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'tag_type', 'resn'])
456061b43d7SGreg Roach                    ->from('default_resn')
457061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
458061b43d7SGreg Roach            }
459061b43d7SGreg Roach        );
4601507cbcaSGreg Roach
461061b43d7SGreg Roach        (new Builder(DB::connection()))->from('block')->insertUsing(
462061b43d7SGreg Roach            ['gedcom_id', 'location', 'block_order', 'module_name'],
463061b43d7SGreg Roach            function (Builder $query) use ($tree_id): void {
464061b43d7SGreg Roach                $query
465061b43d7SGreg Roach                    ->select([DB::raw($tree_id), 'location', 'block_order', 'module_name'])
466061b43d7SGreg Roach                    ->from('block')
467061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
468061b43d7SGreg Roach            }
469061b43d7SGreg Roach        );
4701507cbcaSGreg Roach
471a25f0a04SGreg Roach        // Gedcom and privacy settings
47276f666f4SGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
47376f666f4SGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
474a25f0a04SGreg Roach        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
475a25f0a04SGreg Roach        switch (WT_LOCALE) {
476a25f0a04SGreg Roach            case 'es':
477a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'spanish');
478a25f0a04SGreg Roach                break;
479a25f0a04SGreg Roach            case 'is':
480a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
481a25f0a04SGreg Roach                break;
482a25f0a04SGreg Roach            case 'lt':
483a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
484a25f0a04SGreg Roach                break;
485a25f0a04SGreg Roach            case 'pl':
486a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'polish');
487a25f0a04SGreg Roach                break;
488a25f0a04SGreg Roach            case 'pt':
489a25f0a04SGreg Roach            case 'pt-BR':
490a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
491a25f0a04SGreg Roach                break;
492a25f0a04SGreg Roach            default:
493a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'paternal');
494a25f0a04SGreg Roach                break;
495a25f0a04SGreg Roach        }
496a25f0a04SGreg Roach
497a25f0a04SGreg Roach        // Genealogy data
498a25f0a04SGreg Roach        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
499bbb76c12SGreg Roach        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
500bbb76c12SGreg Roach        $john_doe = I18N::translate('John /DOE/');
50177e70a22SGreg Roach        $note     = I18N::translate('Edit this individual and replace their details with your own.');
502061b43d7SGreg 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";
503061b43d7SGreg Roach
504061b43d7SGreg Roach        DB::table('gedcom_chunk')->insert([
505061b43d7SGreg Roach            'gedcom_id'  => $tree_id,
506061b43d7SGreg Roach            'chunk_data' => $gedcom,
50713abd6f3SGreg Roach        ]);
508a25f0a04SGreg Roach
509a25f0a04SGreg Roach        // Update our cache
51072cf66d4SGreg Roach        self::$trees[$tree->id] = $tree;
511a25f0a04SGreg Roach
512a25f0a04SGreg Roach        return $tree;
513a25f0a04SGreg Roach    }
514a25f0a04SGreg Roach
515a25f0a04SGreg Roach    /**
516b78374c5SGreg Roach     * Are there any pending edits for this tree, than need reviewing by a moderator.
517b78374c5SGreg Roach     *
518b78374c5SGreg Roach     * @return bool
519b78374c5SGreg Roach     */
520771ae10aSGreg Roach    public function hasPendingEdit(): bool
521c1010edaSGreg Roach    {
52215a3f100SGreg Roach        return DB::table('change')
52315a3f100SGreg Roach            ->where('gedcom_id', '=', $this->id)
52415a3f100SGreg Roach            ->where('status', '=', 'pending')
52515a3f100SGreg Roach            ->exists();
526b78374c5SGreg Roach    }
527b78374c5SGreg Roach
528b78374c5SGreg Roach    /**
529a25f0a04SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
530a25f0a04SGreg Roach     * new data. Optionally retain the media data, for when the user has been
531a25f0a04SGreg Roach     * editing their data offline using an application which deletes (or does not
532a25f0a04SGreg Roach     * support) media data.
533a25f0a04SGreg Roach     *
534a25f0a04SGreg Roach     * @param bool $keep_media
535b7e60af1SGreg Roach     *
536b7e60af1SGreg Roach     * @return void
537a25f0a04SGreg Roach     */
538b7e60af1SGreg Roach    public function deleteGenealogyData(bool $keep_media)
539c1010edaSGreg Roach    {
5401ad2dde6SGreg Roach        DB::table('gedcom_chunk')->where('gedcom_id', '=', $this->id)->delete();
5411ad2dde6SGreg Roach        DB::table('individuals')->where('i_file', '=', $this->id)->delete();
5421ad2dde6SGreg Roach        DB::table('families')->where('f_file', '=', $this->id)->delete();
5431ad2dde6SGreg Roach        DB::table('sources')->where('s_file', '=', $this->id)->delete();
5441ad2dde6SGreg Roach        DB::table('other')->where('o_file', '=', $this->id)->delete();
5451ad2dde6SGreg Roach        DB::table('places')->where('p_file', '=', $this->id)->delete();
5461ad2dde6SGreg Roach        DB::table('placelinks')->where('pl_file', '=', $this->id)->delete();
5471ad2dde6SGreg Roach        DB::table('name')->where('n_file', '=', $this->id)->delete();
5481ad2dde6SGreg Roach        DB::table('dates')->where('d_file', '=', $this->id)->delete();
5491ad2dde6SGreg Roach        DB::table('change')->where('gedcom_id', '=', $this->id)->delete();
550a25f0a04SGreg Roach
551a25f0a04SGreg Roach        if ($keep_media) {
5521ad2dde6SGreg Roach            DB::table('link')->where('l_file', '=', $this->id)
5531ad2dde6SGreg Roach                ->where('l_type', '<>', 'OBJE')
5541ad2dde6SGreg Roach                ->delete();
555a25f0a04SGreg Roach        } else {
5561ad2dde6SGreg Roach            DB::table('link')->where('l_file', '=', $this->id)->delete();
5571ad2dde6SGreg Roach            DB::table('media_file')->where('m_file', '=', $this->id)->delete();
5581ad2dde6SGreg Roach            DB::table('media')->where('m_file', '=', $this->id)->delete();
559a25f0a04SGreg Roach        }
560a25f0a04SGreg Roach    }
561a25f0a04SGreg Roach
562a25f0a04SGreg Roach    /**
563a25f0a04SGreg Roach     * Delete everything relating to a tree
564b7e60af1SGreg Roach     *
565b7e60af1SGreg Roach     * @return void
566a25f0a04SGreg Roach     */
567c1010edaSGreg Roach    public function delete()
568c1010edaSGreg Roach    {
569a25f0a04SGreg Roach        // If this is the default tree, then unset it
570ef2fd529SGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
571a25f0a04SGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
572a25f0a04SGreg Roach        }
573a25f0a04SGreg Roach
574a25f0a04SGreg Roach        $this->deleteGenealogyData(false);
575a25f0a04SGreg Roach
576a7890280SGreg Roach        DB::table('block_setting')
577a7890280SGreg Roach            ->join('block', 'block.block_id', '=', 'block_setting.block_id')
578a7890280SGreg Roach            ->where('gedcom_id', '=', $this->id)
579a7890280SGreg Roach            ->delete();
580a7890280SGreg Roach        DB::table('block')->where('gedcom_id', '=', $this->id)->delete();
581a7890280SGreg Roach        DB::table('user_gedcom_setting')->where('gedcom_id', '=', $this->id)->delete();
582a7890280SGreg Roach        DB::table('gedcom_setting')->where('gedcom_id', '=', $this->id)->delete();
583a7890280SGreg Roach        DB::table('module_privacy')->where('gedcom_id', '=', $this->id)->delete();
584a7890280SGreg Roach        DB::table('hit_counter')->where('gedcom_id', '=', $this->id)->delete();
585a7890280SGreg Roach        DB::table('default_resn')->where('gedcom_id', '=', $this->id)->delete();
586a7890280SGreg Roach        DB::table('gedcom_chunk')->where('gedcom_id', '=', $this->id)->delete();
587a7890280SGreg Roach        DB::table('log')->where('gedcom_id', '=', $this->id)->delete();
588a7890280SGreg Roach        DB::table('gedcom')->where('gedcom_id', '=', $this->id)->delete();
589a25f0a04SGreg Roach
590a25f0a04SGreg Roach        // After updating the database, we need to fetch a new (sorted) copy
59175a9f908SGreg Roach        self::$trees = [];
592a25f0a04SGreg Roach    }
593a25f0a04SGreg Roach
594a25f0a04SGreg Roach    /**
595a25f0a04SGreg Roach     * Export the tree to a GEDCOM file
596a25f0a04SGreg Roach     *
5975792757eSGreg Roach     * @param resource $stream
598b7e60af1SGreg Roach     *
599b7e60af1SGreg Roach     * @return void
600a25f0a04SGreg Roach     */
601c1010edaSGreg Roach    public function exportGedcom($stream)
602c1010edaSGreg Roach    {
603a3d8780cSGreg Roach        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this, 'UTF-8'));
60494026f20SGreg Roach
60594026f20SGreg Roach        $union_families = DB::table('families')
60694026f20SGreg Roach            ->where('f_file', '=', $this->id)
60794026f20SGreg Roach            ->select(['f_gedcom AS gedcom', 'f_id AS xref', DB::raw('LENGTH(f_id) AS len'), DB::raw('2 AS n')]);
60894026f20SGreg Roach
60994026f20SGreg Roach        $union_sources = DB::table('sources')
61094026f20SGreg Roach            ->where('s_file', '=', $this->id)
61194026f20SGreg Roach            ->select(['s_gedcom AS gedcom', 's_id AS xref', DB::raw('LENGTH(s_id) AS len'), DB::raw('3 AS n')]);
61294026f20SGreg Roach
61394026f20SGreg Roach        $union_other = DB::table('other')
61494026f20SGreg Roach            ->where('o_file', '=', $this->id)
61594026f20SGreg Roach            ->whereNotIn('o_type', ['HEAD', 'TRLR'])
61694026f20SGreg Roach            ->select(['o_gedcom AS gedcom', 'o_id AS xref', DB::raw('LENGTH(o_id) AS len'), DB::raw('4 AS n')]);
61794026f20SGreg Roach
61894026f20SGreg Roach        $union_media = DB::table('media')
61994026f20SGreg Roach            ->where('m_file', '=', $this->id)
62094026f20SGreg Roach            ->select(['m_gedcom AS gedcom', 'm_id AS xref', DB::raw('LENGTH(m_id) AS len'), DB::raw('5 AS n')]);
62194026f20SGreg Roach
62294026f20SGreg Roach        $rows = DB::table('individuals')
62394026f20SGreg Roach            ->where('i_file', '=', $this->id)
62494026f20SGreg Roach            ->select(['i_gedcom AS gedcom', 'i_id AS xref', DB::raw('LENGTH(i_id) AS len'), DB::raw('1 AS n')])
62594026f20SGreg Roach            ->union($union_families)
62694026f20SGreg Roach            ->union($union_sources)
62794026f20SGreg Roach            ->union($union_other)
62894026f20SGreg Roach            ->union($union_media)
62994026f20SGreg Roach            ->orderBy('n')
63094026f20SGreg Roach            ->orderBy('len')
63194026f20SGreg Roach            ->orderBy('xref')
63294026f20SGreg Roach            ->chunk(100, function (Collection $rows) use ($stream, &$buffer): void {
63394026f20SGreg Roach                foreach ($rows as $row) {
6343d7a8a4cSGreg Roach                    $buffer .= FunctionsExport::reformatRecord($row->gedcom);
635a25f0a04SGreg Roach                    if (strlen($buffer) > 65535) {
6365792757eSGreg Roach                        fwrite($stream, $buffer);
637a25f0a04SGreg Roach                        $buffer = '';
638a25f0a04SGreg Roach                    }
639a25f0a04SGreg Roach                }
64094026f20SGreg Roach            });
64194026f20SGreg Roach
6420f471f91SGreg Roach        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
643a25f0a04SGreg Roach    }
644a25f0a04SGreg Roach
645a25f0a04SGreg Roach    /**
646a25f0a04SGreg Roach     * Import data from a gedcom file into this tree.
647a25f0a04SGreg Roach     *
648a25f0a04SGreg Roach     * @param string $path     The full path to the (possibly temporary) file.
649a25f0a04SGreg Roach     * @param string $filename The preferred filename, for export/download.
650a25f0a04SGreg Roach     *
651b7e60af1SGreg Roach     * @return void
652a25f0a04SGreg Roach     */
653771ae10aSGreg Roach    public function importGedcomFile(string $path, string $filename)
654c1010edaSGreg Roach    {
655a25f0a04SGreg Roach        // Read the file in blocks of roughly 64K. Ensure that each block
656a25f0a04SGreg Roach        // contains complete gedcom records. This will ensure we don’t split
657a25f0a04SGreg Roach        // multi-byte characters, as well as simplifying the code to import
658a25f0a04SGreg Roach        // each block.
659a25f0a04SGreg Roach
660a25f0a04SGreg Roach        $file_data = '';
661a25f0a04SGreg Roach        $fp        = fopen($path, 'rb');
662a25f0a04SGreg Roach
663b7e60af1SGreg Roach        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
664a25f0a04SGreg Roach        $this->setPreference('gedcom_filename', $filename);
665a25f0a04SGreg Roach        $this->setPreference('imported', '0');
666a25f0a04SGreg Roach
667a25f0a04SGreg Roach        while (!feof($fp)) {
668a25f0a04SGreg Roach            $file_data .= fread($fp, 65536);
669a25f0a04SGreg Roach            // There is no strrpos() function that searches for substrings :-(
670a25f0a04SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
671a25f0a04SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
672a25f0a04SGreg Roach                    // We’ve found the last record boundary in this chunk of data
673a25f0a04SGreg Roach                    break;
674a25f0a04SGreg Roach                }
675a25f0a04SGreg Roach            }
676a25f0a04SGreg Roach            if ($pos) {
6771ad2dde6SGreg Roach                DB::table('gedcom_chunk')->insert([
6781ad2dde6SGreg Roach                    'gedcom_id'  => $this->id,
6791ad2dde6SGreg Roach                    'chunk_data' => substr($file_data, 0, $pos),
680c1010edaSGreg Roach                ]);
6811ad2dde6SGreg Roach
682a25f0a04SGreg Roach                $file_data = substr($file_data, $pos);
683a25f0a04SGreg Roach            }
684a25f0a04SGreg Roach        }
6851ad2dde6SGreg Roach        DB::table('gedcom_chunk')->insert([
6861ad2dde6SGreg Roach            'gedcom_id'  => $this->id,
6871ad2dde6SGreg Roach            'chunk_data' => $file_data,
688c1010edaSGreg Roach        ]);
689a25f0a04SGreg Roach
690a25f0a04SGreg Roach        fclose($fp);
691a25f0a04SGreg Roach    }
692304f20d5SGreg Roach
693304f20d5SGreg Roach    /**
694b90d8accSGreg Roach     * Generate a new XREF, unique across all family trees
695b90d8accSGreg Roach     *
696b90d8accSGreg Roach     * @return string
697b90d8accSGreg Roach     */
698771ae10aSGreg Roach    public function getNewXref(): string
699c1010edaSGreg Roach    {
700963fbaeeSGreg Roach        // Lock the row, so that only one new XREF may be generated at a time.
701963fbaeeSGreg Roach        DB::table('site_setting')
702963fbaeeSGreg Roach            ->where('setting_name', '=', 'next_xref')
703963fbaeeSGreg Roach            ->lockForUpdate()
704963fbaeeSGreg Roach            ->get();
705963fbaeeSGreg Roach
706a214e186SGreg Roach        $prefix = 'X';
707b90d8accSGreg Roach
708971d66c8SGreg Roach        $increment = 1.0;
709b90d8accSGreg Roach        do {
710963fbaeeSGreg Roach            $num = (int) Site::getPreference('next_xref') + (int) $increment;
711971d66c8SGreg Roach
712971d66c8SGreg Roach            // This exponential increment allows us to scan over large blocks of
713971d66c8SGreg Roach            // existing data in a reasonable time.
714971d66c8SGreg Roach            $increment *= 1.01;
715963fbaeeSGreg Roach
716963fbaeeSGreg Roach            $xref = $prefix . $num;
717963fbaeeSGreg Roach
718963fbaeeSGreg Roach            // Records may already exist with this sequence number.
719963fbaeeSGreg Roach            $already_used =
720963fbaeeSGreg Roach                DB::table('individuals')->where('i_id', '=', $xref)->exists() ||
721963fbaeeSGreg Roach                DB::table('families')->where('f_id', '=', $xref)->exists() ||
722963fbaeeSGreg Roach                DB::table('sources')->where('s_id', '=', $xref)->exists() ||
723963fbaeeSGreg Roach                DB::table('media')->where('m_id', '=', $xref)->exists() ||
724963fbaeeSGreg Roach                DB::table('other')->where('o_id', '=', $xref)->exists() ||
725963fbaeeSGreg Roach                DB::table('change')->where('xref', '=', $xref)->exists();
726963fbaeeSGreg Roach        } while ($already_used);
727963fbaeeSGreg Roach
728963fbaeeSGreg Roach        Site::setPreference('next_xref', (string) $num);
729b90d8accSGreg Roach
730a214e186SGreg Roach        return $xref;
731b90d8accSGreg Roach    }
732b90d8accSGreg Roach
733b90d8accSGreg Roach    /**
734304f20d5SGreg Roach     * Create a new record from GEDCOM data.
735304f20d5SGreg Roach     *
736304f20d5SGreg Roach     * @param string $gedcom
737304f20d5SGreg Roach     *
73815d603e7SGreg Roach     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
739afb591d7SGreg Roach     * @throws InvalidArgumentException
740304f20d5SGreg Roach     */
741771ae10aSGreg Roach    public function createRecord(string $gedcom): GedcomRecord
742c1010edaSGreg Roach    {
743bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ ')) {
744afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createRecord(' . $gedcom . ') does not begin 0 @@');
745304f20d5SGreg Roach        }
746304f20d5SGreg Roach
747a214e186SGreg Roach        $xref   = $this->getNewXref();
748bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ ' . Str::after($gedcom, '0 @@ ');
749304f20d5SGreg Roach
750afb591d7SGreg Roach        // Create a change record
751304f20d5SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
752304f20d5SGreg Roach
753304f20d5SGreg Roach        // Create a pending change
754963fbaeeSGreg Roach        DB::table('change')->insert([
755963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
756963fbaeeSGreg Roach            'xref'       => $xref,
757963fbaeeSGreg Roach            'old_gedcom' => '',
758963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
759963fbaeeSGreg Roach            'user_id'    => Auth::id(),
76013abd6f3SGreg Roach        ]);
761304f20d5SGreg Roach
762afb591d7SGreg Roach        // Accept this pending change
763afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
764afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
765afb591d7SGreg Roach
766afb591d7SGreg Roach            return new GedcomRecord($xref, $gedcom, null, $this);
767afb591d7SGreg Roach        }
768afb591d7SGreg Roach
769313e72b3SGreg Roach        return GedcomRecord::getInstance($xref, $this, $gedcom);
770afb591d7SGreg Roach    }
771afb591d7SGreg Roach
772afb591d7SGreg Roach    /**
773afb591d7SGreg Roach     * Create a new family from GEDCOM data.
774afb591d7SGreg Roach     *
775afb591d7SGreg Roach     * @param string $gedcom
776afb591d7SGreg Roach     *
777afb591d7SGreg Roach     * @return Family
778afb591d7SGreg Roach     * @throws InvalidArgumentException
779afb591d7SGreg Roach     */
780afb591d7SGreg Roach    public function createFamily(string $gedcom): GedcomRecord
781afb591d7SGreg Roach    {
782bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ FAM')) {
783afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createFamily(' . $gedcom . ') does not begin 0 @@ FAM');
784afb591d7SGreg Roach        }
785afb591d7SGreg Roach
786afb591d7SGreg Roach        $xref   = $this->getNewXref();
787bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ FAM' . Str::after($gedcom, '0 @@ FAM');
788afb591d7SGreg Roach
789afb591d7SGreg Roach        // Create a change record
790afb591d7SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
791afb591d7SGreg Roach
792afb591d7SGreg Roach        // Create a pending change
793963fbaeeSGreg Roach        DB::table('change')->insert([
794963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
795963fbaeeSGreg Roach            'xref'       => $xref,
796963fbaeeSGreg Roach            'old_gedcom' => '',
797963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
798963fbaeeSGreg Roach            'user_id'    => Auth::id(),
799afb591d7SGreg Roach        ]);
800304f20d5SGreg Roach
801304f20d5SGreg Roach        // Accept this pending change
802304f20d5SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
803cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
804afb591d7SGreg Roach
805afb591d7SGreg Roach            return new Family($xref, $gedcom, null, $this);
806304f20d5SGreg Roach        }
807afb591d7SGreg Roach
808afb591d7SGreg Roach        return new Family($xref, '', $gedcom, $this);
809afb591d7SGreg Roach    }
810afb591d7SGreg Roach
811afb591d7SGreg Roach    /**
812afb591d7SGreg Roach     * Create a new individual from GEDCOM data.
813afb591d7SGreg Roach     *
814afb591d7SGreg Roach     * @param string $gedcom
815afb591d7SGreg Roach     *
816afb591d7SGreg Roach     * @return Individual
817afb591d7SGreg Roach     * @throws InvalidArgumentException
818afb591d7SGreg Roach     */
819afb591d7SGreg Roach    public function createIndividual(string $gedcom): GedcomRecord
820afb591d7SGreg Roach    {
821bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ INDI')) {
822afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ INDI');
823afb591d7SGreg Roach        }
824afb591d7SGreg Roach
825afb591d7SGreg Roach        $xref   = $this->getNewXref();
826bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ INDI' . Str::after($gedcom, '0 @@ INDI');
827afb591d7SGreg Roach
828afb591d7SGreg Roach        // Create a change record
829afb591d7SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
830afb591d7SGreg Roach
831afb591d7SGreg Roach        // Create a pending change
832963fbaeeSGreg Roach        DB::table('change')->insert([
833963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
834963fbaeeSGreg Roach            'xref'       => $xref,
835963fbaeeSGreg Roach            'old_gedcom' => '',
836963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
837963fbaeeSGreg Roach            'user_id'    => Auth::id(),
838afb591d7SGreg Roach        ]);
839afb591d7SGreg Roach
840afb591d7SGreg Roach        // Accept this pending change
841afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
842afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
843afb591d7SGreg Roach
844afb591d7SGreg Roach            return new Individual($xref, $gedcom, null, $this);
845afb591d7SGreg Roach        }
846afb591d7SGreg Roach
847afb591d7SGreg Roach        return new Individual($xref, '', $gedcom, $this);
848304f20d5SGreg Roach    }
8498586983fSGreg Roach
8508586983fSGreg Roach    /**
85120b58d20SGreg Roach     * Create a new media object from GEDCOM data.
85220b58d20SGreg Roach     *
85320b58d20SGreg Roach     * @param string $gedcom
85420b58d20SGreg Roach     *
85520b58d20SGreg Roach     * @return Media
85620b58d20SGreg Roach     * @throws InvalidArgumentException
85720b58d20SGreg Roach     */
85820b58d20SGreg Roach    public function createMediaObject(string $gedcom): Media
85920b58d20SGreg Roach    {
860bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ OBJE')) {
86120b58d20SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ OBJE');
86220b58d20SGreg Roach        }
86320b58d20SGreg Roach
86420b58d20SGreg Roach        $xref   = $this->getNewXref();
865bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ OBJE' . Str::after($gedcom, '0 @@ OBJE');
86620b58d20SGreg Roach
86720b58d20SGreg Roach        // Create a change record
86820b58d20SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
86920b58d20SGreg Roach
87020b58d20SGreg Roach        // Create a pending change
871963fbaeeSGreg Roach        DB::table('change')->insert([
872963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
873963fbaeeSGreg Roach            'xref'       => $xref,
874963fbaeeSGreg Roach            'old_gedcom' => '',
875963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
876963fbaeeSGreg Roach            'user_id'    => Auth::id(),
87720b58d20SGreg Roach        ]);
87820b58d20SGreg Roach
87920b58d20SGreg Roach        // Accept this pending change
88020b58d20SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
88120b58d20SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
88220b58d20SGreg Roach
88320b58d20SGreg Roach            return new Media($xref, $gedcom, null, $this);
88420b58d20SGreg Roach        }
88520b58d20SGreg Roach
88620b58d20SGreg Roach        return new Media($xref, '', $gedcom, $this);
88720b58d20SGreg Roach    }
88820b58d20SGreg Roach
88920b58d20SGreg Roach    /**
8908586983fSGreg Roach     * What is the most significant individual in this tree.
8918586983fSGreg Roach     *
8928586983fSGreg Roach     * @param User $user
8938586983fSGreg Roach     *
8948586983fSGreg Roach     * @return Individual
8958586983fSGreg Roach     */
896c1010edaSGreg Roach    public function significantIndividual(User $user): Individual
897c1010edaSGreg Roach    {
8988f9b0fb2SGreg Roach        $individual = null;
8998586983fSGreg Roach
9008f9b0fb2SGreg Roach        if ($this->getUserPreference($user, 'rootid') !== '') {
9018586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
9028586983fSGreg Roach        }
9038f9b0fb2SGreg Roach
9048f9b0fb2SGreg Roach        if ($individual === null && $this->getUserPreference($user, 'gedcomid') !== '') {
9058586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
9068586983fSGreg Roach        }
9078f9b0fb2SGreg Roach
908bec87e94SGreg Roach        if ($individual === null && $this->getPreference('PEDIGREE_ROOT_ID') !== '') {
9098586983fSGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
9108586983fSGreg Roach        }
9118f9b0fb2SGreg Roach        if ($individual === null) {
9128f9b0fb2SGreg Roach            $xref = (string) DB::table('individuals')
9138f9b0fb2SGreg Roach                ->where('i_file', '=', $this->id())
9148f9b0fb2SGreg Roach                ->min('i_id');
915769d7d6eSGreg Roach
916769d7d6eSGreg Roach            $individual = Individual::getInstance($xref, $this);
9175fe1add5SGreg Roach        }
9188f9b0fb2SGreg Roach        if ($individual === null) {
9195fe1add5SGreg Roach            // always return a record
9205fe1add5SGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
9215fe1add5SGreg Roach        }
9225fe1add5SGreg Roach
9235fe1add5SGreg Roach        return $individual;
9245fe1add5SGreg Roach    }
925a25f0a04SGreg Roach}
926