xref: /webtrees/app/Tree.php (revision 54c7f8df0fc7bddb0bcc1441937c30320ca68563)
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
285     * @return Tree[]
286     */
287    public static function all(): Collection
288    {
289        return app('cache.array')->rememberForever(__CLASS__, function () {
290            // Admins see all trees
291            $query = DB::table('gedcom')
292                ->leftJoin('gedcom_setting', function (JoinClause $join): void {
293                    $join->on('gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
294                        ->where('gedcom_setting.setting_name', '=', 'title');
295                })
296                ->where('gedcom.gedcom_id', '>', 0)
297                ->select([
298                    'gedcom.gedcom_id AS tree_id',
299                    'gedcom.gedcom_name AS tree_name',
300                    'gedcom_setting.setting_value AS tree_title',
301                ])
302                ->orderBy('gedcom.sort_order')
303                ->orderBy('gedcom_setting.setting_value');
304
305            // Non-admins may not see all trees
306            if (!Auth::isAdmin()) {
307                $query
308                    ->join('gedcom_setting AS gs2', function (JoinClause $join): void {
309                        $join->on('gs2.gedcom_id', '=', 'gedcom.gedcom_id')
310                            ->where('gs2.setting_name', '=', 'imported');
311                    })
312                    ->join('gedcom_setting AS gs3', function (JoinClause $join): void {
313                        $join->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
314                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
315                    })
316                    ->leftJoin('user_gedcom_setting', function (JoinClause $join): void {
317                        $join->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
318                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
319                            ->where('user_gedcom_setting.setting_name', '=', 'canedit');
320                    })
321                    ->where(function (Builder $query): void {
322                        $query
323                            // Managers
324                            ->where('user_gedcom_setting.setting_value', '=', 'admin')
325                            // Members
326                            ->orWhere(function (Builder $query): void {
327                                $query
328                                    ->where('gs2.setting_value', '=', '1')
329                                    ->where('gs3.setting_value', '=', '1')
330                                    ->where('user_gedcom_setting.setting_value', '<>', 'none');
331                            })
332                            // Public trees
333                            ->orWhere(function (Builder $query): void {
334                                $query
335                                    ->where('gs2.setting_value', '=', '1')
336                                    ->where('gs3.setting_value', '<>', '1');
337                            });
338                    });
339            }
340
341            return $query
342                ->get()
343                ->mapWithKeys(function (stdClass $row): array {
344                    return [$row->tree_id => new self((int) $row->tree_id, $row->tree_name, $row->tree_title)];
345                });
346        });
347    }
348
349    /**
350     * Fetch all the trees that we have permission to access.
351     *
352     * @return Tree[]
353     */
354    public static function getAll(): array
355    {
356        if (empty(self::$trees)) {
357            self::$trees = self::all()->all();
358        }
359
360        return self::$trees;
361    }
362
363    /**
364     * Find the tree with a specific ID.
365     *
366     * @param int $tree_id
367     *
368     * @return Tree
369     */
370    public static function findById(int $tree_id): Tree
371    {
372        return self::getAll()[$tree_id];
373    }
374
375    /**
376     * Find the tree with a specific name.
377     *
378     * @param string $tree_name
379     *
380     * @return Tree|null
381     */
382    public static function findByName($tree_name)
383    {
384        foreach (self::getAll() as $tree) {
385            if ($tree->name === $tree_name) {
386                return $tree;
387            }
388        }
389
390        return null;
391    }
392
393    /**
394     * Create arguments to select_edit_control()
395     * Note - these will be escaped later
396     *
397     * @return string[]
398     */
399    public static function getIdList(): array
400    {
401        $list = [];
402        foreach (self::getAll() as $tree) {
403            $list[$tree->id] = $tree->title;
404        }
405
406        return $list;
407    }
408
409    /**
410     * Create arguments to select_edit_control()
411     * Note - these will be escaped later
412     *
413     * @return string[]
414     */
415    public static function getNameList(): array
416    {
417        $list = [];
418        foreach (self::getAll() as $tree) {
419            $list[$tree->name] = $tree->title;
420        }
421
422        return $list;
423    }
424
425    /**
426     * Create a new tree
427     *
428     * @param string $tree_name
429     * @param string $tree_title
430     *
431     * @return Tree
432     */
433    public static function create(string $tree_name, string $tree_title): Tree
434    {
435        try {
436            // Create a new tree
437            DB::table('gedcom')->insert([
438                'gedcom_name' => $tree_name,
439            ]);
440
441            $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
442
443            $tree = new self($tree_id, $tree_name, $tree_title);
444        } catch (PDOException $ex) {
445            // A tree with that name already exists?
446            return self::findByName($tree_name);
447        }
448
449        $tree->setPreference('imported', '0');
450        $tree->setPreference('title', $tree_title);
451
452        // Set preferences from default tree
453        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
454            ['gedcom_id', 'setting_name', 'setting_value'],
455            function (Builder $query) use ($tree_id): void {
456                $query
457                    ->select([DB::raw($tree_id), 'setting_name', 'setting_value'])
458                    ->from('gedcom_setting')
459                    ->where('gedcom_id', '=', -1);
460            }
461        );
462
463        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
464            ['gedcom_id', 'tag_type', 'resn'],
465            function (Builder $query) use ($tree_id): void {
466                $query
467                    ->select([DB::raw($tree_id), 'tag_type', 'resn'])
468                    ->from('default_resn')
469                    ->where('gedcom_id', '=', -1);
470            }
471        );
472
473        // Gedcom and privacy settings
474        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
475        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
476        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
477        switch (WT_LOCALE) {
478            case 'es':
479                $tree->setPreference('SURNAME_TRADITION', 'spanish');
480                break;
481            case 'is':
482                $tree->setPreference('SURNAME_TRADITION', 'icelandic');
483                break;
484            case 'lt':
485                $tree->setPreference('SURNAME_TRADITION', 'lithuanian');
486                break;
487            case 'pl':
488                $tree->setPreference('SURNAME_TRADITION', 'polish');
489                break;
490            case 'pt':
491            case 'pt-BR':
492                $tree->setPreference('SURNAME_TRADITION', 'portuguese');
493                break;
494            default:
495                $tree->setPreference('SURNAME_TRADITION', 'paternal');
496                break;
497        }
498
499        // Genealogy data
500        // It is simpler to create a temporary/unimported GEDCOM than to populate all the tables...
501        /* I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname. */
502        $john_doe = I18N::translate('John /DOE/');
503        $note     = I18N::translate('Edit this individual and replace their details with your own.');
504        $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";
505
506        DB::table('gedcom_chunk')->insert([
507            'gedcom_id'  => $tree_id,
508            'chunk_data' => $gedcom,
509        ]);
510
511        // Update our cache
512        self::$trees[$tree->id] = $tree;
513
514        return $tree;
515    }
516
517    /**
518     * Are there any pending edits for this tree, than need reviewing by a moderator.
519     *
520     * @return bool
521     */
522    public function hasPendingEdit(): bool
523    {
524        return DB::table('change')
525            ->where('gedcom_id', '=', $this->id)
526            ->where('status', '=', 'pending')
527            ->exists();
528    }
529
530    /**
531     * Delete all the genealogy data from a tree - in preparation for importing
532     * new data. Optionally retain the media data, for when the user has been
533     * editing their data offline using an application which deletes (or does not
534     * support) media data.
535     *
536     * @param bool $keep_media
537     *
538     * @return void
539     */
540    public function deleteGenealogyData(bool $keep_media)
541    {
542        DB::table('gedcom_chunk')->where('gedcom_id', '=', $this->id)->delete();
543        DB::table('individuals')->where('i_file', '=', $this->id)->delete();
544        DB::table('families')->where('f_file', '=', $this->id)->delete();
545        DB::table('sources')->where('s_file', '=', $this->id)->delete();
546        DB::table('other')->where('o_file', '=', $this->id)->delete();
547        DB::table('places')->where('p_file', '=', $this->id)->delete();
548        DB::table('placelinks')->where('pl_file', '=', $this->id)->delete();
549        DB::table('name')->where('n_file', '=', $this->id)->delete();
550        DB::table('dates')->where('d_file', '=', $this->id)->delete();
551        DB::table('change')->where('gedcom_id', '=', $this->id)->delete();
552
553        if ($keep_media) {
554            DB::table('link')->where('l_file', '=', $this->id)
555                ->where('l_type', '<>', 'OBJE')
556                ->delete();
557        } else {
558            DB::table('link')->where('l_file', '=', $this->id)->delete();
559            DB::table('media_file')->where('m_file', '=', $this->id)->delete();
560            DB::table('media')->where('m_file', '=', $this->id)->delete();
561        }
562    }
563
564    /**
565     * Delete everything relating to a tree
566     *
567     * @return void
568     */
569    public function delete()
570    {
571        // If this is the default tree, then unset it
572        if (Site::getPreference('DEFAULT_GEDCOM') === $this->name) {
573            Site::setPreference('DEFAULT_GEDCOM', '');
574        }
575
576        $this->deleteGenealogyData(false);
577
578        DB::table('block_setting')
579            ->join('block', 'block.block_id', '=', 'block_setting.block_id')
580            ->where('gedcom_id', '=', $this->id)
581            ->delete();
582        DB::table('block')->where('gedcom_id', '=', $this->id)->delete();
583        DB::table('user_gedcom_setting')->where('gedcom_id', '=', $this->id)->delete();
584        DB::table('gedcom_setting')->where('gedcom_id', '=', $this->id)->delete();
585        DB::table('module_privacy')->where('gedcom_id', '=', $this->id)->delete();
586        DB::table('hit_counter')->where('gedcom_id', '=', $this->id)->delete();
587        DB::table('default_resn')->where('gedcom_id', '=', $this->id)->delete();
588        DB::table('gedcom_chunk')->where('gedcom_id', '=', $this->id)->delete();
589        DB::table('log')->where('gedcom_id', '=', $this->id)->delete();
590        DB::table('gedcom')->where('gedcom_id', '=', $this->id)->delete();
591
592        // After updating the database, we need to fetch a new (sorted) copy
593        self::$trees = [];
594    }
595
596    /**
597     * Export the tree to a GEDCOM file
598     *
599     * @param resource $stream
600     *
601     * @return void
602     */
603    public function exportGedcom($stream)
604    {
605        $buffer = FunctionsExport::reformatRecord(FunctionsExport::gedcomHeader($this, 'UTF-8'));
606
607        $union_families = DB::table('families')
608            ->where('f_file', '=', $this->id)
609            ->select(['f_gedcom AS gedcom', 'f_id AS xref', DB::raw('LENGTH(f_id) AS len'), DB::raw('2 AS n')]);
610
611        $union_sources = DB::table('sources')
612            ->where('s_file', '=', $this->id)
613            ->select(['s_gedcom AS gedcom', 's_id AS xref', DB::raw('LENGTH(s_id) AS len'), DB::raw('3 AS n')]);
614
615        $union_other = DB::table('other')
616            ->where('o_file', '=', $this->id)
617            ->whereNotIn('o_type', ['HEAD', 'TRLR'])
618            ->select(['o_gedcom AS gedcom', 'o_id AS xref', DB::raw('LENGTH(o_id) AS len'), DB::raw('4 AS n')]);
619
620        $union_media = DB::table('media')
621            ->where('m_file', '=', $this->id)
622            ->select(['m_gedcom AS gedcom', 'm_id AS xref', DB::raw('LENGTH(m_id) AS len'), DB::raw('5 AS n')]);
623
624        DB::table('individuals')
625            ->where('i_file', '=', $this->id)
626            ->select(['i_gedcom AS gedcom', 'i_id AS xref', DB::raw('LENGTH(i_id) AS len'), DB::raw('1 AS n')])
627            ->union($union_families)
628            ->union($union_sources)
629            ->union($union_other)
630            ->union($union_media)
631            ->orderBy('n')
632            ->orderBy('len')
633            ->orderBy('xref')
634            ->chunk(100, function (Collection $rows) use ($stream, &$buffer): void {
635                foreach ($rows as $row) {
636                    $buffer .= FunctionsExport::reformatRecord($row->gedcom);
637                    if (strlen($buffer) > 65535) {
638                        fwrite($stream, $buffer);
639                        $buffer = '';
640                    }
641                }
642            });
643
644        fwrite($stream, $buffer . '0 TRLR' . Gedcom::EOL);
645    }
646
647    /**
648     * Import data from a gedcom file into this tree.
649     *
650     * @param string $path     The full path to the (possibly temporary) file.
651     * @param string $filename The preferred filename, for export/download.
652     *
653     * @return void
654     */
655    public function importGedcomFile(string $path, string $filename)
656    {
657        // Read the file in blocks of roughly 64K. Ensure that each block
658        // contains complete gedcom records. This will ensure we don’t split
659        // multi-byte characters, as well as simplifying the code to import
660        // each block.
661
662        $file_data = '';
663        $fp        = fopen($path, 'rb');
664
665        $this->deleteGenealogyData((bool) $this->getPreference('keep_media'));
666        $this->setPreference('gedcom_filename', $filename);
667        $this->setPreference('imported', '0');
668
669        while (!feof($fp)) {
670            $file_data .= fread($fp, 65536);
671            // There is no strrpos() function that searches for substrings :-(
672            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
673                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
674                    // We’ve found the last record boundary in this chunk of data
675                    break;
676                }
677            }
678            if ($pos) {
679                DB::table('gedcom_chunk')->insert([
680                    'gedcom_id'  => $this->id,
681                    'chunk_data' => substr($file_data, 0, $pos),
682                ]);
683
684                $file_data = substr($file_data, $pos);
685            }
686        }
687        DB::table('gedcom_chunk')->insert([
688            'gedcom_id'  => $this->id,
689            'chunk_data' => $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        // Lock the row, so that only one new XREF may be generated at a time.
703        DB::table('site_setting')
704            ->where('setting_name', '=', 'next_xref')
705            ->lockForUpdate()
706            ->get();
707
708        $prefix = 'X';
709
710        $increment = 1.0;
711        do {
712            $num = (int) Site::getPreference('next_xref') + (int) $increment;
713
714            // This exponential increment allows us to scan over large blocks of
715            // existing data in a reasonable time.
716            $increment *= 1.01;
717
718            $xref = $prefix . $num;
719
720            // Records may already exist with this sequence number.
721            $already_used =
722                DB::table('individuals')->where('i_id', '=', $xref)->exists() ||
723                DB::table('families')->where('f_id', '=', $xref)->exists() ||
724                DB::table('sources')->where('s_id', '=', $xref)->exists() ||
725                DB::table('media')->where('m_id', '=', $xref)->exists() ||
726                DB::table('other')->where('o_id', '=', $xref)->exists() ||
727                DB::table('change')->where('xref', '=', $xref)->exists();
728        } while ($already_used);
729
730        Site::setPreference('next_xref', (string) $num);
731
732        return $xref;
733    }
734
735    /**
736     * Create a new record from GEDCOM data.
737     *
738     * @param string $gedcom
739     *
740     * @return GedcomRecord|Individual|Family|Note|Source|Repository|Media
741     * @throws InvalidArgumentException
742     */
743    public function createRecord(string $gedcom): GedcomRecord
744    {
745        if (!Str::startsWith($gedcom, '0 @@ ')) {
746            throw new InvalidArgumentException('GedcomRecord::createRecord(' . $gedcom . ') does not begin 0 @@');
747        }
748
749        $xref   = $this->getNewXref();
750        $gedcom = '0 @' . $xref . '@ ' . Str::after($gedcom, '0 @@ ');
751
752        // Create a change record
753        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
754
755        // Create a pending change
756        DB::table('change')->insert([
757            'gedcom_id'  => $this->id,
758            'xref'       => $xref,
759            'old_gedcom' => '',
760            'new_gedcom' => $gedcom,
761            'user_id'    => Auth::id(),
762        ]);
763
764        // Accept this pending change
765        if (Auth::user()->getPreference('auto_accept')) {
766            FunctionsImport::acceptAllChanges($xref, $this);
767
768            return new GedcomRecord($xref, $gedcom, null, $this);
769        }
770
771        return GedcomRecord::getInstance($xref, $this, $gedcom);
772    }
773
774    /**
775     * Create a new family from GEDCOM data.
776     *
777     * @param string $gedcom
778     *
779     * @return Family
780     * @throws InvalidArgumentException
781     */
782    public function createFamily(string $gedcom): GedcomRecord
783    {
784        if (!Str::startsWith($gedcom, '0 @@ FAM')) {
785            throw new InvalidArgumentException('GedcomRecord::createFamily(' . $gedcom . ') does not begin 0 @@ FAM');
786        }
787
788        $xref   = $this->getNewXref();
789        $gedcom = '0 @' . $xref . '@ FAM' . Str::after($gedcom, '0 @@ FAM');
790
791        // Create a change record
792        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
793
794        // Create a pending change
795        DB::table('change')->insert([
796            'gedcom_id'  => $this->id,
797            'xref'       => $xref,
798            'old_gedcom' => '',
799            'new_gedcom' => $gedcom,
800            'user_id'    => Auth::id(),
801        ]);
802
803        // Accept this pending change
804        if (Auth::user()->getPreference('auto_accept')) {
805            FunctionsImport::acceptAllChanges($xref, $this);
806
807            return new Family($xref, $gedcom, null, $this);
808        }
809
810        return new Family($xref, '', $gedcom, $this);
811    }
812
813    /**
814     * Create a new individual from GEDCOM data.
815     *
816     * @param string $gedcom
817     *
818     * @return Individual
819     * @throws InvalidArgumentException
820     */
821    public function createIndividual(string $gedcom): GedcomRecord
822    {
823        if (!Str::startsWith($gedcom, '0 @@ INDI')) {
824            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ INDI');
825        }
826
827        $xref   = $this->getNewXref();
828        $gedcom = '0 @' . $xref . '@ INDI' . Str::after($gedcom, '0 @@ INDI');
829
830        // Create a change record
831        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
832
833        // Create a pending change
834        DB::table('change')->insert([
835            'gedcom_id'  => $this->id,
836            'xref'       => $xref,
837            'old_gedcom' => '',
838            'new_gedcom' => $gedcom,
839            'user_id'    => Auth::id(),
840        ]);
841
842        // Accept this pending change
843        if (Auth::user()->getPreference('auto_accept')) {
844            FunctionsImport::acceptAllChanges($xref, $this);
845
846            return new Individual($xref, $gedcom, null, $this);
847        }
848
849        return new Individual($xref, '', $gedcom, $this);
850    }
851
852    /**
853     * Create a new media object from GEDCOM data.
854     *
855     * @param string $gedcom
856     *
857     * @return Media
858     * @throws InvalidArgumentException
859     */
860    public function createMediaObject(string $gedcom): Media
861    {
862        if (!Str::startsWith($gedcom, '0 @@ OBJE')) {
863            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ OBJE');
864        }
865
866        $xref   = $this->getNewXref();
867        $gedcom = '0 @' . $xref . '@ OBJE' . Str::after($gedcom, '0 @@ OBJE');
868
869        // Create a change record
870        $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
871
872        // Create a pending change
873        DB::table('change')->insert([
874            'gedcom_id'  => $this->id,
875            'xref'       => $xref,
876            'old_gedcom' => '',
877            'new_gedcom' => $gedcom,
878            'user_id'    => Auth::id(),
879        ]);
880
881        // Accept this pending change
882        if (Auth::user()->getPreference('auto_accept')) {
883            FunctionsImport::acceptAllChanges($xref, $this);
884
885            return new Media($xref, $gedcom, null, $this);
886        }
887
888        return new Media($xref, '', $gedcom, $this);
889    }
890
891    /**
892     * What is the most significant individual in this tree.
893     *
894     * @param UserInterface $user
895     *
896     * @return Individual
897     */
898    public function significantIndividual(UserInterface $user): Individual
899    {
900        $individual = null;
901
902        if ($this->getUserPreference($user, 'rootid') !== '') {
903            $individual = Individual::getInstance($this->getUserPreference($user, 'rootid'), $this);
904        }
905
906        if ($individual === null && $this->getUserPreference($user, 'gedcomid') !== '') {
907            $individual = Individual::getInstance($this->getUserPreference($user, 'gedcomid'), $this);
908        }
909
910        if ($individual === null && $this->getPreference('PEDIGREE_ROOT_ID') !== '') {
911            $individual = Individual::getInstance($this->getPreference('PEDIGREE_ROOT_ID'), $this);
912        }
913        if ($individual === null) {
914            $xref = (string) DB::table('individuals')
915                ->where('i_file', '=', $this->id())
916                ->min('i_id');
917
918            $individual = Individual::getInstance($xref, $this);
919        }
920        if ($individual === null) {
921            // always return a record
922            $individual = new Individual('I', '0 @I@ INDI', null, $this);
923        }
924
925        return $individual;
926    }
927}
928