xref: /webtrees/app/GedcomRecord.php (revision 47256fc55b9e67669baf4ed9ab0f12daab839d41)
1a25f0a04SGreg Roach<?php
23976b470SGreg Roach
3a25f0a04SGreg Roach/**
4a25f0a04SGreg Roach * webtrees: online genealogy
58fcd0d32SGreg Roach * Copyright (C) 2019 webtrees development team
6a25f0a04SGreg Roach * This program is free software: you can redistribute it and/or modify
7a25f0a04SGreg Roach * it under the terms of the GNU General Public License as published by
8a25f0a04SGreg Roach * the Free Software Foundation, either version 3 of the License, or
9a25f0a04SGreg Roach * (at your option) any later version.
10a25f0a04SGreg Roach * This program is distributed in the hope that it will be useful,
11a25f0a04SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
12a25f0a04SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13a25f0a04SGreg Roach * GNU General Public License for more details.
14a25f0a04SGreg Roach * You should have received a copy of the GNU General Public License
15a25f0a04SGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
16a25f0a04SGreg Roach */
17e7f56f2aSGreg Roachdeclare(strict_types=1);
18e7f56f2aSGreg Roach
1976692c8bSGreg Roachnamespace Fisharebest\Webtrees;
2076692c8bSGreg Roach
21886b77daSGreg Roachuse Closure;
227e96c925SGreg Roachuse Exception;
233d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
243d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsPrint;
25bf4eb542SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
2683242252SGreg Roachuse Illuminate\Database\Query\Builder;
2783242252SGreg Roachuse Illuminate\Database\Query\Expression;
28ba1c12e8SGreg Roachuse Illuminate\Database\Query\JoinClause;
2939ca88baSGreg Roachuse Illuminate\Support\Collection;
3079529c87SGreg Roachuse stdClass;
31a25f0a04SGreg Roach
32a25f0a04SGreg Roach/**
3376692c8bSGreg Roach * A GEDCOM object.
34a25f0a04SGreg Roach */
35c1010edaSGreg Roachclass GedcomRecord
36c1010edaSGreg Roach{
3716d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
3816d6367aSGreg Roach
3916d6367aSGreg Roach    protected const ROUTE_NAME = 'record';
40a25f0a04SGreg Roach
41a25f0a04SGreg Roach    /** @var string The record identifier */
42a25f0a04SGreg Roach    protected $xref;
43a25f0a04SGreg Roach
44000959d9SGreg Roach    /** @var Tree  The family tree to which this record belongs */
45000959d9SGreg Roach    protected $tree;
46a25f0a04SGreg Roach
47a25f0a04SGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
48a25f0a04SGreg Roach    protected $gedcom;
49a25f0a04SGreg Roach
50a25f0a04SGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
51a25f0a04SGreg Roach    protected $pending;
52a25f0a04SGreg Roach
53a25f0a04SGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
54a25f0a04SGreg Roach    protected $facts;
55a25f0a04SGreg Roach
56a25f0a04SGreg Roach    /** @var string[][] All the names of this individual */
57bdb3725aSGreg Roach    protected $getAllNames;
58a25f0a04SGreg Roach
59d17d7b9eSGreg Roach    /** @var int|null Cached result */
60bdb3725aSGreg Roach    protected $getPrimaryName;
61a25f0a04SGreg Roach
62d17d7b9eSGreg Roach    /** @var int|null Cached result */
63bdb3725aSGreg Roach    protected $getSecondaryName;
64a25f0a04SGreg Roach
6576692c8bSGreg Roach    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
66bec87e94SGreg Roach    public static $gedcom_record_cache;
671ae87ce5SGreg Roach
6879529c87SGreg Roach    /** @var stdClass[][] Fetch all pending edits in one database query */
69bec87e94SGreg Roach    public static $pending_record_cache;
70a25f0a04SGreg Roach
71a25f0a04SGreg Roach    /**
72a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
73a25f0a04SGreg Roach     *
74a25f0a04SGreg Roach     * @param string      $xref
75a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
76a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
77a25f0a04SGreg Roach     *                             empty string for records with pending deletions
7824ec66ceSGreg Roach     * @param Tree        $tree
79a25f0a04SGreg Roach     */
80e364afe4SGreg Roach    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
81c1010edaSGreg Roach    {
82a25f0a04SGreg Roach        $this->xref    = $xref;
83a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
84a25f0a04SGreg Roach        $this->pending = $pending;
8524ec66ceSGreg Roach        $this->tree    = $tree;
86a25f0a04SGreg Roach
87a25f0a04SGreg Roach        $this->parseFacts();
88a25f0a04SGreg Roach    }
89a25f0a04SGreg Roach
90a25f0a04SGreg Roach    /**
91886b77daSGreg Roach     * A closure which will create a record from a database row.
92886b77daSGreg Roach     *
93886b77daSGreg Roach     * @return Closure
94886b77daSGreg Roach     */
95c0804649SGreg Roach    public static function rowMapper(): Closure
96886b77daSGreg Roach    {
976c2179e2SGreg Roach        return static function (stdClass $row): GedcomRecord {
98e3bddf11SGreg Roach            return GedcomRecord::getInstance($row->o_id, Tree::findById((int) $row->o_file), $row->o_gedcom);
99886b77daSGreg Roach        };
100886b77daSGreg Roach    }
101886b77daSGreg Roach
102886b77daSGreg Roach    /**
103886b77daSGreg Roach     * A closure which will filter out private records.
104886b77daSGreg Roach     *
105886b77daSGreg Roach     * @return Closure
106886b77daSGreg Roach     */
1074146fabcSGreg Roach    public static function accessFilter(): Closure
108886b77daSGreg Roach    {
1096c2179e2SGreg Roach        return static function (GedcomRecord $record): bool {
110886b77daSGreg Roach            return $record->canShow();
111886b77daSGreg Roach        };
112886b77daSGreg Roach    }
113886b77daSGreg Roach
114886b77daSGreg Roach    /**
115c156e8f5SGreg Roach     * A closure which will compare records by name.
116c156e8f5SGreg Roach     *
117c156e8f5SGreg Roach     * @return Closure
118c156e8f5SGreg Roach     */
119c156e8f5SGreg Roach    public static function nameComparator(): Closure
120c156e8f5SGreg Roach    {
1216c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y): int {
122c156e8f5SGreg Roach            if ($x->canShowName()) {
123c156e8f5SGreg Roach                if ($y->canShowName()) {
12439ca88baSGreg Roach                    return I18N::strcasecmp($x->sortName(), $y->sortName());
125c156e8f5SGreg Roach                }
126c156e8f5SGreg Roach
127c156e8f5SGreg Roach                return -1; // only $y is private
128c156e8f5SGreg Roach            }
129c156e8f5SGreg Roach
130c156e8f5SGreg Roach            if ($y->canShowName()) {
131c156e8f5SGreg Roach                return 1; // only $x is private
132c156e8f5SGreg Roach            }
133c156e8f5SGreg Roach
134c156e8f5SGreg Roach            return 0; // both $x and $y private
135c156e8f5SGreg Roach        };
136c156e8f5SGreg Roach    }
137c156e8f5SGreg Roach
138c156e8f5SGreg Roach    /**
139c156e8f5SGreg Roach     * A closure which will compare records by change time.
140c156e8f5SGreg Roach     *
141c156e8f5SGreg Roach     * @param int $direction +1 to sort ascending, -1 to sort descending
142c156e8f5SGreg Roach     *
143c156e8f5SGreg Roach     * @return Closure
144c156e8f5SGreg Roach     */
145c156e8f5SGreg Roach    public static function lastChangeComparator(int $direction = 1): Closure
146c156e8f5SGreg Roach    {
1476c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
1484459dc9aSGreg Roach            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
149c156e8f5SGreg Roach        };
150c156e8f5SGreg Roach    }
151c156e8f5SGreg Roach
152c156e8f5SGreg Roach    /**
153a25f0a04SGreg Roach     * Split the record into facts
1547e96c925SGreg Roach     *
1557e96c925SGreg Roach     * @return void
156a25f0a04SGreg Roach     */
157e364afe4SGreg Roach    private function parseFacts(): void
158c1010edaSGreg Roach    {
159a25f0a04SGreg Roach        // Split the record into facts
160a25f0a04SGreg Roach        if ($this->gedcom) {
161a25f0a04SGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
162a25f0a04SGreg Roach            array_shift($gedcom_facts);
163a25f0a04SGreg Roach        } else {
16413abd6f3SGreg Roach            $gedcom_facts = [];
165a25f0a04SGreg Roach        }
166a25f0a04SGreg Roach        if ($this->pending) {
167a25f0a04SGreg Roach            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
168a25f0a04SGreg Roach            array_shift($pending_facts);
169a25f0a04SGreg Roach        } else {
17013abd6f3SGreg Roach            $pending_facts = [];
171a25f0a04SGreg Roach        }
172a25f0a04SGreg Roach
17313abd6f3SGreg Roach        $this->facts = [];
174a25f0a04SGreg Roach
175a25f0a04SGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
176a25f0a04SGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
17722d65e5aSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
178a25f0a04SGreg Roach                $fact->setPendingDeletion();
179a25f0a04SGreg Roach            }
180a25f0a04SGreg Roach            $this->facts[] = $fact;
181a25f0a04SGreg Roach        }
182a25f0a04SGreg Roach        foreach ($pending_facts as $pending_fact) {
18322d65e5aSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
184a25f0a04SGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
185a25f0a04SGreg Roach                $fact->setPendingAddition();
186a25f0a04SGreg Roach                $this->facts[] = $fact;
187a25f0a04SGreg Roach            }
188a25f0a04SGreg Roach        }
189a25f0a04SGreg Roach    }
190a25f0a04SGreg Roach
191a25f0a04SGreg Roach    /**
192a25f0a04SGreg Roach     * Get an instance of a GedcomRecord object. For single records,
193a25f0a04SGreg Roach     * we just receive the XREF. For bulk records (such as lists
194a25f0a04SGreg Roach     * and search results) we can receive the GEDCOM data as well.
195a25f0a04SGreg Roach     *
196a25f0a04SGreg Roach     * @param string      $xref
19724ec66ceSGreg Roach     * @param Tree        $tree
198a25f0a04SGreg Roach     * @param string|null $gedcom
199a25f0a04SGreg Roach     *
2007e96c925SGreg Roach     * @throws Exception
20184658595SGreg Roach     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|null
202a25f0a04SGreg Roach     */
20376f666f4SGreg Roach    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
204c1010edaSGreg Roach    {
20572cf66d4SGreg Roach        $tree_id = $tree->id();
20624ec66ceSGreg Roach
207e71ef9d2SGreg Roach        // Is this record already in the cache?
20824ec66ceSGreg Roach        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
209e71ef9d2SGreg Roach            return self::$gedcom_record_cache[$xref][$tree_id];
210a25f0a04SGreg Roach        }
211a25f0a04SGreg Roach
212a25f0a04SGreg Roach        // Do we need to fetch the record from the database?
213a25f0a04SGreg Roach        if ($gedcom === null) {
21424ec66ceSGreg Roach            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
215a25f0a04SGreg Roach        }
216a25f0a04SGreg Roach
217a25f0a04SGreg Roach        // If we can edit, then we also need to be able to see pending records.
21894075df0SGreg Roach        if (Auth::isEditor($tree)) {
21924ec66ceSGreg Roach            if (!isset(self::$pending_record_cache[$tree_id])) {
220a25f0a04SGreg Roach                // Fetch all pending records in one database query
22113abd6f3SGreg Roach                self::$pending_record_cache[$tree_id] = [];
22285fc8064SGreg Roach                $rows                                 = DB::table('change')
22385fc8064SGreg Roach                    ->where('gedcom_id', '=', $tree_id)
22485fc8064SGreg Roach                    ->where('status', '=', 'pending')
22585fc8064SGreg Roach                    ->orderBy('change_id')
22685fc8064SGreg Roach                    ->select(['xref', 'new_gedcom'])
22785fc8064SGreg Roach                    ->get();
228d17d7b9eSGreg Roach
229a25f0a04SGreg Roach                foreach ($rows as $row) {
23024ec66ceSGreg Roach                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
231a25f0a04SGreg Roach                }
232a25f0a04SGreg Roach            }
233a25f0a04SGreg Roach
234d17d7b9eSGreg Roach            $pending = self::$pending_record_cache[$tree_id][$xref] ?? null;
235a25f0a04SGreg Roach        } else {
236a25f0a04SGreg Roach            // There are no pending changes for this record
237a25f0a04SGreg Roach            $pending = null;
238a25f0a04SGreg Roach        }
239a25f0a04SGreg Roach
240a25f0a04SGreg Roach        // No such record exists
241a25f0a04SGreg Roach        if ($gedcom === null && $pending === null) {
242a25f0a04SGreg Roach            return null;
243a25f0a04SGreg Roach        }
244a25f0a04SGreg Roach
245fc3ccce4SGreg Roach        // No such record, but a pending creation exists
246fc3ccce4SGreg Roach        if ($gedcom === null) {
247fc3ccce4SGreg Roach            $gedcom = '';
248fc3ccce4SGreg Roach        }
249fc3ccce4SGreg Roach
250a25f0a04SGreg Roach        // Create the object
2518d0ebef0SGreg Roach        if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedcom . $pending, $match)) {
252a25f0a04SGreg Roach            $xref = $match[1]; // Collation - we may have requested I123 and found i123
253a25f0a04SGreg Roach            $type = $match[2];
254a25f0a04SGreg Roach        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
255a25f0a04SGreg Roach            $xref = $match[1];
256a25f0a04SGreg Roach            $type = $match[1];
257a25f0a04SGreg Roach        } elseif ($gedcom . $pending) {
2587e96c925SGreg Roach            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
259a25f0a04SGreg Roach        } else {
260a25f0a04SGreg Roach            // A record with both pending creation and pending deletion
261a25f0a04SGreg Roach            $type = static::RECORD_TYPE;
262a25f0a04SGreg Roach        }
263a25f0a04SGreg Roach
264a25f0a04SGreg Roach        switch ($type) {
265a25f0a04SGreg Roach            case 'INDI':
26624ec66ceSGreg Roach                $record = new Individual($xref, $gedcom, $pending, $tree);
267a25f0a04SGreg Roach                break;
268a25f0a04SGreg Roach            case 'FAM':
26924ec66ceSGreg Roach                $record = new Family($xref, $gedcom, $pending, $tree);
270a25f0a04SGreg Roach                break;
271a25f0a04SGreg Roach            case 'SOUR':
27224ec66ceSGreg Roach                $record = new Source($xref, $gedcom, $pending, $tree);
273a25f0a04SGreg Roach                break;
274a25f0a04SGreg Roach            case 'OBJE':
27524ec66ceSGreg Roach                $record = new Media($xref, $gedcom, $pending, $tree);
276a25f0a04SGreg Roach                break;
277a25f0a04SGreg Roach            case 'REPO':
27824ec66ceSGreg Roach                $record = new Repository($xref, $gedcom, $pending, $tree);
279a25f0a04SGreg Roach                break;
280a25f0a04SGreg Roach            case 'NOTE':
28124ec66ceSGreg Roach                $record = new Note($xref, $gedcom, $pending, $tree);
282a25f0a04SGreg Roach                break;
283a25f0a04SGreg Roach            default:
28406ef8e02SGreg Roach                $record = new self($xref, $gedcom, $pending, $tree);
285a25f0a04SGreg Roach                break;
286a25f0a04SGreg Roach        }
287a25f0a04SGreg Roach
288a25f0a04SGreg Roach        // Store it in the cache
28924ec66ceSGreg Roach        self::$gedcom_record_cache[$xref][$tree_id] = $record;
290a25f0a04SGreg Roach
291a25f0a04SGreg Roach        return $record;
292a25f0a04SGreg Roach    }
293a25f0a04SGreg Roach
294a25f0a04SGreg Roach    /**
295a25f0a04SGreg Roach     * Fetch data from the database
296a25f0a04SGreg Roach     *
297a25f0a04SGreg Roach     * @param string $xref
298cbc1590aSGreg Roach     * @param int    $tree_id
299a25f0a04SGreg Roach     *
300e364afe4SGreg Roach     * @return string|null
301a25f0a04SGreg Roach     */
302e364afe4SGreg Roach    protected static function fetchGedcomRecord(string $xref, int $tree_id): ?string
303c1010edaSGreg Roach    {
304a25f0a04SGreg Roach        // We don't know what type of object this is. Try each one in turn.
30564d9078aSGreg Roach        $data = Individual::fetchGedcomRecord($xref, $tree_id);
30685fc8064SGreg Roach        if ($data !== null) {
307a25f0a04SGreg Roach            return $data;
308a25f0a04SGreg Roach        }
30964d9078aSGreg Roach        $data = Family::fetchGedcomRecord($xref, $tree_id);
31085fc8064SGreg Roach        if ($data !== null) {
311a25f0a04SGreg Roach            return $data;
312a25f0a04SGreg Roach        }
31364d9078aSGreg Roach        $data = Source::fetchGedcomRecord($xref, $tree_id);
31485fc8064SGreg Roach        if ($data !== null) {
315a25f0a04SGreg Roach            return $data;
316a25f0a04SGreg Roach        }
31764d9078aSGreg Roach        $data = Repository::fetchGedcomRecord($xref, $tree_id);
31885fc8064SGreg Roach        if ($data !== null) {
319a25f0a04SGreg Roach            return $data;
320a25f0a04SGreg Roach        }
32164d9078aSGreg Roach        $data = Media::fetchGedcomRecord($xref, $tree_id);
32285fc8064SGreg Roach        if ($data !== null) {
323a25f0a04SGreg Roach            return $data;
324a25f0a04SGreg Roach        }
32564d9078aSGreg Roach        $data = Note::fetchGedcomRecord($xref, $tree_id);
32685fc8064SGreg Roach        if ($data !== null) {
327a25f0a04SGreg Roach            return $data;
328a25f0a04SGreg Roach        }
329c1010edaSGreg Roach
330a25f0a04SGreg Roach        // Some other type of record...
331d09b6323SGreg Roach        return DB::table('other')
33285fc8064SGreg Roach            ->where('o_file', '=', $tree_id)
33385fc8064SGreg Roach            ->where('o_id', '=', $xref)
33485fc8064SGreg Roach            ->value('o_gedcom');
335a25f0a04SGreg Roach    }
336a25f0a04SGreg Roach
337a25f0a04SGreg Roach    /**
338a25f0a04SGreg Roach     * Get the XREF for this record
339a25f0a04SGreg Roach     *
340a25f0a04SGreg Roach     * @return string
341a25f0a04SGreg Roach     */
342c0935879SGreg Roach    public function xref(): string
343c1010edaSGreg Roach    {
344a25f0a04SGreg Roach        return $this->xref;
345a25f0a04SGreg Roach    }
346a25f0a04SGreg Roach
347a25f0a04SGreg Roach    /**
348000959d9SGreg Roach     * Get the tree to which this record belongs
349000959d9SGreg Roach     *
350000959d9SGreg Roach     * @return Tree
351000959d9SGreg Roach     */
352f4afa648SGreg Roach    public function tree(): Tree
353c1010edaSGreg Roach    {
354518bbdc1SGreg Roach        return $this->tree;
355000959d9SGreg Roach    }
356000959d9SGreg Roach
357000959d9SGreg Roach    /**
358a25f0a04SGreg Roach     * Application code should access data via Fact objects.
359a25f0a04SGreg Roach     * This function exists to support old code.
360a25f0a04SGreg Roach     *
361a25f0a04SGreg Roach     * @return string
362a25f0a04SGreg Roach     */
363e364afe4SGreg Roach    public function gedcom(): string
364c1010edaSGreg Roach    {
365b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
366a25f0a04SGreg Roach    }
367a25f0a04SGreg Roach
368a25f0a04SGreg Roach    /**
369a25f0a04SGreg Roach     * Does this record have a pending change?
370a25f0a04SGreg Roach     *
371cbc1590aSGreg Roach     * @return bool
372a25f0a04SGreg Roach     */
3738f53f488SRico Sonntag    public function isPendingAddition(): bool
374c1010edaSGreg Roach    {
375a25f0a04SGreg Roach        return $this->pending !== null;
376a25f0a04SGreg Roach    }
377a25f0a04SGreg Roach
378a25f0a04SGreg Roach    /**
379a25f0a04SGreg Roach     * Does this record have a pending deletion?
380a25f0a04SGreg Roach     *
381cbc1590aSGreg Roach     * @return bool
382a25f0a04SGreg Roach     */
3838f53f488SRico Sonntag    public function isPendingDeletion(): bool
384c1010edaSGreg Roach    {
385a25f0a04SGreg Roach        return $this->pending === '';
386a25f0a04SGreg Roach    }
387a25f0a04SGreg Roach
388a25f0a04SGreg Roach    /**
389225e381fSGreg Roach     * Generate a URL to this record.
390a25f0a04SGreg Roach     *
391a25f0a04SGreg Roach     * @return string
392a25f0a04SGreg Roach     */
3938f53f488SRico Sonntag    public function url(): string
394c1010edaSGreg Roach    {
395225e381fSGreg Roach        return route(static::ROUTE_NAME, [
396c0935879SGreg Roach            'xref' => $this->xref(),
397aa6f03bbSGreg Roach            'ged'  => $this->tree->name(),
398225e381fSGreg Roach        ]);
399a25f0a04SGreg Roach    }
400a25f0a04SGreg Roach
401a25f0a04SGreg Roach    /**
402a25f0a04SGreg Roach     * Work out whether this record can be shown to a user with a given access level
403a25f0a04SGreg Roach     *
404cbc1590aSGreg Roach     * @param int $access_level
405a25f0a04SGreg Roach     *
406cbc1590aSGreg Roach     * @return bool
407a25f0a04SGreg Roach     */
40876f666f4SGreg Roach    private function canShowRecord(int $access_level): bool
409c1010edaSGreg Roach    {
410a25f0a04SGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
411518bbdc1SGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
412a25f0a04SGreg Roach            return true;
413a25f0a04SGreg Roach        }
414a25f0a04SGreg Roach
415a25f0a04SGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
416c0935879SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), 'gedcomid') && $access_level === Auth::accessLevel($this->tree)) {
417a25f0a04SGreg Roach            return true;
418a25f0a04SGreg Roach        }
419a25f0a04SGreg Roach
420a25f0a04SGreg Roach        // Does this record have a RESN?
42120ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
4224b9ff166SGreg Roach            return Auth::PRIV_NONE >= $access_level;
423a25f0a04SGreg Roach        }
42420ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
4254b9ff166SGreg Roach            return Auth::PRIV_USER >= $access_level;
426a25f0a04SGreg Roach        }
42720ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
428a25f0a04SGreg Roach            return true;
429a25f0a04SGreg Roach        }
430a25f0a04SGreg Roach
431a25f0a04SGreg Roach        // Does this record have a default RESN?
432518bbdc1SGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
433c0935879SGreg Roach        if (isset($individual_privacy[$this->xref()])) {
434c0935879SGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
435a25f0a04SGreg Roach        }
436a25f0a04SGreg Roach
437a25f0a04SGreg Roach        // Privacy rules do not apply to admins
4384b9ff166SGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
439a25f0a04SGreg Roach            return true;
440a25f0a04SGreg Roach        }
441a25f0a04SGreg Roach
442a25f0a04SGreg Roach        // Different types of record have different privacy rules
443a25f0a04SGreg Roach        return $this->canShowByType($access_level);
444a25f0a04SGreg Roach    }
445a25f0a04SGreg Roach
446a25f0a04SGreg Roach    /**
447a25f0a04SGreg Roach     * Each object type may have its own special rules, and re-implement this function.
448a25f0a04SGreg Roach     *
449cbc1590aSGreg Roach     * @param int $access_level
450a25f0a04SGreg Roach     *
451cbc1590aSGreg Roach     * @return bool
452a25f0a04SGreg Roach     */
45335584196SGreg Roach    protected function canShowByType(int $access_level): bool
454c1010edaSGreg Roach    {
455518bbdc1SGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
456a25f0a04SGreg Roach
457518bbdc1SGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
458a25f0a04SGreg Roach            // Restriction found
459518bbdc1SGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
460b2ce94c6SRico Sonntag        }
461b2ce94c6SRico Sonntag
462a25f0a04SGreg Roach        // No restriction found - must be public:
463a25f0a04SGreg Roach        return true;
464a25f0a04SGreg Roach    }
465a25f0a04SGreg Roach
466a25f0a04SGreg Roach    /**
467a25f0a04SGreg Roach     * Can the details of this record be shown?
468a25f0a04SGreg Roach     *
469cbc1590aSGreg Roach     * @param int|null $access_level
470a25f0a04SGreg Roach     *
471cbc1590aSGreg Roach     * @return bool
472a25f0a04SGreg Roach     */
47335584196SGreg Roach    public function canShow(int $access_level = null): bool
474c1010edaSGreg Roach    {
475f0b9c048SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
4764b9ff166SGreg Roach
477a25f0a04SGreg Roach        // We use this value to bypass privacy checks. For example,
478a25f0a04SGreg Roach        // when downloading data or when calculating privacy itself.
479f0b9c048SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
480a25f0a04SGreg Roach            return true;
481a25f0a04SGreg Roach        }
482f0b9c048SGreg Roach
483f0b9c048SGreg Roach        $cache_key = 'canShow' . $this->xref . ':' . $this->tree->id() . ':' . $access_level;
484f0b9c048SGreg Roach
485f0b9c048SGreg Roach        return app('cache.array')->rememberForever($cache_key, function () use ($access_level) {
486f0b9c048SGreg Roach            return $this->canShowRecord($access_level);
487f0b9c048SGreg Roach        });
488a25f0a04SGreg Roach    }
489a25f0a04SGreg Roach
490a25f0a04SGreg Roach    /**
491a25f0a04SGreg Roach     * Can the name of this record be shown?
492a25f0a04SGreg Roach     *
493cbc1590aSGreg Roach     * @param int|null $access_level
494a25f0a04SGreg Roach     *
495cbc1590aSGreg Roach     * @return bool
496a25f0a04SGreg Roach     */
49776f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
498c1010edaSGreg Roach    {
499a25f0a04SGreg Roach        return $this->canShow($access_level);
500a25f0a04SGreg Roach    }
501a25f0a04SGreg Roach
502a25f0a04SGreg Roach    /**
503a25f0a04SGreg Roach     * Can we edit this record?
504a25f0a04SGreg Roach     *
505cbc1590aSGreg Roach     * @return bool
506a25f0a04SGreg Roach     */
5078f53f488SRico Sonntag    public function canEdit(): bool
508c1010edaSGreg Roach    {
5091450f098SGreg Roach        if ($this->isPendingDeletion()) {
5101450f098SGreg Roach            return false;
5111450f098SGreg Roach        }
5121450f098SGreg Roach
5131450f098SGreg Roach        if (Auth::isManager($this->tree)) {
5141450f098SGreg Roach            return true;
5151450f098SGreg Roach        }
5161450f098SGreg Roach
5171450f098SGreg Roach        return Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
518a25f0a04SGreg Roach    }
519a25f0a04SGreg Roach
520a25f0a04SGreg Roach    /**
521a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
522a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
523a25f0a04SGreg Roach     *
524cbc1590aSGreg Roach     * @param int $access_level
525a25f0a04SGreg Roach     *
526a25f0a04SGreg Roach     * @return string
527a25f0a04SGreg Roach     */
528e364afe4SGreg Roach    public function privatizeGedcom(int $access_level): string
529c1010edaSGreg Roach    {
530e364afe4SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
531a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
532a25f0a04SGreg Roach            return $this->gedcom;
533b2ce94c6SRico Sonntag        }
534b2ce94c6SRico Sonntag
535b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
536a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
537a25f0a04SGreg Roach
538a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
53965e02381SGreg Roach            [$gedrec] = explode("\n", $this->gedcom, 2);
540a25f0a04SGreg Roach
541a25f0a04SGreg Roach            // Check each of the facts for access
5428d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
543138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
544a25f0a04SGreg Roach            }
545cbc1590aSGreg Roach
546a25f0a04SGreg Roach            return $gedrec;
547b2ce94c6SRico Sonntag        }
548b2ce94c6SRico Sonntag
549a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
550a25f0a04SGreg Roach        // limited data, such as links to other records.
551a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
552a25f0a04SGreg Roach    }
553a25f0a04SGreg Roach
554a25f0a04SGreg Roach    /**
555a25f0a04SGreg Roach     * Generate a private version of this record
556a25f0a04SGreg Roach     *
557cbc1590aSGreg Roach     * @param int $access_level
558a25f0a04SGreg Roach     *
559a25f0a04SGreg Roach     * @return string
560a25f0a04SGreg Roach     */
56176f666f4SGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
562c1010edaSGreg Roach    {
563a25f0a04SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
564a25f0a04SGreg Roach    }
565a25f0a04SGreg Roach
566a25f0a04SGreg Roach    /**
567a25f0a04SGreg Roach     * Convert a name record into sortable and full/display versions. This default
568a25f0a04SGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
569a25f0a04SGreg Roach     *
570a25f0a04SGreg Roach     * @param string $type
571a25f0a04SGreg Roach     * @param string $value
572a25f0a04SGreg Roach     * @param string $gedcom
5737e96c925SGreg Roach     *
5747e96c925SGreg Roach     * @return void
575a25f0a04SGreg Roach     */
576e364afe4SGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
577c1010edaSGreg Roach    {
578bdb3725aSGreg Roach        $this->getAllNames[] = [
579a25f0a04SGreg Roach            'type'   => $type,
5800b5fd0a6SGreg Roach            'sort'   => preg_replace_callback('/([0-9]+)/', static function (array $matches): string {
5818d68cabeSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
5828d68cabeSGreg Roach            }, $value),
583c1010edaSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
584c1010edaSGreg Roach            // This is used for display
585c1010edaSGreg Roach            'fullNN' => $value,
586c1010edaSGreg Roach            // This goes into the database
58713abd6f3SGreg Roach        ];
588a25f0a04SGreg Roach    }
589a25f0a04SGreg Roach
590a25f0a04SGreg Roach    /**
591a25f0a04SGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
592a25f0a04SGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
593a25f0a04SGreg Roach     * Parameters: the level 1 fact containing the name.
594a25f0a04SGreg Roach     * Return value: an array of name structures, each containing
595a25f0a04SGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
596a25f0a04SGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
597a25f0a04SGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
598a25f0a04SGreg Roach     *
599cbc1590aSGreg Roach     * @param int        $level
600a25f0a04SGreg Roach     * @param string     $fact_type
60154c7f8dfSGreg Roach     * @param Collection $facts
6027e96c925SGreg Roach     *
6037e96c925SGreg Roach     * @return void
604a25f0a04SGreg Roach     */
605e364afe4SGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
606c1010edaSGreg Roach    {
607a25f0a04SGreg Roach        $sublevel    = $level + 1;
608a25f0a04SGreg Roach        $subsublevel = $sublevel + 1;
609a25f0a04SGreg Roach        foreach ($facts as $fact) {
610138ca96cSGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
611a25f0a04SGreg Roach                foreach ($matches as $match) {
612a25f0a04SGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
613e364afe4SGreg Roach                    if ($match[1] === 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
614138ca96cSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
615a25f0a04SGreg Roach                    } else {
616138ca96cSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
617a25f0a04SGreg Roach                    }
618a25f0a04SGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
619a25f0a04SGreg Roach                        foreach ($submatches as $submatch) {
620a25f0a04SGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
621a25f0a04SGreg Roach                        }
622a25f0a04SGreg Roach                    }
623a25f0a04SGreg Roach                }
624a25f0a04SGreg Roach            }
625a25f0a04SGreg Roach        }
626a25f0a04SGreg Roach    }
627a25f0a04SGreg Roach
628a25f0a04SGreg Roach    /**
629a25f0a04SGreg Roach     * Default for "other" object types
630c7ff4153SGreg Roach     *
631c7ff4153SGreg Roach     * @return void
632a25f0a04SGreg Roach     */
633e364afe4SGreg Roach    public function extractNames(): void
634c1010edaSGreg Roach    {
63576f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
636a25f0a04SGreg Roach    }
637a25f0a04SGreg Roach
638a25f0a04SGreg Roach    /**
639a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
640a25f0a04SGreg Roach     *
641a25f0a04SGreg Roach     * @return string[][]
642a25f0a04SGreg Roach     */
6438f53f488SRico Sonntag    public function getAllNames(): array
644c1010edaSGreg Roach    {
645bdb3725aSGreg Roach        if ($this->getAllNames === null) {
646bdb3725aSGreg Roach            $this->getAllNames = [];
647a25f0a04SGreg Roach            if ($this->canShowName()) {
648a25f0a04SGreg Roach                // Ask the record to extract its names
649a25f0a04SGreg Roach                $this->extractNames();
650a25f0a04SGreg Roach                // No name found? Use a fallback.
651bdb3725aSGreg Roach                if (!$this->getAllNames) {
652db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
653a25f0a04SGreg Roach                }
654a25f0a04SGreg Roach            } else {
655db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
656a25f0a04SGreg Roach            }
657a25f0a04SGreg Roach        }
658cbc1590aSGreg Roach
659bdb3725aSGreg Roach        return $this->getAllNames;
660a25f0a04SGreg Roach    }
661a25f0a04SGreg Roach
662a25f0a04SGreg Roach    /**
663a25f0a04SGreg Roach     * If this object has no name, what do we call it?
664a25f0a04SGreg Roach     *
665a25f0a04SGreg Roach     * @return string
666a25f0a04SGreg Roach     */
6678f53f488SRico Sonntag    public function getFallBackName(): string
668c1010edaSGreg Roach    {
669c0935879SGreg Roach        return e($this->xref());
670a25f0a04SGreg Roach    }
671a25f0a04SGreg Roach
672a25f0a04SGreg Roach    /**
673a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
674a25f0a04SGreg Roach     *
675cbc1590aSGreg Roach     * @return int
676a25f0a04SGreg Roach     */
6778f53f488SRico Sonntag    public function getPrimaryName(): int
678c1010edaSGreg Roach    {
679a25f0a04SGreg Roach        static $language_script;
680a25f0a04SGreg Roach
681a25f0a04SGreg Roach        if ($language_script === null) {
682a25f0a04SGreg Roach            $language_script = I18N::languageScript(WT_LOCALE);
683a25f0a04SGreg Roach        }
684a25f0a04SGreg Roach
685bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
686a25f0a04SGreg Roach            // Generally, the first name is the primary one....
687bdb3725aSGreg Roach            $this->getPrimaryName = 0;
688a25f0a04SGreg Roach            // ...except when the language/name use different character sets
689a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
69069546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
691bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
692a25f0a04SGreg Roach                    break;
693a25f0a04SGreg Roach                }
694a25f0a04SGreg Roach            }
695a25f0a04SGreg Roach        }
696a25f0a04SGreg Roach
697bdb3725aSGreg Roach        return $this->getPrimaryName;
698a25f0a04SGreg Roach    }
699a25f0a04SGreg Roach
700a25f0a04SGreg Roach    /**
701a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
702a25f0a04SGreg Roach     *
703cbc1590aSGreg Roach     * @return int
704a25f0a04SGreg Roach     */
7058f53f488SRico Sonntag    public function getSecondaryName(): int
706c1010edaSGreg Roach    {
7078f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
708a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
709bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
710a25f0a04SGreg Roach            // ....except when there are names with different character sets
711a25f0a04SGreg Roach            $all_names = $this->getAllNames();
712a25f0a04SGreg Roach            if (count($all_names) > 1) {
713a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
714a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
715e364afe4SGreg Roach                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
716bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
717a25f0a04SGreg Roach                        break;
718a25f0a04SGreg Roach                    }
719a25f0a04SGreg Roach                }
720a25f0a04SGreg Roach            }
721a25f0a04SGreg Roach        }
722cbc1590aSGreg Roach
723bdb3725aSGreg Roach        return $this->getSecondaryName;
724a25f0a04SGreg Roach    }
725a25f0a04SGreg Roach
726a25f0a04SGreg Roach    /**
727a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
728a25f0a04SGreg Roach     *
72976f666f4SGreg Roach     * @param int|null $n
7307e96c925SGreg Roach     *
7317e96c925SGreg Roach     * @return void
732a25f0a04SGreg Roach     */
733e364afe4SGreg Roach    public function setPrimaryName(int $n = null): void
734c1010edaSGreg Roach    {
735bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
736bdb3725aSGreg Roach        $this->getSecondaryName = null;
737a25f0a04SGreg Roach    }
738a25f0a04SGreg Roach
739a25f0a04SGreg Roach    /**
740a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
741a25f0a04SGreg Roach     *
742a25f0a04SGreg Roach     * @return string
743a25f0a04SGreg Roach     */
744c1010edaSGreg Roach    public function __toString()
745c1010edaSGreg Roach    {
74672cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
747a25f0a04SGreg Roach    }
748a25f0a04SGreg Roach
749a25f0a04SGreg Roach    /**
750c156e8f5SGreg Roach     * /**
751a25f0a04SGreg Roach     * Get variants of the name
752a25f0a04SGreg Roach     *
753a25f0a04SGreg Roach     * @return string
754a25f0a04SGreg Roach     */
755e364afe4SGreg Roach    public function fullName(): string
756c1010edaSGreg Roach    {
757a25f0a04SGreg Roach        if ($this->canShowName()) {
758a25f0a04SGreg Roach            $tmp = $this->getAllNames();
759cbc1590aSGreg Roach
760a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
761a25f0a04SGreg Roach        }
762b2ce94c6SRico Sonntag
763b2ce94c6SRico Sonntag        return I18N::translate('Private');
764a25f0a04SGreg Roach    }
765a25f0a04SGreg Roach
766a25f0a04SGreg Roach    /**
767a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
768a25f0a04SGreg Roach     *
769a25f0a04SGreg Roach     * @return string
770a25f0a04SGreg Roach     */
77139ca88baSGreg Roach    public function sortName(): string
772c1010edaSGreg Roach    {
773a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
774a25f0a04SGreg Roach        $tmp = $this->getAllNames();
775cbc1590aSGreg Roach
776a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
777a25f0a04SGreg Roach    }
778a25f0a04SGreg Roach
779a25f0a04SGreg Roach    /**
780a25f0a04SGreg Roach     * Get the full name in an alternative character set
781a25f0a04SGreg Roach     *
782e364afe4SGreg Roach     * @return string|null
783a25f0a04SGreg Roach     */
784e364afe4SGreg Roach    public function alternateName(): ?string
785c1010edaSGreg Roach    {
786e364afe4SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
787a25f0a04SGreg Roach            $all_names = $this->getAllNames();
788cbc1590aSGreg Roach
789a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
790a25f0a04SGreg Roach        }
791b2ce94c6SRico Sonntag
792b2ce94c6SRico Sonntag        return null;
793a25f0a04SGreg Roach    }
794a25f0a04SGreg Roach
795a25f0a04SGreg Roach    /**
796a25f0a04SGreg Roach     * Format this object for display in a list
797a25f0a04SGreg Roach     *
798a25f0a04SGreg Roach     * @return string
799a25f0a04SGreg Roach     */
8008f53f488SRico Sonntag    public function formatList(): string
801c1010edaSGreg Roach    {
802b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
80339ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
804a25f0a04SGreg Roach        $html .= $this->formatListDetails();
805b165e17cSGreg Roach        $html .= '</a>';
806cbc1590aSGreg Roach
807a25f0a04SGreg Roach        return $html;
808a25f0a04SGreg Roach    }
809a25f0a04SGreg Roach
810a25f0a04SGreg Roach    /**
811a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
812a25f0a04SGreg Roach     * identifying characteristics of this record.
813a25f0a04SGreg Roach     *
814a25f0a04SGreg Roach     * @return string
815a25f0a04SGreg Roach     */
8168f53f488SRico Sonntag    public function formatListDetails(): string
817c1010edaSGreg Roach    {
818a25f0a04SGreg Roach        return '';
819a25f0a04SGreg Roach    }
820a25f0a04SGreg Roach
821a25f0a04SGreg Roach    /**
822a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
823a25f0a04SGreg Roach     *
8248d0ebef0SGreg Roach     * @param string[] $facts
825cbc1590aSGreg Roach     * @param int      $style
826a25f0a04SGreg Roach     *
827a25f0a04SGreg Roach     * @return string
828a25f0a04SGreg Roach     */
8298d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
830c1010edaSGreg Roach    {
83130158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
832a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
833e364afe4SGreg Roach            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
834d93f11b5SGreg Roach                $joiner = ' — ';
835d93f11b5SGreg Roach            } else {
836d93f11b5SGreg Roach                $joiner = '';
837d93f11b5SGreg Roach            }
838e364afe4SGreg Roach            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
839a25f0a04SGreg Roach                switch ($style) {
840a25f0a04SGreg Roach                    case 1:
8417b7d8067SGreg Roach                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
842a25f0a04SGreg Roach                    case 2:
8437b7d8067SGreg Roach                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
844a25f0a04SGreg Roach                }
845a25f0a04SGreg Roach            }
846a25f0a04SGreg Roach        }
847cbc1590aSGreg Roach
848a25f0a04SGreg Roach        return '';
849a25f0a04SGreg Roach    }
850a25f0a04SGreg Roach
851a25f0a04SGreg Roach    /**
852a25f0a04SGreg Roach     * Find individuals linked to this record.
853a25f0a04SGreg Roach     *
854a25f0a04SGreg Roach     * @param string $link
855a25f0a04SGreg Roach     *
856907c1109SGreg Roach     * @return Collection
857a25f0a04SGreg Roach     */
858907c1109SGreg Roach    public function linkedIndividuals(string $link): Collection
859c1010edaSGreg Roach    {
860907c1109SGreg Roach        return DB::table('individuals')
8610b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
862907c1109SGreg Roach                $join
863907c1109SGreg Roach                    ->on('l_file', '=', 'i_file')
864907c1109SGreg Roach                    ->on('l_from', '=', 'i_id');
865ba1c12e8SGreg Roach            })
866ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
867ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
868ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
869907c1109SGreg Roach            ->select(['individuals.*'])
870907c1109SGreg Roach            ->get()
871907c1109SGreg Roach            ->map(Individual::rowMapper())
872907c1109SGreg Roach            ->filter(self::accessFilter());
873a25f0a04SGreg Roach    }
874a25f0a04SGreg Roach
875a25f0a04SGreg Roach    /**
876a25f0a04SGreg Roach     * Find families linked to this record.
877a25f0a04SGreg Roach     *
878a25f0a04SGreg Roach     * @param string $link
879a25f0a04SGreg Roach     *
880907c1109SGreg Roach     * @return Collection
881a25f0a04SGreg Roach     */
882907c1109SGreg Roach    public function linkedFamilies(string $link): Collection
883c1010edaSGreg Roach    {
884907c1109SGreg Roach        return DB::table('families')
8850b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
886907c1109SGreg Roach                $join
887907c1109SGreg Roach                    ->on('l_file', '=', 'f_file')
888907c1109SGreg Roach                    ->on('l_from', '=', 'f_id');
889ba1c12e8SGreg Roach            })
890ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
891ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
892ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
893907c1109SGreg Roach            ->select(['families.*'])
894907c1109SGreg Roach            ->get()
895907c1109SGreg Roach            ->map(Family::rowMapper())
896907c1109SGreg Roach            ->filter(self::accessFilter());
897a25f0a04SGreg Roach    }
898a25f0a04SGreg Roach
899a25f0a04SGreg Roach    /**
900a25f0a04SGreg Roach     * Find sources linked to this record.
901a25f0a04SGreg Roach     *
902a25f0a04SGreg Roach     * @param string $link
903a25f0a04SGreg Roach     *
904907c1109SGreg Roach     * @return Collection
905a25f0a04SGreg Roach     */
906907c1109SGreg Roach    public function linkedSources(string $link): Collection
907c1010edaSGreg Roach    {
908907c1109SGreg Roach        return DB::table('sources')
9090b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
910907c1109SGreg Roach                $join
911907c1109SGreg Roach                    ->on('l_file', '=', 's_file')
912907c1109SGreg Roach                    ->on('l_from', '=', 's_id');
913ba1c12e8SGreg Roach            })
914ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
915ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
916ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
917907c1109SGreg Roach            ->select(['sources.*'])
918907c1109SGreg Roach            ->get()
919907c1109SGreg Roach            ->map(Source::rowMapper())
920907c1109SGreg Roach            ->filter(self::accessFilter());
921a25f0a04SGreg Roach    }
922a25f0a04SGreg Roach
923a25f0a04SGreg Roach    /**
924a25f0a04SGreg Roach     * Find media objects linked to this record.
925a25f0a04SGreg Roach     *
926a25f0a04SGreg Roach     * @param string $link
927a25f0a04SGreg Roach     *
928907c1109SGreg Roach     * @return Collection
929a25f0a04SGreg Roach     */
930907c1109SGreg Roach    public function linkedMedia(string $link): Collection
931c1010edaSGreg Roach    {
932907c1109SGreg Roach        return DB::table('media')
9330b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
934907c1109SGreg Roach                $join
935907c1109SGreg Roach                    ->on('l_file', '=', 'm_file')
936907c1109SGreg Roach                    ->on('l_from', '=', 'm_id');
937ba1c12e8SGreg Roach            })
938ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
939ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
940ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
941907c1109SGreg Roach            ->select(['media.*'])
942907c1109SGreg Roach            ->get()
943907c1109SGreg Roach            ->map(Media::rowMapper())
944907c1109SGreg Roach            ->filter(self::accessFilter());
945a25f0a04SGreg Roach    }
946a25f0a04SGreg Roach
947a25f0a04SGreg Roach    /**
948a25f0a04SGreg Roach     * Find notes linked to this record.
949a25f0a04SGreg Roach     *
950a25f0a04SGreg Roach     * @param string $link
951a25f0a04SGreg Roach     *
952907c1109SGreg Roach     * @return Collection
953a25f0a04SGreg Roach     */
954907c1109SGreg Roach    public function linkedNotes(string $link): Collection
955c1010edaSGreg Roach    {
956907c1109SGreg Roach        return DB::table('other')
9570b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
958907c1109SGreg Roach                $join
959907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
960907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
961ba1c12e8SGreg Roach            })
962ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
963ba1c12e8SGreg Roach            ->where('o_type', '=', 'NOTE')
964ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
965ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
966907c1109SGreg Roach            ->select(['other.*'])
967907c1109SGreg Roach            ->get()
968907c1109SGreg Roach            ->map(Note::rowMapper())
969907c1109SGreg Roach            ->filter(self::accessFilter());
970a25f0a04SGreg Roach    }
971a25f0a04SGreg Roach
972a25f0a04SGreg Roach    /**
973a25f0a04SGreg Roach     * Find repositories linked to this record.
974a25f0a04SGreg Roach     *
975a25f0a04SGreg Roach     * @param string $link
976a25f0a04SGreg Roach     *
977907c1109SGreg Roach     * @return Collection
978a25f0a04SGreg Roach     */
979907c1109SGreg Roach    public function linkedRepositories(string $link): Collection
980c1010edaSGreg Roach    {
981907c1109SGreg Roach        return DB::table('other')
9820b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
983907c1109SGreg Roach                $join
984907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
985907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
986ba1c12e8SGreg Roach            })
987ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
988ba1c12e8SGreg Roach            ->where('o_type', '=', 'REPO')
989ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
990ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
991907c1109SGreg Roach            ->select(['other.*'])
992907c1109SGreg Roach            ->get()
993907c1109SGreg Roach            ->map(Individual::rowMapper())
994907c1109SGreg Roach            ->filter(self::accessFilter());
995a25f0a04SGreg Roach    }
996a25f0a04SGreg Roach
997a25f0a04SGreg Roach    /**
998a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
999a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
1000a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
1001a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
1002a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
1003a25f0a04SGreg Roach     *
10048d0ebef0SGreg Roach     * @param string[] $events
1005a25f0a04SGreg Roach     *
1006a25f0a04SGreg Roach     * @return Date[]
1007a25f0a04SGreg Roach     */
10088d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
1009c1010edaSGreg Roach    {
101013abd6f3SGreg Roach        $dates = [];
10118d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
10122decada7SGreg Roach            if ($event->date()->isOK()) {
10132decada7SGreg Roach                $dates[] = $event->date();
1014a25f0a04SGreg Roach            }
1015a25f0a04SGreg Roach        }
1016a25f0a04SGreg Roach
1017a25f0a04SGreg Roach        return $dates;
1018a25f0a04SGreg Roach    }
1019a25f0a04SGreg Roach
1020a25f0a04SGreg Roach    /**
1021a25f0a04SGreg Roach     * Get all the places for a particular type of event
1022a25f0a04SGreg Roach     *
10238d0ebef0SGreg Roach     * @param string[] $events
1024a25f0a04SGreg Roach     *
10254080d558SGreg Roach     * @return Place[]
1026a25f0a04SGreg Roach     */
10278d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
1028c1010edaSGreg Roach    {
102913abd6f3SGreg Roach        $places = [];
10308d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
1031138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
1032a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
103316d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
1034a25f0a04SGreg Roach                }
1035a25f0a04SGreg Roach            }
1036a25f0a04SGreg Roach        }
1037a25f0a04SGreg Roach
1038a25f0a04SGreg Roach        return $places;
1039a25f0a04SGreg Roach    }
1040a25f0a04SGreg Roach
1041a25f0a04SGreg Roach    /**
1042a25f0a04SGreg Roach     * The facts and events for this record.
1043a25f0a04SGreg Roach     *
10448d0ebef0SGreg Roach     * @param string[] $filter
1045cbc1590aSGreg Roach     * @param bool     $sort
1046cbc1590aSGreg Roach     * @param int|null $access_level
1047cbc1590aSGreg Roach     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1048a25f0a04SGreg Roach     *
104954c7f8dfSGreg Roach     * @return Collection
1050a25f0a04SGreg Roach     */
105139ca88baSGreg Roach    public function facts(array $filter = [], bool $sort = false, int $access_level = null, bool $override = false): Collection
1052c1010edaSGreg Roach    {
10534b9ff166SGreg Roach        if ($access_level === null) {
10544b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
10554b9ff166SGreg Roach        }
10564b9ff166SGreg Roach
10578af3e5c1SGreg Roach        $facts = new Collection();
1058a25f0a04SGreg Roach        if ($this->canShow($access_level) || $override) {
1059a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
106022d65e5aSGreg Roach                if (($filter === [] || in_array($fact->getTag(), $filter, true)) && $fact->canShow($access_level)) {
10618af3e5c1SGreg Roach                    $facts->push($fact);
1062a25f0a04SGreg Roach                }
1063a25f0a04SGreg Roach            }
1064a25f0a04SGreg Roach        }
1065d17d7b9eSGreg Roach
1066a25f0a04SGreg Roach        if ($sort) {
1067580a4d11SGreg Roach            $facts = Fact::sortFacts($facts);
1068a25f0a04SGreg Roach        }
1069cbc1590aSGreg Roach
107039ca88baSGreg Roach        return new Collection($facts);
1071a25f0a04SGreg Roach    }
1072a25f0a04SGreg Roach
1073a25f0a04SGreg Roach    /**
10744459dc9aSGreg Roach     * Get the last-change timestamp for this record
1075a25f0a04SGreg Roach     *
10764459dc9aSGreg Roach     * @return Carbon
1077a25f0a04SGreg Roach     */
10784459dc9aSGreg Roach    public function lastChangeTimestamp(): Carbon
1079c1010edaSGreg Roach    {
10804459dc9aSGreg Roach        /** @var Fact|null $chan */
1081820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
1082a25f0a04SGreg Roach
10834459dc9aSGreg Roach        if ($chan instanceof Fact) {
1084a25f0a04SGreg Roach            // The record does have a CHAN event
10852decada7SGreg Roach            $d = $chan->date()->minimumDate();
10864459dc9aSGreg Roach
1087138ca96cSGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
10884459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
1089e364afe4SGreg Roach            }
1090e364afe4SGreg Roach
1091e364afe4SGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
10924459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
1093b2ce94c6SRico Sonntag            }
1094b2ce94c6SRico Sonntag
10954459dc9aSGreg Roach            return Carbon::create($d->year(), $d->month(), $d->day());
1096a25f0a04SGreg Roach        }
1097b2ce94c6SRico Sonntag
1098a25f0a04SGreg Roach        // The record does not have a CHAN event
10994459dc9aSGreg Roach        return Carbon::createFromTimestamp(0);
1100a25f0a04SGreg Roach    }
1101a25f0a04SGreg Roach
1102a25f0a04SGreg Roach    /**
1103a25f0a04SGreg Roach     * Get the last-change user for this record
1104a25f0a04SGreg Roach     *
1105a25f0a04SGreg Roach     * @return string
1106a25f0a04SGreg Roach     */
1107e364afe4SGreg Roach    public function lastChangeUser(): string
1108c1010edaSGreg Roach    {
1109820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
1110a25f0a04SGreg Roach
1111a25f0a04SGreg Roach        if ($chan === null) {
1112a25f0a04SGreg Roach            return I18N::translate('Unknown');
1113b2ce94c6SRico Sonntag        }
1114b2ce94c6SRico Sonntag
11153425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
1116baacc364SGreg Roach        if ($chan_user === '') {
1117a25f0a04SGreg Roach            return I18N::translate('Unknown');
1118b2ce94c6SRico Sonntag        }
1119b2ce94c6SRico Sonntag
1120a25f0a04SGreg Roach        return $chan_user;
1121a25f0a04SGreg Roach    }
1122a25f0a04SGreg Roach
1123a25f0a04SGreg Roach    /**
1124a25f0a04SGreg Roach     * Add a new fact to this record
1125a25f0a04SGreg Roach     *
1126a25f0a04SGreg Roach     * @param string $gedcom
1127cbc1590aSGreg Roach     * @param bool   $update_chan
11287e96c925SGreg Roach     *
11297e96c925SGreg Roach     * @return void
1130a25f0a04SGreg Roach     */
1131e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
1132c1010edaSGreg Roach    {
1133fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
1134a25f0a04SGreg Roach    }
1135a25f0a04SGreg Roach
1136a25f0a04SGreg Roach    /**
1137a25f0a04SGreg Roach     * Delete a fact from this record
1138a25f0a04SGreg Roach     *
1139a25f0a04SGreg Roach     * @param string $fact_id
1140cbc1590aSGreg Roach     * @param bool   $update_chan
11417e96c925SGreg Roach     *
11427e96c925SGreg Roach     * @return void
1143a25f0a04SGreg Roach     */
1144e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
1145c1010edaSGreg Roach    {
1146db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
1147a25f0a04SGreg Roach    }
1148a25f0a04SGreg Roach
1149a25f0a04SGreg Roach    /**
1150a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
1151a25f0a04SGreg Roach     *
1152a25f0a04SGreg Roach     * @param string $fact_id
1153a25f0a04SGreg Roach     * @param string $gedcom
1154cbc1590aSGreg Roach     * @param bool   $update_chan
1155a25f0a04SGreg Roach     *
11567e96c925SGreg Roach     * @return void
11577e96c925SGreg Roach     * @throws Exception
1158a25f0a04SGreg Roach     */
1159e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
1160c1010edaSGreg Roach    {
1161a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1162a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1163a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1164a25f0a04SGreg Roach
1165a25f0a04SGreg Roach        if ($this->pending === '') {
11667e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
1167a25f0a04SGreg Roach        }
11688d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
11697e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1170a25f0a04SGreg Roach        }
1171a25f0a04SGreg Roach
1172a25f0a04SGreg Roach        if ($this->pending) {
1173a25f0a04SGreg Roach            $old_gedcom = $this->pending;
1174a25f0a04SGreg Roach        } else {
1175a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
1176a25f0a04SGreg Roach        }
1177a25f0a04SGreg Roach
1178a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
117965e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
1180a25f0a04SGreg Roach
1181a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
11828d0ebef0SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) {
1183a25f0a04SGreg Roach            if (!$fact->isPendingDeletion()) {
1184905ab80aSGreg Roach                if ($fact->id() === $fact_id) {
1185db7bb364SGreg Roach                    if ($gedcom !== '') {
1186a25f0a04SGreg Roach                        $new_gedcom .= "\n" . $gedcom;
1187a25f0a04SGreg Roach                    }
1188fc3ccce4SGreg Roach                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1189e364afe4SGreg Roach                } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) {
1190138ca96cSGreg Roach                    $new_gedcom .= "\n" . $fact->gedcom();
1191a25f0a04SGreg Roach                }
1192a25f0a04SGreg Roach            }
1193a25f0a04SGreg Roach        }
1194a25f0a04SGreg Roach        if ($update_chan) {
1195e5a6b4d4SGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1196a25f0a04SGreg Roach        }
1197a25f0a04SGreg Roach
1198a25f0a04SGreg Roach        // Adding a new fact
1199fc3ccce4SGreg Roach        if ($fact_id === '') {
1200a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
1201a25f0a04SGreg Roach        }
1202a25f0a04SGreg Roach
1203e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
1204a25f0a04SGreg Roach            // Save the changes
1205d09b6323SGreg Roach            DB::table('change')->insert([
1206d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1207d09b6323SGreg Roach                'xref'       => $this->xref,
1208d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
1209d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
1210d09b6323SGreg Roach                'user_id'    => Auth::id(),
121113abd6f3SGreg Roach            ]);
1212a25f0a04SGreg Roach
1213a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1214a25f0a04SGreg Roach
1215a25f0a04SGreg Roach            if (Auth::user()->getPreference('auto_accept')) {
1216cc5684fdSGreg Roach                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1217a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1218a25f0a04SGreg Roach                $this->pending = null;
1219a25f0a04SGreg Roach            }
1220a25f0a04SGreg Roach        }
1221a25f0a04SGreg Roach        $this->parseFacts();
1222a25f0a04SGreg Roach    }
1223a25f0a04SGreg Roach
1224a25f0a04SGreg Roach    /**
1225a25f0a04SGreg Roach     * Update this record
1226a25f0a04SGreg Roach     *
1227a25f0a04SGreg Roach     * @param string $gedcom
1228cbc1590aSGreg Roach     * @param bool   $update_chan
12297e96c925SGreg Roach     *
12307e96c925SGreg Roach     * @return void
1231a25f0a04SGreg Roach     */
1232e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
1233c1010edaSGreg Roach    {
1234a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1235a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1236a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1237a25f0a04SGreg Roach
1238a25f0a04SGreg Roach        // Update the CHAN record
1239a25f0a04SGreg Roach        if ($update_chan) {
1240a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1241e5a6b4d4SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1242a25f0a04SGreg Roach        }
1243a25f0a04SGreg Roach
1244a25f0a04SGreg Roach        // Create a pending change
1245d09b6323SGreg Roach        DB::table('change')->insert([
1246d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1247d09b6323SGreg Roach            'xref'       => $this->xref,
1248d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1249d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1250d09b6323SGreg Roach            'user_id'    => Auth::id(),
125113abd6f3SGreg Roach        ]);
1252a25f0a04SGreg Roach
1253a25f0a04SGreg Roach        // Clear the cache
1254a25f0a04SGreg Roach        $this->pending = $gedcom;
1255a25f0a04SGreg Roach
1256a25f0a04SGreg Roach        // Accept this pending change
1257a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1258cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1259a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1260a25f0a04SGreg Roach            $this->pending = null;
1261a25f0a04SGreg Roach        }
1262a25f0a04SGreg Roach
1263a25f0a04SGreg Roach        $this->parseFacts();
1264a25f0a04SGreg Roach
1265847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1266a25f0a04SGreg Roach    }
1267a25f0a04SGreg Roach
1268a25f0a04SGreg Roach    /**
1269a25f0a04SGreg Roach     * Delete this record
1270b874da82SGreg Roach     *
1271b874da82SGreg Roach     * @return void
1272a25f0a04SGreg Roach     */
1273e364afe4SGreg Roach    public function deleteRecord(): void
1274c1010edaSGreg Roach    {
1275a25f0a04SGreg Roach        // Create a pending change
12764c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1277d09b6323SGreg Roach            DB::table('change')->insert([
1278d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1279d09b6323SGreg Roach                'xref'       => $this->xref,
1280d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1281d09b6323SGreg Roach                'new_gedcom' => '',
1282d09b6323SGreg Roach                'user_id'    => Auth::id(),
128313abd6f3SGreg Roach            ]);
12844c0b5256SGreg Roach        }
1285a25f0a04SGreg Roach
12864c0b5256SGreg Roach        // Auto-accept this pending change
1287a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1288cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1289a25f0a04SGreg Roach        }
1290a25f0a04SGreg Roach
1291a25f0a04SGreg Roach        // Clear the cache
1292d17d7b9eSGreg Roach        self::$gedcom_record_cache  = [];
1293d17d7b9eSGreg Roach        self::$pending_record_cache = [];
1294a25f0a04SGreg Roach
1295847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1296a25f0a04SGreg Roach    }
1297a25f0a04SGreg Roach
1298a25f0a04SGreg Roach    /**
1299a25f0a04SGreg Roach     * Remove all links from this record to $xref
1300a25f0a04SGreg Roach     *
1301a25f0a04SGreg Roach     * @param string $xref
1302cbc1590aSGreg Roach     * @param bool   $update_chan
13037e96c925SGreg Roach     *
13047e96c925SGreg Roach     * @return void
1305a25f0a04SGreg Roach     */
1306e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
1307c1010edaSGreg Roach    {
1308a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1309a25f0a04SGreg Roach
131030158ae7SGreg Roach        foreach ($this->facts() as $fact) {
131184586c02SGreg Roach            if ($fact->value() === $value) {
1312905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
13138d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1314138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1315a25f0a04SGreg Roach                foreach ($matches as $match) {
1316a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1317a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1318a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1319a25f0a04SGreg Roach                }
1320905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1321a25f0a04SGreg Roach            }
1322a25f0a04SGreg Roach        }
1323a25f0a04SGreg Roach    }
1324bf4eb542SGreg Roach
1325bf4eb542SGreg Roach    /**
1326bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1327bf4eb542SGreg Roach     * also delete all links to it.
1328bf4eb542SGreg Roach     *
1329bf4eb542SGreg Roach     * @return GedcomRecord[]
1330bf4eb542SGreg Roach     */
1331bf4eb542SGreg Roach    public function linkingRecords(): array
1332bf4eb542SGreg Roach    {
1333bf4eb542SGreg Roach        $union = DB::table('change')
1334bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1335fbbe964bSGreg Roach            ->whereContains('new_gedcom', '@' . $this->xref() . '@')
1336bf4eb542SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%')
133783242252SGreg Roach            ->whereIn('change_id', function (Builder $query): void {
133883242252SGreg Roach                $query->select(new Expression('MAX(change_id)'))
133983242252SGreg Roach                    ->from('change')
134083242252SGreg Roach                    ->where('gedcom_id', '=', $this->tree->id())
134183242252SGreg Roach                    ->where('status', '=', 'pending')
13427f5c2944SGreg Roach                    ->groupBy(['xref']);
134383242252SGreg Roach            })
1344bf4eb542SGreg Roach            ->select(['xref']);
1345bf4eb542SGreg Roach
1346bf4eb542SGreg Roach        $xrefs = DB::table('link')
1347bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1348bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
1349*47256fc5SGreg Roach            ->select(['l_from'])
1350bf4eb542SGreg Roach            ->union($union)
1351bf4eb542SGreg Roach            ->pluck('l_from');
1352bf4eb542SGreg Roach
1353bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
1354bf4eb542SGreg Roach            return GedcomRecord::getInstance($xref, $this->tree);
1355bf4eb542SGreg Roach        })->all();
1356bf4eb542SGreg Roach    }
1357a25f0a04SGreg Roach}
1358