xref: /webtrees/app/GedcomRecord.php (revision 886b77daa151baff5435671d4ed5ba22ff96b9d6)
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
20*886b77daSGreg Roachuse Closure;
217e96c925SGreg Roachuse Exception;
223d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\Functions;
233d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsDate;
243d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
253d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsPrint;
26bf4eb542SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
27ba1c12e8SGreg Roachuse Illuminate\Database\Query\JoinClause;
2879529c87SGreg Roachuse stdClass;
29a25f0a04SGreg Roach
30a25f0a04SGreg Roach/**
3176692c8bSGreg Roach * A GEDCOM object.
32a25f0a04SGreg Roach */
33c1010edaSGreg Roachclass GedcomRecord
34c1010edaSGreg Roach{
3516d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
3616d6367aSGreg Roach
3716d6367aSGreg Roach    protected const ROUTE_NAME = 'record';
38a25f0a04SGreg Roach
39a25f0a04SGreg Roach    /** @var string The record identifier */
40a25f0a04SGreg Roach    protected $xref;
41a25f0a04SGreg Roach
42000959d9SGreg Roach    /** @var Tree  The family tree to which this record belongs */
43000959d9SGreg Roach    protected $tree;
44a25f0a04SGreg Roach
45a25f0a04SGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
46a25f0a04SGreg Roach    protected $gedcom;
47a25f0a04SGreg Roach
48a25f0a04SGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
49a25f0a04SGreg Roach    protected $pending;
50a25f0a04SGreg Roach
51a25f0a04SGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
52a25f0a04SGreg Roach    protected $facts;
53a25f0a04SGreg Roach
54cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_PRIVATE */
55a25f0a04SGreg Roach    private $disp_public;
56a25f0a04SGreg Roach
57cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_USER */
58a25f0a04SGreg Roach    private $disp_user;
59a25f0a04SGreg Roach
60cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_NONE */
61a25f0a04SGreg Roach    private $disp_none;
62a25f0a04SGreg Roach
63a25f0a04SGreg Roach    /** @var string[][] All the names of this individual */
64bdb3725aSGreg Roach    protected $getAllNames;
65a25f0a04SGreg Roach
66d17d7b9eSGreg Roach    /** @var int|null Cached result */
67bdb3725aSGreg Roach    protected $getPrimaryName;
68a25f0a04SGreg Roach
69d17d7b9eSGreg Roach    /** @var int|null Cached result */
70bdb3725aSGreg Roach    protected $getSecondaryName;
71a25f0a04SGreg Roach
7276692c8bSGreg Roach    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
73bec87e94SGreg Roach    public static $gedcom_record_cache;
741ae87ce5SGreg Roach
7579529c87SGreg Roach    /** @var stdClass[][] Fetch all pending edits in one database query */
76bec87e94SGreg Roach    public static $pending_record_cache;
77a25f0a04SGreg Roach
78a25f0a04SGreg Roach    /**
79a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
80a25f0a04SGreg Roach     *
81a25f0a04SGreg Roach     * @param string      $xref
82a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
83a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
84a25f0a04SGreg Roach     *                             empty string for records with pending deletions
8524ec66ceSGreg Roach     * @param Tree        $tree
86a25f0a04SGreg Roach     */
8776f666f4SGreg Roach    public function __construct(string $xref, string $gedcom, $pending, Tree $tree)
88c1010edaSGreg Roach    {
89a25f0a04SGreg Roach        $this->xref    = $xref;
90a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
91a25f0a04SGreg Roach        $this->pending = $pending;
9224ec66ceSGreg Roach        $this->tree    = $tree;
93a25f0a04SGreg Roach
94a25f0a04SGreg Roach        $this->parseFacts();
95a25f0a04SGreg Roach    }
96a25f0a04SGreg Roach
97a25f0a04SGreg Roach    /**
98*886b77daSGreg Roach     * A closure which will create a record from a database row.
99*886b77daSGreg Roach     *
100*886b77daSGreg Roach     * @param Tree $tree
101*886b77daSGreg Roach     *
102*886b77daSGreg Roach     * @return Closure
103*886b77daSGreg Roach     */
104*886b77daSGreg Roach    public static function rowMapper(Tree $tree): Closure
105*886b77daSGreg Roach    {
106*886b77daSGreg Roach        return function (stdClass $row) use ($tree): GedcomRecord {
107*886b77daSGreg Roach            return GedcomRecord::getInstance($row->o_id, $tree, $row->o_gedcom);
108*886b77daSGreg Roach        };
109*886b77daSGreg Roach    }
110*886b77daSGreg Roach
111*886b77daSGreg Roach    /**
112*886b77daSGreg Roach     * A closure which will filter out private records.
113*886b77daSGreg Roach     *
114*886b77daSGreg Roach     * @return Closure
115*886b77daSGreg Roach     */
116*886b77daSGreg Roach    public static function filter(): Closure
117*886b77daSGreg Roach    {
118*886b77daSGreg Roach        return function (GedcomRecord $record): bool {
119*886b77daSGreg Roach            return $record->canShow();
120*886b77daSGreg Roach        };
121*886b77daSGreg Roach    }
122*886b77daSGreg Roach
123*886b77daSGreg Roach    /**
124a25f0a04SGreg Roach     * Split the record into facts
1257e96c925SGreg Roach     *
1267e96c925SGreg Roach     * @return void
127a25f0a04SGreg Roach     */
128c1010edaSGreg Roach    private function parseFacts()
129c1010edaSGreg Roach    {
130a25f0a04SGreg Roach        // Split the record into facts
131a25f0a04SGreg Roach        if ($this->gedcom) {
132a25f0a04SGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
133a25f0a04SGreg Roach            array_shift($gedcom_facts);
134a25f0a04SGreg Roach        } else {
13513abd6f3SGreg Roach            $gedcom_facts = [];
136a25f0a04SGreg Roach        }
137a25f0a04SGreg Roach        if ($this->pending) {
138a25f0a04SGreg Roach            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
139a25f0a04SGreg Roach            array_shift($pending_facts);
140a25f0a04SGreg Roach        } else {
14113abd6f3SGreg Roach            $pending_facts = [];
142a25f0a04SGreg Roach        }
143a25f0a04SGreg Roach
14413abd6f3SGreg Roach        $this->facts = [];
145a25f0a04SGreg Roach
146a25f0a04SGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
147a25f0a04SGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
148a25f0a04SGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts)) {
149a25f0a04SGreg Roach                $fact->setPendingDeletion();
150a25f0a04SGreg Roach            }
151a25f0a04SGreg Roach            $this->facts[] = $fact;
152a25f0a04SGreg Roach        }
153a25f0a04SGreg Roach        foreach ($pending_facts as $pending_fact) {
154a25f0a04SGreg Roach            if (!in_array($pending_fact, $gedcom_facts)) {
155a25f0a04SGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
156a25f0a04SGreg Roach                $fact->setPendingAddition();
157a25f0a04SGreg Roach                $this->facts[] = $fact;
158a25f0a04SGreg Roach            }
159a25f0a04SGreg Roach        }
160a25f0a04SGreg Roach    }
161a25f0a04SGreg Roach
162a25f0a04SGreg Roach    /**
163a25f0a04SGreg Roach     * Get an instance of a GedcomRecord object. For single records,
164a25f0a04SGreg Roach     * we just receive the XREF. For bulk records (such as lists
165a25f0a04SGreg Roach     * and search results) we can receive the GEDCOM data as well.
166a25f0a04SGreg Roach     *
167a25f0a04SGreg Roach     * @param string      $xref
16824ec66ceSGreg Roach     * @param Tree        $tree
169a25f0a04SGreg Roach     * @param string|null $gedcom
170a25f0a04SGreg Roach     *
1717e96c925SGreg Roach     * @throws Exception
172cbc1590aSGreg Roach     *
17384658595SGreg Roach     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|null
174a25f0a04SGreg Roach     */
17576f666f4SGreg Roach    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
176c1010edaSGreg Roach    {
17772cf66d4SGreg Roach        $tree_id = $tree->id();
17824ec66ceSGreg Roach
179e71ef9d2SGreg Roach        // Is this record already in the cache?
18024ec66ceSGreg Roach        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
181e71ef9d2SGreg Roach            return self::$gedcom_record_cache[$xref][$tree_id];
182a25f0a04SGreg Roach        }
183a25f0a04SGreg Roach
184a25f0a04SGreg Roach        // Do we need to fetch the record from the database?
185a25f0a04SGreg Roach        if ($gedcom === null) {
18624ec66ceSGreg Roach            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
187a25f0a04SGreg Roach        }
188a25f0a04SGreg Roach
189a25f0a04SGreg Roach        // If we can edit, then we also need to be able to see pending records.
19094075df0SGreg Roach        if (Auth::isEditor($tree)) {
19124ec66ceSGreg Roach            if (!isset(self::$pending_record_cache[$tree_id])) {
192a25f0a04SGreg Roach                // Fetch all pending records in one database query
19313abd6f3SGreg Roach                self::$pending_record_cache[$tree_id] = [];
19485fc8064SGreg Roach                $rows = DB::table('change')
19585fc8064SGreg Roach                    ->where('gedcom_id', '=', $tree_id)
19685fc8064SGreg Roach                    ->where('status', '=', 'pending')
19785fc8064SGreg Roach                    ->orderBy('change_id')
19885fc8064SGreg Roach                    ->select(['xref', 'new_gedcom'])
19985fc8064SGreg Roach                    ->get();
200d17d7b9eSGreg Roach
201a25f0a04SGreg Roach                foreach ($rows as $row) {
20224ec66ceSGreg Roach                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
203a25f0a04SGreg Roach                }
204a25f0a04SGreg Roach            }
205a25f0a04SGreg Roach
206d17d7b9eSGreg Roach            $pending = self::$pending_record_cache[$tree_id][$xref] ?? null;
207a25f0a04SGreg Roach        } else {
208a25f0a04SGreg Roach            // There are no pending changes for this record
209a25f0a04SGreg Roach            $pending = null;
210a25f0a04SGreg Roach        }
211a25f0a04SGreg Roach
212a25f0a04SGreg Roach        // No such record exists
213a25f0a04SGreg Roach        if ($gedcom === null && $pending === null) {
214a25f0a04SGreg Roach            return null;
215a25f0a04SGreg Roach        }
216a25f0a04SGreg Roach
217fc3ccce4SGreg Roach        // No such record, but a pending creation exists
218fc3ccce4SGreg Roach        if ($gedcom === null) {
219fc3ccce4SGreg Roach            $gedcom = '';
220fc3ccce4SGreg Roach        }
221fc3ccce4SGreg Roach
222a25f0a04SGreg Roach        // Create the object
2238d0ebef0SGreg Roach        if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedcom . $pending, $match)) {
224a25f0a04SGreg Roach            $xref = $match[1]; // Collation - we may have requested I123 and found i123
225a25f0a04SGreg Roach            $type = $match[2];
226a25f0a04SGreg Roach        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
227a25f0a04SGreg Roach            $xref = $match[1];
228a25f0a04SGreg Roach            $type = $match[1];
229a25f0a04SGreg Roach        } elseif ($gedcom . $pending) {
2307e96c925SGreg Roach            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
231a25f0a04SGreg Roach        } else {
232a25f0a04SGreg Roach            // A record with both pending creation and pending deletion
233a25f0a04SGreg Roach            $type = static::RECORD_TYPE;
234a25f0a04SGreg Roach        }
235a25f0a04SGreg Roach
236a25f0a04SGreg Roach        switch ($type) {
237a25f0a04SGreg Roach            case 'INDI':
23824ec66ceSGreg Roach                $record = new Individual($xref, $gedcom, $pending, $tree);
239a25f0a04SGreg Roach                break;
240a25f0a04SGreg Roach            case 'FAM':
24124ec66ceSGreg Roach                $record = new Family($xref, $gedcom, $pending, $tree);
242a25f0a04SGreg Roach                break;
243a25f0a04SGreg Roach            case 'SOUR':
24424ec66ceSGreg Roach                $record = new Source($xref, $gedcom, $pending, $tree);
245a25f0a04SGreg Roach                break;
246a25f0a04SGreg Roach            case 'OBJE':
24724ec66ceSGreg Roach                $record = new Media($xref, $gedcom, $pending, $tree);
248a25f0a04SGreg Roach                break;
249a25f0a04SGreg Roach            case 'REPO':
25024ec66ceSGreg Roach                $record = new Repository($xref, $gedcom, $pending, $tree);
251a25f0a04SGreg Roach                break;
252a25f0a04SGreg Roach            case 'NOTE':
25324ec66ceSGreg Roach                $record = new Note($xref, $gedcom, $pending, $tree);
254a25f0a04SGreg Roach                break;
255a25f0a04SGreg Roach            default:
25606ef8e02SGreg Roach                $record = new self($xref, $gedcom, $pending, $tree);
257a25f0a04SGreg Roach                break;
258a25f0a04SGreg Roach        }
259a25f0a04SGreg Roach
260a25f0a04SGreg Roach        // Store it in the cache
26124ec66ceSGreg Roach        self::$gedcom_record_cache[$xref][$tree_id] = $record;
262a25f0a04SGreg Roach
263a25f0a04SGreg Roach        return $record;
264a25f0a04SGreg Roach    }
265a25f0a04SGreg Roach
266a25f0a04SGreg Roach    /**
267a25f0a04SGreg Roach     * Fetch data from the database
268a25f0a04SGreg Roach     *
269a25f0a04SGreg Roach     * @param string $xref
270cbc1590aSGreg Roach     * @param int    $tree_id
271a25f0a04SGreg Roach     *
272a25f0a04SGreg Roach     * @return null|string
273a25f0a04SGreg Roach     */
27476f666f4SGreg Roach    protected static function fetchGedcomRecord(string $xref, int $tree_id)
275c1010edaSGreg Roach    {
276a25f0a04SGreg Roach        // We don't know what type of object this is. Try each one in turn.
27764d9078aSGreg Roach        $data = Individual::fetchGedcomRecord($xref, $tree_id);
27885fc8064SGreg Roach        if ($data !== null) {
279a25f0a04SGreg Roach            return $data;
280a25f0a04SGreg Roach        }
28164d9078aSGreg Roach        $data = Family::fetchGedcomRecord($xref, $tree_id);
28285fc8064SGreg Roach        if ($data !== null) {
283a25f0a04SGreg Roach            return $data;
284a25f0a04SGreg Roach        }
28564d9078aSGreg Roach        $data = Source::fetchGedcomRecord($xref, $tree_id);
28685fc8064SGreg Roach        if ($data !== null) {
287a25f0a04SGreg Roach            return $data;
288a25f0a04SGreg Roach        }
28964d9078aSGreg Roach        $data = Repository::fetchGedcomRecord($xref, $tree_id);
29085fc8064SGreg Roach        if ($data !== null) {
291a25f0a04SGreg Roach            return $data;
292a25f0a04SGreg Roach        }
29364d9078aSGreg Roach        $data = Media::fetchGedcomRecord($xref, $tree_id);
29485fc8064SGreg Roach        if ($data !== null) {
295a25f0a04SGreg Roach            return $data;
296a25f0a04SGreg Roach        }
29764d9078aSGreg Roach        $data = Note::fetchGedcomRecord($xref, $tree_id);
29885fc8064SGreg Roach        if ($data !== null) {
299a25f0a04SGreg Roach            return $data;
300a25f0a04SGreg Roach        }
301c1010edaSGreg Roach
302a25f0a04SGreg Roach        // Some other type of record...
303d09b6323SGreg Roach        return DB::table('other')
30485fc8064SGreg Roach            ->where('o_file', '=', $tree_id)
30585fc8064SGreg Roach            ->where('o_id', '=', $xref)
30685fc8064SGreg Roach            ->value('o_gedcom');
307a25f0a04SGreg Roach    }
308a25f0a04SGreg Roach
309a25f0a04SGreg Roach    /**
310a25f0a04SGreg Roach     * Get the XREF for this record
311a25f0a04SGreg Roach     *
312a25f0a04SGreg Roach     * @return string
313a25f0a04SGreg Roach     */
314c0935879SGreg Roach    public function xref(): string
315c1010edaSGreg Roach    {
316a25f0a04SGreg Roach        return $this->xref;
317a25f0a04SGreg Roach    }
318a25f0a04SGreg Roach
319a25f0a04SGreg Roach    /**
320000959d9SGreg Roach     * Get the tree to which this record belongs
321000959d9SGreg Roach     *
322000959d9SGreg Roach     * @return Tree
323000959d9SGreg Roach     */
324f4afa648SGreg Roach    public function tree(): Tree
325c1010edaSGreg Roach    {
326518bbdc1SGreg Roach        return $this->tree;
327000959d9SGreg Roach    }
328000959d9SGreg Roach
329000959d9SGreg Roach    /**
330a25f0a04SGreg Roach     * Application code should access data via Fact objects.
331a25f0a04SGreg Roach     * This function exists to support old code.
332a25f0a04SGreg Roach     *
333a25f0a04SGreg Roach     * @return string
334a25f0a04SGreg Roach     */
3357d0db648SGreg Roach    public function gedcom()
336c1010edaSGreg Roach    {
337b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
338a25f0a04SGreg Roach    }
339a25f0a04SGreg Roach
340a25f0a04SGreg Roach    /**
341a25f0a04SGreg Roach     * Does this record have a pending change?
342a25f0a04SGreg Roach     *
343cbc1590aSGreg Roach     * @return bool
344a25f0a04SGreg Roach     */
3458f53f488SRico Sonntag    public function isPendingAddition(): bool
346c1010edaSGreg Roach    {
347a25f0a04SGreg Roach        return $this->pending !== null;
348a25f0a04SGreg Roach    }
349a25f0a04SGreg Roach
350a25f0a04SGreg Roach    /**
351a25f0a04SGreg Roach     * Does this record have a pending deletion?
352a25f0a04SGreg Roach     *
353cbc1590aSGreg Roach     * @return bool
354a25f0a04SGreg Roach     */
3558f53f488SRico Sonntag    public function isPendingDeletion(): bool
356c1010edaSGreg Roach    {
357a25f0a04SGreg Roach        return $this->pending === '';
358a25f0a04SGreg Roach    }
359a25f0a04SGreg Roach
360a25f0a04SGreg Roach    /**
361225e381fSGreg Roach     * Generate a URL to this record.
362a25f0a04SGreg Roach     *
363a25f0a04SGreg Roach     * @return string
364a25f0a04SGreg Roach     */
3658f53f488SRico Sonntag    public function url(): string
366c1010edaSGreg Roach    {
367225e381fSGreg Roach        return route(static::ROUTE_NAME, [
368c0935879SGreg Roach            'xref' => $this->xref(),
369aa6f03bbSGreg Roach            'ged'  => $this->tree->name(),
370225e381fSGreg Roach        ]);
371a25f0a04SGreg Roach    }
372a25f0a04SGreg Roach
373a25f0a04SGreg Roach    /**
374a25f0a04SGreg Roach     * Work out whether this record can be shown to a user with a given access level
375a25f0a04SGreg Roach     *
376cbc1590aSGreg Roach     * @param int $access_level
377a25f0a04SGreg Roach     *
378cbc1590aSGreg Roach     * @return bool
379a25f0a04SGreg Roach     */
38076f666f4SGreg Roach    private function canShowRecord(int $access_level): bool
381c1010edaSGreg Roach    {
382a25f0a04SGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
383518bbdc1SGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
384a25f0a04SGreg Roach            return true;
385a25f0a04SGreg Roach        }
386a25f0a04SGreg Roach
387a25f0a04SGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
388c0935879SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), 'gedcomid') && $access_level === Auth::accessLevel($this->tree)) {
389a25f0a04SGreg Roach            return true;
390a25f0a04SGreg Roach        }
391a25f0a04SGreg Roach
392a25f0a04SGreg Roach        // Does this record have a RESN?
39320ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
3944b9ff166SGreg Roach            return Auth::PRIV_NONE >= $access_level;
395a25f0a04SGreg Roach        }
39620ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
3974b9ff166SGreg Roach            return Auth::PRIV_USER >= $access_level;
398a25f0a04SGreg Roach        }
39920ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
400a25f0a04SGreg Roach            return true;
401a25f0a04SGreg Roach        }
402a25f0a04SGreg Roach
403a25f0a04SGreg Roach        // Does this record have a default RESN?
404518bbdc1SGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
405c0935879SGreg Roach        if (isset($individual_privacy[$this->xref()])) {
406c0935879SGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
407a25f0a04SGreg Roach        }
408a25f0a04SGreg Roach
409a25f0a04SGreg Roach        // Privacy rules do not apply to admins
4104b9ff166SGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
411a25f0a04SGreg Roach            return true;
412a25f0a04SGreg Roach        }
413a25f0a04SGreg Roach
414a25f0a04SGreg Roach        // Different types of record have different privacy rules
415a25f0a04SGreg Roach        return $this->canShowByType($access_level);
416a25f0a04SGreg Roach    }
417a25f0a04SGreg Roach
418a25f0a04SGreg Roach    /**
419a25f0a04SGreg Roach     * Each object type may have its own special rules, and re-implement this function.
420a25f0a04SGreg Roach     *
421cbc1590aSGreg Roach     * @param int $access_level
422a25f0a04SGreg Roach     *
423cbc1590aSGreg Roach     * @return bool
424a25f0a04SGreg Roach     */
42535584196SGreg Roach    protected function canShowByType(int $access_level): bool
426c1010edaSGreg Roach    {
427518bbdc1SGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
428a25f0a04SGreg Roach
429518bbdc1SGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
430a25f0a04SGreg Roach            // Restriction found
431518bbdc1SGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
432b2ce94c6SRico Sonntag        }
433b2ce94c6SRico Sonntag
434a25f0a04SGreg Roach        // No restriction found - must be public:
435a25f0a04SGreg Roach        return true;
436a25f0a04SGreg Roach    }
437a25f0a04SGreg Roach
438a25f0a04SGreg Roach    /**
439a25f0a04SGreg Roach     * Can the details of this record be shown?
440a25f0a04SGreg Roach     *
441cbc1590aSGreg Roach     * @param int|null $access_level
442a25f0a04SGreg Roach     *
443cbc1590aSGreg Roach     * @return bool
444a25f0a04SGreg Roach     */
44535584196SGreg Roach    public function canShow(int $access_level = null): bool
446c1010edaSGreg Roach    {
4474b9ff166SGreg Roach        if ($access_level === null) {
4484b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
4494b9ff166SGreg Roach        }
4504b9ff166SGreg Roach
451a25f0a04SGreg Roach        // CACHING: this function can take three different parameters,
452a25f0a04SGreg Roach        // and therefore needs three different caches for the result.
453a25f0a04SGreg Roach        switch ($access_level) {
4544b9ff166SGreg Roach            case Auth::PRIV_PRIVATE: // visitor
455a25f0a04SGreg Roach                if ($this->disp_public === null) {
4564b9ff166SGreg Roach                    $this->disp_public = $this->canShowRecord(Auth::PRIV_PRIVATE);
457a25f0a04SGreg Roach                }
458cbc1590aSGreg Roach
459a25f0a04SGreg Roach                return $this->disp_public;
4604b9ff166SGreg Roach            case Auth::PRIV_USER: // member
461a25f0a04SGreg Roach                if ($this->disp_user === null) {
4624b9ff166SGreg Roach                    $this->disp_user = $this->canShowRecord(Auth::PRIV_USER);
463a25f0a04SGreg Roach                }
464cbc1590aSGreg Roach
465a25f0a04SGreg Roach                return $this->disp_user;
4664b9ff166SGreg Roach            case Auth::PRIV_NONE: // admin
467a25f0a04SGreg Roach                if ($this->disp_none === null) {
4684b9ff166SGreg Roach                    $this->disp_none = $this->canShowRecord(Auth::PRIV_NONE);
469a25f0a04SGreg Roach                }
470cbc1590aSGreg Roach
471a25f0a04SGreg Roach                return $this->disp_none;
4724b9ff166SGreg Roach            case Auth::PRIV_HIDE: // hidden from admins
473a25f0a04SGreg Roach                // We use this value to bypass privacy checks. For example,
474a25f0a04SGreg Roach                // when downloading data or when calculating privacy itself.
475a25f0a04SGreg Roach                return true;
476a25f0a04SGreg Roach            default:
477a25f0a04SGreg Roach                // Should never get here.
478a25f0a04SGreg Roach                return false;
479a25f0a04SGreg Roach        }
480a25f0a04SGreg Roach    }
481a25f0a04SGreg Roach
482a25f0a04SGreg Roach    /**
483a25f0a04SGreg Roach     * Can the name of this record be shown?
484a25f0a04SGreg Roach     *
485cbc1590aSGreg Roach     * @param int|null $access_level
486a25f0a04SGreg Roach     *
487cbc1590aSGreg Roach     * @return bool
488a25f0a04SGreg Roach     */
48976f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
490c1010edaSGreg Roach    {
4914b9ff166SGreg Roach        if ($access_level === null) {
4924b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
4934b9ff166SGreg Roach        }
4944b9ff166SGreg Roach
495a25f0a04SGreg Roach        return $this->canShow($access_level);
496a25f0a04SGreg Roach    }
497a25f0a04SGreg Roach
498a25f0a04SGreg Roach    /**
499a25f0a04SGreg Roach     * Can we edit this record?
500a25f0a04SGreg Roach     *
501cbc1590aSGreg Roach     * @return bool
502a25f0a04SGreg Roach     */
5038f53f488SRico Sonntag    public function canEdit(): bool
504c1010edaSGreg Roach    {
5054b9ff166SGreg Roach        return Auth::isManager($this->tree) || Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
506a25f0a04SGreg Roach    }
507a25f0a04SGreg Roach
508a25f0a04SGreg Roach    /**
509a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
510a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
511a25f0a04SGreg Roach     *
512cbc1590aSGreg Roach     * @param int $access_level
513a25f0a04SGreg Roach     *
514a25f0a04SGreg Roach     * @return string
515a25f0a04SGreg Roach     */
51676f666f4SGreg Roach    public function privatizeGedcom(int $access_level)
517c1010edaSGreg Roach    {
5184b9ff166SGreg Roach        if ($access_level == Auth::PRIV_HIDE) {
519a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
520a25f0a04SGreg Roach            return $this->gedcom;
521b2ce94c6SRico Sonntag        }
522b2ce94c6SRico Sonntag
523b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
524a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
525a25f0a04SGreg Roach
526a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
52765e02381SGreg Roach            [$gedrec] = explode("\n", $this->gedcom, 2);
528a25f0a04SGreg Roach
529a25f0a04SGreg Roach            // Check each of the facts for access
5308d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
531138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
532a25f0a04SGreg Roach            }
533cbc1590aSGreg Roach
534a25f0a04SGreg Roach            return $gedrec;
535b2ce94c6SRico Sonntag        }
536b2ce94c6SRico Sonntag
537a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
538a25f0a04SGreg Roach        // limited data, such as links to other records.
539a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
540a25f0a04SGreg Roach    }
541a25f0a04SGreg Roach
542a25f0a04SGreg Roach    /**
543a25f0a04SGreg Roach     * Generate a private version of this record
544a25f0a04SGreg Roach     *
545cbc1590aSGreg Roach     * @param int $access_level
546a25f0a04SGreg Roach     *
547a25f0a04SGreg Roach     * @return string
548a25f0a04SGreg Roach     */
54976f666f4SGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
550c1010edaSGreg Roach    {
551a25f0a04SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
552a25f0a04SGreg Roach    }
553a25f0a04SGreg Roach
554a25f0a04SGreg Roach    /**
555a25f0a04SGreg Roach     * Convert a name record into sortable and full/display versions. This default
556a25f0a04SGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
557a25f0a04SGreg Roach     *
558a25f0a04SGreg Roach     * @param string $type
559a25f0a04SGreg Roach     * @param string $value
560a25f0a04SGreg Roach     * @param string $gedcom
5617e96c925SGreg Roach     *
5627e96c925SGreg Roach     * @return void
563a25f0a04SGreg Roach     */
56476f666f4SGreg Roach    protected function addName(string $type, string $value, string $gedcom)
565c1010edaSGreg Roach    {
566bdb3725aSGreg Roach        $this->getAllNames[] = [
567a25f0a04SGreg Roach            'type'   => $type,
5687e96c925SGreg Roach            'sort'   => preg_replace_callback('/([0-9]+)/', function (array $matches): string {
5698d68cabeSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
5708d68cabeSGreg Roach            }, $value),
571c1010edaSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
572c1010edaSGreg Roach            // This is used for display
573c1010edaSGreg Roach            'fullNN' => $value,
574c1010edaSGreg Roach            // This goes into the database
57513abd6f3SGreg Roach        ];
576a25f0a04SGreg Roach    }
577a25f0a04SGreg Roach
578a25f0a04SGreg Roach    /**
579a25f0a04SGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
580a25f0a04SGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
581a25f0a04SGreg Roach     * Parameters: the level 1 fact containing the name.
582a25f0a04SGreg Roach     * Return value: an array of name structures, each containing
583a25f0a04SGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
584a25f0a04SGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
585a25f0a04SGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
586a25f0a04SGreg Roach     *
587cbc1590aSGreg Roach     * @param int    $level
588a25f0a04SGreg Roach     * @param string $fact_type
589a25f0a04SGreg Roach     * @param Fact[] $facts
5907e96c925SGreg Roach     *
5917e96c925SGreg Roach     * @return void
592a25f0a04SGreg Roach     */
59376f666f4SGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, array $facts)
594c1010edaSGreg Roach    {
595a25f0a04SGreg Roach        $sublevel    = $level + 1;
596a25f0a04SGreg Roach        $subsublevel = $sublevel + 1;
597a25f0a04SGreg Roach        foreach ($facts as $fact) {
598138ca96cSGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
599a25f0a04SGreg Roach                foreach ($matches as $match) {
600a25f0a04SGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
601a25f0a04SGreg Roach                    if ($match[1] == 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
602138ca96cSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
603a25f0a04SGreg Roach                    } else {
604138ca96cSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
605a25f0a04SGreg Roach                    }
606a25f0a04SGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
607a25f0a04SGreg Roach                        foreach ($submatches as $submatch) {
608a25f0a04SGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
609a25f0a04SGreg Roach                        }
610a25f0a04SGreg Roach                    }
611a25f0a04SGreg Roach                }
612a25f0a04SGreg Roach            }
613a25f0a04SGreg Roach        }
614a25f0a04SGreg Roach    }
615a25f0a04SGreg Roach
616a25f0a04SGreg Roach    /**
617a25f0a04SGreg Roach     * Default for "other" object types
618c7ff4153SGreg Roach     *
619c7ff4153SGreg Roach     * @return void
620a25f0a04SGreg Roach     */
621c1010edaSGreg Roach    public function extractNames()
622c1010edaSGreg Roach    {
62376f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
624a25f0a04SGreg Roach    }
625a25f0a04SGreg Roach
626a25f0a04SGreg Roach    /**
627a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
628a25f0a04SGreg Roach     *
629a25f0a04SGreg Roach     * @return string[][]
630a25f0a04SGreg Roach     */
6318f53f488SRico Sonntag    public function getAllNames(): array
632c1010edaSGreg Roach    {
633bdb3725aSGreg Roach        if ($this->getAllNames === null) {
634bdb3725aSGreg Roach            $this->getAllNames = [];
635a25f0a04SGreg Roach            if ($this->canShowName()) {
636a25f0a04SGreg Roach                // Ask the record to extract its names
637a25f0a04SGreg Roach                $this->extractNames();
638a25f0a04SGreg Roach                // No name found? Use a fallback.
639bdb3725aSGreg Roach                if (!$this->getAllNames) {
640db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
641a25f0a04SGreg Roach                }
642a25f0a04SGreg Roach            } else {
643db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
644a25f0a04SGreg Roach            }
645a25f0a04SGreg Roach        }
646cbc1590aSGreg Roach
647bdb3725aSGreg Roach        return $this->getAllNames;
648a25f0a04SGreg Roach    }
649a25f0a04SGreg Roach
650a25f0a04SGreg Roach    /**
651a25f0a04SGreg Roach     * If this object has no name, what do we call it?
652a25f0a04SGreg Roach     *
653a25f0a04SGreg Roach     * @return string
654a25f0a04SGreg Roach     */
6558f53f488SRico Sonntag    public function getFallBackName(): string
656c1010edaSGreg Roach    {
657c0935879SGreg Roach        return e($this->xref());
658a25f0a04SGreg Roach    }
659a25f0a04SGreg Roach
660a25f0a04SGreg Roach    /**
661a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
662a25f0a04SGreg Roach     *
663cbc1590aSGreg Roach     * @return int
664a25f0a04SGreg Roach     */
6658f53f488SRico Sonntag    public function getPrimaryName(): int
666c1010edaSGreg Roach    {
667a25f0a04SGreg Roach        static $language_script;
668a25f0a04SGreg Roach
669a25f0a04SGreg Roach        if ($language_script === null) {
670a25f0a04SGreg Roach            $language_script = I18N::languageScript(WT_LOCALE);
671a25f0a04SGreg Roach        }
672a25f0a04SGreg Roach
673bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
674a25f0a04SGreg Roach            // Generally, the first name is the primary one....
675bdb3725aSGreg Roach            $this->getPrimaryName = 0;
676a25f0a04SGreg Roach            // ...except when the language/name use different character sets
677a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
67869546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
679bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
680a25f0a04SGreg Roach                    break;
681a25f0a04SGreg Roach                }
682a25f0a04SGreg Roach            }
683a25f0a04SGreg Roach        }
684a25f0a04SGreg Roach
685bdb3725aSGreg Roach        return $this->getPrimaryName;
686a25f0a04SGreg Roach    }
687a25f0a04SGreg Roach
688a25f0a04SGreg Roach    /**
689a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
690a25f0a04SGreg Roach     *
691cbc1590aSGreg Roach     * @return int
692a25f0a04SGreg Roach     */
6938f53f488SRico Sonntag    public function getSecondaryName(): int
694c1010edaSGreg Roach    {
6958f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
696a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
697bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
698a25f0a04SGreg Roach            // ....except when there are names with different character sets
699a25f0a04SGreg Roach            $all_names = $this->getAllNames();
700a25f0a04SGreg Roach            if (count($all_names) > 1) {
701a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
702a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
703a25f0a04SGreg Roach                    if ($n != $this->getPrimaryName() && $name['type'] != '_MARNM' && I18N::textScript($name['sort']) != $primary_script) {
704bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
705a25f0a04SGreg Roach                        break;
706a25f0a04SGreg Roach                    }
707a25f0a04SGreg Roach                }
708a25f0a04SGreg Roach            }
709a25f0a04SGreg Roach        }
710cbc1590aSGreg Roach
711bdb3725aSGreg Roach        return $this->getSecondaryName;
712a25f0a04SGreg Roach    }
713a25f0a04SGreg Roach
714a25f0a04SGreg Roach    /**
715a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
716a25f0a04SGreg Roach     *
71776f666f4SGreg Roach     * @param int|null $n
7187e96c925SGreg Roach     *
7197e96c925SGreg Roach     * @return void
720a25f0a04SGreg Roach     */
721251a9de7SGreg Roach    public function setPrimaryName(int $n = null)
722c1010edaSGreg Roach    {
723bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
724bdb3725aSGreg Roach        $this->getSecondaryName = null;
725a25f0a04SGreg Roach    }
726a25f0a04SGreg Roach
727a25f0a04SGreg Roach    /**
728a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
729a25f0a04SGreg Roach     *
730a25f0a04SGreg Roach     * @return string
731a25f0a04SGreg Roach     */
732c1010edaSGreg Roach    public function __toString()
733c1010edaSGreg Roach    {
73472cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
735a25f0a04SGreg Roach    }
736a25f0a04SGreg Roach
737a25f0a04SGreg Roach    /**
738a25f0a04SGreg Roach     * Static helper function to sort an array of objects by name
739a25f0a04SGreg Roach     * Records whose names cannot be displayed are sorted at the end.
740a25f0a04SGreg Roach     *
741a25f0a04SGreg Roach     * @param GedcomRecord $x
742a25f0a04SGreg Roach     * @param GedcomRecord $y
743a25f0a04SGreg Roach     *
744cbc1590aSGreg Roach     * @return int
745a25f0a04SGreg Roach     */
746c1010edaSGreg Roach    public static function compare(GedcomRecord $x, GedcomRecord $y)
747c1010edaSGreg Roach    {
748a25f0a04SGreg Roach        if ($x->canShowName()) {
749a25f0a04SGreg Roach            if ($y->canShowName()) {
750a25f0a04SGreg Roach                return I18N::strcasecmp($x->getSortName(), $y->getSortName());
751b2ce94c6SRico Sonntag            }
752b2ce94c6SRico Sonntag
753a25f0a04SGreg Roach            return -1; // only $y is private
754a25f0a04SGreg Roach        }
755b2ce94c6SRico Sonntag
756a25f0a04SGreg Roach        if ($y->canShowName()) {
757a25f0a04SGreg Roach            return 1; // only $x is private
758b2ce94c6SRico Sonntag        }
759b2ce94c6SRico Sonntag
760a25f0a04SGreg Roach        return 0; // both $x and $y private
761a25f0a04SGreg Roach    }
762a25f0a04SGreg Roach
763a25f0a04SGreg Roach    /**
764a25f0a04SGreg Roach     * Get variants of the name
765a25f0a04SGreg Roach     *
766a25f0a04SGreg Roach     * @return string
767a25f0a04SGreg Roach     */
768c1010edaSGreg Roach    public function getFullName()
769c1010edaSGreg Roach    {
770a25f0a04SGreg Roach        if ($this->canShowName()) {
771a25f0a04SGreg Roach            $tmp = $this->getAllNames();
772cbc1590aSGreg Roach
773a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
774a25f0a04SGreg Roach        }
775b2ce94c6SRico Sonntag
776b2ce94c6SRico Sonntag        return I18N::translate('Private');
777a25f0a04SGreg Roach    }
778a25f0a04SGreg Roach
779a25f0a04SGreg Roach    /**
780a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
781a25f0a04SGreg Roach     *
782a25f0a04SGreg Roach     * @return string
783a25f0a04SGreg Roach     */
7848f53f488SRico Sonntag    public function getSortName(): string
785c1010edaSGreg Roach    {
786a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
787a25f0a04SGreg Roach        $tmp = $this->getAllNames();
788cbc1590aSGreg Roach
789a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
790a25f0a04SGreg Roach    }
791a25f0a04SGreg Roach
792a25f0a04SGreg Roach    /**
793a25f0a04SGreg Roach     * Get the full name in an alternative character set
794a25f0a04SGreg Roach     *
795a25f0a04SGreg Roach     * @return null|string
796a25f0a04SGreg Roach     */
797c1010edaSGreg Roach    public function getAddName()
798c1010edaSGreg Roach    {
799a25f0a04SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() != $this->getSecondaryName()) {
800a25f0a04SGreg Roach            $all_names = $this->getAllNames();
801cbc1590aSGreg Roach
802a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
803a25f0a04SGreg Roach        }
804b2ce94c6SRico Sonntag
805b2ce94c6SRico Sonntag        return null;
806a25f0a04SGreg Roach    }
807a25f0a04SGreg Roach
808a25f0a04SGreg Roach    /**
809a25f0a04SGreg Roach     * Format this object for display in a list
810a25f0a04SGreg Roach     *
811a25f0a04SGreg Roach     * @return string
812a25f0a04SGreg Roach     */
8138f53f488SRico Sonntag    public function formatList(): string
814c1010edaSGreg Roach    {
815b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
816b165e17cSGreg Roach        $html .= '<b>' . $this->getFullName() . '</b>';
817a25f0a04SGreg Roach        $html .= $this->formatListDetails();
818b165e17cSGreg Roach        $html .= '</a>';
819cbc1590aSGreg Roach
820a25f0a04SGreg Roach        return $html;
821a25f0a04SGreg Roach    }
822a25f0a04SGreg Roach
823a25f0a04SGreg Roach    /**
824a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
825a25f0a04SGreg Roach     * identifying characteristics of this record.
826a25f0a04SGreg Roach     *
827a25f0a04SGreg Roach     * @return string
828a25f0a04SGreg Roach     */
8298f53f488SRico Sonntag    public function formatListDetails(): string
830c1010edaSGreg Roach    {
831a25f0a04SGreg Roach        return '';
832a25f0a04SGreg Roach    }
833a25f0a04SGreg Roach
834a25f0a04SGreg Roach    /**
835a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
836a25f0a04SGreg Roach     *
8378d0ebef0SGreg Roach     * @param string[] $facts
838cbc1590aSGreg Roach     * @param int      $style
839a25f0a04SGreg Roach     *
840a25f0a04SGreg Roach     * @return string
841a25f0a04SGreg Roach     */
8428d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
843c1010edaSGreg Roach    {
84430158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
845a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
8462decada7SGreg Roach            if ($event->date()->isOK() && !$event->place()->isEmpty()) {
847d93f11b5SGreg Roach                $joiner = ' — ';
848d93f11b5SGreg Roach            } else {
849d93f11b5SGreg Roach                $joiner = '';
850d93f11b5SGreg Roach            }
8512decada7SGreg Roach            if ($event->date()->isOK() || !$event->place()->isEmpty()) {
852a25f0a04SGreg Roach                switch ($style) {
853a25f0a04SGreg Roach                    case 1:
8547b7d8067SGreg Roach                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
855a25f0a04SGreg Roach                    case 2:
8567b7d8067SGreg Roach                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
857a25f0a04SGreg Roach                }
858a25f0a04SGreg Roach            }
859a25f0a04SGreg Roach        }
860cbc1590aSGreg Roach
861a25f0a04SGreg Roach        return '';
862a25f0a04SGreg Roach    }
863a25f0a04SGreg Roach
864a25f0a04SGreg Roach    /**
865a25f0a04SGreg Roach     * Find individuals linked to this record.
866a25f0a04SGreg Roach     *
867a25f0a04SGreg Roach     * @param string $link
868a25f0a04SGreg Roach     *
869360dbd2cSGreg Roach     * @return Individual[]
870a25f0a04SGreg Roach     */
87176f666f4SGreg Roach    public function linkedIndividuals(string $link): array
872c1010edaSGreg Roach    {
873ba1c12e8SGreg Roach        $rows = DB::table('individuals')
874ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
875ba1c12e8SGreg Roach                $join->on('l_file', '=', 'i_file')->on('l_from', '=', 'i_id');
876ba1c12e8SGreg Roach            })
877ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
878ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
879ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
880ba1c12e8SGreg Roach            ->select(['i_id AS xref', 'i_gedcom AS gedcom'])
881ba1c12e8SGreg Roach            ->get();
882a25f0a04SGreg Roach
88313abd6f3SGreg Roach        $list = [];
884a25f0a04SGreg Roach        foreach ($rows as $row) {
88524ec66ceSGreg Roach            $record = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
886a25f0a04SGreg Roach            if ($record->canShowName()) {
887a25f0a04SGreg Roach                $list[] = $record;
888a25f0a04SGreg Roach            }
889a25f0a04SGreg Roach        }
890cbc1590aSGreg Roach
891a25f0a04SGreg Roach        return $list;
892a25f0a04SGreg Roach    }
893a25f0a04SGreg Roach
894a25f0a04SGreg Roach    /**
895a25f0a04SGreg Roach     * Find families linked to this record.
896a25f0a04SGreg Roach     *
897a25f0a04SGreg Roach     * @param string $link
898a25f0a04SGreg Roach     *
899360dbd2cSGreg Roach     * @return Family[]
900a25f0a04SGreg Roach     */
90176f666f4SGreg Roach    public function linkedFamilies(string $link): array
902c1010edaSGreg Roach    {
903ba1c12e8SGreg Roach        $rows = DB::table('families')
904ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
905ba1c12e8SGreg Roach                $join->on('l_file', '=', 'f_file')->on('l_from', '=', 'f_id');
906ba1c12e8SGreg Roach            })
907ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
908ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
909ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
910ba1c12e8SGreg Roach            ->select(['f_id AS xref', 'f_gedcom AS gedcom'])
911ba1c12e8SGreg Roach            ->get();
912a25f0a04SGreg Roach
91313abd6f3SGreg Roach        $list = [];
914a25f0a04SGreg Roach        foreach ($rows as $row) {
91524ec66ceSGreg Roach            $record = Family::getInstance($row->xref, $this->tree, $row->gedcom);
916a25f0a04SGreg Roach            if ($record->canShowName()) {
917a25f0a04SGreg Roach                $list[] = $record;
918a25f0a04SGreg Roach            }
919a25f0a04SGreg Roach        }
920cbc1590aSGreg Roach
921a25f0a04SGreg Roach        return $list;
922a25f0a04SGreg Roach    }
923a25f0a04SGreg Roach
924a25f0a04SGreg Roach    /**
925a25f0a04SGreg Roach     * Find sources linked to this record.
926a25f0a04SGreg Roach     *
927a25f0a04SGreg Roach     * @param string $link
928a25f0a04SGreg Roach     *
929360dbd2cSGreg Roach     * @return Source[]
930a25f0a04SGreg Roach     */
93176f666f4SGreg Roach    public function linkedSources(string $link): array
932c1010edaSGreg Roach    {
933ba1c12e8SGreg Roach        $rows = DB::table('sources')
934ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
935ba1c12e8SGreg Roach                $join->on('l_file', '=', 's_file')->on('l_from', '=', 's_id');
936ba1c12e8SGreg Roach            })
937ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
938ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
939ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
940ba1c12e8SGreg Roach            ->select(['s_id AS xref', 's_gedcom AS gedcom'])
941ba1c12e8SGreg Roach            ->get();
942a25f0a04SGreg Roach
94313abd6f3SGreg Roach        $list = [];
944a25f0a04SGreg Roach        foreach ($rows as $row) {
94524ec66ceSGreg Roach            $record = Source::getInstance($row->xref, $this->tree, $row->gedcom);
946a25f0a04SGreg Roach            if ($record->canShowName()) {
947a25f0a04SGreg Roach                $list[] = $record;
948a25f0a04SGreg Roach            }
949a25f0a04SGreg Roach        }
950cbc1590aSGreg Roach
951a25f0a04SGreg Roach        return $list;
952a25f0a04SGreg Roach    }
953a25f0a04SGreg Roach
954a25f0a04SGreg Roach    /**
955a25f0a04SGreg Roach     * Find media objects linked to this record.
956a25f0a04SGreg Roach     *
957a25f0a04SGreg Roach     * @param string $link
958a25f0a04SGreg Roach     *
959360dbd2cSGreg Roach     * @return Media[]
960a25f0a04SGreg Roach     */
96176f666f4SGreg Roach    public function linkedMedia(string $link): array
962c1010edaSGreg Roach    {
963ba1c12e8SGreg Roach        $rows = DB::table('media')
964ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
965ba1c12e8SGreg Roach                $join->on('l_file', '=', 'm_file')->on('l_from', '=', 'm_id');
966ba1c12e8SGreg Roach            })
967ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
968ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
969ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
970ba1c12e8SGreg Roach            ->select(['m_id AS xref', 'm_gedcom AS gedcom'])
971ba1c12e8SGreg Roach            ->get();
972a25f0a04SGreg Roach
97313abd6f3SGreg Roach        $list = [];
974a25f0a04SGreg Roach        foreach ($rows as $row) {
97524ec66ceSGreg Roach            $record = Media::getInstance($row->xref, $this->tree, $row->gedcom);
976a25f0a04SGreg Roach            if ($record->canShowName()) {
977a25f0a04SGreg Roach                $list[] = $record;
978a25f0a04SGreg Roach            }
979a25f0a04SGreg Roach        }
980cbc1590aSGreg Roach
981a25f0a04SGreg Roach        return $list;
982a25f0a04SGreg Roach    }
983a25f0a04SGreg Roach
984a25f0a04SGreg Roach    /**
985a25f0a04SGreg Roach     * Find notes linked to this record.
986a25f0a04SGreg Roach     *
987a25f0a04SGreg Roach     * @param string $link
988a25f0a04SGreg Roach     *
989a25f0a04SGreg Roach     * @return Note[]
990a25f0a04SGreg Roach     */
99176f666f4SGreg Roach    public function linkedNotes(string $link): array
992c1010edaSGreg Roach    {
993ba1c12e8SGreg Roach        $rows = DB::table('other')
994ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
995ba1c12e8SGreg Roach                $join->on('l_file', '=', 'o_file')->on('l_from', '=', 'o_id');
996ba1c12e8SGreg Roach            })
997ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
998ba1c12e8SGreg Roach            ->where('o_type', '=', 'NOTE')
999ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
1000ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
1001ba1c12e8SGreg Roach            ->select(['o_id AS xref', 'o_gedcom AS gedcom'])
1002ba1c12e8SGreg Roach            ->get();
1003a25f0a04SGreg Roach
100413abd6f3SGreg Roach        $list = [];
1005a25f0a04SGreg Roach        foreach ($rows as $row) {
100624ec66ceSGreg Roach            $record = Note::getInstance($row->xref, $this->tree, $row->gedcom);
1007a25f0a04SGreg Roach            if ($record->canShowName()) {
1008a25f0a04SGreg Roach                $list[] = $record;
1009a25f0a04SGreg Roach            }
1010a25f0a04SGreg Roach        }
1011cbc1590aSGreg Roach
1012a25f0a04SGreg Roach        return $list;
1013a25f0a04SGreg Roach    }
1014a25f0a04SGreg Roach
1015a25f0a04SGreg Roach    /**
1016a25f0a04SGreg Roach     * Find repositories linked to this record.
1017a25f0a04SGreg Roach     *
1018a25f0a04SGreg Roach     * @param string $link
1019a25f0a04SGreg Roach     *
1020360dbd2cSGreg Roach     * @return Repository[]
1021a25f0a04SGreg Roach     */
102276f666f4SGreg Roach    public function linkedRepositories(string $link): array
1023c1010edaSGreg Roach    {
1024ba1c12e8SGreg Roach        $rows = DB::table('other')
1025ba1c12e8SGreg Roach            ->join('link', function (JoinClause $join): void {
1026ba1c12e8SGreg Roach                $join->on('l_file', '=', 'o_file')->on('l_from', '=', 'o_id');
1027ba1c12e8SGreg Roach            })
1028ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
1029ba1c12e8SGreg Roach            ->where('o_type', '=', 'REPO')
1030ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
1031ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
1032ba1c12e8SGreg Roach            ->select(['o_id AS xref', 'o_gedcom AS gedcom'])
1033ba1c12e8SGreg Roach            ->get();
1034a25f0a04SGreg Roach
103513abd6f3SGreg Roach        $list = [];
1036a25f0a04SGreg Roach        foreach ($rows as $row) {
103724ec66ceSGreg Roach            $record = Repository::getInstance($row->xref, $this->tree, $row->gedcom);
1038a25f0a04SGreg Roach            if ($record->canShowName()) {
1039a25f0a04SGreg Roach                $list[] = $record;
1040a25f0a04SGreg Roach            }
1041a25f0a04SGreg Roach        }
1042cbc1590aSGreg Roach
1043a25f0a04SGreg Roach        return $list;
1044a25f0a04SGreg Roach    }
1045a25f0a04SGreg Roach
1046a25f0a04SGreg Roach    /**
1047a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
1048a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
1049a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
1050a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
1051a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
1052a25f0a04SGreg Roach     *
10538d0ebef0SGreg Roach     * @param string[] $events
1054a25f0a04SGreg Roach     *
1055a25f0a04SGreg Roach     * @return Date[]
1056a25f0a04SGreg Roach     */
10578d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
1058c1010edaSGreg Roach    {
105913abd6f3SGreg Roach        $dates = [];
10608d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
10612decada7SGreg Roach            if ($event->date()->isOK()) {
10622decada7SGreg Roach                $dates[] = $event->date();
1063a25f0a04SGreg Roach            }
1064a25f0a04SGreg Roach        }
1065a25f0a04SGreg Roach
1066a25f0a04SGreg Roach        return $dates;
1067a25f0a04SGreg Roach    }
1068a25f0a04SGreg Roach
1069a25f0a04SGreg Roach    /**
1070a25f0a04SGreg Roach     * Get all the places for a particular type of event
1071a25f0a04SGreg Roach     *
10728d0ebef0SGreg Roach     * @param string[] $events
1073a25f0a04SGreg Roach     *
10744080d558SGreg Roach     * @return Place[]
1075a25f0a04SGreg Roach     */
10768d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
1077c1010edaSGreg Roach    {
107813abd6f3SGreg Roach        $places = [];
10798d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
1080138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
1081a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
108216d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
1083a25f0a04SGreg Roach                }
1084a25f0a04SGreg Roach            }
1085a25f0a04SGreg Roach        }
1086a25f0a04SGreg Roach
1087a25f0a04SGreg Roach        return $places;
1088a25f0a04SGreg Roach    }
1089a25f0a04SGreg Roach
1090a25f0a04SGreg Roach    /**
1091a25f0a04SGreg Roach     * Get the first (i.e. prefered) Fact for the given fact type
1092a25f0a04SGreg Roach     *
1093a25f0a04SGreg Roach     * @param string $tag
1094a25f0a04SGreg Roach     *
1095a25f0a04SGreg Roach     * @return Fact|null
1096a25f0a04SGreg Roach     */
109776f666f4SGreg Roach    public function getFirstFact(string $tag)
1098c1010edaSGreg Roach    {
109930158ae7SGreg Roach        foreach ($this->facts() as $fact) {
1100a25f0a04SGreg Roach            if ($fact->getTag() === $tag) {
1101a25f0a04SGreg Roach                return $fact;
1102a25f0a04SGreg Roach            }
1103a25f0a04SGreg Roach        }
1104a25f0a04SGreg Roach
1105a25f0a04SGreg Roach        return null;
1106a25f0a04SGreg Roach    }
1107a25f0a04SGreg Roach
1108a25f0a04SGreg Roach    /**
1109a25f0a04SGreg Roach     * The facts and events for this record.
1110a25f0a04SGreg Roach     *
11118d0ebef0SGreg Roach     * @param string[] $filter
1112cbc1590aSGreg Roach     * @param bool     $sort
1113cbc1590aSGreg Roach     * @param int|null $access_level
1114cbc1590aSGreg Roach     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1115a25f0a04SGreg Roach     *
1116a25f0a04SGreg Roach     * @return Fact[]
1117a25f0a04SGreg Roach     */
11188d0ebef0SGreg Roach    public function facts(array $filter = [], bool $sort = false, int $access_level = null, bool $override = false): array
1119c1010edaSGreg Roach    {
11204b9ff166SGreg Roach        if ($access_level === null) {
11214b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
11224b9ff166SGreg Roach        }
11234b9ff166SGreg Roach
112413abd6f3SGreg Roach        $facts = [];
1125a25f0a04SGreg Roach        if ($this->canShow($access_level) || $override) {
1126a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
11278d0ebef0SGreg Roach                if (($filter === [] || in_array($fact->getTag(), $filter)) && $fact->canShow($access_level)) {
1128a25f0a04SGreg Roach                    $facts[] = $fact;
1129a25f0a04SGreg Roach                }
1130a25f0a04SGreg Roach            }
1131a25f0a04SGreg Roach        }
1132d17d7b9eSGreg Roach
1133a25f0a04SGreg Roach        if ($sort) {
11343d7a8a4cSGreg Roach            Functions::sortFacts($facts);
1135a25f0a04SGreg Roach        }
1136cbc1590aSGreg Roach
1137a25f0a04SGreg Roach        return $facts;
1138a25f0a04SGreg Roach    }
1139a25f0a04SGreg Roach
1140a25f0a04SGreg Roach    /**
1141a25f0a04SGreg Roach     * Get the last-change timestamp for this record, either as a formatted string
1142a25f0a04SGreg Roach     * (for display) or as a unix timestamp (for sorting)
1143a25f0a04SGreg Roach     *
1144cbc1590aSGreg Roach     * @param bool $sorting
1145a25f0a04SGreg Roach     *
1146589feda3SGreg Roach     * @return string|int
1147a25f0a04SGreg Roach     */
114876f666f4SGreg Roach    public function lastChangeTimestamp(bool $sorting = false)
1149c1010edaSGreg Roach    {
1150a25f0a04SGreg Roach        $chan = $this->getFirstFact('CHAN');
1151a25f0a04SGreg Roach
1152a25f0a04SGreg Roach        if ($chan) {
1153a25f0a04SGreg Roach            // The record does have a CHAN event
11542decada7SGreg Roach            $d = $chan->date()->minimumDate();
1155138ca96cSGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1156a25f0a04SGreg Roach                $t = mktime((int) $match[1], (int) $match[2], (int) $match[3], (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1157138ca96cSGreg Roach            } elseif (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
1158a25f0a04SGreg Roach                $t = mktime((int) $match[1], (int) $match[2], 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1159a25f0a04SGreg Roach            } else {
1160a25f0a04SGreg Roach                $t = mktime(0, 0, 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1161a25f0a04SGreg Roach            }
1162a25f0a04SGreg Roach            if ($sorting) {
1163a25f0a04SGreg Roach                return $t;
1164b2ce94c6SRico Sonntag            }
1165b2ce94c6SRico Sonntag
11663d7a8a4cSGreg Roach            return strip_tags(FunctionsDate::formatTimestamp($t));
1167a25f0a04SGreg Roach        }
1168b2ce94c6SRico Sonntag
1169a25f0a04SGreg Roach        // The record does not have a CHAN event
1170a25f0a04SGreg Roach        if ($sorting) {
1171a25f0a04SGreg Roach            return '0';
1172b2ce94c6SRico Sonntag        }
1173b2ce94c6SRico Sonntag
117466b90994SGreg Roach        return '';
1175a25f0a04SGreg Roach    }
1176a25f0a04SGreg Roach
1177a25f0a04SGreg Roach    /**
1178a25f0a04SGreg Roach     * Get the last-change user for this record
1179a25f0a04SGreg Roach     *
1180a25f0a04SGreg Roach     * @return string
1181a25f0a04SGreg Roach     */
1182c1010edaSGreg Roach    public function lastChangeUser()
1183c1010edaSGreg Roach    {
1184a25f0a04SGreg Roach        $chan = $this->getFirstFact('CHAN');
1185a25f0a04SGreg Roach
1186a25f0a04SGreg Roach        if ($chan === null) {
1187a25f0a04SGreg Roach            return I18N::translate('Unknown');
1188b2ce94c6SRico Sonntag        }
1189b2ce94c6SRico Sonntag
11903425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
1191baacc364SGreg Roach        if ($chan_user === '') {
1192a25f0a04SGreg Roach            return I18N::translate('Unknown');
1193b2ce94c6SRico Sonntag        }
1194b2ce94c6SRico Sonntag
1195a25f0a04SGreg Roach        return $chan_user;
1196a25f0a04SGreg Roach    }
1197a25f0a04SGreg Roach
1198a25f0a04SGreg Roach    /**
1199a25f0a04SGreg Roach     * Add a new fact to this record
1200a25f0a04SGreg Roach     *
1201a25f0a04SGreg Roach     * @param string $gedcom
1202cbc1590aSGreg Roach     * @param bool   $update_chan
12037e96c925SGreg Roach     *
12047e96c925SGreg Roach     * @return void
1205a25f0a04SGreg Roach     */
120676f666f4SGreg Roach    public function createFact(string $gedcom, bool $update_chan)
1207c1010edaSGreg Roach    {
1208fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
1209a25f0a04SGreg Roach    }
1210a25f0a04SGreg Roach
1211a25f0a04SGreg Roach    /**
1212a25f0a04SGreg Roach     * Delete a fact from this record
1213a25f0a04SGreg Roach     *
1214a25f0a04SGreg Roach     * @param string $fact_id
1215cbc1590aSGreg Roach     * @param bool   $update_chan
12167e96c925SGreg Roach     *
12177e96c925SGreg Roach     * @return void
1218a25f0a04SGreg Roach     */
121976f666f4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan)
1220c1010edaSGreg Roach    {
1221db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
1222a25f0a04SGreg Roach    }
1223a25f0a04SGreg Roach
1224a25f0a04SGreg Roach    /**
1225a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
1226a25f0a04SGreg Roach     *
1227a25f0a04SGreg Roach     * @param string $fact_id
1228a25f0a04SGreg Roach     * @param string $gedcom
1229cbc1590aSGreg Roach     * @param bool   $update_chan
1230a25f0a04SGreg Roach     *
12317e96c925SGreg Roach     * @return void
12327e96c925SGreg Roach     * @throws Exception
1233a25f0a04SGreg Roach     */
123476f666f4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan)
1235c1010edaSGreg Roach    {
1236a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1237a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1238a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1239a25f0a04SGreg Roach
1240a25f0a04SGreg Roach        if ($this->pending === '') {
12417e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
1242a25f0a04SGreg Roach        }
12438d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
12447e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1245a25f0a04SGreg Roach        }
1246a25f0a04SGreg Roach
1247a25f0a04SGreg Roach        if ($this->pending) {
1248a25f0a04SGreg Roach            $old_gedcom = $this->pending;
1249a25f0a04SGreg Roach        } else {
1250a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
1251a25f0a04SGreg Roach        }
1252a25f0a04SGreg Roach
1253a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
125465e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
1255a25f0a04SGreg Roach
1256a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
12578d0ebef0SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) {
1258a25f0a04SGreg Roach            if (!$fact->isPendingDeletion()) {
1259905ab80aSGreg Roach                if ($fact->id() === $fact_id) {
1260db7bb364SGreg Roach                    if ($gedcom !== '') {
1261a25f0a04SGreg Roach                        $new_gedcom .= "\n" . $gedcom;
1262a25f0a04SGreg Roach                    }
1263fc3ccce4SGreg Roach                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1264a25f0a04SGreg Roach                } elseif ($fact->getTag() != 'CHAN' || !$update_chan) {
1265138ca96cSGreg Roach                    $new_gedcom .= "\n" . $fact->gedcom();
1266a25f0a04SGreg Roach                }
1267a25f0a04SGreg Roach            }
1268a25f0a04SGreg Roach        }
1269a25f0a04SGreg Roach        if ($update_chan) {
12704e9cf5abSGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1271a25f0a04SGreg Roach        }
1272a25f0a04SGreg Roach
1273a25f0a04SGreg Roach        // Adding a new fact
1274fc3ccce4SGreg Roach        if ($fact_id === '') {
1275a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
1276a25f0a04SGreg Roach        }
1277a25f0a04SGreg Roach
1278a25f0a04SGreg Roach        if ($new_gedcom != $old_gedcom) {
1279a25f0a04SGreg Roach            // Save the changes
1280d09b6323SGreg Roach            DB::table('change')->insert([
1281d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1282d09b6323SGreg Roach                'xref'       => $this->xref,
1283d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
1284d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
1285d09b6323SGreg Roach                'user_id'    => Auth::id(),
128613abd6f3SGreg Roach            ]);
1287a25f0a04SGreg Roach
1288a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1289a25f0a04SGreg Roach
1290a25f0a04SGreg Roach            if (Auth::user()->getPreference('auto_accept')) {
1291cc5684fdSGreg Roach                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1292a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1293a25f0a04SGreg Roach                $this->pending = null;
1294a25f0a04SGreg Roach            }
1295a25f0a04SGreg Roach        }
1296a25f0a04SGreg Roach        $this->parseFacts();
1297a25f0a04SGreg Roach    }
1298a25f0a04SGreg Roach
1299a25f0a04SGreg Roach    /**
1300a25f0a04SGreg Roach     * Update this record
1301a25f0a04SGreg Roach     *
1302a25f0a04SGreg Roach     * @param string $gedcom
1303cbc1590aSGreg Roach     * @param bool   $update_chan
13047e96c925SGreg Roach     *
13057e96c925SGreg Roach     * @return void
1306a25f0a04SGreg Roach     */
130776f666f4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan)
1308c1010edaSGreg Roach    {
1309a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1310a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1311a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1312a25f0a04SGreg Roach
1313a25f0a04SGreg Roach        // Update the CHAN record
1314a25f0a04SGreg Roach        if ($update_chan) {
1315a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1316a25f0a04SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1317a25f0a04SGreg Roach        }
1318a25f0a04SGreg Roach
1319a25f0a04SGreg Roach        // Create a pending change
1320d09b6323SGreg Roach        DB::table('change')->insert([
1321d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1322d09b6323SGreg Roach            'xref'       => $this->xref,
1323d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1324d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1325d09b6323SGreg Roach            'user_id'    => Auth::id(),
132613abd6f3SGreg Roach        ]);
1327a25f0a04SGreg Roach
1328a25f0a04SGreg Roach        // Clear the cache
1329a25f0a04SGreg Roach        $this->pending = $gedcom;
1330a25f0a04SGreg Roach
1331a25f0a04SGreg Roach        // Accept this pending change
1332a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1333cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1334a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1335a25f0a04SGreg Roach            $this->pending = null;
1336a25f0a04SGreg Roach        }
1337a25f0a04SGreg Roach
1338a25f0a04SGreg Roach        $this->parseFacts();
1339a25f0a04SGreg Roach
1340847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1341a25f0a04SGreg Roach    }
1342a25f0a04SGreg Roach
1343a25f0a04SGreg Roach    /**
1344a25f0a04SGreg Roach     * Delete this record
1345b874da82SGreg Roach     *
1346b874da82SGreg Roach     * @return void
1347a25f0a04SGreg Roach     */
1348c1010edaSGreg Roach    public function deleteRecord()
1349c1010edaSGreg Roach    {
1350a25f0a04SGreg Roach        // Create a pending change
13514c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1352d09b6323SGreg Roach            DB::table('change')->insert([
1353d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1354d09b6323SGreg Roach                'xref'       => $this->xref,
1355d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1356d09b6323SGreg Roach                'new_gedcom' => '',
1357d09b6323SGreg Roach                'user_id'    => Auth::id(),
135813abd6f3SGreg Roach            ]);
13594c0b5256SGreg Roach        }
1360a25f0a04SGreg Roach
13614c0b5256SGreg Roach        // Auto-accept this pending change
1362a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1363cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1364a25f0a04SGreg Roach        }
1365a25f0a04SGreg Roach
1366a25f0a04SGreg Roach        // Clear the cache
1367d17d7b9eSGreg Roach        self::$gedcom_record_cache  = [];
1368d17d7b9eSGreg Roach        self::$pending_record_cache = [];
1369a25f0a04SGreg Roach
1370847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1371a25f0a04SGreg Roach    }
1372a25f0a04SGreg Roach
1373a25f0a04SGreg Roach    /**
1374a25f0a04SGreg Roach     * Remove all links from this record to $xref
1375a25f0a04SGreg Roach     *
1376a25f0a04SGreg Roach     * @param string $xref
1377cbc1590aSGreg Roach     * @param bool   $update_chan
13787e96c925SGreg Roach     *
13797e96c925SGreg Roach     * @return void
1380a25f0a04SGreg Roach     */
138176f666f4SGreg Roach    public function removeLinks(string $xref, bool $update_chan)
1382c1010edaSGreg Roach    {
1383a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1384a25f0a04SGreg Roach
138530158ae7SGreg Roach        foreach ($this->facts() as $fact) {
138684586c02SGreg Roach            if ($fact->value() === $value) {
1387905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
13888d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1389138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1390a25f0a04SGreg Roach                foreach ($matches as $match) {
1391a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1392a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1393a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1394a25f0a04SGreg Roach                }
1395905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1396a25f0a04SGreg Roach            }
1397a25f0a04SGreg Roach        }
1398a25f0a04SGreg Roach    }
1399bf4eb542SGreg Roach
1400bf4eb542SGreg Roach    /**
1401bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1402bf4eb542SGreg Roach     * also delete all links to it.
1403bf4eb542SGreg Roach     *
1404bf4eb542SGreg Roach     * @return GedcomRecord[]
1405bf4eb542SGreg Roach     */
1406bf4eb542SGreg Roach    public function linkingRecords(): array
1407bf4eb542SGreg Roach    {
1408bf4eb542SGreg Roach        $union = DB::table('change')
1409bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1410fbbe964bSGreg Roach            ->whereContains('new_gedcom', '@' . $this->xref() . '@')
1411bf4eb542SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%')
1412bf4eb542SGreg Roach            ->select(['xref']);
1413bf4eb542SGreg Roach
1414bf4eb542SGreg Roach        $xrefs = DB::table('link')
1415bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1416bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
1417bf4eb542SGreg Roach            ->select('l_from')
1418bf4eb542SGreg Roach            ->union($union)
1419bf4eb542SGreg Roach            ->pluck('l_from');
1420bf4eb542SGreg Roach
1421bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
1422bf4eb542SGreg Roach            return GedcomRecord::getInstance($xref, $this->tree);
1423bf4eb542SGreg Roach        })->all();
1424bf4eb542SGreg Roach    }
1425a25f0a04SGreg Roach}
1426