xref: /webtrees/app/GedcomRecord.php (revision fbbe964bc80e7afdf862fef357b9aa52ded269cb)
1a25f0a04SGreg Roach<?php
2a25f0a04SGreg Roach/**
3a25f0a04SGreg Roach * webtrees: online genealogy
48fcd0d32SGreg Roach * Copyright (C) 2019 webtrees development team
5a25f0a04SGreg Roach * This program is free software: you can redistribute it and/or modify
6a25f0a04SGreg Roach * it under the terms of the GNU General Public License as published by
7a25f0a04SGreg Roach * the Free Software Foundation, either version 3 of the License, or
8a25f0a04SGreg Roach * (at your option) any later version.
9a25f0a04SGreg Roach * This program is distributed in the hope that it will be useful,
10a25f0a04SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
11a25f0a04SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12a25f0a04SGreg Roach * GNU General Public License for more details.
13a25f0a04SGreg Roach * You should have received a copy of the GNU General Public License
14a25f0a04SGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
15a25f0a04SGreg Roach */
16e7f56f2aSGreg Roachdeclare(strict_types=1);
17e7f56f2aSGreg Roach
1876692c8bSGreg Roachnamespace Fisharebest\Webtrees;
1976692c8bSGreg Roach
207e96c925SGreg Roachuse Exception;
213d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\Functions;
223d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsDate;
233d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
243d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsPrint;
25bf4eb542SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
26ba1c12e8SGreg Roachuse Illuminate\Database\Query\JoinClause;
2779529c87SGreg Roachuse stdClass;
28a25f0a04SGreg Roach
29a25f0a04SGreg Roach/**
3076692c8bSGreg Roach * A GEDCOM object.
31a25f0a04SGreg Roach */
32c1010edaSGreg Roachclass GedcomRecord
33c1010edaSGreg Roach{
3416d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
3516d6367aSGreg Roach
3616d6367aSGreg Roach    protected const ROUTE_NAME = 'record';
37a25f0a04SGreg Roach
38a25f0a04SGreg Roach    /** @var string The record identifier */
39a25f0a04SGreg Roach    protected $xref;
40a25f0a04SGreg Roach
41000959d9SGreg Roach    /** @var Tree  The family tree to which this record belongs */
42000959d9SGreg Roach    protected $tree;
43a25f0a04SGreg Roach
44a25f0a04SGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
45a25f0a04SGreg Roach    protected $gedcom;
46a25f0a04SGreg Roach
47a25f0a04SGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
48a25f0a04SGreg Roach    protected $pending;
49a25f0a04SGreg Roach
50a25f0a04SGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
51a25f0a04SGreg Roach    protected $facts;
52a25f0a04SGreg Roach
53cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_PRIVATE */
54a25f0a04SGreg Roach    private $disp_public;
55a25f0a04SGreg Roach
56cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_USER */
57a25f0a04SGreg Roach    private $disp_user;
58a25f0a04SGreg Roach
59cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_NONE */
60a25f0a04SGreg Roach    private $disp_none;
61a25f0a04SGreg Roach
62a25f0a04SGreg Roach    /** @var string[][] All the names of this individual */
63bdb3725aSGreg Roach    protected $getAllNames;
64a25f0a04SGreg Roach
65d17d7b9eSGreg Roach    /** @var int|null Cached result */
66bdb3725aSGreg Roach    protected $getPrimaryName;
67a25f0a04SGreg Roach
68d17d7b9eSGreg Roach    /** @var int|null Cached result */
69bdb3725aSGreg Roach    protected $getSecondaryName;
70a25f0a04SGreg Roach
7176692c8bSGreg Roach    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
72bec87e94SGreg Roach    public static $gedcom_record_cache;
731ae87ce5SGreg Roach
7479529c87SGreg Roach    /** @var stdClass[][] Fetch all pending edits in one database query */
75bec87e94SGreg Roach    public static $pending_record_cache;
76a25f0a04SGreg Roach
77a25f0a04SGreg Roach    /**
78a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
79a25f0a04SGreg Roach     *
80a25f0a04SGreg Roach     * @param string      $xref
81a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
82a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
83a25f0a04SGreg Roach     *                             empty string for records with pending deletions
8424ec66ceSGreg Roach     * @param Tree        $tree
85a25f0a04SGreg Roach     */
8676f666f4SGreg Roach    public function __construct(string $xref, string $gedcom, $pending, Tree $tree)
87c1010edaSGreg Roach    {
88a25f0a04SGreg Roach        $this->xref    = $xref;
89a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
90a25f0a04SGreg Roach        $this->pending = $pending;
9124ec66ceSGreg Roach        $this->tree    = $tree;
92a25f0a04SGreg Roach
93a25f0a04SGreg Roach        $this->parseFacts();
94a25f0a04SGreg Roach    }
95a25f0a04SGreg Roach
96a25f0a04SGreg Roach    /**
97a25f0a04SGreg Roach     * Split the record into facts
987e96c925SGreg Roach     *
997e96c925SGreg Roach     * @return void
100a25f0a04SGreg Roach     */
101c1010edaSGreg Roach    private function parseFacts()
102c1010edaSGreg Roach    {
103a25f0a04SGreg Roach        // Split the record into facts
104a25f0a04SGreg Roach        if ($this->gedcom) {
105a25f0a04SGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
106a25f0a04SGreg Roach            array_shift($gedcom_facts);
107a25f0a04SGreg Roach        } else {
10813abd6f3SGreg Roach            $gedcom_facts = [];
109a25f0a04SGreg Roach        }
110a25f0a04SGreg Roach        if ($this->pending) {
111a25f0a04SGreg Roach            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
112a25f0a04SGreg Roach            array_shift($pending_facts);
113a25f0a04SGreg Roach        } else {
11413abd6f3SGreg Roach            $pending_facts = [];
115a25f0a04SGreg Roach        }
116a25f0a04SGreg Roach
11713abd6f3SGreg Roach        $this->facts = [];
118a25f0a04SGreg Roach
119a25f0a04SGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
120a25f0a04SGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
121a25f0a04SGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts)) {
122a25f0a04SGreg Roach                $fact->setPendingDeletion();
123a25f0a04SGreg Roach            }
124a25f0a04SGreg Roach            $this->facts[] = $fact;
125a25f0a04SGreg Roach        }
126a25f0a04SGreg Roach        foreach ($pending_facts as $pending_fact) {
127a25f0a04SGreg Roach            if (!in_array($pending_fact, $gedcom_facts)) {
128a25f0a04SGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
129a25f0a04SGreg Roach                $fact->setPendingAddition();
130a25f0a04SGreg Roach                $this->facts[] = $fact;
131a25f0a04SGreg Roach            }
132a25f0a04SGreg Roach        }
133a25f0a04SGreg Roach    }
134a25f0a04SGreg Roach
135a25f0a04SGreg Roach    /**
136a25f0a04SGreg Roach     * Get an instance of a GedcomRecord object. For single records,
137a25f0a04SGreg Roach     * we just receive the XREF. For bulk records (such as lists
138a25f0a04SGreg Roach     * and search results) we can receive the GEDCOM data as well.
139a25f0a04SGreg Roach     *
140a25f0a04SGreg Roach     * @param string      $xref
14124ec66ceSGreg Roach     * @param Tree        $tree
142a25f0a04SGreg Roach     * @param string|null $gedcom
143a25f0a04SGreg Roach     *
1447e96c925SGreg Roach     * @throws Exception
145cbc1590aSGreg Roach     *
14684658595SGreg Roach     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|null
147a25f0a04SGreg Roach     */
14876f666f4SGreg Roach    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
149c1010edaSGreg Roach    {
15072cf66d4SGreg Roach        $tree_id = $tree->id();
15124ec66ceSGreg Roach
152e71ef9d2SGreg Roach        // Is this record already in the cache?
15324ec66ceSGreg Roach        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
154e71ef9d2SGreg Roach            return self::$gedcom_record_cache[$xref][$tree_id];
155a25f0a04SGreg Roach        }
156a25f0a04SGreg Roach
157a25f0a04SGreg Roach        // Do we need to fetch the record from the database?
158a25f0a04SGreg Roach        if ($gedcom === null) {
15924ec66ceSGreg Roach            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
160a25f0a04SGreg Roach        }
161a25f0a04SGreg Roach
162a25f0a04SGreg Roach        // If we can edit, then we also need to be able to see pending records.
16394075df0SGreg Roach        if (Auth::isEditor($tree)) {
16424ec66ceSGreg Roach            if (!isset(self::$pending_record_cache[$tree_id])) {
165a25f0a04SGreg Roach                // Fetch all pending records in one database query
16613abd6f3SGreg Roach                self::$pending_record_cache[$tree_id] = [];
16785fc8064SGreg Roach                $rows = DB::table('change')
16885fc8064SGreg Roach                    ->where('gedcom_id', '=', $tree_id)
16985fc8064SGreg Roach                    ->where('status', '=', 'pending')
17085fc8064SGreg Roach                    ->orderBy('change_id')
17185fc8064SGreg Roach                    ->select(['xref', 'new_gedcom'])
17285fc8064SGreg Roach                    ->get();
173d17d7b9eSGreg Roach
174a25f0a04SGreg Roach                foreach ($rows as $row) {
17524ec66ceSGreg Roach                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
176a25f0a04SGreg Roach                }
177a25f0a04SGreg Roach            }
178a25f0a04SGreg Roach
179d17d7b9eSGreg Roach            $pending = self::$pending_record_cache[$tree_id][$xref] ?? null;
180a25f0a04SGreg Roach        } else {
181a25f0a04SGreg Roach            // There are no pending changes for this record
182a25f0a04SGreg Roach            $pending = null;
183a25f0a04SGreg Roach        }
184a25f0a04SGreg Roach
185a25f0a04SGreg Roach        // No such record exists
186a25f0a04SGreg Roach        if ($gedcom === null && $pending === null) {
187a25f0a04SGreg Roach            return null;
188a25f0a04SGreg Roach        }
189a25f0a04SGreg Roach
190fc3ccce4SGreg Roach        // No such record, but a pending creation exists
191fc3ccce4SGreg Roach        if ($gedcom === null) {
192fc3ccce4SGreg Roach            $gedcom = '';
193fc3ccce4SGreg Roach        }
194fc3ccce4SGreg Roach
195a25f0a04SGreg Roach        // Create the object
1968d0ebef0SGreg Roach        if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedcom . $pending, $match)) {
197a25f0a04SGreg Roach            $xref = $match[1]; // Collation - we may have requested I123 and found i123
198a25f0a04SGreg Roach            $type = $match[2];
199a25f0a04SGreg Roach        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
200a25f0a04SGreg Roach            $xref = $match[1];
201a25f0a04SGreg Roach            $type = $match[1];
202a25f0a04SGreg Roach        } elseif ($gedcom . $pending) {
2037e96c925SGreg Roach            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
204a25f0a04SGreg Roach        } else {
205a25f0a04SGreg Roach            // A record with both pending creation and pending deletion
206a25f0a04SGreg Roach            $type = static::RECORD_TYPE;
207a25f0a04SGreg Roach        }
208a25f0a04SGreg Roach
209a25f0a04SGreg Roach        switch ($type) {
210a25f0a04SGreg Roach            case 'INDI':
21124ec66ceSGreg Roach                $record = new Individual($xref, $gedcom, $pending, $tree);
212a25f0a04SGreg Roach                break;
213a25f0a04SGreg Roach            case 'FAM':
21424ec66ceSGreg Roach                $record = new Family($xref, $gedcom, $pending, $tree);
215a25f0a04SGreg Roach                break;
216a25f0a04SGreg Roach            case 'SOUR':
21724ec66ceSGreg Roach                $record = new Source($xref, $gedcom, $pending, $tree);
218a25f0a04SGreg Roach                break;
219a25f0a04SGreg Roach            case 'OBJE':
22024ec66ceSGreg Roach                $record = new Media($xref, $gedcom, $pending, $tree);
221a25f0a04SGreg Roach                break;
222a25f0a04SGreg Roach            case 'REPO':
22324ec66ceSGreg Roach                $record = new Repository($xref, $gedcom, $pending, $tree);
224a25f0a04SGreg Roach                break;
225a25f0a04SGreg Roach            case 'NOTE':
22624ec66ceSGreg Roach                $record = new Note($xref, $gedcom, $pending, $tree);
227a25f0a04SGreg Roach                break;
228a25f0a04SGreg Roach            default:
22906ef8e02SGreg Roach                $record = new self($xref, $gedcom, $pending, $tree);
230a25f0a04SGreg Roach                break;
231a25f0a04SGreg Roach        }
232a25f0a04SGreg Roach
233a25f0a04SGreg Roach        // Store it in the cache
23424ec66ceSGreg Roach        self::$gedcom_record_cache[$xref][$tree_id] = $record;
235a25f0a04SGreg Roach
236a25f0a04SGreg Roach        return $record;
237a25f0a04SGreg Roach    }
238a25f0a04SGreg Roach
239a25f0a04SGreg Roach    /**
240a25f0a04SGreg Roach     * Fetch data from the database
241a25f0a04SGreg Roach     *
242a25f0a04SGreg Roach     * @param string $xref
243cbc1590aSGreg Roach     * @param int    $tree_id
244a25f0a04SGreg Roach     *
245a25f0a04SGreg Roach     * @return null|string
246a25f0a04SGreg Roach     */
24776f666f4SGreg Roach    protected static function fetchGedcomRecord(string $xref, int $tree_id)
248c1010edaSGreg Roach    {
249a25f0a04SGreg Roach        // We don't know what type of object this is. Try each one in turn.
25064d9078aSGreg Roach        $data = Individual::fetchGedcomRecord($xref, $tree_id);
25185fc8064SGreg Roach        if ($data !== null) {
252a25f0a04SGreg Roach            return $data;
253a25f0a04SGreg Roach        }
25464d9078aSGreg Roach        $data = Family::fetchGedcomRecord($xref, $tree_id);
25585fc8064SGreg Roach        if ($data !== null) {
256a25f0a04SGreg Roach            return $data;
257a25f0a04SGreg Roach        }
25864d9078aSGreg Roach        $data = Source::fetchGedcomRecord($xref, $tree_id);
25985fc8064SGreg Roach        if ($data !== null) {
260a25f0a04SGreg Roach            return $data;
261a25f0a04SGreg Roach        }
26264d9078aSGreg Roach        $data = Repository::fetchGedcomRecord($xref, $tree_id);
26385fc8064SGreg Roach        if ($data !== null) {
264a25f0a04SGreg Roach            return $data;
265a25f0a04SGreg Roach        }
26664d9078aSGreg Roach        $data = Media::fetchGedcomRecord($xref, $tree_id);
26785fc8064SGreg Roach        if ($data !== null) {
268a25f0a04SGreg Roach            return $data;
269a25f0a04SGreg Roach        }
27064d9078aSGreg Roach        $data = Note::fetchGedcomRecord($xref, $tree_id);
27185fc8064SGreg Roach        if ($data !== null) {
272a25f0a04SGreg Roach            return $data;
273a25f0a04SGreg Roach        }
274c1010edaSGreg Roach
275a25f0a04SGreg Roach        // Some other type of record...
276d09b6323SGreg Roach        return DB::table('other')
27785fc8064SGreg Roach            ->where('o_file', '=', $tree_id)
27885fc8064SGreg Roach            ->where('o_id', '=', $xref)
27985fc8064SGreg Roach            ->value('o_gedcom');
280a25f0a04SGreg Roach    }
281a25f0a04SGreg Roach
282a25f0a04SGreg Roach    /**
283a25f0a04SGreg Roach     * Get the XREF for this record
284a25f0a04SGreg Roach     *
285a25f0a04SGreg Roach     * @return string
286a25f0a04SGreg Roach     */
287c0935879SGreg Roach    public function xref(): string
288c1010edaSGreg Roach    {
289a25f0a04SGreg Roach        return $this->xref;
290a25f0a04SGreg Roach    }
291a25f0a04SGreg Roach
292a25f0a04SGreg Roach    /**
293000959d9SGreg Roach     * Get the tree to which this record belongs
294000959d9SGreg Roach     *
295000959d9SGreg Roach     * @return Tree
296000959d9SGreg Roach     */
297f4afa648SGreg Roach    public function tree(): Tree
298c1010edaSGreg Roach    {
299518bbdc1SGreg Roach        return $this->tree;
300000959d9SGreg Roach    }
301000959d9SGreg Roach
302000959d9SGreg Roach    /**
303a25f0a04SGreg Roach     * Application code should access data via Fact objects.
304a25f0a04SGreg Roach     * This function exists to support old code.
305a25f0a04SGreg Roach     *
306a25f0a04SGreg Roach     * @return string
307a25f0a04SGreg Roach     */
3087d0db648SGreg Roach    public function gedcom()
309c1010edaSGreg Roach    {
310b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
311a25f0a04SGreg Roach    }
312a25f0a04SGreg Roach
313a25f0a04SGreg Roach    /**
314a25f0a04SGreg Roach     * Does this record have a pending change?
315a25f0a04SGreg Roach     *
316cbc1590aSGreg Roach     * @return bool
317a25f0a04SGreg Roach     */
3188f53f488SRico Sonntag    public function isPendingAddition(): bool
319c1010edaSGreg Roach    {
320a25f0a04SGreg Roach        return $this->pending !== null;
321a25f0a04SGreg Roach    }
322a25f0a04SGreg Roach
323a25f0a04SGreg Roach    /**
324a25f0a04SGreg Roach     * Does this record have a pending deletion?
325a25f0a04SGreg Roach     *
326cbc1590aSGreg Roach     * @return bool
327a25f0a04SGreg Roach     */
3288f53f488SRico Sonntag    public function isPendingDeletion(): bool
329c1010edaSGreg Roach    {
330a25f0a04SGreg Roach        return $this->pending === '';
331a25f0a04SGreg Roach    }
332a25f0a04SGreg Roach
333a25f0a04SGreg Roach    /**
334225e381fSGreg Roach     * Generate a URL to this record.
335a25f0a04SGreg Roach     *
336a25f0a04SGreg Roach     * @return string
337a25f0a04SGreg Roach     */
3388f53f488SRico Sonntag    public function url(): string
339c1010edaSGreg Roach    {
340225e381fSGreg Roach        return route(static::ROUTE_NAME, [
341c0935879SGreg Roach            'xref' => $this->xref(),
342aa6f03bbSGreg Roach            'ged'  => $this->tree->name(),
343225e381fSGreg Roach        ]);
344a25f0a04SGreg Roach    }
345a25f0a04SGreg Roach
346a25f0a04SGreg Roach    /**
347a25f0a04SGreg Roach     * Work out whether this record can be shown to a user with a given access level
348a25f0a04SGreg Roach     *
349cbc1590aSGreg Roach     * @param int $access_level
350a25f0a04SGreg Roach     *
351cbc1590aSGreg Roach     * @return bool
352a25f0a04SGreg Roach     */
35376f666f4SGreg Roach    private function canShowRecord(int $access_level): bool
354c1010edaSGreg Roach    {
355a25f0a04SGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
356518bbdc1SGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
357a25f0a04SGreg Roach            return true;
358a25f0a04SGreg Roach        }
359a25f0a04SGreg Roach
360a25f0a04SGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
361c0935879SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), 'gedcomid') && $access_level === Auth::accessLevel($this->tree)) {
362a25f0a04SGreg Roach            return true;
363a25f0a04SGreg Roach        }
364a25f0a04SGreg Roach
365a25f0a04SGreg Roach        // Does this record have a RESN?
36620ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
3674b9ff166SGreg Roach            return Auth::PRIV_NONE >= $access_level;
368a25f0a04SGreg Roach        }
36920ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
3704b9ff166SGreg Roach            return Auth::PRIV_USER >= $access_level;
371a25f0a04SGreg Roach        }
37220ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
373a25f0a04SGreg Roach            return true;
374a25f0a04SGreg Roach        }
375a25f0a04SGreg Roach
376a25f0a04SGreg Roach        // Does this record have a default RESN?
377518bbdc1SGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
378c0935879SGreg Roach        if (isset($individual_privacy[$this->xref()])) {
379c0935879SGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
380a25f0a04SGreg Roach        }
381a25f0a04SGreg Roach
382a25f0a04SGreg Roach        // Privacy rules do not apply to admins
3834b9ff166SGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
384a25f0a04SGreg Roach            return true;
385a25f0a04SGreg Roach        }
386a25f0a04SGreg Roach
387a25f0a04SGreg Roach        // Different types of record have different privacy rules
388a25f0a04SGreg Roach        return $this->canShowByType($access_level);
389a25f0a04SGreg Roach    }
390a25f0a04SGreg Roach
391a25f0a04SGreg Roach    /**
392a25f0a04SGreg Roach     * Each object type may have its own special rules, and re-implement this function.
393a25f0a04SGreg Roach     *
394cbc1590aSGreg Roach     * @param int $access_level
395a25f0a04SGreg Roach     *
396cbc1590aSGreg Roach     * @return bool
397a25f0a04SGreg Roach     */
39835584196SGreg Roach    protected function canShowByType(int $access_level): bool
399c1010edaSGreg Roach    {
400518bbdc1SGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
401a25f0a04SGreg Roach
402518bbdc1SGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
403a25f0a04SGreg Roach            // Restriction found
404518bbdc1SGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
405b2ce94c6SRico Sonntag        }
406b2ce94c6SRico Sonntag
407a25f0a04SGreg Roach        // No restriction found - must be public:
408a25f0a04SGreg Roach        return true;
409a25f0a04SGreg Roach    }
410a25f0a04SGreg Roach
411a25f0a04SGreg Roach    /**
412a25f0a04SGreg Roach     * Can the details of this record be shown?
413a25f0a04SGreg Roach     *
414cbc1590aSGreg Roach     * @param int|null $access_level
415a25f0a04SGreg Roach     *
416cbc1590aSGreg Roach     * @return bool
417a25f0a04SGreg Roach     */
41835584196SGreg Roach    public function canShow(int $access_level = null): bool
419c1010edaSGreg Roach    {
4204b9ff166SGreg Roach        if ($access_level === null) {
4214b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
4224b9ff166SGreg Roach        }
4234b9ff166SGreg Roach
424a25f0a04SGreg Roach        // CACHING: this function can take three different parameters,
425a25f0a04SGreg Roach        // and therefore needs three different caches for the result.
426a25f0a04SGreg Roach        switch ($access_level) {
4274b9ff166SGreg Roach            case Auth::PRIV_PRIVATE: // visitor
428a25f0a04SGreg Roach                if ($this->disp_public === null) {
4294b9ff166SGreg Roach                    $this->disp_public = $this->canShowRecord(Auth::PRIV_PRIVATE);
430a25f0a04SGreg Roach                }
431cbc1590aSGreg Roach
432a25f0a04SGreg Roach                return $this->disp_public;
4334b9ff166SGreg Roach            case Auth::PRIV_USER: // member
434a25f0a04SGreg Roach                if ($this->disp_user === null) {
4354b9ff166SGreg Roach                    $this->disp_user = $this->canShowRecord(Auth::PRIV_USER);
436a25f0a04SGreg Roach                }
437cbc1590aSGreg Roach
438a25f0a04SGreg Roach                return $this->disp_user;
4394b9ff166SGreg Roach            case Auth::PRIV_NONE: // admin
440a25f0a04SGreg Roach                if ($this->disp_none === null) {
4414b9ff166SGreg Roach                    $this->disp_none = $this->canShowRecord(Auth::PRIV_NONE);
442a25f0a04SGreg Roach                }
443cbc1590aSGreg Roach
444a25f0a04SGreg Roach                return $this->disp_none;
4454b9ff166SGreg Roach            case Auth::PRIV_HIDE: // hidden from admins
446a25f0a04SGreg Roach                // We use this value to bypass privacy checks. For example,
447a25f0a04SGreg Roach                // when downloading data or when calculating privacy itself.
448a25f0a04SGreg Roach                return true;
449a25f0a04SGreg Roach            default:
450a25f0a04SGreg Roach                // Should never get here.
451a25f0a04SGreg Roach                return false;
452a25f0a04SGreg Roach        }
453a25f0a04SGreg Roach    }
454a25f0a04SGreg Roach
455a25f0a04SGreg Roach    /**
456a25f0a04SGreg Roach     * Can the name of this record be shown?
457a25f0a04SGreg Roach     *
458cbc1590aSGreg Roach     * @param int|null $access_level
459a25f0a04SGreg Roach     *
460cbc1590aSGreg Roach     * @return bool
461a25f0a04SGreg Roach     */
46276f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
463c1010edaSGreg Roach    {
4644b9ff166SGreg Roach        if ($access_level === null) {
4654b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
4664b9ff166SGreg Roach        }
4674b9ff166SGreg Roach
468a25f0a04SGreg Roach        return $this->canShow($access_level);
469a25f0a04SGreg Roach    }
470a25f0a04SGreg Roach
471a25f0a04SGreg Roach    /**
472a25f0a04SGreg Roach     * Can we edit this record?
473a25f0a04SGreg Roach     *
474cbc1590aSGreg Roach     * @return bool
475a25f0a04SGreg Roach     */
4768f53f488SRico Sonntag    public function canEdit(): bool
477c1010edaSGreg Roach    {
4784b9ff166SGreg Roach        return Auth::isManager($this->tree) || Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
479a25f0a04SGreg Roach    }
480a25f0a04SGreg Roach
481a25f0a04SGreg Roach    /**
482a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
483a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
484a25f0a04SGreg Roach     *
485cbc1590aSGreg Roach     * @param int $access_level
486a25f0a04SGreg Roach     *
487a25f0a04SGreg Roach     * @return string
488a25f0a04SGreg Roach     */
48976f666f4SGreg Roach    public function privatizeGedcom(int $access_level)
490c1010edaSGreg Roach    {
4914b9ff166SGreg Roach        if ($access_level == Auth::PRIV_HIDE) {
492a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
493a25f0a04SGreg Roach            return $this->gedcom;
494b2ce94c6SRico Sonntag        }
495b2ce94c6SRico Sonntag
496b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
497a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
498a25f0a04SGreg Roach
499a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
50065e02381SGreg Roach            [$gedrec] = explode("\n", $this->gedcom, 2);
501a25f0a04SGreg Roach
502a25f0a04SGreg Roach            // Check each of the facts for access
5038d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
504138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
505a25f0a04SGreg Roach            }
506cbc1590aSGreg Roach
507a25f0a04SGreg Roach            return $gedrec;
508b2ce94c6SRico Sonntag        }
509b2ce94c6SRico Sonntag
510a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
511a25f0a04SGreg Roach        // limited data, such as links to other records.
512a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
513a25f0a04SGreg Roach    }
514a25f0a04SGreg Roach
515a25f0a04SGreg Roach    /**
516a25f0a04SGreg Roach     * Generate a private version of this record
517a25f0a04SGreg Roach     *
518cbc1590aSGreg Roach     * @param int $access_level
519a25f0a04SGreg Roach     *
520a25f0a04SGreg Roach     * @return string
521a25f0a04SGreg Roach     */
52276f666f4SGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
523c1010edaSGreg Roach    {
524a25f0a04SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
525a25f0a04SGreg Roach    }
526a25f0a04SGreg Roach
527a25f0a04SGreg Roach    /**
528a25f0a04SGreg Roach     * Convert a name record into sortable and full/display versions. This default
529a25f0a04SGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
530a25f0a04SGreg Roach     *
531a25f0a04SGreg Roach     * @param string $type
532a25f0a04SGreg Roach     * @param string $value
533a25f0a04SGreg Roach     * @param string $gedcom
5347e96c925SGreg Roach     *
5357e96c925SGreg Roach     * @return void
536a25f0a04SGreg Roach     */
53776f666f4SGreg Roach    protected function addName(string $type, string $value, string $gedcom)
538c1010edaSGreg Roach    {
539bdb3725aSGreg Roach        $this->getAllNames[] = [
540a25f0a04SGreg Roach            'type'   => $type,
5417e96c925SGreg Roach            'sort'   => preg_replace_callback('/([0-9]+)/', function (array $matches): string {
5428d68cabeSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
5438d68cabeSGreg Roach            }, $value),
544c1010edaSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
545c1010edaSGreg Roach            // This is used for display
546c1010edaSGreg Roach            'fullNN' => $value,
547c1010edaSGreg Roach            // This goes into the database
54813abd6f3SGreg Roach        ];
549a25f0a04SGreg Roach    }
550a25f0a04SGreg Roach
551a25f0a04SGreg Roach    /**
552a25f0a04SGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
553a25f0a04SGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
554a25f0a04SGreg Roach     * Parameters: the level 1 fact containing the name.
555a25f0a04SGreg Roach     * Return value: an array of name structures, each containing
556a25f0a04SGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
557a25f0a04SGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
558a25f0a04SGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
559a25f0a04SGreg Roach     *
560cbc1590aSGreg Roach     * @param int    $level
561a25f0a04SGreg Roach     * @param string $fact_type
562a25f0a04SGreg Roach     * @param Fact[] $facts
5637e96c925SGreg Roach     *
5647e96c925SGreg Roach     * @return void
565a25f0a04SGreg Roach     */
56676f666f4SGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, array $facts)
567c1010edaSGreg Roach    {
568a25f0a04SGreg Roach        $sublevel    = $level + 1;
569a25f0a04SGreg Roach        $subsublevel = $sublevel + 1;
570a25f0a04SGreg Roach        foreach ($facts as $fact) {
571138ca96cSGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
572a25f0a04SGreg Roach                foreach ($matches as $match) {
573a25f0a04SGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
574a25f0a04SGreg Roach                    if ($match[1] == 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
575138ca96cSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
576a25f0a04SGreg Roach                    } else {
577138ca96cSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
578a25f0a04SGreg Roach                    }
579a25f0a04SGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
580a25f0a04SGreg Roach                        foreach ($submatches as $submatch) {
581a25f0a04SGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
582a25f0a04SGreg Roach                        }
583a25f0a04SGreg Roach                    }
584a25f0a04SGreg Roach                }
585a25f0a04SGreg Roach            }
586a25f0a04SGreg Roach        }
587a25f0a04SGreg Roach    }
588a25f0a04SGreg Roach
589a25f0a04SGreg Roach    /**
590a25f0a04SGreg Roach     * Default for "other" object types
591c7ff4153SGreg Roach     *
592c7ff4153SGreg Roach     * @return void
593a25f0a04SGreg Roach     */
594c1010edaSGreg Roach    public function extractNames()
595c1010edaSGreg Roach    {
59676f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
597a25f0a04SGreg Roach    }
598a25f0a04SGreg Roach
599a25f0a04SGreg Roach    /**
600a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
601a25f0a04SGreg Roach     *
602a25f0a04SGreg Roach     * @return string[][]
603a25f0a04SGreg Roach     */
6048f53f488SRico Sonntag    public function getAllNames(): array
605c1010edaSGreg Roach    {
606bdb3725aSGreg Roach        if ($this->getAllNames === null) {
607bdb3725aSGreg Roach            $this->getAllNames = [];
608a25f0a04SGreg Roach            if ($this->canShowName()) {
609a25f0a04SGreg Roach                // Ask the record to extract its names
610a25f0a04SGreg Roach                $this->extractNames();
611a25f0a04SGreg Roach                // No name found? Use a fallback.
612bdb3725aSGreg Roach                if (!$this->getAllNames) {
613db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
614a25f0a04SGreg Roach                }
615a25f0a04SGreg Roach            } else {
616db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
617a25f0a04SGreg Roach            }
618a25f0a04SGreg Roach        }
619cbc1590aSGreg Roach
620bdb3725aSGreg Roach        return $this->getAllNames;
621a25f0a04SGreg Roach    }
622a25f0a04SGreg Roach
623a25f0a04SGreg Roach    /**
624a25f0a04SGreg Roach     * If this object has no name, what do we call it?
625a25f0a04SGreg Roach     *
626a25f0a04SGreg Roach     * @return string
627a25f0a04SGreg Roach     */
6288f53f488SRico Sonntag    public function getFallBackName(): string
629c1010edaSGreg Roach    {
630c0935879SGreg Roach        return e($this->xref());
631a25f0a04SGreg Roach    }
632a25f0a04SGreg Roach
633a25f0a04SGreg Roach    /**
634a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
635a25f0a04SGreg Roach     *
636cbc1590aSGreg Roach     * @return int
637a25f0a04SGreg Roach     */
6388f53f488SRico Sonntag    public function getPrimaryName(): int
639c1010edaSGreg Roach    {
640a25f0a04SGreg Roach        static $language_script;
641a25f0a04SGreg Roach
642a25f0a04SGreg Roach        if ($language_script === null) {
643a25f0a04SGreg Roach            $language_script = I18N::languageScript(WT_LOCALE);
644a25f0a04SGreg Roach        }
645a25f0a04SGreg Roach
646bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
647a25f0a04SGreg Roach            // Generally, the first name is the primary one....
648bdb3725aSGreg Roach            $this->getPrimaryName = 0;
649a25f0a04SGreg Roach            // ...except when the language/name use different character sets
650a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
65169546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
652bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
653a25f0a04SGreg Roach                    break;
654a25f0a04SGreg Roach                }
655a25f0a04SGreg Roach            }
656a25f0a04SGreg Roach        }
657a25f0a04SGreg Roach
658bdb3725aSGreg Roach        return $this->getPrimaryName;
659a25f0a04SGreg Roach    }
660a25f0a04SGreg Roach
661a25f0a04SGreg Roach    /**
662a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
663a25f0a04SGreg Roach     *
664cbc1590aSGreg Roach     * @return int
665a25f0a04SGreg Roach     */
6668f53f488SRico Sonntag    public function getSecondaryName(): int
667c1010edaSGreg Roach    {
6688f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
669a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
670bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
671a25f0a04SGreg Roach            // ....except when there are names with different character sets
672a25f0a04SGreg Roach            $all_names = $this->getAllNames();
673a25f0a04SGreg Roach            if (count($all_names) > 1) {
674a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
675a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
676a25f0a04SGreg Roach                    if ($n != $this->getPrimaryName() && $name['type'] != '_MARNM' && I18N::textScript($name['sort']) != $primary_script) {
677bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
678a25f0a04SGreg Roach                        break;
679a25f0a04SGreg Roach                    }
680a25f0a04SGreg Roach                }
681a25f0a04SGreg Roach            }
682a25f0a04SGreg Roach        }
683cbc1590aSGreg Roach
684bdb3725aSGreg Roach        return $this->getSecondaryName;
685a25f0a04SGreg Roach    }
686a25f0a04SGreg Roach
687a25f0a04SGreg Roach    /**
688a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
689a25f0a04SGreg Roach     *
69076f666f4SGreg Roach     * @param int|null $n
6917e96c925SGreg Roach     *
6927e96c925SGreg Roach     * @return void
693a25f0a04SGreg Roach     */
694251a9de7SGreg Roach    public function setPrimaryName(int $n = null)
695c1010edaSGreg Roach    {
696bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
697bdb3725aSGreg Roach        $this->getSecondaryName = null;
698a25f0a04SGreg Roach    }
699a25f0a04SGreg Roach
700a25f0a04SGreg Roach    /**
701a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
702a25f0a04SGreg Roach     *
703a25f0a04SGreg Roach     * @return string
704a25f0a04SGreg Roach     */
705c1010edaSGreg Roach    public function __toString()
706c1010edaSGreg Roach    {
70772cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
708a25f0a04SGreg Roach    }
709a25f0a04SGreg Roach
710a25f0a04SGreg Roach    /**
711a25f0a04SGreg Roach     * Static helper function to sort an array of objects by name
712a25f0a04SGreg Roach     * Records whose names cannot be displayed are sorted at the end.
713a25f0a04SGreg Roach     *
714a25f0a04SGreg Roach     * @param GedcomRecord $x
715a25f0a04SGreg Roach     * @param GedcomRecord $y
716a25f0a04SGreg Roach     *
717cbc1590aSGreg Roach     * @return int
718a25f0a04SGreg Roach     */
719c1010edaSGreg Roach    public static function compare(GedcomRecord $x, GedcomRecord $y)
720c1010edaSGreg Roach    {
721a25f0a04SGreg Roach        if ($x->canShowName()) {
722a25f0a04SGreg Roach            if ($y->canShowName()) {
723a25f0a04SGreg Roach                return I18N::strcasecmp($x->getSortName(), $y->getSortName());
724b2ce94c6SRico Sonntag            }
725b2ce94c6SRico Sonntag
726a25f0a04SGreg Roach            return -1; // only $y is private
727a25f0a04SGreg Roach        }
728b2ce94c6SRico Sonntag
729a25f0a04SGreg Roach        if ($y->canShowName()) {
730a25f0a04SGreg Roach            return 1; // only $x is private
731b2ce94c6SRico Sonntag        }
732b2ce94c6SRico Sonntag
733a25f0a04SGreg Roach        return 0; // both $x and $y private
734a25f0a04SGreg Roach    }
735a25f0a04SGreg Roach
736a25f0a04SGreg Roach    /**
737a25f0a04SGreg Roach     * Get variants of the name
738a25f0a04SGreg Roach     *
739a25f0a04SGreg Roach     * @return string
740a25f0a04SGreg Roach     */
741c1010edaSGreg Roach    public function getFullName()
742c1010edaSGreg Roach    {
743a25f0a04SGreg Roach        if ($this->canShowName()) {
744a25f0a04SGreg Roach            $tmp = $this->getAllNames();
745cbc1590aSGreg Roach
746a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
747a25f0a04SGreg Roach        }
748b2ce94c6SRico Sonntag
749b2ce94c6SRico Sonntag        return I18N::translate('Private');
750a25f0a04SGreg Roach    }
751a25f0a04SGreg Roach
752a25f0a04SGreg Roach    /**
753a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
754a25f0a04SGreg Roach     *
755a25f0a04SGreg Roach     * @return string
756a25f0a04SGreg Roach     */
7578f53f488SRico Sonntag    public function getSortName(): string
758c1010edaSGreg Roach    {
759a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
760a25f0a04SGreg Roach        $tmp = $this->getAllNames();
761cbc1590aSGreg Roach
762a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
763a25f0a04SGreg Roach    }
764a25f0a04SGreg Roach
765a25f0a04SGreg Roach    /**
766a25f0a04SGreg Roach     * Get the full name in an alternative character set
767a25f0a04SGreg Roach     *
768a25f0a04SGreg Roach     * @return null|string
769a25f0a04SGreg Roach     */
770c1010edaSGreg Roach    public function getAddName()
771c1010edaSGreg Roach    {
772a25f0a04SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() != $this->getSecondaryName()) {
773a25f0a04SGreg Roach            $all_names = $this->getAllNames();
774cbc1590aSGreg Roach
775a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
776a25f0a04SGreg Roach        }
777b2ce94c6SRico Sonntag
778b2ce94c6SRico Sonntag        return null;
779a25f0a04SGreg Roach    }
780a25f0a04SGreg Roach
781a25f0a04SGreg Roach    /**
782a25f0a04SGreg Roach     * Format this object for display in a list
783a25f0a04SGreg Roach     *
784a25f0a04SGreg Roach     * @return string
785a25f0a04SGreg Roach     */
7868f53f488SRico Sonntag    public function formatList(): string
787c1010edaSGreg Roach    {
788b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
789b165e17cSGreg Roach        $html .= '<b>' . $this->getFullName() . '</b>';
790a25f0a04SGreg Roach        $html .= $this->formatListDetails();
791b165e17cSGreg Roach        $html .= '</a>';
792cbc1590aSGreg Roach
793a25f0a04SGreg Roach        return $html;
794a25f0a04SGreg Roach    }
795a25f0a04SGreg Roach
796a25f0a04SGreg Roach    /**
797a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
798a25f0a04SGreg Roach     * identifying characteristics of this record.
799a25f0a04SGreg Roach     *
800a25f0a04SGreg Roach     * @return string
801a25f0a04SGreg Roach     */
8028f53f488SRico Sonntag    public function formatListDetails(): string
803c1010edaSGreg Roach    {
804a25f0a04SGreg Roach        return '';
805a25f0a04SGreg Roach    }
806a25f0a04SGreg Roach
807a25f0a04SGreg Roach    /**
808a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
809a25f0a04SGreg Roach     *
8108d0ebef0SGreg Roach     * @param string[] $facts
811cbc1590aSGreg Roach     * @param int      $style
812a25f0a04SGreg Roach     *
813a25f0a04SGreg Roach     * @return string
814a25f0a04SGreg Roach     */
8158d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
816c1010edaSGreg Roach    {
81730158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
818a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
8192decada7SGreg Roach            if ($event->date()->isOK() && !$event->place()->isEmpty()) {
820d93f11b5SGreg Roach                $joiner = ' — ';
821d93f11b5SGreg Roach            } else {
822d93f11b5SGreg Roach                $joiner = '';
823d93f11b5SGreg Roach            }
8242decada7SGreg Roach            if ($event->date()->isOK() || !$event->place()->isEmpty()) {
825a25f0a04SGreg Roach                switch ($style) {
826a25f0a04SGreg Roach                    case 1:
8277b7d8067SGreg Roach                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
828a25f0a04SGreg Roach                    case 2:
8297b7d8067SGreg Roach                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
830a25f0a04SGreg Roach                }
831a25f0a04SGreg Roach            }
832a25f0a04SGreg Roach        }
833cbc1590aSGreg Roach
834a25f0a04SGreg Roach        return '';
835a25f0a04SGreg Roach    }
836a25f0a04SGreg Roach
837a25f0a04SGreg Roach    /**
838a25f0a04SGreg Roach     * Find individuals linked to this record.
839a25f0a04SGreg Roach     *
840a25f0a04SGreg Roach     * @param string $link
841a25f0a04SGreg Roach     *
842360dbd2cSGreg Roach     * @return Individual[]
843a25f0a04SGreg Roach     */
84476f666f4SGreg Roach    public function linkedIndividuals(string $link): array
845c1010edaSGreg Roach    {
846ba1c12e8SGreg Roach        $rows = DB::table('individuals')
847ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
848ba1c12e8SGreg Roach                $join->on('l_file', '=', 'i_file')->on('l_from', '=', 'i_id');
849ba1c12e8SGreg Roach            })
850ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
851ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
852ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
853ba1c12e8SGreg Roach            ->select(['i_id AS xref', 'i_gedcom AS gedcom'])
854ba1c12e8SGreg Roach            ->get();
855a25f0a04SGreg Roach
85613abd6f3SGreg Roach        $list = [];
857a25f0a04SGreg Roach        foreach ($rows as $row) {
85824ec66ceSGreg Roach            $record = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
859a25f0a04SGreg Roach            if ($record->canShowName()) {
860a25f0a04SGreg Roach                $list[] = $record;
861a25f0a04SGreg Roach            }
862a25f0a04SGreg Roach        }
863cbc1590aSGreg Roach
864a25f0a04SGreg Roach        return $list;
865a25f0a04SGreg Roach    }
866a25f0a04SGreg Roach
867a25f0a04SGreg Roach    /**
868a25f0a04SGreg Roach     * Find families linked to this record.
869a25f0a04SGreg Roach     *
870a25f0a04SGreg Roach     * @param string $link
871a25f0a04SGreg Roach     *
872360dbd2cSGreg Roach     * @return Family[]
873a25f0a04SGreg Roach     */
87476f666f4SGreg Roach    public function linkedFamilies(string $link): array
875c1010edaSGreg Roach    {
876ba1c12e8SGreg Roach        $rows = DB::table('families')
877ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
878ba1c12e8SGreg Roach                $join->on('l_file', '=', 'f_file')->on('l_from', '=', 'f_id');
879ba1c12e8SGreg Roach            })
880ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
881ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
882ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
883ba1c12e8SGreg Roach            ->select(['f_id AS xref', 'f_gedcom AS gedcom'])
884ba1c12e8SGreg Roach            ->get();
885a25f0a04SGreg Roach
88613abd6f3SGreg Roach        $list = [];
887a25f0a04SGreg Roach        foreach ($rows as $row) {
88824ec66ceSGreg Roach            $record = Family::getInstance($row->xref, $this->tree, $row->gedcom);
889a25f0a04SGreg Roach            if ($record->canShowName()) {
890a25f0a04SGreg Roach                $list[] = $record;
891a25f0a04SGreg Roach            }
892a25f0a04SGreg Roach        }
893cbc1590aSGreg Roach
894a25f0a04SGreg Roach        return $list;
895a25f0a04SGreg Roach    }
896a25f0a04SGreg Roach
897a25f0a04SGreg Roach    /**
898a25f0a04SGreg Roach     * Find sources linked to this record.
899a25f0a04SGreg Roach     *
900a25f0a04SGreg Roach     * @param string $link
901a25f0a04SGreg Roach     *
902360dbd2cSGreg Roach     * @return Source[]
903a25f0a04SGreg Roach     */
90476f666f4SGreg Roach    public function linkedSources(string $link): array
905c1010edaSGreg Roach    {
906ba1c12e8SGreg Roach        $rows = DB::table('sources')
907ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
908ba1c12e8SGreg Roach                $join->on('l_file', '=', 's_file')->on('l_from', '=', 's_id');
909ba1c12e8SGreg Roach            })
910ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
911ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
912ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
913ba1c12e8SGreg Roach            ->select(['s_id AS xref', 's_gedcom AS gedcom'])
914ba1c12e8SGreg Roach            ->get();
915a25f0a04SGreg Roach
91613abd6f3SGreg Roach        $list = [];
917a25f0a04SGreg Roach        foreach ($rows as $row) {
91824ec66ceSGreg Roach            $record = Source::getInstance($row->xref, $this->tree, $row->gedcom);
919a25f0a04SGreg Roach            if ($record->canShowName()) {
920a25f0a04SGreg Roach                $list[] = $record;
921a25f0a04SGreg Roach            }
922a25f0a04SGreg Roach        }
923cbc1590aSGreg Roach
924a25f0a04SGreg Roach        return $list;
925a25f0a04SGreg Roach    }
926a25f0a04SGreg Roach
927a25f0a04SGreg Roach    /**
928a25f0a04SGreg Roach     * Find media objects linked to this record.
929a25f0a04SGreg Roach     *
930a25f0a04SGreg Roach     * @param string $link
931a25f0a04SGreg Roach     *
932360dbd2cSGreg Roach     * @return Media[]
933a25f0a04SGreg Roach     */
93476f666f4SGreg Roach    public function linkedMedia(string $link): array
935c1010edaSGreg Roach    {
936ba1c12e8SGreg Roach        $rows = DB::table('media')
937ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
938ba1c12e8SGreg Roach                $join->on('l_file', '=', 'm_file')->on('l_from', '=', 'm_id');
939ba1c12e8SGreg Roach            })
940ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
941ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
942ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
943ba1c12e8SGreg Roach            ->select(['m_id AS xref', 'm_gedcom AS gedcom'])
944ba1c12e8SGreg Roach            ->get();
945a25f0a04SGreg Roach
94613abd6f3SGreg Roach        $list = [];
947a25f0a04SGreg Roach        foreach ($rows as $row) {
94824ec66ceSGreg Roach            $record = Media::getInstance($row->xref, $this->tree, $row->gedcom);
949a25f0a04SGreg Roach            if ($record->canShowName()) {
950a25f0a04SGreg Roach                $list[] = $record;
951a25f0a04SGreg Roach            }
952a25f0a04SGreg Roach        }
953cbc1590aSGreg Roach
954a25f0a04SGreg Roach        return $list;
955a25f0a04SGreg Roach    }
956a25f0a04SGreg Roach
957a25f0a04SGreg Roach    /**
958a25f0a04SGreg Roach     * Find notes linked to this record.
959a25f0a04SGreg Roach     *
960a25f0a04SGreg Roach     * @param string $link
961a25f0a04SGreg Roach     *
962a25f0a04SGreg Roach     * @return Note[]
963a25f0a04SGreg Roach     */
96476f666f4SGreg Roach    public function linkedNotes(string $link): array
965c1010edaSGreg Roach    {
966ba1c12e8SGreg Roach        $rows = DB::table('other')
967ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
968ba1c12e8SGreg Roach                $join->on('l_file', '=', 'o_file')->on('l_from', '=', 'o_id');
969ba1c12e8SGreg Roach            })
970ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
971ba1c12e8SGreg Roach            ->where('o_type', '=', 'NOTE')
972ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
973ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
974ba1c12e8SGreg Roach            ->select(['o_id AS xref', 'o_gedcom AS gedcom'])
975ba1c12e8SGreg Roach            ->get();
976a25f0a04SGreg Roach
97713abd6f3SGreg Roach        $list = [];
978a25f0a04SGreg Roach        foreach ($rows as $row) {
97924ec66ceSGreg Roach            $record = Note::getInstance($row->xref, $this->tree, $row->gedcom);
980a25f0a04SGreg Roach            if ($record->canShowName()) {
981a25f0a04SGreg Roach                $list[] = $record;
982a25f0a04SGreg Roach            }
983a25f0a04SGreg Roach        }
984cbc1590aSGreg Roach
985a25f0a04SGreg Roach        return $list;
986a25f0a04SGreg Roach    }
987a25f0a04SGreg Roach
988a25f0a04SGreg Roach    /**
989a25f0a04SGreg Roach     * Find repositories linked to this record.
990a25f0a04SGreg Roach     *
991a25f0a04SGreg Roach     * @param string $link
992a25f0a04SGreg Roach     *
993360dbd2cSGreg Roach     * @return Repository[]
994a25f0a04SGreg Roach     */
99576f666f4SGreg Roach    public function linkedRepositories(string $link): array
996c1010edaSGreg Roach    {
997ba1c12e8SGreg Roach        $rows = DB::table('other')
998ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
999ba1c12e8SGreg Roach                $join->on('l_file', '=', 'o_file')->on('l_from', '=', 'o_id');
1000ba1c12e8SGreg Roach            })
1001ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
1002ba1c12e8SGreg Roach            ->where('o_type', '=', 'REPO')
1003ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
1004ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
1005ba1c12e8SGreg Roach            ->select(['o_id AS xref', 'o_gedcom AS gedcom'])
1006ba1c12e8SGreg Roach            ->get();
1007a25f0a04SGreg Roach
100813abd6f3SGreg Roach        $list = [];
1009a25f0a04SGreg Roach        foreach ($rows as $row) {
101024ec66ceSGreg Roach            $record = Repository::getInstance($row->xref, $this->tree, $row->gedcom);
1011a25f0a04SGreg Roach            if ($record->canShowName()) {
1012a25f0a04SGreg Roach                $list[] = $record;
1013a25f0a04SGreg Roach            }
1014a25f0a04SGreg Roach        }
1015cbc1590aSGreg Roach
1016a25f0a04SGreg Roach        return $list;
1017a25f0a04SGreg Roach    }
1018a25f0a04SGreg Roach
1019a25f0a04SGreg Roach    /**
1020a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
1021a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
1022a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
1023a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
1024a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
1025a25f0a04SGreg Roach     *
10268d0ebef0SGreg Roach     * @param string[] $events
1027a25f0a04SGreg Roach     *
1028a25f0a04SGreg Roach     * @return Date[]
1029a25f0a04SGreg Roach     */
10308d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
1031c1010edaSGreg Roach    {
103213abd6f3SGreg Roach        $dates = [];
10338d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
10342decada7SGreg Roach            if ($event->date()->isOK()) {
10352decada7SGreg Roach                $dates[] = $event->date();
1036a25f0a04SGreg Roach            }
1037a25f0a04SGreg Roach        }
1038a25f0a04SGreg Roach
1039a25f0a04SGreg Roach        return $dates;
1040a25f0a04SGreg Roach    }
1041a25f0a04SGreg Roach
1042a25f0a04SGreg Roach    /**
1043a25f0a04SGreg Roach     * Get all the places for a particular type of event
1044a25f0a04SGreg Roach     *
10458d0ebef0SGreg Roach     * @param string[] $events
1046a25f0a04SGreg Roach     *
10474080d558SGreg Roach     * @return Place[]
1048a25f0a04SGreg Roach     */
10498d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
1050c1010edaSGreg Roach    {
105113abd6f3SGreg Roach        $places = [];
10528d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
1053138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
1054a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
105516d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
1056a25f0a04SGreg Roach                }
1057a25f0a04SGreg Roach            }
1058a25f0a04SGreg Roach        }
1059a25f0a04SGreg Roach
1060a25f0a04SGreg Roach        return $places;
1061a25f0a04SGreg Roach    }
1062a25f0a04SGreg Roach
1063a25f0a04SGreg Roach    /**
1064a25f0a04SGreg Roach     * Get the first (i.e. prefered) Fact for the given fact type
1065a25f0a04SGreg Roach     *
1066a25f0a04SGreg Roach     * @param string $tag
1067a25f0a04SGreg Roach     *
1068a25f0a04SGreg Roach     * @return Fact|null
1069a25f0a04SGreg Roach     */
107076f666f4SGreg Roach    public function getFirstFact(string $tag)
1071c1010edaSGreg Roach    {
107230158ae7SGreg Roach        foreach ($this->facts() as $fact) {
1073a25f0a04SGreg Roach            if ($fact->getTag() === $tag) {
1074a25f0a04SGreg Roach                return $fact;
1075a25f0a04SGreg Roach            }
1076a25f0a04SGreg Roach        }
1077a25f0a04SGreg Roach
1078a25f0a04SGreg Roach        return null;
1079a25f0a04SGreg Roach    }
1080a25f0a04SGreg Roach
1081a25f0a04SGreg Roach    /**
1082a25f0a04SGreg Roach     * The facts and events for this record.
1083a25f0a04SGreg Roach     *
10848d0ebef0SGreg Roach     * @param string[] $filter
1085cbc1590aSGreg Roach     * @param bool     $sort
1086cbc1590aSGreg Roach     * @param int|null $access_level
1087cbc1590aSGreg Roach     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1088a25f0a04SGreg Roach     *
1089a25f0a04SGreg Roach     * @return Fact[]
1090a25f0a04SGreg Roach     */
10918d0ebef0SGreg Roach    public function facts(array $filter = [], bool $sort = false, int $access_level = null, bool $override = false): array
1092c1010edaSGreg Roach    {
10934b9ff166SGreg Roach        if ($access_level === null) {
10944b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
10954b9ff166SGreg Roach        }
10964b9ff166SGreg Roach
109713abd6f3SGreg Roach        $facts = [];
1098a25f0a04SGreg Roach        if ($this->canShow($access_level) || $override) {
1099a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
11008d0ebef0SGreg Roach                if (($filter === [] || in_array($fact->getTag(), $filter)) && $fact->canShow($access_level)) {
1101a25f0a04SGreg Roach                    $facts[] = $fact;
1102a25f0a04SGreg Roach                }
1103a25f0a04SGreg Roach            }
1104a25f0a04SGreg Roach        }
1105d17d7b9eSGreg Roach
1106a25f0a04SGreg Roach        if ($sort) {
11073d7a8a4cSGreg Roach            Functions::sortFacts($facts);
1108a25f0a04SGreg Roach        }
1109cbc1590aSGreg Roach
1110a25f0a04SGreg Roach        return $facts;
1111a25f0a04SGreg Roach    }
1112a25f0a04SGreg Roach
1113a25f0a04SGreg Roach    /**
1114a25f0a04SGreg Roach     * Get the last-change timestamp for this record, either as a formatted string
1115a25f0a04SGreg Roach     * (for display) or as a unix timestamp (for sorting)
1116a25f0a04SGreg Roach     *
1117cbc1590aSGreg Roach     * @param bool $sorting
1118a25f0a04SGreg Roach     *
1119589feda3SGreg Roach     * @return string|int
1120a25f0a04SGreg Roach     */
112176f666f4SGreg Roach    public function lastChangeTimestamp(bool $sorting = false)
1122c1010edaSGreg Roach    {
1123a25f0a04SGreg Roach        $chan = $this->getFirstFact('CHAN');
1124a25f0a04SGreg Roach
1125a25f0a04SGreg Roach        if ($chan) {
1126a25f0a04SGreg Roach            // The record does have a CHAN event
11272decada7SGreg Roach            $d = $chan->date()->minimumDate();
1128138ca96cSGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1129a25f0a04SGreg Roach                $t = mktime((int) $match[1], (int) $match[2], (int) $match[3], (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1130138ca96cSGreg Roach            } elseif (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1131a25f0a04SGreg Roach                $t = mktime((int) $match[1], (int) $match[2], 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1132a25f0a04SGreg Roach            } else {
1133a25f0a04SGreg Roach                $t = mktime(0, 0, 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1134a25f0a04SGreg Roach            }
1135a25f0a04SGreg Roach            if ($sorting) {
1136a25f0a04SGreg Roach                return $t;
1137b2ce94c6SRico Sonntag            }
1138b2ce94c6SRico Sonntag
11393d7a8a4cSGreg Roach            return strip_tags(FunctionsDate::formatTimestamp($t));
1140a25f0a04SGreg Roach        }
1141b2ce94c6SRico Sonntag
1142a25f0a04SGreg Roach        // The record does not have a CHAN event
1143a25f0a04SGreg Roach        if ($sorting) {
1144a25f0a04SGreg Roach            return '0';
1145b2ce94c6SRico Sonntag        }
1146b2ce94c6SRico Sonntag
114766b90994SGreg Roach        return '';
1148a25f0a04SGreg Roach    }
1149a25f0a04SGreg Roach
1150a25f0a04SGreg Roach    /**
1151a25f0a04SGreg Roach     * Get the last-change user for this record
1152a25f0a04SGreg Roach     *
1153a25f0a04SGreg Roach     * @return string
1154a25f0a04SGreg Roach     */
1155c1010edaSGreg Roach    public function lastChangeUser()
1156c1010edaSGreg Roach    {
1157a25f0a04SGreg Roach        $chan = $this->getFirstFact('CHAN');
1158a25f0a04SGreg Roach
1159a25f0a04SGreg Roach        if ($chan === null) {
1160a25f0a04SGreg Roach            return I18N::translate('Unknown');
1161b2ce94c6SRico Sonntag        }
1162b2ce94c6SRico Sonntag
11633425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
1164baacc364SGreg Roach        if ($chan_user === '') {
1165a25f0a04SGreg Roach            return I18N::translate('Unknown');
1166b2ce94c6SRico Sonntag        }
1167b2ce94c6SRico Sonntag
1168a25f0a04SGreg Roach        return $chan_user;
1169a25f0a04SGreg Roach    }
1170a25f0a04SGreg Roach
1171a25f0a04SGreg Roach    /**
1172a25f0a04SGreg Roach     * Add a new fact to this record
1173a25f0a04SGreg Roach     *
1174a25f0a04SGreg Roach     * @param string $gedcom
1175cbc1590aSGreg Roach     * @param bool   $update_chan
11767e96c925SGreg Roach     *
11777e96c925SGreg Roach     * @return void
1178a25f0a04SGreg Roach     */
117976f666f4SGreg Roach    public function createFact(string $gedcom, bool $update_chan)
1180c1010edaSGreg Roach    {
1181fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
1182a25f0a04SGreg Roach    }
1183a25f0a04SGreg Roach
1184a25f0a04SGreg Roach    /**
1185a25f0a04SGreg Roach     * Delete a fact from this record
1186a25f0a04SGreg Roach     *
1187a25f0a04SGreg Roach     * @param string $fact_id
1188cbc1590aSGreg Roach     * @param bool   $update_chan
11897e96c925SGreg Roach     *
11907e96c925SGreg Roach     * @return void
1191a25f0a04SGreg Roach     */
119276f666f4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan)
1193c1010edaSGreg Roach    {
1194db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
1195a25f0a04SGreg Roach    }
1196a25f0a04SGreg Roach
1197a25f0a04SGreg Roach    /**
1198a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
1199a25f0a04SGreg Roach     *
1200a25f0a04SGreg Roach     * @param string $fact_id
1201a25f0a04SGreg Roach     * @param string $gedcom
1202cbc1590aSGreg Roach     * @param bool   $update_chan
1203a25f0a04SGreg Roach     *
12047e96c925SGreg Roach     * @return void
12057e96c925SGreg Roach     * @throws Exception
1206a25f0a04SGreg Roach     */
120776f666f4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan)
1208c1010edaSGreg Roach    {
1209a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1210a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1211a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1212a25f0a04SGreg Roach
1213a25f0a04SGreg Roach        if ($this->pending === '') {
12147e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
1215a25f0a04SGreg Roach        }
12168d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
12177e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1218a25f0a04SGreg Roach        }
1219a25f0a04SGreg Roach
1220a25f0a04SGreg Roach        if ($this->pending) {
1221a25f0a04SGreg Roach            $old_gedcom = $this->pending;
1222a25f0a04SGreg Roach        } else {
1223a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
1224a25f0a04SGreg Roach        }
1225a25f0a04SGreg Roach
1226a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
122765e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
1228a25f0a04SGreg Roach
1229a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
12308d0ebef0SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) {
1231a25f0a04SGreg Roach            if (!$fact->isPendingDeletion()) {
1232905ab80aSGreg Roach                if ($fact->id() === $fact_id) {
1233db7bb364SGreg Roach                    if ($gedcom !== '') {
1234a25f0a04SGreg Roach                        $new_gedcom .= "\n" . $gedcom;
1235a25f0a04SGreg Roach                    }
1236fc3ccce4SGreg Roach                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1237a25f0a04SGreg Roach                } elseif ($fact->getTag() != 'CHAN' || !$update_chan) {
1238138ca96cSGreg Roach                    $new_gedcom .= "\n" . $fact->gedcom();
1239a25f0a04SGreg Roach                }
1240a25f0a04SGreg Roach            }
1241a25f0a04SGreg Roach        }
1242a25f0a04SGreg Roach        if ($update_chan) {
12434e9cf5abSGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1244a25f0a04SGreg Roach        }
1245a25f0a04SGreg Roach
1246a25f0a04SGreg Roach        // Adding a new fact
1247fc3ccce4SGreg Roach        if ($fact_id === '') {
1248a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
1249a25f0a04SGreg Roach        }
1250a25f0a04SGreg Roach
1251a25f0a04SGreg Roach        if ($new_gedcom != $old_gedcom) {
1252a25f0a04SGreg Roach            // Save the changes
1253d09b6323SGreg Roach            DB::table('change')->insert([
1254d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1255d09b6323SGreg Roach                'xref'       => $this->xref,
1256d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
1257d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
1258d09b6323SGreg Roach                'user_id'    => Auth::id(),
125913abd6f3SGreg Roach            ]);
1260a25f0a04SGreg Roach
1261a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1262a25f0a04SGreg Roach
1263a25f0a04SGreg Roach            if (Auth::user()->getPreference('auto_accept')) {
1264cc5684fdSGreg Roach                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1265a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1266a25f0a04SGreg Roach                $this->pending = null;
1267a25f0a04SGreg Roach            }
1268a25f0a04SGreg Roach        }
1269a25f0a04SGreg Roach        $this->parseFacts();
1270a25f0a04SGreg Roach    }
1271a25f0a04SGreg Roach
1272a25f0a04SGreg Roach    /**
1273a25f0a04SGreg Roach     * Update this record
1274a25f0a04SGreg Roach     *
1275a25f0a04SGreg Roach     * @param string $gedcom
1276cbc1590aSGreg Roach     * @param bool   $update_chan
12777e96c925SGreg Roach     *
12787e96c925SGreg Roach     * @return void
1279a25f0a04SGreg Roach     */
128076f666f4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan)
1281c1010edaSGreg Roach    {
1282a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1283a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1284a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1285a25f0a04SGreg Roach
1286a25f0a04SGreg Roach        // Update the CHAN record
1287a25f0a04SGreg Roach        if ($update_chan) {
1288a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1289a25f0a04SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1290a25f0a04SGreg Roach        }
1291a25f0a04SGreg Roach
1292a25f0a04SGreg Roach        // Create a pending change
1293d09b6323SGreg Roach        DB::table('change')->insert([
1294d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1295d09b6323SGreg Roach            'xref'       => $this->xref,
1296d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1297d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1298d09b6323SGreg Roach            'user_id'    => Auth::id(),
129913abd6f3SGreg Roach        ]);
1300a25f0a04SGreg Roach
1301a25f0a04SGreg Roach        // Clear the cache
1302a25f0a04SGreg Roach        $this->pending = $gedcom;
1303a25f0a04SGreg Roach
1304a25f0a04SGreg Roach        // Accept this pending change
1305a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1306cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1307a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1308a25f0a04SGreg Roach            $this->pending = null;
1309a25f0a04SGreg Roach        }
1310a25f0a04SGreg Roach
1311a25f0a04SGreg Roach        $this->parseFacts();
1312a25f0a04SGreg Roach
1313847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1314a25f0a04SGreg Roach    }
1315a25f0a04SGreg Roach
1316a25f0a04SGreg Roach    /**
1317a25f0a04SGreg Roach     * Delete this record
1318b874da82SGreg Roach     *
1319b874da82SGreg Roach     * @return void
1320a25f0a04SGreg Roach     */
1321c1010edaSGreg Roach    public function deleteRecord()
1322c1010edaSGreg Roach    {
1323a25f0a04SGreg Roach        // Create a pending change
13244c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1325d09b6323SGreg Roach            DB::table('change')->insert([
1326d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1327d09b6323SGreg Roach                'xref'       => $this->xref,
1328d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1329d09b6323SGreg Roach                'new_gedcom' => '',
1330d09b6323SGreg Roach                'user_id'    => Auth::id(),
133113abd6f3SGreg Roach            ]);
13324c0b5256SGreg Roach        }
1333a25f0a04SGreg Roach
13344c0b5256SGreg Roach        // Auto-accept this pending change
1335a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1336cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1337a25f0a04SGreg Roach        }
1338a25f0a04SGreg Roach
1339a25f0a04SGreg Roach        // Clear the cache
1340d17d7b9eSGreg Roach        self::$gedcom_record_cache  = [];
1341d17d7b9eSGreg Roach        self::$pending_record_cache = [];
1342a25f0a04SGreg Roach
1343847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1344a25f0a04SGreg Roach    }
1345a25f0a04SGreg Roach
1346a25f0a04SGreg Roach    /**
1347a25f0a04SGreg Roach     * Remove all links from this record to $xref
1348a25f0a04SGreg Roach     *
1349a25f0a04SGreg Roach     * @param string $xref
1350cbc1590aSGreg Roach     * @param bool   $update_chan
13517e96c925SGreg Roach     *
13527e96c925SGreg Roach     * @return void
1353a25f0a04SGreg Roach     */
135476f666f4SGreg Roach    public function removeLinks(string $xref, bool $update_chan)
1355c1010edaSGreg Roach    {
1356a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1357a25f0a04SGreg Roach
135830158ae7SGreg Roach        foreach ($this->facts() as $fact) {
135984586c02SGreg Roach            if ($fact->value() === $value) {
1360905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
13618d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1362138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1363a25f0a04SGreg Roach                foreach ($matches as $match) {
1364a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1365a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1366a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1367a25f0a04SGreg Roach                }
1368905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1369a25f0a04SGreg Roach            }
1370a25f0a04SGreg Roach        }
1371a25f0a04SGreg Roach    }
1372bf4eb542SGreg Roach
1373bf4eb542SGreg Roach    /**
1374bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1375bf4eb542SGreg Roach     * also delete all links to it.
1376bf4eb542SGreg Roach     *
1377bf4eb542SGreg Roach     * @return GedcomRecord[]
1378bf4eb542SGreg Roach     */
1379bf4eb542SGreg Roach    public function linkingRecords(): array
1380bf4eb542SGreg Roach    {
1381bf4eb542SGreg Roach        $union = DB::table('change')
1382bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1383*fbbe964bSGreg Roach            ->whereContains('new_gedcom', '@' . $this->xref() . '@')
1384bf4eb542SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%')
1385bf4eb542SGreg Roach            ->select(['xref']);
1386bf4eb542SGreg Roach
1387bf4eb542SGreg Roach        $xrefs = DB::table('link')
1388bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1389bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
1390bf4eb542SGreg Roach            ->select('l_from')
1391bf4eb542SGreg Roach            ->union($union)
1392bf4eb542SGreg Roach            ->pluck('l_from');
1393bf4eb542SGreg Roach
1394bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
1395bf4eb542SGreg Roach            return GedcomRecord::getInstance($xref, $this->tree);
1396bf4eb542SGreg Roach        })->all();
1397bf4eb542SGreg Roach    }
1398a25f0a04SGreg Roach}
1399