xref: /webtrees/app/Tree.php (revision 1df7ae396bce24bdf88df379ef175b25f4155d1a)
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;
25a69f5655SGreg Roachuse Illuminate\Database\Query\Expression;
2601461f86SGreg Roachuse Illuminate\Database\Query\JoinClause;
2794026f20SGreg Roachuse Illuminate\Support\Collection;
28bec87e94SGreg Roachuse Illuminate\Support\Str;
29afb591d7SGreg Roachuse InvalidArgumentException;
30*1df7ae39SGreg Roachuse League\Flysystem\Adapter\Local;
31*1df7ae39SGreg Roachuse League\Flysystem\Cached\CachedAdapter;
32*1df7ae39SGreg Roachuse League\Flysystem\Cached\Storage\Memory;
33*1df7ae39SGreg Roachuse League\Flysystem\Filesystem;
34*1df7ae39SGreg Roachuse League\Flysystem\FilesystemInterface;
35a25f0a04SGreg Roachuse PDOException;
366ccdf4f0SGreg Roachuse Psr\Http\Message\StreamInterface;
378b67c11aSGreg Roachuse stdClass;
38a25f0a04SGreg Roach
39a25f0a04SGreg Roach/**
4076692c8bSGreg Roach * Provide an interface to the wt_gedcom table.
41a25f0a04SGreg Roach */
42c1010edaSGreg Roachclass Tree
43c1010edaSGreg Roach{
44061b43d7SGreg Roach    private const RESN_PRIVACY = [
45061b43d7SGreg Roach        'none'         => Auth::PRIV_PRIVATE,
46061b43d7SGreg Roach        'privacy'      => Auth::PRIV_USER,
47061b43d7SGreg Roach        'confidential' => Auth::PRIV_NONE,
48061b43d7SGreg Roach        'hidden'       => Auth::PRIV_HIDE,
49061b43d7SGreg Roach    ];
506ccdf4f0SGreg Roach    /** @var Tree[] All trees that we have permission to see, indexed by ID. */
516ccdf4f0SGreg Roach    public static $trees = [];
526ccdf4f0SGreg Roach    /** @var int The tree's ID number */
536ccdf4f0SGreg Roach    private $id;
546ccdf4f0SGreg Roach    /** @var string The tree's name */
556ccdf4f0SGreg Roach    private $name;
566ccdf4f0SGreg Roach    /** @var string The tree's title */
576ccdf4f0SGreg Roach    private $title;
586ccdf4f0SGreg Roach    /** @var int[] Default access rules for facts in this tree */
596ccdf4f0SGreg Roach    private $fact_privacy;
606ccdf4f0SGreg Roach    /** @var int[] Default access rules for individuals in this tree */
616ccdf4f0SGreg Roach    private $individual_privacy;
626ccdf4f0SGreg Roach    /** @var integer[][] Default access rules for individual facts in this tree */
636ccdf4f0SGreg Roach    private $individual_fact_privacy;
646ccdf4f0SGreg Roach    /** @var string[] Cached copy of the wt_gedcom_setting table. */
656ccdf4f0SGreg Roach    private $preferences = [];
666ccdf4f0SGreg Roach    /** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
676ccdf4f0SGreg Roach    private $user_preferences = [];
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    /**
1086ccdf4f0SGreg Roach     * Find the tree with a specific ID.
109a25f0a04SGreg Roach     *
1106ccdf4f0SGreg Roach     * @param int $tree_id
1116ccdf4f0SGreg Roach     *
1126ccdf4f0SGreg Roach     * @return Tree
113a25f0a04SGreg Roach     */
1146ccdf4f0SGreg Roach    public static function findById(int $tree_id): Tree
115c1010edaSGreg Roach    {
1166ccdf4f0SGreg Roach        return self::getAll()[$tree_id];
117a25f0a04SGreg Roach    }
118a25f0a04SGreg Roach
119a25f0a04SGreg Roach    /**
1206ccdf4f0SGreg Roach     * Fetch all the trees that we have permission to access.
121a25f0a04SGreg Roach     *
1226ccdf4f0SGreg Roach     * @return Tree[]
123a25f0a04SGreg Roach     */
1246ccdf4f0SGreg Roach    public static function getAll(): array
125c1010edaSGreg Roach    {
1266ccdf4f0SGreg Roach        if (empty(self::$trees)) {
1276ccdf4f0SGreg Roach            self::$trees = self::all()->all();
128a25f0a04SGreg Roach        }
129a25f0a04SGreg Roach
1306ccdf4f0SGreg Roach        return self::$trees;
131a25f0a04SGreg Roach    }
132a25f0a04SGreg Roach
133a25f0a04SGreg Roach    /**
1348b67c11aSGreg Roach     * All the trees that we have permission to access.
135a25f0a04SGreg Roach     *
13654c7f8dfSGreg Roach     * @return Collection
137a25f0a04SGreg Roach     */
1388b67c11aSGreg Roach    public static function all(): Collection
139c1010edaSGreg Roach    {
1400b5fd0a6SGreg Roach        return app('cache.array')->rememberForever(__CLASS__, static function (): Collection {
14101461f86SGreg Roach            // Admins see all trees
14201461f86SGreg Roach            $query = DB::table('gedcom')
1430b5fd0a6SGreg Roach                ->leftJoin('gedcom_setting', static function (JoinClause $join): void {
14401461f86SGreg Roach                    $join->on('gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
14501461f86SGreg Roach                        ->where('gedcom_setting.setting_name', '=', 'title');
14601461f86SGreg Roach                })
14701461f86SGreg Roach                ->where('gedcom.gedcom_id', '>', 0)
14801461f86SGreg Roach                ->select([
14901461f86SGreg Roach                    'gedcom.gedcom_id AS tree_id',
15001461f86SGreg Roach                    'gedcom.gedcom_name AS tree_name',
15101461f86SGreg Roach                    'gedcom_setting.setting_value AS tree_title',
15201461f86SGreg Roach                ])
15301461f86SGreg Roach                ->orderBy('gedcom.sort_order')
15401461f86SGreg Roach                ->orderBy('gedcom_setting.setting_value');
15501461f86SGreg Roach
15632f20c14SGreg Roach            // Non-admins may not see all trees
15732f20c14SGreg Roach            if (!Auth::isAdmin()) {
15801461f86SGreg Roach                $query
1590b5fd0a6SGreg Roach                    ->join('gedcom_setting AS gs2', static function (JoinClause $join): void {
16036357577SGreg Roach                        $join->on('gs2.gedcom_id', '=', 'gedcom.gedcom_id')
16101461f86SGreg Roach                            ->where('gs2.setting_name', '=', 'imported');
16236357577SGreg Roach                    })
1630b5fd0a6SGreg Roach                    ->join('gedcom_setting AS gs3', static function (JoinClause $join): void {
16401461f86SGreg Roach                        $join->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
16501461f86SGreg Roach                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
16601461f86SGreg Roach                    })
1670b5fd0a6SGreg Roach                    ->leftJoin('user_gedcom_setting', static function (JoinClause $join): void {
16801461f86SGreg Roach                        $join->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
16901461f86SGreg Roach                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
17001461f86SGreg Roach                            ->where('user_gedcom_setting.setting_name', '=', 'canedit');
17101461f86SGreg Roach                    })
1720b5fd0a6SGreg Roach                    ->where(static function (Builder $query): void {
17301461f86SGreg Roach                        $query
17401461f86SGreg Roach                            // Managers
17501461f86SGreg Roach                            ->where('user_gedcom_setting.setting_value', '=', 'admin')
17601461f86SGreg Roach                            // Members
1770b5fd0a6SGreg Roach                            ->orWhere(static function (Builder $query): void {
17801461f86SGreg Roach                                $query
17901461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
18001461f86SGreg Roach                                    ->where('gs3.setting_value', '=', '1')
18101461f86SGreg Roach                                    ->where('user_gedcom_setting.setting_value', '<>', 'none');
18201461f86SGreg Roach                            })
1838b67c11aSGreg Roach                            // Public trees
1840b5fd0a6SGreg Roach                            ->orWhere(static function (Builder $query): void {
18501461f86SGreg Roach                                $query
18601461f86SGreg Roach                                    ->where('gs2.setting_value', '=', '1')
18736357577SGreg Roach                                    ->where('gs3.setting_value', '<>', '1');
18801461f86SGreg Roach                            });
18901461f86SGreg Roach                    });
19001461f86SGreg Roach            }
19101461f86SGreg Roach
1928b67c11aSGreg Roach            return $query
1938b67c11aSGreg Roach                ->get()
1940b5fd0a6SGreg Roach                ->mapWithKeys(static function (stdClass $row): array {
1958b67c11aSGreg Roach                    return [$row->tree_id => new self((int) $row->tree_id, $row->tree_name, $row->tree_title)];
1968b67c11aSGreg Roach                });
1978b67c11aSGreg Roach        });
198a25f0a04SGreg Roach    }
1998b67c11aSGreg Roach
2008b67c11aSGreg Roach    /**
201a25f0a04SGreg Roach     * Create arguments to select_edit_control()
202a25f0a04SGreg Roach     * Note - these will be escaped later
203a25f0a04SGreg Roach     *
204a25f0a04SGreg Roach     * @return string[]
205a25f0a04SGreg Roach     */
206771ae10aSGreg Roach    public static function getIdList(): array
207c1010edaSGreg Roach    {
20813abd6f3SGreg Roach        $list = [];
209a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
21072cf66d4SGreg Roach            $list[$tree->id] = $tree->title;
211a25f0a04SGreg Roach        }
212a25f0a04SGreg Roach
213a25f0a04SGreg Roach        return $list;
214a25f0a04SGreg Roach    }
215a25f0a04SGreg Roach
216a25f0a04SGreg Roach    /**
217a25f0a04SGreg Roach     * Create arguments to select_edit_control()
218a25f0a04SGreg Roach     * Note - these will be escaped later
219a25f0a04SGreg Roach     *
220a25f0a04SGreg Roach     * @return string[]
221a25f0a04SGreg Roach     */
222771ae10aSGreg Roach    public static function getNameList(): array
223c1010edaSGreg Roach    {
22413abd6f3SGreg Roach        $list = [];
225a25f0a04SGreg Roach        foreach (self::getAll() as $tree) {
226a25f0a04SGreg Roach            $list[$tree->name] = $tree->title;
227a25f0a04SGreg Roach        }
228a25f0a04SGreg Roach
229a25f0a04SGreg Roach        return $list;
230a25f0a04SGreg Roach    }
231a25f0a04SGreg Roach
232a25f0a04SGreg Roach    /**
233a25f0a04SGreg Roach     * Create a new tree
234a25f0a04SGreg Roach     *
235a25f0a04SGreg Roach     * @param string $tree_name
236a25f0a04SGreg Roach     * @param string $tree_title
237a25f0a04SGreg Roach     *
238a25f0a04SGreg Roach     * @return Tree
239a25f0a04SGreg Roach     */
240771ae10aSGreg Roach    public static function create(string $tree_name, string $tree_title): Tree
241c1010edaSGreg Roach    {
242a25f0a04SGreg Roach        try {
243a25f0a04SGreg Roach            // Create a new tree
24401461f86SGreg Roach            DB::table('gedcom')->insert([
24501461f86SGreg Roach                'gedcom_name' => $tree_name,
24601461f86SGreg Roach            ]);
2474a86d714SGreg Roach
248061b43d7SGreg Roach            $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
24932f20c14SGreg Roach
25032f20c14SGreg Roach            $tree = new self($tree_id, $tree_name, $tree_title);
251a25f0a04SGreg Roach        } catch (PDOException $ex) {
252a25f0a04SGreg Roach            // A tree with that name already exists?
253ef2fd529SGreg Roach            return self::findByName($tree_name);
254a25f0a04SGreg Roach        }
255a25f0a04SGreg Roach
256a25f0a04SGreg Roach        $tree->setPreference('imported', '0');
257a25f0a04SGreg Roach        $tree->setPreference('title', $tree_title);
258a25f0a04SGreg Roach
2591507cbcaSGreg Roach        // Set preferences from default tree
260061b43d7SGreg Roach        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
261061b43d7SGreg Roach            ['gedcom_id', 'setting_name', 'setting_value'],
2626ccdf4f0SGreg Roach            static function (Builder $query) use ($tree_id): void {
263061b43d7SGreg Roach                $query
264a69f5655SGreg Roach                    ->select([new Expression($tree_id), 'setting_name', 'setting_value'])
265061b43d7SGreg Roach                    ->from('gedcom_setting')
266061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
267061b43d7SGreg Roach            }
268061b43d7SGreg Roach        );
2691507cbcaSGreg Roach
270061b43d7SGreg Roach        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
271061b43d7SGreg Roach            ['gedcom_id', 'tag_type', 'resn'],
2726c2179e2SGreg Roach            static function (Builder $query) use ($tree_id): void {
273061b43d7SGreg Roach                $query
274a69f5655SGreg Roach                    ->select([new Expression($tree_id), 'tag_type', 'resn'])
275061b43d7SGreg Roach                    ->from('default_resn')
276061b43d7SGreg Roach                    ->where('gedcom_id', '=', -1);
277061b43d7SGreg Roach            }
278061b43d7SGreg Roach        );
2791507cbcaSGreg Roach
280a25f0a04SGreg Roach        // Gedcom and privacy settings
28176f666f4SGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
28276f666f4SGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
283a25f0a04SGreg Roach        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
284e364afe4SGreg Roach
285a25f0a04SGreg Roach        switch (WT_LOCALE) {
286a25f0a04SGreg Roach            case 'es':
287a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'spanish');
288a25f0a04SGreg Roach                break;
289a25f0a04SGreg Roach            case 'is':
290a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
291a25f0a04SGreg Roach                break;
292a25f0a04SGreg Roach            case 'lt':
293a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
294a25f0a04SGreg Roach                break;
295a25f0a04SGreg Roach            case 'pl':
296a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'polish');
297a25f0a04SGreg Roach                break;
298a25f0a04SGreg Roach            case 'pt':
299a25f0a04SGreg Roach            case 'pt-BR':
300a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
301a25f0a04SGreg Roach                break;
302a25f0a04SGreg Roach            default:
303a25f0a04SGreg Roach                $tree->setPreference('SURNAME_TRADITION', 'paternal');
304a25f0a04SGreg Roach                break;
305a25f0a04SGreg Roach        }
306a25f0a04SGreg Roach
307a25f0a04SGreg Roach        // Genealogy data
308a25f0a04SGreg Roach        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
309bbb76c12SGreg Roach        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
310bbb76c12SGreg Roach        $john_doe = I18N::translate('John /DOE/');
31177e70a22SGreg Roach        $note     = I18N::translate('Edit this individual and replace their details with your own.');
312061b43d7SGreg 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";
313061b43d7SGreg Roach
314061b43d7SGreg Roach        DB::table('gedcom_chunk')->insert([
315061b43d7SGreg Roach            'gedcom_id'  => $tree_id,
316061b43d7SGreg Roach            'chunk_data' => $gedcom,
31713abd6f3SGreg Roach        ]);
318a25f0a04SGreg Roach
319a25f0a04SGreg Roach        // Update our cache
32072cf66d4SGreg Roach        self::$trees[$tree->id] = $tree;
321a25f0a04SGreg Roach
322a25f0a04SGreg Roach        return $tree;
323a25f0a04SGreg Roach    }
324a25f0a04SGreg Roach
325a25f0a04SGreg Roach    /**
3266ccdf4f0SGreg Roach     * Find the tree with a specific name.
3276ccdf4f0SGreg Roach     *
3286ccdf4f0SGreg Roach     * @param string $tree_name
3296ccdf4f0SGreg Roach     *
3306ccdf4f0SGreg Roach     * @return Tree|null
3316ccdf4f0SGreg Roach     */
3326ccdf4f0SGreg Roach    public static function findByName($tree_name): ?Tree
3336ccdf4f0SGreg Roach    {
3346ccdf4f0SGreg Roach        foreach (self::getAll() as $tree) {
3356ccdf4f0SGreg Roach            if ($tree->name === $tree_name) {
3366ccdf4f0SGreg Roach                return $tree;
3376ccdf4f0SGreg Roach            }
3386ccdf4f0SGreg Roach        }
3396ccdf4f0SGreg Roach
3406ccdf4f0SGreg Roach        return null;
3416ccdf4f0SGreg Roach    }
3426ccdf4f0SGreg Roach
3436ccdf4f0SGreg Roach    /**
3446ccdf4f0SGreg Roach     * Set the tree’s configuration settings.
3456ccdf4f0SGreg Roach     *
3466ccdf4f0SGreg Roach     * @param string $setting_name
3476ccdf4f0SGreg Roach     * @param string $setting_value
3486ccdf4f0SGreg Roach     *
3496ccdf4f0SGreg Roach     * @return $this
3506ccdf4f0SGreg Roach     */
3516ccdf4f0SGreg Roach    public function setPreference(string $setting_name, string $setting_value): Tree
3526ccdf4f0SGreg Roach    {
3536ccdf4f0SGreg Roach        if ($setting_value !== $this->getPreference($setting_name)) {
3546ccdf4f0SGreg Roach            DB::table('gedcom_setting')->updateOrInsert([
3556ccdf4f0SGreg Roach                'gedcom_id'    => $this->id,
3566ccdf4f0SGreg Roach                'setting_name' => $setting_name,
3576ccdf4f0SGreg Roach            ], [
3586ccdf4f0SGreg Roach                'setting_value' => $setting_value,
3596ccdf4f0SGreg Roach            ]);
3606ccdf4f0SGreg Roach
3616ccdf4f0SGreg Roach            $this->preferences[$setting_name] = $setting_value;
3626ccdf4f0SGreg Roach
3636ccdf4f0SGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
3646ccdf4f0SGreg Roach        }
3656ccdf4f0SGreg Roach
3666ccdf4f0SGreg Roach        return $this;
3676ccdf4f0SGreg Roach    }
3686ccdf4f0SGreg Roach
3696ccdf4f0SGreg Roach    /**
3706ccdf4f0SGreg Roach     * Get the tree’s configuration settings.
3716ccdf4f0SGreg Roach     *
3726ccdf4f0SGreg Roach     * @param string $setting_name
3736ccdf4f0SGreg Roach     * @param string $default
3746ccdf4f0SGreg Roach     *
3756ccdf4f0SGreg Roach     * @return string
3766ccdf4f0SGreg Roach     */
3776ccdf4f0SGreg Roach    public function getPreference(string $setting_name, string $default = ''): string
3786ccdf4f0SGreg Roach    {
3796ccdf4f0SGreg Roach        if (empty($this->preferences)) {
3806ccdf4f0SGreg Roach            $this->preferences = DB::table('gedcom_setting')
3816ccdf4f0SGreg Roach                ->where('gedcom_id', '=', $this->id)
3826ccdf4f0SGreg Roach                ->pluck('setting_value', 'setting_name')
3836ccdf4f0SGreg Roach                ->all();
3846ccdf4f0SGreg Roach        }
3856ccdf4f0SGreg Roach
3866ccdf4f0SGreg Roach        return $this->preferences[$setting_name] ?? $default;
3876ccdf4f0SGreg Roach    }
3886ccdf4f0SGreg Roach
3896ccdf4f0SGreg Roach    /**
3906ccdf4f0SGreg Roach     * The name of this tree
3916ccdf4f0SGreg Roach     *
3926ccdf4f0SGreg Roach     * @return string
3936ccdf4f0SGreg Roach     */
3946ccdf4f0SGreg Roach    public function name(): string
3956ccdf4f0SGreg Roach    {
3966ccdf4f0SGreg Roach        return $this->name;
3976ccdf4f0SGreg Roach    }
3986ccdf4f0SGreg Roach
3996ccdf4f0SGreg Roach    /**
4006ccdf4f0SGreg Roach     * The title of this tree
4016ccdf4f0SGreg Roach     *
4026ccdf4f0SGreg Roach     * @return string
4036ccdf4f0SGreg Roach     */
4046ccdf4f0SGreg Roach    public function title(): string
4056ccdf4f0SGreg Roach    {
4066ccdf4f0SGreg Roach        return $this->title;
4076ccdf4f0SGreg Roach    }
4086ccdf4f0SGreg Roach
4096ccdf4f0SGreg Roach    /**
4106ccdf4f0SGreg Roach     * The fact-level privacy for this tree.
4116ccdf4f0SGreg Roach     *
4126ccdf4f0SGreg Roach     * @return int[]
4136ccdf4f0SGreg Roach     */
4146ccdf4f0SGreg Roach    public function getFactPrivacy(): array
4156ccdf4f0SGreg Roach    {
4166ccdf4f0SGreg Roach        return $this->fact_privacy;
4176ccdf4f0SGreg Roach    }
4186ccdf4f0SGreg Roach
4196ccdf4f0SGreg Roach    /**
4206ccdf4f0SGreg Roach     * The individual-level privacy for this tree.
4216ccdf4f0SGreg Roach     *
4226ccdf4f0SGreg Roach     * @return int[]
4236ccdf4f0SGreg Roach     */
4246ccdf4f0SGreg Roach    public function getIndividualPrivacy(): array
4256ccdf4f0SGreg Roach    {
4266ccdf4f0SGreg Roach        return $this->individual_privacy;
4276ccdf4f0SGreg Roach    }
4286ccdf4f0SGreg Roach
4296ccdf4f0SGreg Roach    /**
4306ccdf4f0SGreg Roach     * The individual-fact-level privacy for this tree.
4316ccdf4f0SGreg Roach     *
4326ccdf4f0SGreg Roach     * @return int[][]
4336ccdf4f0SGreg Roach     */
4346ccdf4f0SGreg Roach    public function getIndividualFactPrivacy(): array
4356ccdf4f0SGreg Roach    {
4366ccdf4f0SGreg Roach        return $this->individual_fact_privacy;
4376ccdf4f0SGreg Roach    }
4386ccdf4f0SGreg Roach
4396ccdf4f0SGreg Roach    /**
4406ccdf4f0SGreg Roach     * Set the tree’s user-configuration settings.
4416ccdf4f0SGreg Roach     *
4426ccdf4f0SGreg Roach     * @param UserInterface $user
4436ccdf4f0SGreg Roach     * @param string        $setting_name
4446ccdf4f0SGreg Roach     * @param string        $setting_value
4456ccdf4f0SGreg Roach     *
4466ccdf4f0SGreg Roach     * @return $this
4476ccdf4f0SGreg Roach     */
4486ccdf4f0SGreg Roach    public function setUserPreference(UserInterface $user, string $setting_name, string $setting_value): Tree
4496ccdf4f0SGreg Roach    {
4506ccdf4f0SGreg Roach        if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
4516ccdf4f0SGreg Roach            // Update the database
4526ccdf4f0SGreg Roach            DB::table('user_gedcom_setting')->updateOrInsert([
4536ccdf4f0SGreg Roach                'gedcom_id'    => $this->id(),
4546ccdf4f0SGreg Roach                'user_id'      => $user->id(),
4556ccdf4f0SGreg Roach                'setting_name' => $setting_name,
4566ccdf4f0SGreg Roach            ], [
4576ccdf4f0SGreg Roach                'setting_value' => $setting_value,
4586ccdf4f0SGreg Roach            ]);
4596ccdf4f0SGreg Roach
4606ccdf4f0SGreg Roach            // Update the cache
4616ccdf4f0SGreg Roach            $this->user_preferences[$user->id()][$setting_name] = $setting_value;
4626ccdf4f0SGreg Roach            // Audit log of changes
4636ccdf4f0SGreg Roach            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->userName() . '"', $this);
4646ccdf4f0SGreg Roach        }
4656ccdf4f0SGreg Roach
4666ccdf4f0SGreg Roach        return $this;
4676ccdf4f0SGreg Roach    }
4686ccdf4f0SGreg Roach
4696ccdf4f0SGreg Roach    /**
4706ccdf4f0SGreg Roach     * Get the tree’s user-configuration settings.
4716ccdf4f0SGreg Roach     *
4726ccdf4f0SGreg Roach     * @param UserInterface $user
4736ccdf4f0SGreg Roach     * @param string        $setting_name
4746ccdf4f0SGreg Roach     * @param string        $default
4756ccdf4f0SGreg Roach     *
4766ccdf4f0SGreg Roach     * @return string
4776ccdf4f0SGreg Roach     */
4786ccdf4f0SGreg Roach    public function getUserPreference(UserInterface $user, string $setting_name, string $default = ''): string
4796ccdf4f0SGreg Roach    {
4806ccdf4f0SGreg Roach        // There are lots of settings, and we need to fetch lots of them on every page
4816ccdf4f0SGreg Roach        // so it is quicker to fetch them all in one go.
4826ccdf4f0SGreg Roach        if (!array_key_exists($user->id(), $this->user_preferences)) {
4836ccdf4f0SGreg Roach            $this->user_preferences[$user->id()] = DB::table('user_gedcom_setting')
4846ccdf4f0SGreg Roach                ->where('user_id', '=', $user->id())
4856ccdf4f0SGreg Roach                ->where('gedcom_id', '=', $this->id)
4866ccdf4f0SGreg Roach                ->pluck('setting_value', 'setting_name')
4876ccdf4f0SGreg Roach                ->all();
4886ccdf4f0SGreg Roach        }
4896ccdf4f0SGreg Roach
4906ccdf4f0SGreg Roach        return $this->user_preferences[$user->id()][$setting_name] ?? $default;
4916ccdf4f0SGreg Roach    }
4926ccdf4f0SGreg Roach
4936ccdf4f0SGreg Roach    /**
4946ccdf4f0SGreg Roach     * The ID of this tree
4956ccdf4f0SGreg Roach     *
4966ccdf4f0SGreg Roach     * @return int
4976ccdf4f0SGreg Roach     */
4986ccdf4f0SGreg Roach    public function id(): int
4996ccdf4f0SGreg Roach    {
5006ccdf4f0SGreg Roach        return $this->id;
5016ccdf4f0SGreg Roach    }
5026ccdf4f0SGreg Roach
5036ccdf4f0SGreg Roach    /**
5046ccdf4f0SGreg Roach     * Can a user accept changes for this tree?
5056ccdf4f0SGreg Roach     *
5066ccdf4f0SGreg Roach     * @param UserInterface $user
5076ccdf4f0SGreg Roach     *
5086ccdf4f0SGreg Roach     * @return bool
5096ccdf4f0SGreg Roach     */
5106ccdf4f0SGreg Roach    public function canAcceptChanges(UserInterface $user): bool
5116ccdf4f0SGreg Roach    {
5126ccdf4f0SGreg Roach        return Auth::isModerator($this, $user);
5136ccdf4f0SGreg Roach    }
5146ccdf4f0SGreg Roach
5156ccdf4f0SGreg 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    /**
5296ccdf4f0SGreg Roach     * Delete everything relating to a tree
5306ccdf4f0SGreg Roach     *
5316ccdf4f0SGreg Roach     * @return void
5326ccdf4f0SGreg Roach     */
5336ccdf4f0SGreg Roach    public function delete(): void
5346ccdf4f0SGreg Roach    {
5356ccdf4f0SGreg Roach        // If this is the default tree, then unset it
5366ccdf4f0SGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
5376ccdf4f0SGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
5386ccdf4f0SGreg Roach        }
5396ccdf4f0SGreg Roach
5406ccdf4f0SGreg Roach        $this->deleteGenealogyData(false);
5416ccdf4f0SGreg Roach
5426ccdf4f0SGreg Roach        DB::table('block_setting')
5436ccdf4f0SGreg Roach            ->join('block', 'block.block_id', '=', 'block_setting.block_id')
5446ccdf4f0SGreg Roach            ->where('gedcom_id', '=', $this->id)
5456ccdf4f0SGreg Roach            ->delete();
5466ccdf4f0SGreg Roach        DB::table('block')->where('gedcom_id', '=', $this->id)->delete();
5476ccdf4f0SGreg Roach        DB::table('user_gedcom_setting')->where('gedcom_id', '=', $this->id)->delete();
5486ccdf4f0SGreg Roach        DB::table('gedcom_setting')->where('gedcom_id', '=', $this->id)->delete();
5496ccdf4f0SGreg Roach        DB::table('module_privacy')->where('gedcom_id', '=', $this->id)->delete();
5506ccdf4f0SGreg Roach        DB::table('hit_counter')->where('gedcom_id', '=', $this->id)->delete();
5516ccdf4f0SGreg Roach        DB::table('default_resn')->where('gedcom_id', '=', $this->id)->delete();
5526ccdf4f0SGreg Roach        DB::table('gedcom_chunk')->where('gedcom_id', '=', $this->id)->delete();
5536ccdf4f0SGreg Roach        DB::table('log')->where('gedcom_id', '=', $this->id)->delete();
5546ccdf4f0SGreg Roach        DB::table('gedcom')->where('gedcom_id', '=', $this->id)->delete();
5556ccdf4f0SGreg Roach
5566ccdf4f0SGreg Roach        // After updating the database, we need to fetch a new (sorted) copy
5576ccdf4f0SGreg Roach        self::$trees = [];
5586ccdf4f0SGreg Roach    }
5596ccdf4f0SGreg Roach
5606ccdf4f0SGreg Roach    /**
561a25f0a04SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
562a25f0a04SGreg Roach     * new data. Optionally retain the media data, for when the user has been
563a25f0a04SGreg Roach     * editing their data offline using an application which deletes (or does not
564a25f0a04SGreg Roach     * support) media data.
565a25f0a04SGreg Roach     *
566a25f0a04SGreg Roach     * @param bool $keep_media
567b7e60af1SGreg Roach     *
568b7e60af1SGreg Roach     * @return void
569a25f0a04SGreg Roach     */
570e364afe4SGreg Roach    public function deleteGenealogyData(bool $keep_media): void
571c1010edaSGreg Roach    {
5721ad2dde6SGreg Roach        DB::table('gedcom_chunk')->where('gedcom_id', '=', $this->id)->delete();
5731ad2dde6SGreg Roach        DB::table('individuals')->where('i_file', '=', $this->id)->delete();
5741ad2dde6SGreg Roach        DB::table('families')->where('f_file', '=', $this->id)->delete();
5751ad2dde6SGreg Roach        DB::table('sources')->where('s_file', '=', $this->id)->delete();
5761ad2dde6SGreg Roach        DB::table('other')->where('o_file', '=', $this->id)->delete();
5771ad2dde6SGreg Roach        DB::table('places')->where('p_file', '=', $this->id)->delete();
5781ad2dde6SGreg Roach        DB::table('placelinks')->where('pl_file', '=', $this->id)->delete();
5791ad2dde6SGreg Roach        DB::table('name')->where('n_file', '=', $this->id)->delete();
5801ad2dde6SGreg Roach        DB::table('dates')->where('d_file', '=', $this->id)->delete();
5811ad2dde6SGreg Roach        DB::table('change')->where('gedcom_id', '=', $this->id)->delete();
582a25f0a04SGreg Roach
583a25f0a04SGreg Roach        if ($keep_media) {
5841ad2dde6SGreg Roach            DB::table('link')->where('l_file', '=', $this->id)
5851ad2dde6SGreg Roach                ->where('l_type', '<>', 'OBJE')
5861ad2dde6SGreg Roach                ->delete();
587a25f0a04SGreg Roach        } else {
5881ad2dde6SGreg Roach            DB::table('link')->where('l_file', '=', $this->id)->delete();
5891ad2dde6SGreg Roach            DB::table('media_file')->where('m_file', '=', $this->id)->delete();
5901ad2dde6SGreg Roach            DB::table('media')->where('m_file', '=', $this->id)->delete();
591a25f0a04SGreg Roach        }
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     */
601425af8b9SGreg Roach    public function exportGedcom($stream): void
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)
607a69f5655SGreg Roach            ->select(['f_gedcom AS gedcom', 'f_id AS xref', new Expression('LENGTH(f_id) AS len'), new Expression('2 AS n')]);
60894026f20SGreg Roach
60994026f20SGreg Roach        $union_sources = DB::table('sources')
61094026f20SGreg Roach            ->where('s_file', '=', $this->id)
611a69f5655SGreg Roach            ->select(['s_gedcom AS gedcom', 's_id AS xref', new Expression('LENGTH(s_id) AS len'), new Expression('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'])
616a69f5655SGreg Roach            ->select(['o_gedcom AS gedcom', 'o_id AS xref', new Expression('LENGTH(o_id) AS len'), new Expression('4 AS n')]);
61794026f20SGreg Roach
61894026f20SGreg Roach        $union_media = DB::table('media')
61994026f20SGreg Roach            ->where('m_file', '=', $this->id)
620a69f5655SGreg Roach            ->select(['m_gedcom AS gedcom', 'm_id AS xref', new Expression('LENGTH(m_id) AS len'), new Expression('5 AS n')]);
62194026f20SGreg Roach
622e5a6b4d4SGreg Roach        DB::table('individuals')
62394026f20SGreg Roach            ->where('i_file', '=', $this->id)
624a69f5655SGreg Roach            ->select(['i_gedcom AS gedcom', 'i_id AS xref', new Expression('LENGTH(i_id) AS len'), new Expression('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')
63227825e0aSGreg Roach            ->chunk(1000, static 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     *
6486ccdf4f0SGreg Roach     * @param StreamInterface $stream   The GEDCOM file.
649a25f0a04SGreg Roach     * @param string          $filename The preferred filename, for export/download.
650a25f0a04SGreg Roach     *
651b7e60af1SGreg Roach     * @return void
652a25f0a04SGreg Roach     */
6536ccdf4f0SGreg Roach    public function importGedcomFile(StreamInterface $stream, string $filename): void
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
662b7e60af1SGreg Roach        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
663a25f0a04SGreg Roach        $this->setPreference('gedcom_filename', $filename);
664a25f0a04SGreg Roach        $this->setPreference('imported', '0');
665a25f0a04SGreg Roach
6666ccdf4f0SGreg Roach        while (!$stream->eof()) {
6676ccdf4f0SGreg Roach            $file_data .= $stream->read(65536);
668a25f0a04SGreg Roach            // There is no strrpos() function that searches for substrings :-(
669a25f0a04SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
670a25f0a04SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
671a25f0a04SGreg Roach                    // We’ve found the last record boundary in this chunk of data
672a25f0a04SGreg Roach                    break;
673a25f0a04SGreg Roach                }
674a25f0a04SGreg Roach            }
675a25f0a04SGreg Roach            if ($pos) {
6761ad2dde6SGreg Roach                DB::table('gedcom_chunk')->insert([
6771ad2dde6SGreg Roach                    'gedcom_id'  => $this->id,
6781ad2dde6SGreg Roach                    'chunk_data' => substr($file_data, 0, $pos),
679c1010edaSGreg Roach                ]);
6801ad2dde6SGreg Roach
681a25f0a04SGreg Roach                $file_data = substr($file_data, $pos);
682a25f0a04SGreg Roach            }
683a25f0a04SGreg Roach        }
6841ad2dde6SGreg Roach        DB::table('gedcom_chunk')->insert([
6851ad2dde6SGreg Roach            'gedcom_id'  => $this->id,
6861ad2dde6SGreg Roach            'chunk_data' => $file_data,
687c1010edaSGreg Roach        ]);
688a25f0a04SGreg Roach
6896ccdf4f0SGreg Roach        $stream->close();
6906ccdf4f0SGreg Roach    }
6916ccdf4f0SGreg Roach
6926ccdf4f0SGreg Roach    /**
6936ccdf4f0SGreg Roach     * Create a new record from GEDCOM data.
6946ccdf4f0SGreg Roach     *
6956ccdf4f0SGreg Roach     * @param string $gedcom
6966ccdf4f0SGreg Roach     *
6976ccdf4f0SGreg Roach     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
6986ccdf4f0SGreg Roach     * @throws InvalidArgumentException
6996ccdf4f0SGreg Roach     */
7006ccdf4f0SGreg Roach    public function createRecord(string $gedcom): GedcomRecord
7016ccdf4f0SGreg Roach    {
7026ccdf4f0SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ ')) {
7036ccdf4f0SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createRecord(' . $gedcom . ') does not begin 0 @@');
7046ccdf4f0SGreg Roach        }
7056ccdf4f0SGreg Roach
7066ccdf4f0SGreg Roach        $xref   = $this->getNewXref();
7076ccdf4f0SGreg Roach        $gedcom = '0 @' . $xref . '@ ' . Str::after($gedcom, '0 @@ ');
7086ccdf4f0SGreg Roach
7096ccdf4f0SGreg Roach        // Create a change record
7106ccdf4f0SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
7116ccdf4f0SGreg Roach
7126ccdf4f0SGreg Roach        // Create a pending change
7136ccdf4f0SGreg Roach        DB::table('change')->insert([
7146ccdf4f0SGreg Roach            'gedcom_id'  => $this->id,
7156ccdf4f0SGreg Roach            'xref'       => $xref,
7166ccdf4f0SGreg Roach            'old_gedcom' => '',
7176ccdf4f0SGreg Roach            'new_gedcom' => $gedcom,
7186ccdf4f0SGreg Roach            'user_id'    => Auth::id(),
7196ccdf4f0SGreg Roach        ]);
7206ccdf4f0SGreg Roach
7216ccdf4f0SGreg Roach        // Accept this pending change
7226ccdf4f0SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
7236ccdf4f0SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
7246ccdf4f0SGreg Roach
7256ccdf4f0SGreg Roach            return new GedcomRecord($xref, $gedcom, null, $this);
7266ccdf4f0SGreg Roach        }
7276ccdf4f0SGreg Roach
7286ccdf4f0SGreg Roach        return GedcomRecord::getInstance($xref, $this, $gedcom);
729a25f0a04SGreg Roach    }
730304f20d5SGreg Roach
731304f20d5SGreg Roach    /**
732b90d8accSGreg Roach     * Generate a new XREF, unique across all family trees
733b90d8accSGreg Roach     *
734b90d8accSGreg Roach     * @return string
735b90d8accSGreg Roach     */
736771ae10aSGreg Roach    public function getNewXref(): string
737c1010edaSGreg Roach    {
738963fbaeeSGreg Roach        // Lock the row, so that only one new XREF may be generated at a time.
739963fbaeeSGreg Roach        DB::table('site_setting')
740963fbaeeSGreg Roach            ->where('setting_name', '=', 'next_xref')
741963fbaeeSGreg Roach            ->lockForUpdate()
742963fbaeeSGreg Roach            ->get();
743963fbaeeSGreg Roach
744a214e186SGreg Roach        $prefix = 'X';
745b90d8accSGreg Roach
746971d66c8SGreg Roach        $increment = 1.0;
747b90d8accSGreg Roach        do {
748963fbaeeSGreg Roach            $num = (int) Site::getPreference('next_xref') + (int) $increment;
749971d66c8SGreg Roach
750971d66c8SGreg Roach            // This exponential increment allows us to scan over large blocks of
751971d66c8SGreg Roach            // existing data in a reasonable time.
752971d66c8SGreg Roach            $increment *= 1.01;
753963fbaeeSGreg Roach
754963fbaeeSGreg Roach            $xref = $prefix . $num;
755963fbaeeSGreg Roach
756963fbaeeSGreg Roach            // Records may already exist with this sequence number.
757963fbaeeSGreg Roach            $already_used =
758963fbaeeSGreg Roach                DB::table('individuals')->where('i_id', '=', $xref)->exists() ||
759963fbaeeSGreg Roach                DB::table('families')->where('f_id', '=', $xref)->exists() ||
760963fbaeeSGreg Roach                DB::table('sources')->where('s_id', '=', $xref)->exists() ||
761963fbaeeSGreg Roach                DB::table('media')->where('m_id', '=', $xref)->exists() ||
762963fbaeeSGreg Roach                DB::table('other')->where('o_id', '=', $xref)->exists() ||
763963fbaeeSGreg Roach                DB::table('change')->where('xref', '=', $xref)->exists();
764963fbaeeSGreg Roach        } while ($already_used);
765963fbaeeSGreg Roach
766963fbaeeSGreg Roach        Site::setPreference('next_xref', (string) $num);
767b90d8accSGreg Roach
768a214e186SGreg Roach        return $xref;
769b90d8accSGreg Roach    }
770b90d8accSGreg Roach
771b90d8accSGreg Roach    /**
772afb591d7SGreg Roach     * Create a new family from GEDCOM data.
773afb591d7SGreg Roach     *
774afb591d7SGreg Roach     * @param string $gedcom
775afb591d7SGreg Roach     *
776afb591d7SGreg Roach     * @return Family
777afb591d7SGreg Roach     * @throws InvalidArgumentException
778afb591d7SGreg Roach     */
779afb591d7SGreg Roach    public function createFamily(string $gedcom): GedcomRecord
780afb591d7SGreg Roach    {
781bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ FAM')) {
782afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createFamily(' . $gedcom . ') does not begin 0 @@ FAM');
783afb591d7SGreg Roach        }
784afb591d7SGreg Roach
785afb591d7SGreg Roach        $xref   = $this->getNewXref();
786bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ FAM' . Str::after($gedcom, '0 @@ FAM');
787afb591d7SGreg Roach
788afb591d7SGreg Roach        // Create a change record
789e5a6b4d4SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
790afb591d7SGreg Roach
791afb591d7SGreg Roach        // Create a pending change
792963fbaeeSGreg Roach        DB::table('change')->insert([
793963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
794963fbaeeSGreg Roach            'xref'       => $xref,
795963fbaeeSGreg Roach            'old_gedcom' => '',
796963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
797963fbaeeSGreg Roach            'user_id'    => Auth::id(),
798afb591d7SGreg Roach        ]);
799304f20d5SGreg Roach
800304f20d5SGreg Roach        // Accept this pending change
801304f20d5SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
802cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
803afb591d7SGreg Roach
804afb591d7SGreg Roach            return new Family($xref, $gedcom, null, $this);
805304f20d5SGreg Roach        }
806afb591d7SGreg Roach
807afb591d7SGreg Roach        return new Family($xref, '', $gedcom, $this);
808afb591d7SGreg Roach    }
809afb591d7SGreg Roach
810afb591d7SGreg Roach    /**
811afb591d7SGreg Roach     * Create a new individual from GEDCOM data.
812afb591d7SGreg Roach     *
813afb591d7SGreg Roach     * @param string $gedcom
814afb591d7SGreg Roach     *
815afb591d7SGreg Roach     * @return Individual
816afb591d7SGreg Roach     * @throws InvalidArgumentException
817afb591d7SGreg Roach     */
818afb591d7SGreg Roach    public function createIndividual(string $gedcom): GedcomRecord
819afb591d7SGreg Roach    {
820bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ INDI')) {
821afb591d7SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ INDI');
822afb591d7SGreg Roach        }
823afb591d7SGreg Roach
824afb591d7SGreg Roach        $xref   = $this->getNewXref();
825bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ INDI' . Str::after($gedcom, '0 @@ INDI');
826afb591d7SGreg Roach
827afb591d7SGreg Roach        // Create a change record
828e5a6b4d4SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
829afb591d7SGreg Roach
830afb591d7SGreg Roach        // Create a pending change
831963fbaeeSGreg Roach        DB::table('change')->insert([
832963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
833963fbaeeSGreg Roach            'xref'       => $xref,
834963fbaeeSGreg Roach            'old_gedcom' => '',
835963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
836963fbaeeSGreg Roach            'user_id'    => Auth::id(),
837afb591d7SGreg Roach        ]);
838afb591d7SGreg Roach
839afb591d7SGreg Roach        // Accept this pending change
840afb591d7SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
841afb591d7SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
842afb591d7SGreg Roach
843afb591d7SGreg Roach            return new Individual($xref, $gedcom, null, $this);
844afb591d7SGreg Roach        }
845afb591d7SGreg Roach
846afb591d7SGreg Roach        return new Individual($xref, '', $gedcom, $this);
847304f20d5SGreg Roach    }
8488586983fSGreg Roach
8498586983fSGreg Roach    /**
85020b58d20SGreg Roach     * Create a new media object from GEDCOM data.
85120b58d20SGreg Roach     *
85220b58d20SGreg Roach     * @param string $gedcom
85320b58d20SGreg Roach     *
85420b58d20SGreg Roach     * @return Media
85520b58d20SGreg Roach     * @throws InvalidArgumentException
85620b58d20SGreg Roach     */
85720b58d20SGreg Roach    public function createMediaObject(string $gedcom): Media
85820b58d20SGreg Roach    {
859bec87e94SGreg Roach        if (!Str::startsWith($gedcom, '0 @@ OBJE')) {
86020b58d20SGreg Roach            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ OBJE');
86120b58d20SGreg Roach        }
86220b58d20SGreg Roach
86320b58d20SGreg Roach        $xref   = $this->getNewXref();
864bec87e94SGreg Roach        $gedcom = '0 @' . $xref . '@ OBJE' . Str::after($gedcom, '0 @@ OBJE');
86520b58d20SGreg Roach
86620b58d20SGreg Roach        // Create a change record
867e5a6b4d4SGreg Roach        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
86820b58d20SGreg Roach
86920b58d20SGreg Roach        // Create a pending change
870963fbaeeSGreg Roach        DB::table('change')->insert([
871963fbaeeSGreg Roach            'gedcom_id'  => $this->id,
872963fbaeeSGreg Roach            'xref'       => $xref,
873963fbaeeSGreg Roach            'old_gedcom' => '',
874963fbaeeSGreg Roach            'new_gedcom' => $gedcom,
875963fbaeeSGreg Roach            'user_id'    => Auth::id(),
87620b58d20SGreg Roach        ]);
87720b58d20SGreg Roach
87820b58d20SGreg Roach        // Accept this pending change
87920b58d20SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
88020b58d20SGreg Roach            FunctionsImport::acceptAllChanges($xref, $this);
88120b58d20SGreg Roach
88220b58d20SGreg Roach            return new Media($xref, $gedcom, null, $this);
88320b58d20SGreg Roach        }
88420b58d20SGreg Roach
88520b58d20SGreg Roach        return new Media($xref, '', $gedcom, $this);
88620b58d20SGreg Roach    }
88720b58d20SGreg Roach
88820b58d20SGreg Roach    /**
8898586983fSGreg Roach     * What is the most significant individual in this tree.
8908586983fSGreg Roach     *
891e5a6b4d4SGreg Roach     * @param UserInterface $user
8928586983fSGreg Roach     *
8938586983fSGreg Roach     * @return Individual
8948586983fSGreg Roach     */
895e5a6b4d4SGreg Roach    public function significantIndividual(UserInterface $user): Individual
896c1010edaSGreg Roach    {
8978f9b0fb2SGreg Roach        $individual = null;
8988586983fSGreg Roach
8998f9b0fb2SGreg Roach        if ($this->getUserPreference($user, 'rootid') !== '') {
9008586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
9018586983fSGreg Roach        }
9028f9b0fb2SGreg Roach
9038f9b0fb2SGreg Roach        if ($individual === null && $this->getUserPreference($user, 'gedcomid') !== '') {
9048586983fSGreg Roach            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
9058586983fSGreg Roach        }
9068f9b0fb2SGreg Roach
907bec87e94SGreg Roach        if ($individual === null && $this->getPreference('PEDIGREE_ROOT_ID') !== '') {
9088586983fSGreg Roach            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
9098586983fSGreg Roach        }
9108f9b0fb2SGreg Roach        if ($individual === null) {
9118f9b0fb2SGreg Roach            $xref = (string) DB::table('individuals')
9128f9b0fb2SGreg Roach                ->where('i_file', '=', $this->id())
9138f9b0fb2SGreg Roach                ->min('i_id');
914769d7d6eSGreg Roach
915769d7d6eSGreg Roach            $individual = Individual::getInstance($xref, $this);
9165fe1add5SGreg Roach        }
9178f9b0fb2SGreg Roach        if ($individual === null) {
9185fe1add5SGreg Roach            // always return a record
9195fe1add5SGreg Roach            $individual = new Individual('I', '0 @I@ INDI', null, $this);
9205fe1add5SGreg Roach        }
9215fe1add5SGreg Roach
9225fe1add5SGreg Roach        return $individual;
9235fe1add5SGreg Roach    }
924*1df7ae39SGreg Roach
925*1df7ae39SGreg Roach    public function mediaFilesystem(): FilesystemInterface
926*1df7ae39SGreg Roach    {
927*1df7ae39SGreg Roach        $media_dir = WT_DATA_DIR . $this->getPreference('MEDIA_DIRECTORY', 'media/');
928*1df7ae39SGreg Roach
929*1df7ae39SGreg Roach        return new Filesystem(new CachedAdapter(new Local($media_dir), new Memory()));
930*1df7ae39SGreg Roach    }
931a25f0a04SGreg Roach}
932