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