xref: /webtrees/app/Tree.php (revision 37b0f34f0addc8d3fe661aca488ebda8027f894f)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees;
19
20use Exception;
21use Fisharebest\Webtrees\Functions\FunctionsExport;
22use Fisharebest\Webtrees\Functions\FunctionsImport;
23use Illuminate\Database\Capsule\Manager as DB;
24use Illuminate\Database\Query\Builder;
25use Illuminate\Database\Query\JoinClause;
26use InvalidArgumentException;
27use PDOException;
28use function substr_compare;
29
30/**
31 * Provide an interface to the wt_gedcom table.
32 */
33class Tree
34{
35    /** @var int The tree's ID number */
36    private $id;
37
38    /** @var string The tree's name */
39    private $name;
40
41    /** @var string The tree's title */
42    private $title;
43
44    /** @var int[] Default access rules for facts in this tree */
45    private $fact_privacy;
46
47    /** @var int[] Default access rules for individuals in this tree */
48    private $individual_privacy;
49
50    /** @var integer[][] Default access rules for individual facts in this tree */
51    private $individual_fact_privacy;
52
53    /** @var Tree[] All trees that we have permission to see. */
54    public static $trees = [];
55
56    /** @var string[] Cached copy of the wt_gedcom_setting table. */
57    private $preferences = [];
58
59    /** @var string[][] Cached copy of the wt_user_gedcom_setting table. */
60    private $user_preferences = [];
61
62    private const RESN_PRIVACY = [
63        'none'         => Auth::PRIV_PRIVATE,
64        'privacy'      => Auth::PRIV_USER,
65        'confidential' => Auth::PRIV_NONE,
66        'hidden'       => Auth::PRIV_HIDE,
67    ];
68
69    /**
70     * Create a tree object. This is a private constructor - it can only
71     * be called from Tree::getAll() to ensure proper initialisation.
72     *
73     * @param int    $id
74     * @param string $name
75     * @param string $title
76     */
77    private function __construct($id, $name, $title)
78    {
79        $this->id                      = $id;
80        $this->name                    = $name;
81        $this->title                   = $title;
82        $this->fact_privacy            = [];
83        $this->individual_privacy      = [];
84        $this->individual_fact_privacy = [];
85
86        // Load the privacy settings for this tree
87        $rows = DB::table('default_resn')
88            ->where('gedcom_id', '=', $this->id)
89            ->get();
90
91        foreach ($rows as $row) {
92            // Convert GEDCOM privacy restriction to a webtrees access level.
93            $row->resn = self::RESN_PRIVACY[$row->resn];
94
95            if ($row->xref !== null) {
96                if ($row->tag_type !== null) {
97                    $this->individual_fact_privacy[$row->xref][$row->tag_type] = (int) $row->resn;
98                } else {
99                    $this->individual_privacy[$row->xref] = (int) $row->resn;
100                }
101            } else {
102                $this->fact_privacy[$row->tag_type] = (int) $row->resn;
103            }
104        }
105    }
106
107    /**
108     * The ID of this tree
109     *
110     * @return int
111     */
112    public function id(): int
113    {
114        return $this->id;
115    }
116
117    /**
118     * The name of this tree
119     *
120     * @return string
121     */
122    public function name(): string
123    {
124        return $this->name;
125    }
126
127    /**
128     * The title of this tree
129     *
130     * @return string
131     */
132    public function title(): string
133    {
134        return $this->title;
135    }
136
137    /**
138     * The fact-level privacy for this tree.
139     *
140     * @return int[]
141     */
142    public function getFactPrivacy(): array
143    {
144        return $this->fact_privacy;
145    }
146
147    /**
148     * The individual-level privacy for this tree.
149     *
150     * @return int[]
151     */
152    public function getIndividualPrivacy(): array
153    {
154        return $this->individual_privacy;
155    }
156
157    /**
158     * The individual-fact-level privacy for this tree.
159     *
160     * @return int[][]
161     */
162    public function getIndividualFactPrivacy(): array
163    {
164        return $this->individual_fact_privacy;
165    }
166
167    /**
168     * Get the tree’s configuration settings.
169     *
170     * @param string $setting_name
171     * @param string $default
172     *
173     * @return string
174     */
175    public function getPreference(string $setting_name, string $default = ''): string
176    {
177        if (empty($this->preferences)) {
178            $this->preferences = DB::table('gedcom_setting')
179                ->where('gedcom_id', '=', $this->id)
180                ->pluck('setting_value', 'setting_name')
181                ->all();
182        }
183
184        return $this->preferences[$setting_name] ?? $default;
185    }
186
187    /**
188     * Set the tree’s configuration settings.
189     *
190     * @param string $setting_name
191     * @param string $setting_value
192     *
193     * @return $this
194     */
195    public function setPreference(string $setting_name, string $setting_value): Tree
196    {
197        if ($setting_value !== $this->getPreference($setting_name)) {
198            DB::table('gedcom_setting')->updateOrInsert([
199                'gedcom_id' =>$this->id,
200                'setting_name' => $setting_name,
201            ], [
202                'setting_value' => $setting_value,
203            ]);
204
205            $this->preferences[$setting_name] = $setting_value;
206
207            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
208        }
209
210        return $this;
211    }
212
213    /**
214     * Get the tree’s user-configuration settings.
215     *
216     * @param User   $user
217     * @param string $setting_name
218     * @param string $default
219     *
220     * @return string
221     */
222    public function getUserPreference(User $user, string $setting_name, string $default = ''): string
223    {
224        // There are lots of settings, and we need to fetch lots of them on every page
225        // so it is quicker to fetch them all in one go.
226        if (!array_key_exists($user->getUserId(), $this->user_preferences)) {
227            $this->user_preferences[$user->getUserId()] = DB::table('user_gedcom_setting')
228                ->where('user_id', '=', $user->getUserId())
229                ->where('gedcom_id', '=', $this->id)
230                ->pluck('setting_value', 'setting_name')
231                ->all();
232        }
233
234        return $this->user_preferences[$user->getUserId()][$setting_name] ?? $default;
235    }
236
237    /**
238     * Set the tree’s user-configuration settings.
239     *
240     * @param User   $user
241     * @param string $setting_name
242     * @param string $setting_value
243     *
244     * @return $this
245     */
246    public function setUserPreference(User $user, string $setting_name, string $setting_value): Tree
247    {
248        if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
249            // Update the database
250            DB::table('user_gedcom_setting')->updateOrInsert([
251                'gedcom_id' => $this->id(),
252                'user_id' =>$user->getUserId(),
253                'setting_name' => $setting_name,
254            ], [
255                'setting_value' => $setting_value,
256            ]);
257
258            // Update the cache
259            $this->user_preferences[$user->getUserId()][$setting_name] = $setting_value;
260            // Audit log of changes
261            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->getUserName() . '"', $this);
262        }
263
264        return $this;
265    }
266
267    /**
268     * Can a user accept changes for this tree?
269     *
270     * @param User $user
271     *
272     * @return bool
273     */
274    public function canAcceptChanges(User $user): bool
275    {
276        return Auth::isModerator($this, $user);
277    }
278
279    /**
280     * Fetch all the trees that we have permission to access.
281     *
282     * @return Tree[]
283     */
284    public static function getAll(): array
285    {
286        if (empty(self::$trees)) {
287            // Admins see all trees
288            $query = DB::table('gedcom')
289                ->leftJoin('gedcom_setting', function (JoinClause $join): void {
290                    $join->on('gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
291                        ->where('gedcom_setting.setting_name', '=', 'title');
292                })
293                ->where('gedcom.gedcom_id', '>', 0)
294                ->select([
295                    'gedcom.gedcom_id AS tree_id',
296                    'gedcom.gedcom_name AS tree_name',
297                    'gedcom_setting.setting_value AS tree_title',
298                ])
299                ->orderBy('gedcom.sort_order')
300                ->orderBy('gedcom_setting.setting_value');
301
302            // Non-admins may not see all trees
303            if (!Auth::isAdmin()) {
304                $query
305                    ->join('gedcom_setting AS gs2', function (JoinClause $join): void {
306                        $join->on('gs2.gedcom_id', '=', 'gedcom.gedcom_id')
307                            ->where('gs2.setting_name', '=', 'imported');
308                    })
309                    ->join('gedcom_setting AS gs3', function (JoinClause $join): void {
310                        $join->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
311                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
312                    })
313                    ->leftJoin('user_gedcom_setting', function (JoinClause $join): void {
314                        $join->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
315                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
316                            ->where('user_gedcom_setting.setting_name', '=', 'canedit');
317                    })
318                    ->where(function (Builder $query): void {
319                        $query
320                            // Managers
321                            ->where('user_gedcom_setting.setting_value', '=', 'admin')
322                            // Members
323                            ->orWhere(function (Builder $query): void {
324                                $query
325                                    ->where('gs2.setting_value', '=', '1')
326                                    ->where('gs3.setting_value', '=', '1')
327                                    ->where('user_gedcom_setting.setting_value', '<>', 'none');
328                            })
329                            // PUblic trees
330                            ->orWhere(function (Builder $query): void {
331                                $query
332                                    ->where('gs2.setting_value', '=', '1')
333                                    ->where('gs3.setting_value', '<>', '1');
334                            });
335                    });
336            }
337
338            $rows = $query->get();
339
340            foreach ($rows as $row) {
341                self::$trees[$row->tree_name] = new self((int) $row->tree_id, $row->tree_name, $row->tree_title);
342            }
343        }
344
345        return self::$trees;
346    }
347
348    /**
349     * Find the tree with a specific ID.
350     *
351     * @param int $tree_id
352     *
353     * @throws \DomainException
354     * @return Tree
355     */
356    public static function findById($tree_id): Tree
357    {
358        foreach (self::getAll() as $tree) {
359            if ($tree->id == $tree_id) {
360                return $tree;
361            }
362        }
363        throw new \DomainException();
364    }
365
366    /**
367     * Find the tree with a specific name.
368     *
369     * @param string $tree_name
370     *
371     * @return Tree|null
372     */
373    public static function findByName($tree_name)
374    {
375        foreach (self::getAll() as $tree) {
376            if ($tree->name === $tree_name) {
377                return $tree;
378            }
379        }
380
381        return null;
382    }
383
384    /**
385     * Create arguments to select_edit_control()
386     * Note - these will be escaped later
387     *
388     * @return string[]
389     */
390    public static function getIdList(): array
391    {
392        $list = [];
393        foreach (self::getAll() as $tree) {
394            $list[$tree->id] = $tree->title;
395        }
396
397        return $list;
398    }
399
400    /**
401     * Create arguments to select_edit_control()
402     * Note - these will be escaped later
403     *
404     * @return string[]
405     */
406    public static function getNameList(): array
407    {
408        $list = [];
409        foreach (self::getAll() as $tree) {
410            $list[$tree->name] = $tree->title;
411        }
412
413        return $list;
414    }
415
416    /**
417     * Create a new tree
418     *
419     * @param string $tree_name
420     * @param string $tree_title
421     *
422     * @return Tree
423     */
424    public static function create(string $tree_name, string $tree_title): Tree
425    {
426        try {
427            // Create a new tree
428            DB::table('gedcom')->insert([
429                'gedcom_name' => $tree_name,
430            ]);
431
432            $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
433
434            $tree = new self($tree_id, $tree_name, $tree_title);
435        } catch (PDOException $ex) {
436            // A tree with that name already exists?
437            return self::findByName($tree_name);
438        }
439
440        // Update the list of trees - to include this new one
441        self::$trees[$tree_name] = $tree;
442
443        $tree->setPreference('imported', '0');
444        $tree->setPreference('title', $tree_title);
445
446        // Module privacy
447        Module::setDefaultAccess($tree_id);
448
449        // Set preferences from default tree
450        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
451            ['gedcom_id', 'setting_name', 'setting_value'],
452            function (Builder $query) use ($tree_id): void {
453                $query
454                    ->select([DB::raw($tree_id), 'setting_name', 'setting_value'])
455                    ->from('gedcom_setting')
456                    ->where('gedcom_id', '=', -1);
457            }
458        );
459
460        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
461            ['gedcom_id', 'tag_type', 'resn'],
462            function (Builder $query) use ($tree_id): void {
463                $query
464                    ->select([DB::raw($tree_id), 'tag_type', 'resn'])
465                    ->from('default_resn')
466                    ->where('gedcom_id', '=', -1);
467            }
468        );
469
470        (new Builder(DB::connection()))->from('block')->insertUsing(
471            ['gedcom_id', 'location', 'block_order', 'module_name'],
472            function (Builder $query) use ($tree_id): void {
473                $query
474                    ->select([DB::raw($tree_id), 'location', 'block_order', 'module_name'])
475                    ->from('block')
476                    ->where('gedcom_id', '=', -1);
477            }
478        );
479
480        // Gedcom and privacy settings
481        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
482        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
483        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
484        switch (WT_LOCALE) {
485            case 'es':
486                $tree->setPreference('SURNAME_TRADITION', 'spanish');
487                break;
488            case 'is':
489                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
490                break;
491            case 'lt':
492                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
493                break;
494            case 'pl':
495                $tree->setPreference('SURNAME_TRADITION', 'polish');
496                break;
497            case 'pt':
498            case 'pt-BR':
499                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
500                break;
501            default:
502                $tree->setPreference('SURNAME_TRADITION', 'paternal');
503                break;
504        }
505
506        // Genealogy data
507        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
508        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
509        $john_doe = I18N::translate('John /DOE/');
510        $note     = I18N::translate('Edit this individual and replace their details with your own.');
511        $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";
512
513        DB::table('gedcom_chunk')->insert([
514            'gedcom_id'  => $tree_id,
515            'chunk_data' => $gedcom,
516        ]);
517
518        // Update our cache
519        self::$trees[$tree->id] = $tree;
520
521        return $tree;
522    }
523
524    /**
525     * Are there any pending edits for this tree, than need reviewing by a moderator.
526     *
527     * @return bool
528     */
529    public function hasPendingEdit(): bool
530    {
531        return (bool) Database::prepare(
532            "SELECT 1 FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id"
533        )->execute([
534            'tree_id' => $this->id,
535        ])->fetchOne();
536    }
537
538    /**
539     * Delete all the genealogy data from a tree - in preparation for importing
540     * new data. Optionally retain the media data, for when the user has been
541     * editing their data offline using an application which deletes (or does not
542     * support) media data.
543     *
544     * @param bool $keep_media
545     *
546     * @return void
547     */
548    public function deleteGenealogyData(bool $keep_media)
549    {
550        Database::prepare("DELETE FROM `##gedcom_chunk` WHERE gedcom_id = ?")->execute([$this->id]);
551        Database::prepare("DELETE FROM `##individuals`  WHERE i_file    = ?")->execute([$this->id]);
552        Database::prepare("DELETE FROM `##families`     WHERE f_file    = ?")->execute([$this->id]);
553        Database::prepare("DELETE FROM `##sources`      WHERE s_file    = ?")->execute([$this->id]);
554        Database::prepare("DELETE FROM `##other`        WHERE o_file    = ?")->execute([$this->id]);
555        Database::prepare("DELETE FROM `##places`       WHERE p_file    = ?")->execute([$this->id]);
556        Database::prepare("DELETE FROM `##placelinks`   WHERE pl_file   = ?")->execute([$this->id]);
557        Database::prepare("DELETE FROM `##name`         WHERE n_file    = ?")->execute([$this->id]);
558        Database::prepare("DELETE FROM `##dates`        WHERE d_file    = ?")->execute([$this->id]);
559        Database::prepare("DELETE FROM `##change`       WHERE gedcom_id = ?")->execute([$this->id]);
560
561        if ($keep_media) {
562            Database::prepare("DELETE FROM `##link` WHERE l_file =? AND l_type<>'OBJE'")->execute([$this->id]);
563        } else {
564            Database::prepare("DELETE FROM `##link`  WHERE l_file =?")->execute([$this->id]);
565            Database::prepare("DELETE FROM `##media` WHERE m_file =?")->execute([$this->id]);
566            Database::prepare("DELETE FROM `##media_file` WHERE m_file =?")->execute([$this->id]);
567        }
568    }
569
570    /**
571     * Delete everything relating to a tree
572     *
573     * @return void
574     */
575    public function delete()
576    {
577        // If this is the default tree, then unset it
578        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
579            Site::setPreference('DEFAULT_GEDCOM', '');
580        }
581
582        $this->deleteGenealogyData(false);
583
584        Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE gedcom_id=?")->execute([$this->id]);
585        Database::prepare("DELETE FROM `##block`               WHERE gedcom_id = ?")->execute([$this->id]);
586        Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE gedcom_id = ?")->execute([$this->id]);
587        Database::prepare("DELETE FROM `##gedcom_setting`      WHERE gedcom_id = ?")->execute([$this->id]);
588        Database::prepare("DELETE FROM `##module_privacy`      WHERE gedcom_id = ?")->execute([$this->id]);
589        Database::prepare("DELETE FROM `##hit_counter`         WHERE gedcom_id = ?")->execute([$this->id]);
590        Database::prepare("DELETE FROM `##default_resn`        WHERE gedcom_id = ?")->execute([$this->id]);
591        Database::prepare("DELETE FROM `##gedcom_chunk`        WHERE gedcom_id = ?")->execute([$this->id]);
592        Database::prepare("DELETE FROM `##log`                 WHERE gedcom_id = ?")->execute([$this->id]);
593        Database::prepare("DELETE FROM `##gedcom`              WHERE gedcom_id = ?")->execute([$this->id]);
594
595        // After updating the database, we need to fetch a new (sorted) copy
596        self::$trees = [];
597    }
598
599    /**
600     * Export the tree to a GEDCOM file
601     *
602     * @param resource $stream
603     *
604     * @return void
605     */
606    public function exportGedcom($stream)
607    {
608        $stmt = Database::prepare(
609            "SELECT i_gedcom AS gedcom, i_id AS xref, 1 AS n FROM `##individuals` WHERE i_file = :tree_id_1" .
610            " UNION ALL " .
611            "SELECT f_gedcom AS gedcom, f_id AS xref, 2 AS n FROM `##families`    WHERE f_file = :tree_id_2" .
612            " UNION ALL " .
613            "SELECT s_gedcom AS gedcom, s_id AS xref, 3 AS n FROM `##sources`     WHERE s_file = :tree_id_3" .
614            " UNION ALL " .
615            "SELECT o_gedcom AS gedcom, o_id AS xref, 4 AS n FROM `##other`       WHERE o_file = :tree_id_4 AND o_type NOT IN ('HEAD', 'TRLR')" .
616            " UNION ALL " .
617            "SELECT m_gedcom AS gedcom, m_id AS xref, 5 AS n FROM `##media`       WHERE m_file = :tree_id_5" .
618            " ORDER BY n, LENGTH(xref), xref"
619        )->execute([
620            'tree_id_1' => $this->id,
621            'tree_id_2' => $this->id,
622            'tree_id_3' => $this->id,
623            'tree_id_4' => $this->id,
624            'tree_id_5' => $this->id,
625        ]);
626
627        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this, 'UTF-8'));
628        while (($row = $stmt->fetch()) !== false) {
629            $buffer .= FunctionsExport::reformatRecord($row->gedcom);
630            if (strlen($buffer) > 65535) {
631                fwrite($stream, $buffer);
632                $buffer = '';
633            }
634        }
635        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
636        $stmt->closeCursor();
637    }
638
639    /**
640     * Import data from a gedcom file into this tree.
641     *
642     * @param string $path     The full path to the (possibly temporary) file.
643     * @param string $filename The preferred filename, for export/download.
644     *
645     * @return void
646     * @throws Exception
647     */
648    public function importGedcomFile(string $path, string $filename)
649    {
650        // Read the file in blocks of roughly 64K. Ensure that each block
651        // contains complete gedcom records. This will ensure we don’t split
652        // multi-byte characters, as well as simplifying the code to import
653        // each block.
654
655        $file_data = '';
656        $fp        = fopen($path, 'rb');
657
658        if ($fp === false) {
659            throw new Exception('Cannot write file: ' . $path);
660        }
661
662        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
663        $this->setPreference('gedcom_filename', $filename);
664        $this->setPreference('imported', '0');
665
666        while (!feof($fp)) {
667            $file_data .= fread($fp, 65536);
668            // There is no strrpos() function that searches for substrings :-(
669            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
670                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
671                    // We’ve found the last record boundary in this chunk of data
672                    break;
673                }
674            }
675            if ($pos) {
676                Database::prepare(
677                    "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
678                )->execute([
679                    $this->id,
680                    substr($file_data, 0, $pos),
681                ]);
682                $file_data = substr($file_data, $pos);
683            }
684        }
685        Database::prepare(
686            "INSERT INTO `##gedcom_chunk` (gedcom_id, chunk_data) VALUES (?, ?)"
687        )->execute([
688            $this->id,
689            $file_data,
690        ]);
691
692        fclose($fp);
693    }
694
695    /**
696     * Generate a new XREF, unique across all family trees
697     *
698     * @return string
699     */
700    public function getNewXref(): string
701    {
702        $prefix = 'X';
703
704        $increment = 1.0;
705        do {
706            // Use LAST_INSERT_ID(expr) to provide a transaction-safe sequence. See
707            // http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
708            $statement = Database::prepare(
709                "UPDATE `##site_setting` SET setting_value = LAST_INSERT_ID(setting_value + :increment) WHERE setting_name = 'next_xref'"
710            );
711            $statement->execute([
712                'increment' => (int) $increment,
713            ]);
714
715            if ($statement->rowCount() === 0) {
716                $num = '1';
717                Site::setPreference('next_xref', $num);
718            } else {
719                $num = (string) Database::prepare("SELECT LAST_INSERT_ID()")->fetchOne();
720            }
721
722            $xref = $prefix . $num;
723
724            // Records may already exist with this sequence number.
725            $already_used = Database::prepare(
726                "SELECT" .
727                " EXISTS (SELECT 1 FROM `##individuals` WHERE i_id = :i_id) OR" .
728                " EXISTS (SELECT 1 FROM `##families` WHERE f_id = :f_id) OR" .
729                " EXISTS (SELECT 1 FROM `##sources` WHERE s_id = :s_id) OR" .
730                " EXISTS (SELECT 1 FROM `##media` WHERE m_id = :m_id) OR" .
731                " EXISTS (SELECT 1 FROM `##other` WHERE o_id = :o_id) OR" .
732                " EXISTS (SELECT 1 FROM `##change` WHERE xref = :xref)"
733            )->execute([
734                'i_id' => $xref,
735                'f_id' => $xref,
736                's_id' => $xref,
737                'm_id' => $xref,
738                'o_id' => $xref,
739                'xref' => $xref,
740            ])->fetchOne();
741
742            // This exponential increment allows us to scan over large blocks of
743            // existing data in a reasonable time.
744            $increment *= 1.01;
745        } while ($already_used !== '0');
746
747        return $xref;
748    }
749
750    /**
751     * Create a new record from GEDCOM data.
752     *
753     * @param string $gedcom
754     *
755     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
756     * @throws InvalidArgumentException
757     */
758    public function createRecord(string $gedcom): GedcomRecord
759    {
760        if (substr_compare($gedcom, '0 @@', 0, 4) !== 0) {
761            throw new InvalidArgumentException('GedcomRecord::createRecord(' . $gedcom . ') does not begin 0 @@');
762        }
763
764        $xref   = $this->getNewXref();
765        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
766
767        // Create a change record
768        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
769
770        // Create a pending change
771        Database::prepare(
772            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
773        )->execute([
774            $this->id,
775            $xref,
776            $gedcom,
777            Auth::id(),
778        ]);
779
780        // Accept this pending change
781        if (Auth::user()->getPreference('auto_accept')) {
782            FunctionsImport::acceptAllChanges($xref, $this);
783
784            return new GedcomRecord($xref, $gedcom, null, $this);
785        }
786
787        return GedcomRecord::getInstance($xref, $this, $gedcom);
788    }
789
790    /**
791     * Create a new family from GEDCOM data.
792     *
793     * @param string $gedcom
794     *
795     * @return Family
796     * @throws InvalidArgumentException
797     */
798    public function createFamily(string $gedcom): GedcomRecord
799    {
800        if (substr_compare($gedcom, '0 @@ FAM', 0, 8) !== 0) {
801            throw new InvalidArgumentException('GedcomRecord::createFamily(' . $gedcom . ') does not begin 0 @@ FAM');
802        }
803
804        $xref   = $this->getNewXref();
805        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
806
807        // Create a change record
808        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
809
810        // Create a pending change
811        Database::prepare(
812            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
813        )->execute([
814            $this->id,
815            $xref,
816            $gedcom,
817            Auth::id(),
818        ]);
819
820        // Accept this pending change
821        if (Auth::user()->getPreference('auto_accept')) {
822            FunctionsImport::acceptAllChanges($xref, $this);
823
824            return new Family($xref, $gedcom, null, $this);
825        }
826
827        return new Family($xref, '', $gedcom, $this);
828    }
829
830    /**
831     * Create a new individual from GEDCOM data.
832     *
833     * @param string $gedcom
834     *
835     * @return Individual
836     * @throws InvalidArgumentException
837     */
838    public function createIndividual(string $gedcom): GedcomRecord
839    {
840        if (substr_compare($gedcom, '0 @@ INDI', 0, 9) !== 0) {
841            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ INDI');
842        }
843
844        $xref   = $this->getNewXref();
845        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
846
847        // Create a change record
848        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
849
850        // Create a pending change
851        Database::prepare(
852            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
853        )->execute([
854            $this->id,
855            $xref,
856            $gedcom,
857            Auth::id(),
858        ]);
859
860        // Accept this pending change
861        if (Auth::user()->getPreference('auto_accept')) {
862            FunctionsImport::acceptAllChanges($xref, $this);
863
864            return new Individual($xref, $gedcom, null, $this);
865        }
866
867        return new Individual($xref, '', $gedcom, $this);
868    }
869
870    /**
871     * Create a new media object from GEDCOM data.
872     *
873     * @param string $gedcom
874     *
875     * @return Media
876     * @throws InvalidArgumentException
877     */
878    public function createMediaObject(string $gedcom): Media
879    {
880        if (substr_compare($gedcom, '0 @@ OBJE', 0, 9) !== 0) {
881            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ OBJE');
882        }
883
884        $xref   = $this->getNewXref();
885        $gedcom = '0 @' . $xref . '@' . substr($gedcom, 4);
886
887        // Create a change record
888        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
889
890        // Create a pending change
891        Database::prepare(
892            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
893        )->execute([
894            $this->id,
895            $xref,
896            $gedcom,
897            Auth::id(),
898        ]);
899
900        // Accept this pending change
901        if (Auth::user()->getPreference('auto_accept')) {
902            FunctionsImport::acceptAllChanges($xref, $this);
903
904            return new Media($xref, $gedcom, null, $this);
905        }
906
907        return new Media($xref, '', $gedcom, $this);
908    }
909
910    /**
911     * What is the most significant individual in this tree.
912     *
913     * @param User $user
914     *
915     * @return Individual
916     */
917    public function significantIndividual(User $user): Individual
918    {
919        static $individual; // Only query the DB once.
920
921        if (!$individual && $this->getUserPreference($user, 'rootid') !== '') {
922            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
923        }
924        if (!$individual && $this->getUserPreference($user, 'gedcomid') !== '') {
925            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
926        }
927        if (!$individual) {
928            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
929        }
930        if (!$individual) {
931            $xref = (string) Database::prepare(
932                "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
933            )->execute([
934                'tree_id' => $this->id(),
935            ])->fetchOne();
936
937            $individual = Individual::getInstance($xref, $this);
938        }
939        if (!$individual) {
940            // always return a record
941            $individual = new Individual('I', '0 @I@ INDI', null, $this);
942        }
943
944        return $individual;
945    }
946
947    /**
948     * Get significant information from this page, to allow other pages such as
949     * charts and reports to initialise with the same records
950     *
951     * @return Individual
952     */
953    public function getSignificantIndividual(): Individual
954    {
955        static $individual; // Only query the DB once.
956
957        if (!$individual && $this->getUserPreference(Auth::user(), 'rootid') !== '') {
958            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'rootid'), $this);
959        }
960        if (!$individual && $this->getUserPreference(Auth::user(), 'gedcomid') !== '') {
961            $individual = Individual::getInstance($this->getUserPreference(Auth::user(), 'gedcomid'), $this);
962        }
963        if (!$individual) {
964            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
965        }
966        if (!$individual) {
967            $xref = (string) Database::prepare(
968                "SELECT MIN(i_id) FROM `##individuals` WHERE i_file = :tree_id"
969            )->execute([
970                'tree_id' => $this->id(),
971            ])->fetchOne();
972
973            $individual = Individual::getInstance($xref, $this);
974        }
975        if (!$individual) {
976            // always return a record
977            $individual = new Individual('I', '0 @I@ INDI', null, $this);
978        }
979
980        return $individual;
981    }
982}
983