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