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