xref: /webtrees/app/GedcomRecord.php (revision a091ac74647eab281b25090b737835eeea14ae10)
1a25f0a04SGreg Roach<?php
23976b470SGreg Roach
3a25f0a04SGreg Roach/**
4a25f0a04SGreg Roach * webtrees: online genealogy
519aed3a1SGreg Roach * Copyright (C) 2020 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 */
17fcfa147eSGreg Roach
18e7f56f2aSGreg Roachdeclare(strict_types=1);
19e7f56f2aSGreg Roach
2076692c8bSGreg Roachnamespace Fisharebest\Webtrees;
2176692c8bSGreg Roach
22886b77daSGreg Roachuse Closure;
237e96c925SGreg Roachuse Exception;
243d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsPrint;
255818a371SGreg Roachuse Fisharebest\Webtrees\Http\RequestHandlers\GedcomRecordPage;
2622e73debSGreg Roachuse Fisharebest\Webtrees\Services\PendingChangesService;
27bf4eb542SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
2883242252SGreg Roachuse Illuminate\Database\Query\Builder;
2983242252SGreg Roachuse Illuminate\Database\Query\Expression;
30ba1c12e8SGreg Roachuse Illuminate\Database\Query\JoinClause;
3139ca88baSGreg Roachuse Illuminate\Support\Collection;
3274670d65SGreg Roachuse Throwable;
335ab92b3fSGreg Roachuse Transliterator;
34a25f0a04SGreg Roach
35b5961194SGreg Roachuse function addcslashes;
3622e73debSGreg Roachuse function app;
37f7440925SGreg Roachuse function array_shift;
38f7440925SGreg Roachuse function assert;
39f7440925SGreg Roachuse function count;
40f7440925SGreg Roachuse function date;
41f7440925SGreg Roachuse function e;
42f7440925SGreg Roachuse function explode;
43f7440925SGreg Roachuse function in_array;
44f7440925SGreg Roachuse function md5;
45f7440925SGreg Roachuse function preg_match;
46f7440925SGreg Roachuse function preg_match_all;
47f7440925SGreg Roachuse function preg_replace;
48f7440925SGreg Roachuse function preg_replace_callback;
49f7440925SGreg Roachuse function preg_split;
50f7440925SGreg Roachuse function route;
51f7440925SGreg Roachuse function str_pad;
52f7440925SGreg Roachuse function strip_tags;
53f7440925SGreg Roachuse function strpos;
54f7440925SGreg Roachuse function strtoupper;
55f7440925SGreg Roachuse function trim;
56f7440925SGreg Roach
57f7440925SGreg Roachuse const PREG_SET_ORDER;
58f7440925SGreg Roachuse const STR_PAD_LEFT;
5922e73debSGreg Roach
60a25f0a04SGreg Roach/**
6176692c8bSGreg Roach * A GEDCOM object.
62a25f0a04SGreg Roach */
63c1010edaSGreg Roachclass GedcomRecord
64c1010edaSGreg Roach{
6516d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
6616d6367aSGreg Roach
675818a371SGreg Roach    protected const ROUTE_NAME = GedcomRecordPage::class;
685818a371SGreg Roach
6922e73debSGreg Roach    /** @var string The record identifier */
7022e73debSGreg Roach    protected $xref;
71bb03c9f0SGreg Roach
7222e73debSGreg Roach    /** @var Tree  The family tree to which this record belongs */
7322e73debSGreg Roach    protected $tree;
74bb03c9f0SGreg Roach
7522e73debSGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
7622e73debSGreg Roach    protected $gedcom;
77bb03c9f0SGreg Roach
7822e73debSGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
7922e73debSGreg Roach    protected $pending;
80bb03c9f0SGreg Roach
8122e73debSGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
8222e73debSGreg Roach    protected $facts;
83bb03c9f0SGreg Roach
8422e73debSGreg Roach    /** @var string[][] All the names of this individual */
8522e73debSGreg Roach    protected $getAllNames;
86bb03c9f0SGreg Roach
8722e73debSGreg Roach    /** @var int|null Cached result */
8822e73debSGreg Roach    protected $getPrimaryName;
8922e73debSGreg Roach    /** @var int|null Cached result */
9022e73debSGreg Roach    protected $getSecondaryName;
91a25f0a04SGreg Roach
92a25f0a04SGreg Roach    /**
93a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
94a25f0a04SGreg Roach     *
95a25f0a04SGreg Roach     * @param string      $xref
96a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
97a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
98a25f0a04SGreg Roach     *                             empty string for records with pending deletions
9924ec66ceSGreg Roach     * @param Tree        $tree
100a25f0a04SGreg Roach     */
101e364afe4SGreg Roach    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
102c1010edaSGreg Roach    {
103a25f0a04SGreg Roach        $this->xref    = $xref;
104a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
105a25f0a04SGreg Roach        $this->pending = $pending;
10624ec66ceSGreg Roach        $this->tree    = $tree;
107a25f0a04SGreg Roach
108a25f0a04SGreg Roach        $this->parseFacts();
109a25f0a04SGreg Roach    }
110a25f0a04SGreg Roach
111a25f0a04SGreg Roach    /**
112886b77daSGreg Roach     * A closure which will create a record from a database row.
113886b77daSGreg Roach     *
114bb03c9f0SGreg Roach     * @deprecated since 2.0.4.  Will be removed in 2.1.0 - Use Factory::gedcomRecord()
115bb03c9f0SGreg Roach     *
116d5ad3db0SGreg Roach     * @param Tree $tree
117d5ad3db0SGreg Roach     *
118886b77daSGreg Roach     * @return Closure
119886b77daSGreg Roach     */
120d5ad3db0SGreg Roach    public static function rowMapper(Tree $tree): Closure
121886b77daSGreg Roach    {
122bb03c9f0SGreg Roach        return Factory::gedcomRecord()->mapper($tree);
123886b77daSGreg Roach    }
124886b77daSGreg Roach
125886b77daSGreg Roach    /**
126886b77daSGreg Roach     * A closure which will filter out private records.
127886b77daSGreg Roach     *
128886b77daSGreg Roach     * @return Closure
129886b77daSGreg Roach     */
1304146fabcSGreg Roach    public static function accessFilter(): Closure
131886b77daSGreg Roach    {
1326c2179e2SGreg Roach        return static function (GedcomRecord $record): bool {
133886b77daSGreg Roach            return $record->canShow();
134886b77daSGreg Roach        };
135886b77daSGreg Roach    }
136886b77daSGreg Roach
137886b77daSGreg Roach    /**
138c156e8f5SGreg Roach     * A closure which will compare records by name.
139c156e8f5SGreg Roach     *
140c156e8f5SGreg Roach     * @return Closure
141c156e8f5SGreg Roach     */
142c156e8f5SGreg Roach    public static function nameComparator(): Closure
143c156e8f5SGreg Roach    {
1446c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y): int {
145c156e8f5SGreg Roach            if ($x->canShowName()) {
146c156e8f5SGreg Roach                if ($y->canShowName()) {
14739ca88baSGreg Roach                    return I18N::strcasecmp($x->sortName(), $y->sortName());
148c156e8f5SGreg Roach                }
149c156e8f5SGreg Roach
150c156e8f5SGreg Roach                return -1; // only $y is private
151c156e8f5SGreg Roach            }
152c156e8f5SGreg Roach
153c156e8f5SGreg Roach            if ($y->canShowName()) {
154c156e8f5SGreg Roach                return 1; // only $x is private
155c156e8f5SGreg Roach            }
156c156e8f5SGreg Roach
157c156e8f5SGreg Roach            return 0; // both $x and $y private
158c156e8f5SGreg Roach        };
159c156e8f5SGreg Roach    }
160c156e8f5SGreg Roach
161c156e8f5SGreg Roach    /**
162c156e8f5SGreg Roach     * A closure which will compare records by change time.
163c156e8f5SGreg Roach     *
164c156e8f5SGreg Roach     * @param int $direction +1 to sort ascending, -1 to sort descending
165c156e8f5SGreg Roach     *
166c156e8f5SGreg Roach     * @return Closure
167c156e8f5SGreg Roach     */
168c156e8f5SGreg Roach    public static function lastChangeComparator(int $direction = 1): Closure
169c156e8f5SGreg Roach    {
1706c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
1714459dc9aSGreg Roach            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
172c156e8f5SGreg Roach        };
173c156e8f5SGreg Roach    }
174c156e8f5SGreg Roach
175c156e8f5SGreg Roach    /**
176a25f0a04SGreg Roach     * Get an instance of a GedcomRecord object. For single records,
177a25f0a04SGreg Roach     * we just receive the XREF. For bulk records (such as lists
178a25f0a04SGreg Roach     * and search results) we can receive the GEDCOM data as well.
179a25f0a04SGreg Roach     *
180bb03c9f0SGreg Roach     * @deprecated since 2.0.4.  Will be removed in 2.1.0 - Use Factory::gedcomRecord()
181bb03c9f0SGreg Roach     *
182a25f0a04SGreg Roach     * @param string      $xref
18324ec66ceSGreg Roach     * @param Tree        $tree
184a25f0a04SGreg Roach     * @param string|null $gedcom
185a25f0a04SGreg Roach     *
186ffc0a61fSGreg Roach     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|Submitter|null
187a25f0a04SGreg Roach     */
18876f666f4SGreg Roach    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
189c1010edaSGreg Roach    {
190bb03c9f0SGreg Roach        return Factory::gedcomRecord()->make($xref, $tree, $gedcom);
191a25f0a04SGreg Roach    }
192a25f0a04SGreg Roach
193a25f0a04SGreg Roach    /**
194a25f0a04SGreg Roach     * Get the XREF for this record
195a25f0a04SGreg Roach     *
196a25f0a04SGreg Roach     * @return string
197a25f0a04SGreg Roach     */
198c0935879SGreg Roach    public function xref(): string
199c1010edaSGreg Roach    {
200a25f0a04SGreg Roach        return $this->xref;
201a25f0a04SGreg Roach    }
202a25f0a04SGreg Roach
203a25f0a04SGreg Roach    /**
204000959d9SGreg Roach     * Get the tree to which this record belongs
205000959d9SGreg Roach     *
206000959d9SGreg Roach     * @return Tree
207000959d9SGreg Roach     */
208f4afa648SGreg Roach    public function tree(): Tree
209c1010edaSGreg Roach    {
210518bbdc1SGreg Roach        return $this->tree;
211000959d9SGreg Roach    }
212000959d9SGreg Roach
213000959d9SGreg Roach    /**
214a25f0a04SGreg Roach     * Application code should access data via Fact objects.
215a25f0a04SGreg Roach     * This function exists to support old code.
216a25f0a04SGreg Roach     *
217a25f0a04SGreg Roach     * @return string
218a25f0a04SGreg Roach     */
219e364afe4SGreg Roach    public function gedcom(): string
220c1010edaSGreg Roach    {
221b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
222a25f0a04SGreg Roach    }
223a25f0a04SGreg Roach
224a25f0a04SGreg Roach    /**
225a25f0a04SGreg Roach     * Does this record have a pending change?
226a25f0a04SGreg Roach     *
227cbc1590aSGreg Roach     * @return bool
228a25f0a04SGreg Roach     */
2298f53f488SRico Sonntag    public function isPendingAddition(): bool
230c1010edaSGreg Roach    {
231a25f0a04SGreg Roach        return $this->pending !== null;
232a25f0a04SGreg Roach    }
233a25f0a04SGreg Roach
234a25f0a04SGreg Roach    /**
235a25f0a04SGreg Roach     * Does this record have a pending deletion?
236a25f0a04SGreg Roach     *
237cbc1590aSGreg Roach     * @return bool
238a25f0a04SGreg Roach     */
2398f53f488SRico Sonntag    public function isPendingDeletion(): bool
240c1010edaSGreg Roach    {
241a25f0a04SGreg Roach        return $this->pending === '';
242a25f0a04SGreg Roach    }
243a25f0a04SGreg Roach
244a25f0a04SGreg Roach    /**
245ee4364daSGreg Roach     * Generate a "slug" to use in pretty URLs.
246ee4364daSGreg Roach     *
247ee4364daSGreg Roach     * @return string
248ee4364daSGreg Roach     */
249ee4364daSGreg Roach    public function slug(): string
250ee4364daSGreg Roach    {
2515ab92b3fSGreg Roach        $slug = strip_tags($this->fullName());
252f7440925SGreg Roach
25374670d65SGreg Roach        try {
254f7440925SGreg Roach            $transliterator = Transliterator::create('Any-Latin;Latin-ASCII');
2555ab92b3fSGreg Roach            $slug           = $transliterator->transliterate($slug);
25674670d65SGreg Roach        } catch (Throwable $ex) {
25774670d65SGreg Roach            // ext-intl not installed?
25874670d65SGreg Roach            // Transliteration algorithms not present in lib-icu?
259f7440925SGreg Roach        }
260f7440925SGreg Roach
2615ab92b3fSGreg Roach        $slug = preg_replace('/[^A-Za-z0-9]+/', '-', $slug);
2625ab92b3fSGreg Roach
2635ab92b3fSGreg Roach        return trim($slug, '-') ?: '-';
264ee4364daSGreg Roach    }
265ee4364daSGreg Roach
266ee4364daSGreg Roach    /**
267225e381fSGreg Roach     * Generate a URL to this record.
268a25f0a04SGreg Roach     *
269a25f0a04SGreg Roach     * @return string
270a25f0a04SGreg Roach     */
2718f53f488SRico Sonntag    public function url(): string
272c1010edaSGreg Roach    {
273225e381fSGreg Roach        return route(static::ROUTE_NAME, [
274c0935879SGreg Roach            'xref' => $this->xref(),
275ee4364daSGreg Roach            'tree' => $this->tree->name(),
276ee4364daSGreg Roach            'slug' => $this->slug(),
277225e381fSGreg Roach        ]);
278a25f0a04SGreg Roach    }
279a25f0a04SGreg Roach
280a25f0a04SGreg Roach    /**
281a25f0a04SGreg Roach     * Can the details of this record be shown?
282a25f0a04SGreg Roach     *
283cbc1590aSGreg Roach     * @param int|null $access_level
284a25f0a04SGreg Roach     *
285cbc1590aSGreg Roach     * @return bool
286a25f0a04SGreg Roach     */
28735584196SGreg Roach    public function canShow(int $access_level = null): bool
288c1010edaSGreg Roach    {
289f0b9c048SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
2904b9ff166SGreg Roach
291a25f0a04SGreg Roach        // We use this value to bypass privacy checks. For example,
292a25f0a04SGreg Roach        // when downloading data or when calculating privacy itself.
293f0b9c048SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
294a25f0a04SGreg Roach            return true;
295a25f0a04SGreg Roach        }
296f0b9c048SGreg Roach
2977476e8a5SGreg Roach        $cache_key = 'show-' . $this->xref . '-' . $this->tree->id() . '-' . $access_level;
298f0b9c048SGreg Roach
299c692965aSGreg Roach        return app('cache.array')->remember($cache_key, function () use ($access_level) {
300f0b9c048SGreg Roach            return $this->canShowRecord($access_level);
301f0b9c048SGreg Roach        });
302a25f0a04SGreg Roach    }
303a25f0a04SGreg Roach
304a25f0a04SGreg Roach    /**
305a25f0a04SGreg Roach     * Can the name of this record be shown?
306a25f0a04SGreg Roach     *
307cbc1590aSGreg Roach     * @param int|null $access_level
308a25f0a04SGreg Roach     *
309cbc1590aSGreg Roach     * @return bool
310a25f0a04SGreg Roach     */
31176f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
312c1010edaSGreg Roach    {
313a25f0a04SGreg Roach        return $this->canShow($access_level);
314a25f0a04SGreg Roach    }
315a25f0a04SGreg Roach
316a25f0a04SGreg Roach    /**
317a25f0a04SGreg Roach     * Can we edit this record?
318a25f0a04SGreg Roach     *
319cbc1590aSGreg Roach     * @return bool
320a25f0a04SGreg Roach     */
3218f53f488SRico Sonntag    public function canEdit(): bool
322c1010edaSGreg Roach    {
3231450f098SGreg Roach        if ($this->isPendingDeletion()) {
3241450f098SGreg Roach            return false;
3251450f098SGreg Roach        }
3261450f098SGreg Roach
3271450f098SGreg Roach        if (Auth::isManager($this->tree)) {
3281450f098SGreg Roach            return true;
3291450f098SGreg Roach        }
3301450f098SGreg Roach
3311450f098SGreg Roach        return Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
332a25f0a04SGreg Roach    }
333a25f0a04SGreg Roach
334a25f0a04SGreg Roach    /**
335a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
336a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
337a25f0a04SGreg Roach     *
338cbc1590aSGreg Roach     * @param int $access_level
339a25f0a04SGreg Roach     *
340a25f0a04SGreg Roach     * @return string
341a25f0a04SGreg Roach     */
342e364afe4SGreg Roach    public function privatizeGedcom(int $access_level): string
343c1010edaSGreg Roach    {
344e364afe4SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
345a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
346a25f0a04SGreg Roach            return $this->gedcom;
347b2ce94c6SRico Sonntag        }
348b2ce94c6SRico Sonntag
349b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
350a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
351a25f0a04SGreg Roach
352a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
353dc141db3SGreg Roach            [$gedrec] = explode("\n", $this->gedcom . $this->pending, 2);
354a25f0a04SGreg Roach
355a25f0a04SGreg Roach            // Check each of the facts for access
3568d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
357138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
358a25f0a04SGreg Roach            }
359cbc1590aSGreg Roach
360a25f0a04SGreg Roach            return $gedrec;
361b2ce94c6SRico Sonntag        }
362b2ce94c6SRico Sonntag
363a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
364a25f0a04SGreg Roach        // limited data, such as links to other records.
365a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
366a25f0a04SGreg Roach    }
367a25f0a04SGreg Roach
368a25f0a04SGreg Roach    /**
369a25f0a04SGreg Roach     * Default for "other" object types
370c7ff4153SGreg Roach     *
371c7ff4153SGreg Roach     * @return void
372a25f0a04SGreg Roach     */
373e364afe4SGreg Roach    public function extractNames(): void
374c1010edaSGreg Roach    {
37576f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
376a25f0a04SGreg Roach    }
377a25f0a04SGreg Roach
378a25f0a04SGreg Roach    /**
379a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
380a25f0a04SGreg Roach     *
381a25f0a04SGreg Roach     * @return string[][]
382a25f0a04SGreg Roach     */
3838f53f488SRico Sonntag    public function getAllNames(): array
384c1010edaSGreg Roach    {
385bdb3725aSGreg Roach        if ($this->getAllNames === null) {
386bdb3725aSGreg Roach            $this->getAllNames = [];
387a25f0a04SGreg Roach            if ($this->canShowName()) {
388a25f0a04SGreg Roach                // Ask the record to extract its names
389a25f0a04SGreg Roach                $this->extractNames();
390a25f0a04SGreg Roach                // No name found? Use a fallback.
391bdb3725aSGreg Roach                if (!$this->getAllNames) {
392db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
393a25f0a04SGreg Roach                }
394a25f0a04SGreg Roach            } else {
395db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
396a25f0a04SGreg Roach            }
397a25f0a04SGreg Roach        }
398cbc1590aSGreg Roach
399bdb3725aSGreg Roach        return $this->getAllNames;
400a25f0a04SGreg Roach    }
401a25f0a04SGreg Roach
402a25f0a04SGreg Roach    /**
403a25f0a04SGreg Roach     * If this object has no name, what do we call it?
404a25f0a04SGreg Roach     *
405a25f0a04SGreg Roach     * @return string
406a25f0a04SGreg Roach     */
4078f53f488SRico Sonntag    public function getFallBackName(): string
408c1010edaSGreg Roach    {
409c0935879SGreg Roach        return e($this->xref());
410a25f0a04SGreg Roach    }
411a25f0a04SGreg Roach
412a25f0a04SGreg Roach    /**
413a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
414a25f0a04SGreg Roach     *
415cbc1590aSGreg Roach     * @return int
416a25f0a04SGreg Roach     */
4178f53f488SRico Sonntag    public function getPrimaryName(): int
418c1010edaSGreg Roach    {
419a25f0a04SGreg Roach        static $language_script;
420a25f0a04SGreg Roach
421a25f0a04SGreg Roach        if ($language_script === null) {
42265cf5706SGreg Roach            $language_script = $language_script ?? I18N::locale()->script()->code();
423a25f0a04SGreg Roach        }
424a25f0a04SGreg Roach
425bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
426a25f0a04SGreg Roach            // Generally, the first name is the primary one....
427bdb3725aSGreg Roach            $this->getPrimaryName = 0;
428a25f0a04SGreg Roach            // ...except when the language/name use different character sets
429a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
43069546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
431bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
432a25f0a04SGreg Roach                    break;
433a25f0a04SGreg Roach                }
434a25f0a04SGreg Roach            }
435a25f0a04SGreg Roach        }
436a25f0a04SGreg Roach
437bdb3725aSGreg Roach        return $this->getPrimaryName;
438a25f0a04SGreg Roach    }
439a25f0a04SGreg Roach
440a25f0a04SGreg Roach    /**
441a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
442a25f0a04SGreg Roach     *
443cbc1590aSGreg Roach     * @return int
444a25f0a04SGreg Roach     */
4458f53f488SRico Sonntag    public function getSecondaryName(): int
446c1010edaSGreg Roach    {
4478f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
448a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
449bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
450a25f0a04SGreg Roach            // ....except when there are names with different character sets
451a25f0a04SGreg Roach            $all_names = $this->getAllNames();
452a25f0a04SGreg Roach            if (count($all_names) > 1) {
453a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
454a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
455e364afe4SGreg Roach                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
456bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
457a25f0a04SGreg Roach                        break;
458a25f0a04SGreg Roach                    }
459a25f0a04SGreg Roach                }
460a25f0a04SGreg Roach            }
461a25f0a04SGreg Roach        }
462cbc1590aSGreg Roach
463bdb3725aSGreg Roach        return $this->getSecondaryName;
464a25f0a04SGreg Roach    }
465a25f0a04SGreg Roach
466a25f0a04SGreg Roach    /**
467a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
468a25f0a04SGreg Roach     *
46976f666f4SGreg Roach     * @param int|null $n
4707e96c925SGreg Roach     *
4717e96c925SGreg Roach     * @return void
472a25f0a04SGreg Roach     */
473e364afe4SGreg Roach    public function setPrimaryName(int $n = null): void
474c1010edaSGreg Roach    {
475bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
476bdb3725aSGreg Roach        $this->getSecondaryName = null;
477a25f0a04SGreg Roach    }
478a25f0a04SGreg Roach
479a25f0a04SGreg Roach    /**
480a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
481a25f0a04SGreg Roach     *
482a25f0a04SGreg Roach     * @return string
483a25f0a04SGreg Roach     */
484c1010edaSGreg Roach    public function __toString()
485c1010edaSGreg Roach    {
48672cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
487a25f0a04SGreg Roach    }
488a25f0a04SGreg Roach
489a25f0a04SGreg Roach    /**
490c156e8f5SGreg Roach     * /**
491a25f0a04SGreg Roach     * Get variants of the name
492a25f0a04SGreg Roach     *
493a25f0a04SGreg Roach     * @return string
494a25f0a04SGreg Roach     */
495e364afe4SGreg Roach    public function fullName(): string
496c1010edaSGreg Roach    {
497a25f0a04SGreg Roach        if ($this->canShowName()) {
498a25f0a04SGreg Roach            $tmp = $this->getAllNames();
499cbc1590aSGreg Roach
500a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
501a25f0a04SGreg Roach        }
502b2ce94c6SRico Sonntag
503b2ce94c6SRico Sonntag        return I18N::translate('Private');
504a25f0a04SGreg Roach    }
505a25f0a04SGreg Roach
506a25f0a04SGreg Roach    /**
507a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
508a25f0a04SGreg Roach     *
509a25f0a04SGreg Roach     * @return string
510a25f0a04SGreg Roach     */
51139ca88baSGreg Roach    public function sortName(): string
512c1010edaSGreg Roach    {
513a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
514a25f0a04SGreg Roach        $tmp = $this->getAllNames();
515cbc1590aSGreg Roach
516a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
517a25f0a04SGreg Roach    }
518a25f0a04SGreg Roach
519a25f0a04SGreg Roach    /**
520a25f0a04SGreg Roach     * Get the full name in an alternative character set
521a25f0a04SGreg Roach     *
522e364afe4SGreg Roach     * @return string|null
523a25f0a04SGreg Roach     */
524e364afe4SGreg Roach    public function alternateName(): ?string
525c1010edaSGreg Roach    {
526e364afe4SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
527a25f0a04SGreg Roach            $all_names = $this->getAllNames();
528cbc1590aSGreg Roach
529a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
530a25f0a04SGreg Roach        }
531b2ce94c6SRico Sonntag
532b2ce94c6SRico Sonntag        return null;
533a25f0a04SGreg Roach    }
534a25f0a04SGreg Roach
535a25f0a04SGreg Roach    /**
536a25f0a04SGreg Roach     * Format this object for display in a list
537a25f0a04SGreg Roach     *
538a25f0a04SGreg Roach     * @return string
539a25f0a04SGreg Roach     */
5408f53f488SRico Sonntag    public function formatList(): string
541c1010edaSGreg Roach    {
542b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
54339ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
544a25f0a04SGreg Roach        $html .= $this->formatListDetails();
545b165e17cSGreg Roach        $html .= '</a>';
546cbc1590aSGreg Roach
547a25f0a04SGreg Roach        return $html;
548a25f0a04SGreg Roach    }
549a25f0a04SGreg Roach
550a25f0a04SGreg Roach    /**
551a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
552a25f0a04SGreg Roach     * identifying characteristics of this record.
553a25f0a04SGreg Roach     *
554a25f0a04SGreg Roach     * @return string
555a25f0a04SGreg Roach     */
5568f53f488SRico Sonntag    public function formatListDetails(): string
557c1010edaSGreg Roach    {
558a25f0a04SGreg Roach        return '';
559a25f0a04SGreg Roach    }
560a25f0a04SGreg Roach
561a25f0a04SGreg Roach    /**
562a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
563a25f0a04SGreg Roach     *
5648d0ebef0SGreg Roach     * @param string[] $facts
565cbc1590aSGreg Roach     * @param int      $style
566a25f0a04SGreg Roach     *
567a25f0a04SGreg Roach     * @return string
568a25f0a04SGreg Roach     */
5698d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
570c1010edaSGreg Roach    {
57130158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
572a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
573e364afe4SGreg Roach            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
574d93f11b5SGreg Roach                $joiner = ' — ';
575d93f11b5SGreg Roach            } else {
576d93f11b5SGreg Roach                $joiner = '';
577d93f11b5SGreg Roach            }
578e364afe4SGreg Roach            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
579a25f0a04SGreg Roach                switch ($style) {
580a25f0a04SGreg Roach                    case 1:
5817b7d8067SGreg Roach                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
582a25f0a04SGreg Roach                    case 2:
5837b7d8067SGreg Roach                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
584a25f0a04SGreg Roach                }
585a25f0a04SGreg Roach            }
586a25f0a04SGreg Roach        }
587cbc1590aSGreg Roach
588a25f0a04SGreg Roach        return '';
589a25f0a04SGreg Roach    }
590a25f0a04SGreg Roach
591a25f0a04SGreg Roach    /**
592a25f0a04SGreg Roach     * Find individuals linked to this record.
593a25f0a04SGreg Roach     *
594a25f0a04SGreg Roach     * @param string $link
595a25f0a04SGreg Roach     *
596b5c8fd7eSGreg Roach     * @return Collection<Individual>
597a25f0a04SGreg Roach     */
598907c1109SGreg Roach    public function linkedIndividuals(string $link): Collection
599c1010edaSGreg Roach    {
600907c1109SGreg Roach        return DB::table('individuals')
6010b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
602907c1109SGreg Roach                $join
603907c1109SGreg Roach                    ->on('l_file', '=', 'i_file')
604907c1109SGreg Roach                    ->on('l_from', '=', 'i_id');
605ba1c12e8SGreg Roach            })
606ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
607ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
608ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
609907c1109SGreg Roach            ->select(['individuals.*'])
610907c1109SGreg Roach            ->get()
611*a091ac74SGreg Roach            ->map(Factory::individual()->mapper($this->tree))
612907c1109SGreg Roach            ->filter(self::accessFilter());
613a25f0a04SGreg Roach    }
614a25f0a04SGreg Roach
615a25f0a04SGreg Roach    /**
616a25f0a04SGreg Roach     * Find families linked to this record.
617a25f0a04SGreg Roach     *
618a25f0a04SGreg Roach     * @param string $link
619a25f0a04SGreg Roach     *
620b5c8fd7eSGreg Roach     * @return Collection<Family>
621a25f0a04SGreg Roach     */
622907c1109SGreg Roach    public function linkedFamilies(string $link): Collection
623c1010edaSGreg Roach    {
624907c1109SGreg Roach        return DB::table('families')
6250b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
626907c1109SGreg Roach                $join
627907c1109SGreg Roach                    ->on('l_file', '=', 'f_file')
628907c1109SGreg Roach                    ->on('l_from', '=', 'f_id');
629ba1c12e8SGreg Roach            })
630ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
631ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
632ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
633907c1109SGreg Roach            ->select(['families.*'])
634907c1109SGreg Roach            ->get()
635*a091ac74SGreg Roach            ->map(Factory::family()->mapper($this->tree))
636907c1109SGreg Roach            ->filter(self::accessFilter());
637a25f0a04SGreg Roach    }
638a25f0a04SGreg Roach
639a25f0a04SGreg Roach    /**
640a25f0a04SGreg Roach     * Find sources linked to this record.
641a25f0a04SGreg Roach     *
642a25f0a04SGreg Roach     * @param string $link
643a25f0a04SGreg Roach     *
644b5c8fd7eSGreg Roach     * @return Collection<Source>
645a25f0a04SGreg Roach     */
646907c1109SGreg Roach    public function linkedSources(string $link): Collection
647c1010edaSGreg Roach    {
648907c1109SGreg Roach        return DB::table('sources')
6490b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
650907c1109SGreg Roach                $join
651907c1109SGreg Roach                    ->on('l_file', '=', 's_file')
652907c1109SGreg Roach                    ->on('l_from', '=', 's_id');
653ba1c12e8SGreg Roach            })
654ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
655ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
656ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
657907c1109SGreg Roach            ->select(['sources.*'])
658907c1109SGreg Roach            ->get()
659*a091ac74SGreg Roach            ->map(Factory::source()->mapper($this->tree))
660907c1109SGreg Roach            ->filter(self::accessFilter());
661a25f0a04SGreg Roach    }
662a25f0a04SGreg Roach
663a25f0a04SGreg Roach    /**
664a25f0a04SGreg Roach     * Find media objects linked to this record.
665a25f0a04SGreg Roach     *
666a25f0a04SGreg Roach     * @param string $link
667a25f0a04SGreg Roach     *
668b5c8fd7eSGreg Roach     * @return Collection<Media>
669a25f0a04SGreg Roach     */
670907c1109SGreg Roach    public function linkedMedia(string $link): Collection
671c1010edaSGreg Roach    {
672907c1109SGreg Roach        return DB::table('media')
6730b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
674907c1109SGreg Roach                $join
675907c1109SGreg Roach                    ->on('l_file', '=', 'm_file')
676907c1109SGreg Roach                    ->on('l_from', '=', 'm_id');
677ba1c12e8SGreg Roach            })
678ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
679ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
680ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
681907c1109SGreg Roach            ->select(['media.*'])
682907c1109SGreg Roach            ->get()
683*a091ac74SGreg Roach            ->map(Factory::media()->mapper($this->tree))
684907c1109SGreg Roach            ->filter(self::accessFilter());
685a25f0a04SGreg Roach    }
686a25f0a04SGreg Roach
687a25f0a04SGreg Roach    /**
688a25f0a04SGreg Roach     * Find notes linked to this record.
689a25f0a04SGreg Roach     *
690a25f0a04SGreg Roach     * @param string $link
691a25f0a04SGreg Roach     *
692b5c8fd7eSGreg Roach     * @return Collection<Note>
693a25f0a04SGreg Roach     */
694907c1109SGreg Roach    public function linkedNotes(string $link): Collection
695c1010edaSGreg Roach    {
696907c1109SGreg Roach        return DB::table('other')
6970b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
698907c1109SGreg Roach                $join
699907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
700907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
701ba1c12e8SGreg Roach            })
702ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
703ba1c12e8SGreg Roach            ->where('o_type', '=', 'NOTE')
704ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
705ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
706907c1109SGreg Roach            ->select(['other.*'])
707907c1109SGreg Roach            ->get()
708*a091ac74SGreg Roach            ->map(Factory::note()->mapper($this->tree))
709907c1109SGreg Roach            ->filter(self::accessFilter());
710a25f0a04SGreg Roach    }
711a25f0a04SGreg Roach
712a25f0a04SGreg Roach    /**
713a25f0a04SGreg Roach     * Find repositories linked to this record.
714a25f0a04SGreg Roach     *
715a25f0a04SGreg Roach     * @param string $link
716a25f0a04SGreg Roach     *
717b5c8fd7eSGreg Roach     * @return Collection<Repository>
718a25f0a04SGreg Roach     */
719907c1109SGreg Roach    public function linkedRepositories(string $link): Collection
720c1010edaSGreg Roach    {
721907c1109SGreg Roach        return DB::table('other')
7220b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
723907c1109SGreg Roach                $join
724907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
725907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
726ba1c12e8SGreg Roach            })
727ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
728ba1c12e8SGreg Roach            ->where('o_type', '=', 'REPO')
729ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
730ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
731907c1109SGreg Roach            ->select(['other.*'])
732907c1109SGreg Roach            ->get()
733*a091ac74SGreg Roach            ->map(Factory::repository()->mapper($this->tree))
734907c1109SGreg Roach            ->filter(self::accessFilter());
735a25f0a04SGreg Roach    }
736a25f0a04SGreg Roach
737a25f0a04SGreg Roach    /**
738a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
739a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
740a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
741a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
742a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
743a25f0a04SGreg Roach     *
7448d0ebef0SGreg Roach     * @param string[] $events
745a25f0a04SGreg Roach     *
746a25f0a04SGreg Roach     * @return Date[]
747a25f0a04SGreg Roach     */
7488d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
749c1010edaSGreg Roach    {
75013abd6f3SGreg Roach        $dates = [];
7518d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
7522decada7SGreg Roach            if ($event->date()->isOK()) {
7532decada7SGreg Roach                $dates[] = $event->date();
754a25f0a04SGreg Roach            }
755a25f0a04SGreg Roach        }
756a25f0a04SGreg Roach
757a25f0a04SGreg Roach        return $dates;
758a25f0a04SGreg Roach    }
759a25f0a04SGreg Roach
760a25f0a04SGreg Roach    /**
761a25f0a04SGreg Roach     * Get all the places for a particular type of event
762a25f0a04SGreg Roach     *
7638d0ebef0SGreg Roach     * @param string[] $events
764a25f0a04SGreg Roach     *
7654080d558SGreg Roach     * @return Place[]
766a25f0a04SGreg Roach     */
7678d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
768c1010edaSGreg Roach    {
76913abd6f3SGreg Roach        $places = [];
7708d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
771138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
772a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
77316d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
774a25f0a04SGreg Roach                }
775a25f0a04SGreg Roach            }
776a25f0a04SGreg Roach        }
777a25f0a04SGreg Roach
778a25f0a04SGreg Roach        return $places;
779a25f0a04SGreg Roach    }
780a25f0a04SGreg Roach
781a25f0a04SGreg Roach    /**
782a25f0a04SGreg Roach     * The facts and events for this record.
783a25f0a04SGreg Roach     *
7848d0ebef0SGreg Roach     * @param string[] $filter
785cbc1590aSGreg Roach     * @param bool     $sort
786cbc1590aSGreg Roach     * @param int|null $access_level
787ce42304aSGreg Roach     * @param bool     $ignore_deleted
788a25f0a04SGreg Roach     *
789b5c8fd7eSGreg Roach     * @return Collection<Fact>
790a25f0a04SGreg Roach     */
791ce42304aSGreg Roach    public function facts(
792ce42304aSGreg Roach        array $filter = [],
793ce42304aSGreg Roach        bool $sort = false,
794ce42304aSGreg Roach        int $access_level = null,
795ce42304aSGreg Roach        bool $ignore_deleted = false
796ce42304aSGreg Roach    ): Collection {
797d9e083e7SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
7984b9ff166SGreg Roach
7998af3e5c1SGreg Roach        $facts = new Collection();
800ce42304aSGreg Roach        if ($this->canShow($access_level)) {
801a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
80222d65e5aSGreg Roach                if (($filter === [] || in_array($fact->getTag(), $filter, true)) && $fact->canShow($access_level)) {
8038af3e5c1SGreg Roach                    $facts->push($fact);
804a25f0a04SGreg Roach                }
805a25f0a04SGreg Roach            }
806a25f0a04SGreg Roach        }
807d17d7b9eSGreg Roach
808a25f0a04SGreg Roach        if ($sort) {
809580a4d11SGreg Roach            $facts = Fact::sortFacts($facts);
810a25f0a04SGreg Roach        }
811cbc1590aSGreg Roach
812ce42304aSGreg Roach        if ($ignore_deleted) {
813ce42304aSGreg Roach            $facts = $facts->filter(static function (Fact $fact): bool {
814ce42304aSGreg Roach                return !$fact->isPendingDeletion();
815ce42304aSGreg Roach            });
816ce42304aSGreg Roach        }
817ce42304aSGreg Roach
81839ca88baSGreg Roach        return new Collection($facts);
819a25f0a04SGreg Roach    }
820a25f0a04SGreg Roach
821a25f0a04SGreg Roach    /**
8224459dc9aSGreg Roach     * Get the last-change timestamp for this record
823a25f0a04SGreg Roach     *
8244459dc9aSGreg Roach     * @return Carbon
825a25f0a04SGreg Roach     */
8264459dc9aSGreg Roach    public function lastChangeTimestamp(): Carbon
827c1010edaSGreg Roach    {
8284459dc9aSGreg Roach        /** @var Fact|null $chan */
829820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
830a25f0a04SGreg Roach
8314459dc9aSGreg Roach        if ($chan instanceof Fact) {
832a25f0a04SGreg Roach            // The record does have a CHAN event
8332decada7SGreg Roach            $d = $chan->date()->minimumDate();
8344459dc9aSGreg Roach
835138ca96cSGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
8364459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
837e364afe4SGreg Roach            }
838e364afe4SGreg Roach
839e364afe4SGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
8404459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
841b2ce94c6SRico Sonntag            }
842b2ce94c6SRico Sonntag
8434459dc9aSGreg Roach            return Carbon::create($d->year(), $d->month(), $d->day());
844a25f0a04SGreg Roach        }
845b2ce94c6SRico Sonntag
846a25f0a04SGreg Roach        // The record does not have a CHAN event
8474459dc9aSGreg Roach        return Carbon::createFromTimestamp(0);
848a25f0a04SGreg Roach    }
849a25f0a04SGreg Roach
850a25f0a04SGreg Roach    /**
851a25f0a04SGreg Roach     * Get the last-change user for this record
852a25f0a04SGreg Roach     *
853a25f0a04SGreg Roach     * @return string
854a25f0a04SGreg Roach     */
855e364afe4SGreg Roach    public function lastChangeUser(): string
856c1010edaSGreg Roach    {
857820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
858a25f0a04SGreg Roach
859a25f0a04SGreg Roach        if ($chan === null) {
860a25f0a04SGreg Roach            return I18N::translate('Unknown');
861b2ce94c6SRico Sonntag        }
862b2ce94c6SRico Sonntag
8633425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
864baacc364SGreg Roach        if ($chan_user === '') {
865a25f0a04SGreg Roach            return I18N::translate('Unknown');
866b2ce94c6SRico Sonntag        }
867b2ce94c6SRico Sonntag
868a25f0a04SGreg Roach        return $chan_user;
869a25f0a04SGreg Roach    }
870a25f0a04SGreg Roach
871a25f0a04SGreg Roach    /**
872a25f0a04SGreg Roach     * Add a new fact to this record
873a25f0a04SGreg Roach     *
874a25f0a04SGreg Roach     * @param string $gedcom
875cbc1590aSGreg Roach     * @param bool   $update_chan
8767e96c925SGreg Roach     *
8777e96c925SGreg Roach     * @return void
878a25f0a04SGreg Roach     */
879e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
880c1010edaSGreg Roach    {
881fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
882a25f0a04SGreg Roach    }
883a25f0a04SGreg Roach
884a25f0a04SGreg Roach    /**
885a25f0a04SGreg Roach     * Delete a fact from this record
886a25f0a04SGreg Roach     *
887a25f0a04SGreg Roach     * @param string $fact_id
888cbc1590aSGreg Roach     * @param bool   $update_chan
8897e96c925SGreg Roach     *
8907e96c925SGreg Roach     * @return void
891a25f0a04SGreg Roach     */
892e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
893c1010edaSGreg Roach    {
894db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
895a25f0a04SGreg Roach    }
896a25f0a04SGreg Roach
897a25f0a04SGreg Roach    /**
898a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
899a25f0a04SGreg Roach     *
900a25f0a04SGreg Roach     * @param string $fact_id
901a25f0a04SGreg Roach     * @param string $gedcom
902cbc1590aSGreg Roach     * @param bool   $update_chan
903a25f0a04SGreg Roach     *
9047e96c925SGreg Roach     * @return void
9057e96c925SGreg Roach     * @throws Exception
906a25f0a04SGreg Roach     */
907e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
908c1010edaSGreg Roach    {
90971f696adSGreg Roach        // Not all record types allow a CHAN event.
91071f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
91171f696adSGreg Roach
912a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
913a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
914a25f0a04SGreg Roach        $gedcom = trim($gedcom);
915a25f0a04SGreg Roach
916a25f0a04SGreg Roach        if ($this->pending === '') {
9177e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
918a25f0a04SGreg Roach        }
9198d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
9207e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
921a25f0a04SGreg Roach        }
922a25f0a04SGreg Roach
923a25f0a04SGreg Roach        if ($this->pending) {
924a25f0a04SGreg Roach            $old_gedcom = $this->pending;
925a25f0a04SGreg Roach        } else {
926a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
927a25f0a04SGreg Roach        }
928a25f0a04SGreg Roach
929a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
93065e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
931a25f0a04SGreg Roach
932a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
93319aed3a1SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE, true) as $fact) {
934905ab80aSGreg Roach            if ($fact->id() === $fact_id) {
935db7bb364SGreg Roach                if ($gedcom !== '') {
936a25f0a04SGreg Roach                    $new_gedcom .= "\n" . $gedcom;
937a25f0a04SGreg Roach                }
938fc3ccce4SGreg Roach                $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
939e364afe4SGreg Roach            } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) {
940138ca96cSGreg Roach                $new_gedcom .= "\n" . $fact->gedcom();
941a25f0a04SGreg Roach            }
942a25f0a04SGreg Roach        }
943a25f0a04SGreg Roach
944a25f0a04SGreg Roach        // Adding a new fact
945fc3ccce4SGreg Roach        if ($fact_id === '') {
946a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
947a25f0a04SGreg Roach        }
948a25f0a04SGreg Roach
94919aed3a1SGreg Roach        if ($update_chan && strpos($new_gedcom, "\n1 CHAN") === false) {
95019aed3a1SGreg Roach            $today = strtoupper(date('d M Y'));
95119aed3a1SGreg Roach            $now   = date('H:i:s');
95219aed3a1SGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
95319aed3a1SGreg Roach        }
95419aed3a1SGreg Roach
955e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
956a25f0a04SGreg Roach            // Save the changes
957d09b6323SGreg Roach            DB::table('change')->insert([
958d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
959d09b6323SGreg Roach                'xref'       => $this->xref,
960d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
961d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
962d09b6323SGreg Roach                'user_id'    => Auth::id(),
96313abd6f3SGreg Roach            ]);
964a25f0a04SGreg Roach
965a25f0a04SGreg Roach            $this->pending = $new_gedcom;
966a25f0a04SGreg Roach
9677c4add84SGreg Roach            if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') {
96822e73debSGreg Roach                app(PendingChangesService::class)->acceptRecord($this);
969a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
970a25f0a04SGreg Roach                $this->pending = null;
971a25f0a04SGreg Roach            }
972a25f0a04SGreg Roach        }
973a25f0a04SGreg Roach        $this->parseFacts();
974a25f0a04SGreg Roach    }
975a25f0a04SGreg Roach
976a25f0a04SGreg Roach    /**
977a25f0a04SGreg Roach     * Update this record
978a25f0a04SGreg Roach     *
979a25f0a04SGreg Roach     * @param string $gedcom
980cbc1590aSGreg Roach     * @param bool   $update_chan
9817e96c925SGreg Roach     *
9827e96c925SGreg Roach     * @return void
983a25f0a04SGreg Roach     */
984e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
985c1010edaSGreg Roach    {
98671f696adSGreg Roach        // Not all record types allow a CHAN event.
98771f696adSGreg Roach        $update_chan = $update_chan && in_array(static::RECORD_TYPE, Gedcom::RECORDS_WITH_CHAN, true);
98871f696adSGreg Roach
989a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
990a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
991a25f0a04SGreg Roach        $gedcom = trim($gedcom);
992a25f0a04SGreg Roach
993a25f0a04SGreg Roach        // Update the CHAN record
994a25f0a04SGreg Roach        if ($update_chan) {
995a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
99653432476SGreg Roach            $today = strtoupper(date('d M Y'));
99753432476SGreg Roach            $now   = date('H:i:s');
99853432476SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
999a25f0a04SGreg Roach        }
1000a25f0a04SGreg Roach
1001a25f0a04SGreg Roach        // Create a pending change
1002d09b6323SGreg Roach        DB::table('change')->insert([
1003d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1004d09b6323SGreg Roach            'xref'       => $this->xref,
1005d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1006d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1007d09b6323SGreg Roach            'user_id'    => Auth::id(),
100813abd6f3SGreg Roach        ]);
1009a25f0a04SGreg Roach
1010a25f0a04SGreg Roach        // Clear the cache
1011a25f0a04SGreg Roach        $this->pending = $gedcom;
1012a25f0a04SGreg Roach
1013a25f0a04SGreg Roach        // Accept this pending change
10147c4add84SGreg Roach        if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') {
101522e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1016a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1017a25f0a04SGreg Roach            $this->pending = null;
1018a25f0a04SGreg Roach        }
1019a25f0a04SGreg Roach
1020a25f0a04SGreg Roach        $this->parseFacts();
1021a25f0a04SGreg Roach
1022847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1023a25f0a04SGreg Roach    }
1024a25f0a04SGreg Roach
1025a25f0a04SGreg Roach    /**
1026a25f0a04SGreg Roach     * Delete this record
1027b874da82SGreg Roach     *
1028b874da82SGreg Roach     * @return void
1029a25f0a04SGreg Roach     */
1030e364afe4SGreg Roach    public function deleteRecord(): void
1031c1010edaSGreg Roach    {
1032a25f0a04SGreg Roach        // Create a pending change
10334c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1034d09b6323SGreg Roach            DB::table('change')->insert([
1035d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1036d09b6323SGreg Roach                'xref'       => $this->xref,
1037d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1038d09b6323SGreg Roach                'new_gedcom' => '',
1039d09b6323SGreg Roach                'user_id'    => Auth::id(),
104013abd6f3SGreg Roach            ]);
10414c0b5256SGreg Roach        }
1042a25f0a04SGreg Roach
10434c0b5256SGreg Roach        // Auto-accept this pending change
10447c4add84SGreg Roach        if (Auth::user()->getPreference(User::PREF_AUTO_ACCEPT_EDITS) === '1') {
104522e73debSGreg Roach            app(PendingChangesService::class)->acceptRecord($this);
1046a25f0a04SGreg Roach        }
1047a25f0a04SGreg Roach
1048847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1049a25f0a04SGreg Roach    }
1050a25f0a04SGreg Roach
1051a25f0a04SGreg Roach    /**
1052a25f0a04SGreg Roach     * Remove all links from this record to $xref
1053a25f0a04SGreg Roach     *
1054a25f0a04SGreg Roach     * @param string $xref
1055cbc1590aSGreg Roach     * @param bool   $update_chan
10567e96c925SGreg Roach     *
10577e96c925SGreg Roach     * @return void
1058a25f0a04SGreg Roach     */
1059e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
1060c1010edaSGreg Roach    {
1061a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1062a25f0a04SGreg Roach
106330158ae7SGreg Roach        foreach ($this->facts() as $fact) {
106484586c02SGreg Roach            if ($fact->value() === $value) {
1065905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
10668d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1067138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1068a25f0a04SGreg Roach                foreach ($matches as $match) {
1069a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1070a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1071a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1072a25f0a04SGreg Roach                }
1073905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1074a25f0a04SGreg Roach            }
1075a25f0a04SGreg Roach        }
1076a25f0a04SGreg Roach    }
1077bf4eb542SGreg Roach
1078bf4eb542SGreg Roach    /**
1079bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1080bf4eb542SGreg Roach     * also delete all links to it.
1081bf4eb542SGreg Roach     *
1082bf4eb542SGreg Roach     * @return GedcomRecord[]
1083bf4eb542SGreg Roach     */
1084bf4eb542SGreg Roach    public function linkingRecords(): array
1085bf4eb542SGreg Roach    {
1086b5961194SGreg Roach        $like = addcslashes($this->xref(), '\\%_');
1087b5961194SGreg Roach
1088bf4eb542SGreg Roach        $union = DB::table('change')
1089bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1090b5961194SGreg Roach            ->where('new_gedcom', 'LIKE', '%@' . $like . '@%')
1091b5961194SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $like . '@%')
109283242252SGreg Roach            ->whereIn('change_id', function (Builder $query): void {
109383242252SGreg Roach                $query->select(new Expression('MAX(change_id)'))
109483242252SGreg Roach                    ->from('change')
109583242252SGreg Roach                    ->where('gedcom_id', '=', $this->tree->id())
109683242252SGreg Roach                    ->where('status', '=', 'pending')
10977f5c2944SGreg Roach                    ->groupBy(['xref']);
109883242252SGreg Roach            })
1099bf4eb542SGreg Roach            ->select(['xref']);
1100bf4eb542SGreg Roach
1101bf4eb542SGreg Roach        $xrefs = DB::table('link')
1102bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1103bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
110447256fc5SGreg Roach            ->select(['l_from'])
1105bf4eb542SGreg Roach            ->union($union)
1106bf4eb542SGreg Roach            ->pluck('l_from');
1107bf4eb542SGreg Roach
1108bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
1109*a091ac74SGreg Roach            $record = Factory::gedcomRecord()->make($xref, $this->tree);
1110ffc0a61fSGreg Roach            assert($record instanceof GedcomRecord);
1111ffc0a61fSGreg Roach
1112ffc0a61fSGreg Roach            return $record;
1113bf4eb542SGreg Roach        })->all();
1114bf4eb542SGreg Roach    }
111522e73debSGreg Roach
111622e73debSGreg Roach    /**
111722e73debSGreg Roach     * Each object type may have its own special rules, and re-implement this function.
111822e73debSGreg Roach     *
111922e73debSGreg Roach     * @param int $access_level
112022e73debSGreg Roach     *
112122e73debSGreg Roach     * @return bool
112222e73debSGreg Roach     */
112322e73debSGreg Roach    protected function canShowByType(int $access_level): bool
112422e73debSGreg Roach    {
112522e73debSGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
112622e73debSGreg Roach
112722e73debSGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
112822e73debSGreg Roach            // Restriction found
112922e73debSGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
113022e73debSGreg Roach        }
113122e73debSGreg Roach
113222e73debSGreg Roach        // No restriction found - must be public:
113322e73debSGreg Roach        return true;
113422e73debSGreg Roach    }
113522e73debSGreg Roach
113622e73debSGreg Roach    /**
113722e73debSGreg Roach     * Generate a private version of this record
113822e73debSGreg Roach     *
113922e73debSGreg Roach     * @param int $access_level
114022e73debSGreg Roach     *
114122e73debSGreg Roach     * @return string
114222e73debSGreg Roach     */
114322e73debSGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
114422e73debSGreg Roach    {
114522e73debSGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
114622e73debSGreg Roach    }
114722e73debSGreg Roach
114822e73debSGreg Roach    /**
114922e73debSGreg Roach     * Convert a name record into sortable and full/display versions. This default
115022e73debSGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
115122e73debSGreg Roach     *
115222e73debSGreg Roach     * @param string $type
115322e73debSGreg Roach     * @param string $value
115422e73debSGreg Roach     * @param string $gedcom
115522e73debSGreg Roach     *
115622e73debSGreg Roach     * @return void
115722e73debSGreg Roach     */
115822e73debSGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
115922e73debSGreg Roach    {
116022e73debSGreg Roach        $this->getAllNames[] = [
116122e73debSGreg Roach            'type'   => $type,
116222e73debSGreg Roach            'sort'   => preg_replace_callback('/([0-9]+)/', static function (array $matches): string {
116322e73debSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
116422e73debSGreg Roach            }, $value),
116522e73debSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
116622e73debSGreg Roach            // This is used for display
116722e73debSGreg Roach            'fullNN' => $value,
116822e73debSGreg Roach            // This goes into the database
116922e73debSGreg Roach        ];
117022e73debSGreg Roach    }
117122e73debSGreg Roach
117222e73debSGreg Roach    /**
117322e73debSGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
117422e73debSGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
117522e73debSGreg Roach     * Parameters: the level 1 fact containing the name.
117622e73debSGreg Roach     * Return value: an array of name structures, each containing
117722e73debSGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
117822e73debSGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
117922e73debSGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
118022e73debSGreg Roach     *
118122e73debSGreg Roach     * @param int        $level
118222e73debSGreg Roach     * @param string     $fact_type
118322e73debSGreg Roach     * @param Collection $facts
118422e73debSGreg Roach     *
118522e73debSGreg Roach     * @return void
118622e73debSGreg Roach     */
118722e73debSGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
118822e73debSGreg Roach    {
118922e73debSGreg Roach        $sublevel    = $level + 1;
119022e73debSGreg Roach        $subsublevel = $sublevel + 1;
119122e73debSGreg Roach        foreach ($facts as $fact) {
119222e73debSGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
119322e73debSGreg Roach                foreach ($matches as $match) {
119422e73debSGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
119522e73debSGreg Roach                    if ($match[1] === 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
119622e73debSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
119722e73debSGreg Roach                    } else {
119822e73debSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
119922e73debSGreg Roach                    }
120022e73debSGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
120122e73debSGreg Roach                        foreach ($submatches as $submatch) {
120222e73debSGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
120322e73debSGreg Roach                        }
120422e73debSGreg Roach                    }
120522e73debSGreg Roach                }
120622e73debSGreg Roach            }
120722e73debSGreg Roach        }
120822e73debSGreg Roach    }
120922e73debSGreg Roach
121022e73debSGreg Roach    /**
121122e73debSGreg Roach     * Split the record into facts
121222e73debSGreg Roach     *
121322e73debSGreg Roach     * @return void
121422e73debSGreg Roach     */
121522e73debSGreg Roach    private function parseFacts(): void
121622e73debSGreg Roach    {
121722e73debSGreg Roach        // Split the record into facts
121822e73debSGreg Roach        if ($this->gedcom) {
121922e73debSGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
122022e73debSGreg Roach            array_shift($gedcom_facts);
122122e73debSGreg Roach        } else {
122222e73debSGreg Roach            $gedcom_facts = [];
122322e73debSGreg Roach        }
122422e73debSGreg Roach        if ($this->pending) {
122522e73debSGreg Roach            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
122622e73debSGreg Roach            array_shift($pending_facts);
122722e73debSGreg Roach        } else {
122822e73debSGreg Roach            $pending_facts = [];
122922e73debSGreg Roach        }
123022e73debSGreg Roach
123122e73debSGreg Roach        $this->facts = [];
123222e73debSGreg Roach
123322e73debSGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
123422e73debSGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
123522e73debSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
123622e73debSGreg Roach                $fact->setPendingDeletion();
123722e73debSGreg Roach            }
123822e73debSGreg Roach            $this->facts[] = $fact;
123922e73debSGreg Roach        }
124022e73debSGreg Roach        foreach ($pending_facts as $pending_fact) {
124122e73debSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
124222e73debSGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
124322e73debSGreg Roach                $fact->setPendingAddition();
124422e73debSGreg Roach                $this->facts[] = $fact;
124522e73debSGreg Roach            }
124622e73debSGreg Roach        }
124722e73debSGreg Roach    }
124822e73debSGreg Roach
124922e73debSGreg Roach    /**
125022e73debSGreg Roach     * Work out whether this record can be shown to a user with a given access level
125122e73debSGreg Roach     *
125222e73debSGreg Roach     * @param int $access_level
125322e73debSGreg Roach     *
125422e73debSGreg Roach     * @return bool
125522e73debSGreg Roach     */
125622e73debSGreg Roach    private function canShowRecord(int $access_level): bool
125722e73debSGreg Roach    {
125822e73debSGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
125922e73debSGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
126022e73debSGreg Roach            return true;
126122e73debSGreg Roach        }
126222e73debSGreg Roach
126322e73debSGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
12647c4add84SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), User::PREF_TREE_ACCOUNT_XREF) && $access_level === Auth::accessLevel($this->tree)) {
126522e73debSGreg Roach            return true;
126622e73debSGreg Roach        }
126722e73debSGreg Roach
126822e73debSGreg Roach        // Does this record have a RESN?
126922e73debSGreg Roach        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
127022e73debSGreg Roach            return Auth::PRIV_NONE >= $access_level;
127122e73debSGreg Roach        }
127222e73debSGreg Roach        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
127322e73debSGreg Roach            return Auth::PRIV_USER >= $access_level;
127422e73debSGreg Roach        }
127522e73debSGreg Roach        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
127622e73debSGreg Roach            return true;
127722e73debSGreg Roach        }
127822e73debSGreg Roach
127922e73debSGreg Roach        // Does this record have a default RESN?
128022e73debSGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
128122e73debSGreg Roach        if (isset($individual_privacy[$this->xref()])) {
128222e73debSGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
128322e73debSGreg Roach        }
128422e73debSGreg Roach
128522e73debSGreg Roach        // Privacy rules do not apply to admins
128622e73debSGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
128722e73debSGreg Roach            return true;
128822e73debSGreg Roach        }
128922e73debSGreg Roach
129022e73debSGreg Roach        // Different types of record have different privacy rules
129122e73debSGreg Roach        return $this->canShowByType($access_level);
129222e73debSGreg Roach    }
1293a25f0a04SGreg Roach}
1294