xref: /webtrees/app/GedcomRecord.php (revision 589feda391b943b928aea0b4107591eb0e7bbf89)
1a25f0a04SGreg Roach<?php
2a25f0a04SGreg Roach/**
3a25f0a04SGreg Roach * webtrees: online genealogy
41062a142SGreg Roach * Copyright (C) 2018 webtrees development team
5a25f0a04SGreg Roach * This program is free software: you can redistribute it and/or modify
6a25f0a04SGreg Roach * it under the terms of the GNU General Public License as published by
7a25f0a04SGreg Roach * the Free Software Foundation, either version 3 of the License, or
8a25f0a04SGreg Roach * (at your option) any later version.
9a25f0a04SGreg Roach * This program is distributed in the hope that it will be useful,
10a25f0a04SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
11a25f0a04SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12a25f0a04SGreg Roach * GNU General Public License for more details.
13a25f0a04SGreg Roach * You should have received a copy of the GNU General Public License
14a25f0a04SGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
15a25f0a04SGreg Roach */
16e7f56f2aSGreg Roachdeclare(strict_types=1);
17e7f56f2aSGreg Roach
1876692c8bSGreg Roachnamespace Fisharebest\Webtrees;
1976692c8bSGreg Roach
207e96c925SGreg Roachuse Exception;
213d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\Functions;
223d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsDate;
233d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
243d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsPrint;
2579529c87SGreg Roachuse stdClass;
26a25f0a04SGreg Roach
27a25f0a04SGreg Roach/**
2876692c8bSGreg Roach * A GEDCOM object.
29a25f0a04SGreg Roach */
30c1010edaSGreg Roachclass GedcomRecord
31c1010edaSGreg Roach{
32a25f0a04SGreg Roach    const RECORD_TYPE = 'UNKNOWN';
33225e381fSGreg Roach    const ROUTE_NAME  = 'record';
34a25f0a04SGreg Roach
35a25f0a04SGreg Roach    /** @var string The record identifier */
36a25f0a04SGreg Roach    protected $xref;
37a25f0a04SGreg Roach
38000959d9SGreg Roach    /** @var Tree  The family tree to which this record belongs */
39000959d9SGreg Roach    protected $tree;
40a25f0a04SGreg Roach
41a25f0a04SGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
42a25f0a04SGreg Roach    protected $gedcom;
43a25f0a04SGreg Roach
44a25f0a04SGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
45a25f0a04SGreg Roach    protected $pending;
46a25f0a04SGreg Roach
47a25f0a04SGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
48a25f0a04SGreg Roach    protected $facts;
49a25f0a04SGreg Roach
50cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_PRIVATE */
51a25f0a04SGreg Roach    private $disp_public;
52a25f0a04SGreg Roach
53cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_USER */
54a25f0a04SGreg Roach    private $disp_user;
55a25f0a04SGreg Roach
56cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_NONE */
57a25f0a04SGreg Roach    private $disp_none;
58a25f0a04SGreg Roach
59a25f0a04SGreg Roach    /** @var string[][] All the names of this individual */
60bdb3725aSGreg Roach    protected $getAllNames;
61a25f0a04SGreg Roach
62cbc1590aSGreg Roach    /** @var int Cached result */
63bdb3725aSGreg Roach    protected $getPrimaryName;
64a25f0a04SGreg Roach
65cbc1590aSGreg Roach    /** @var int Cached result */
66bdb3725aSGreg Roach    protected $getSecondaryName;
67a25f0a04SGreg Roach
6876692c8bSGreg Roach    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
69395f0fe0SGreg Roach    protected static $gedcom_record_cache;
701ae87ce5SGreg Roach
7179529c87SGreg Roach    /** @var stdClass[][] Fetch all pending edits in one database query */
72a25f0a04SGreg Roach    private static $pending_record_cache;
73a25f0a04SGreg Roach
74a25f0a04SGreg Roach    /**
75a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
76a25f0a04SGreg Roach     *
77a25f0a04SGreg Roach     * @param string      $xref
78a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
79a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
80a25f0a04SGreg Roach     *                             empty string for records with pending deletions
8124ec66ceSGreg Roach     * @param Tree        $tree
82a25f0a04SGreg Roach     */
8376f666f4SGreg Roach    public function __construct(string $xref, string $gedcom, $pending, Tree $tree)
84c1010edaSGreg Roach    {
85a25f0a04SGreg Roach        $this->xref    = $xref;
86a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
87a25f0a04SGreg Roach        $this->pending = $pending;
8824ec66ceSGreg Roach        $this->tree    = $tree;
89a25f0a04SGreg Roach
90a25f0a04SGreg Roach        $this->parseFacts();
91a25f0a04SGreg Roach    }
92a25f0a04SGreg Roach
93a25f0a04SGreg Roach    /**
94a25f0a04SGreg Roach     * Split the record into facts
957e96c925SGreg Roach     *
967e96c925SGreg Roach     * @return void
97a25f0a04SGreg Roach     */
98c1010edaSGreg Roach    private function parseFacts()
99c1010edaSGreg Roach    {
100a25f0a04SGreg Roach        // Split the record into facts
101a25f0a04SGreg Roach        if ($this->gedcom) {
102a25f0a04SGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
103a25f0a04SGreg Roach            array_shift($gedcom_facts);
104a25f0a04SGreg Roach        } else {
10513abd6f3SGreg Roach            $gedcom_facts = [];
106a25f0a04SGreg Roach        }
107a25f0a04SGreg Roach        if ($this->pending) {
108a25f0a04SGreg Roach            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
109a25f0a04SGreg Roach            array_shift($pending_facts);
110a25f0a04SGreg Roach        } else {
11113abd6f3SGreg Roach            $pending_facts = [];
112a25f0a04SGreg Roach        }
113a25f0a04SGreg Roach
11413abd6f3SGreg Roach        $this->facts = [];
115a25f0a04SGreg Roach
116a25f0a04SGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
117a25f0a04SGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
118a25f0a04SGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts)) {
119a25f0a04SGreg Roach                $fact->setPendingDeletion();
120a25f0a04SGreg Roach            }
121a25f0a04SGreg Roach            $this->facts[] = $fact;
122a25f0a04SGreg Roach        }
123a25f0a04SGreg Roach        foreach ($pending_facts as $pending_fact) {
124a25f0a04SGreg Roach            if (!in_array($pending_fact, $gedcom_facts)) {
125a25f0a04SGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
126a25f0a04SGreg Roach                $fact->setPendingAddition();
127a25f0a04SGreg Roach                $this->facts[] = $fact;
128a25f0a04SGreg Roach            }
129a25f0a04SGreg Roach        }
130a25f0a04SGreg Roach    }
131a25f0a04SGreg Roach
132a25f0a04SGreg Roach    /**
133a25f0a04SGreg Roach     * Get an instance of a GedcomRecord object. For single records,
134a25f0a04SGreg Roach     * we just receive the XREF. For bulk records (such as lists
135a25f0a04SGreg Roach     * and search results) we can receive the GEDCOM data as well.
136a25f0a04SGreg Roach     *
137a25f0a04SGreg Roach     * @param string      $xref
13824ec66ceSGreg Roach     * @param Tree        $tree
139a25f0a04SGreg Roach     * @param string|null $gedcom
140a25f0a04SGreg Roach     *
1417e96c925SGreg Roach     * @throws Exception
142cbc1590aSGreg Roach     *
14384658595SGreg Roach     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|null
144a25f0a04SGreg Roach     */
14576f666f4SGreg Roach    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
146c1010edaSGreg Roach    {
14724ec66ceSGreg Roach        $tree_id = $tree->getTreeId();
14824ec66ceSGreg Roach
149e71ef9d2SGreg Roach        // Is this record already in the cache?
15024ec66ceSGreg Roach        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
151e71ef9d2SGreg Roach            return self::$gedcom_record_cache[$xref][$tree_id];
152a25f0a04SGreg Roach        }
153a25f0a04SGreg Roach
154a25f0a04SGreg Roach        // Do we need to fetch the record from the database?
155a25f0a04SGreg Roach        if ($gedcom === null) {
15624ec66ceSGreg Roach            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
157a25f0a04SGreg Roach        }
158a25f0a04SGreg Roach
159a25f0a04SGreg Roach        // If we can edit, then we also need to be able to see pending records.
16094075df0SGreg Roach        if (Auth::isEditor($tree)) {
16124ec66ceSGreg Roach            if (!isset(self::$pending_record_cache[$tree_id])) {
162a25f0a04SGreg Roach                // Fetch all pending records in one database query
16313abd6f3SGreg Roach                self::$pending_record_cache[$tree_id] = [];
164a25f0a04SGreg Roach                $rows                                 = Database::prepare(
16594075df0SGreg Roach                    "SELECT xref, new_gedcom FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id ORDER BY change_id"
16613abd6f3SGreg Roach                )->execute([
167cbc1590aSGreg Roach                    'tree_id' => $tree_id,
16813abd6f3SGreg Roach                ])->fetchAll();
169a25f0a04SGreg Roach                foreach ($rows as $row) {
17024ec66ceSGreg Roach                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
171a25f0a04SGreg Roach                }
172a25f0a04SGreg Roach            }
173a25f0a04SGreg Roach
17424ec66ceSGreg Roach            if (isset(self::$pending_record_cache[$tree_id][$xref])) {
175a25f0a04SGreg Roach                // A pending edit exists for this record
17624ec66ceSGreg Roach                $pending = self::$pending_record_cache[$tree_id][$xref];
177a25f0a04SGreg Roach            } else {
178a25f0a04SGreg Roach                $pending = null;
179a25f0a04SGreg Roach            }
180a25f0a04SGreg Roach        } else {
181a25f0a04SGreg Roach            // There are no pending changes for this record
182a25f0a04SGreg Roach            $pending = null;
183a25f0a04SGreg Roach        }
184a25f0a04SGreg Roach
185a25f0a04SGreg Roach        // No such record exists
186a25f0a04SGreg Roach        if ($gedcom === null && $pending === null) {
187a25f0a04SGreg Roach            return null;
188a25f0a04SGreg Roach        }
189a25f0a04SGreg Roach
190a25f0a04SGreg Roach        // Create the object
191a25f0a04SGreg Roach        if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom . $pending, $match)) {
192a25f0a04SGreg Roach            $xref = $match[1]; // Collation - we may have requested I123 and found i123
193a25f0a04SGreg Roach            $type = $match[2];
194a25f0a04SGreg Roach        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
195a25f0a04SGreg Roach            $xref = $match[1];
196a25f0a04SGreg Roach            $type = $match[1];
197a25f0a04SGreg Roach        } elseif ($gedcom . $pending) {
1987e96c925SGreg Roach            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
199a25f0a04SGreg Roach        } else {
200a25f0a04SGreg Roach            // A record with both pending creation and pending deletion
201a25f0a04SGreg Roach            $type = static::RECORD_TYPE;
202a25f0a04SGreg Roach        }
203a25f0a04SGreg Roach
204a25f0a04SGreg Roach        switch ($type) {
205a25f0a04SGreg Roach            case 'INDI':
20624ec66ceSGreg Roach                $record = new Individual($xref, $gedcom, $pending, $tree);
207a25f0a04SGreg Roach                break;
208a25f0a04SGreg Roach            case 'FAM':
20924ec66ceSGreg Roach                $record = new Family($xref, $gedcom, $pending, $tree);
210a25f0a04SGreg Roach                break;
211a25f0a04SGreg Roach            case 'SOUR':
21224ec66ceSGreg Roach                $record = new Source($xref, $gedcom, $pending, $tree);
213a25f0a04SGreg Roach                break;
214a25f0a04SGreg Roach            case 'OBJE':
21524ec66ceSGreg Roach                $record = new Media($xref, $gedcom, $pending, $tree);
216a25f0a04SGreg Roach                break;
217a25f0a04SGreg Roach            case 'REPO':
21824ec66ceSGreg Roach                $record = new Repository($xref, $gedcom, $pending, $tree);
219a25f0a04SGreg Roach                break;
220a25f0a04SGreg Roach            case 'NOTE':
22124ec66ceSGreg Roach                $record = new Note($xref, $gedcom, $pending, $tree);
222a25f0a04SGreg Roach                break;
223a25f0a04SGreg Roach            default:
22406ef8e02SGreg Roach                $record = new self($xref, $gedcom, $pending, $tree);
225a25f0a04SGreg Roach                break;
226a25f0a04SGreg Roach        }
227a25f0a04SGreg Roach
228a25f0a04SGreg Roach        // Store it in the cache
22924ec66ceSGreg Roach        self::$gedcom_record_cache[$xref][$tree_id] = $record;
230a25f0a04SGreg Roach
231a25f0a04SGreg Roach        return $record;
232a25f0a04SGreg Roach    }
233a25f0a04SGreg Roach
234a25f0a04SGreg Roach    /**
235a25f0a04SGreg Roach     * Fetch data from the database
236a25f0a04SGreg Roach     *
237a25f0a04SGreg Roach     * @param string $xref
238cbc1590aSGreg Roach     * @param int    $tree_id
239a25f0a04SGreg Roach     *
240a25f0a04SGreg Roach     * @return null|string
241a25f0a04SGreg Roach     */
24276f666f4SGreg Roach    protected static function fetchGedcomRecord(string $xref, int $tree_id)
243c1010edaSGreg Roach    {
244a25f0a04SGreg Roach        // We don't know what type of object this is. Try each one in turn.
24564d9078aSGreg Roach        $data = Individual::fetchGedcomRecord($xref, $tree_id);
246a25f0a04SGreg Roach        if ($data) {
247a25f0a04SGreg Roach            return $data;
248a25f0a04SGreg Roach        }
24964d9078aSGreg Roach        $data = Family::fetchGedcomRecord($xref, $tree_id);
250a25f0a04SGreg Roach        if ($data) {
251a25f0a04SGreg Roach            return $data;
252a25f0a04SGreg Roach        }
25364d9078aSGreg Roach        $data = Source::fetchGedcomRecord($xref, $tree_id);
254a25f0a04SGreg Roach        if ($data) {
255a25f0a04SGreg Roach            return $data;
256a25f0a04SGreg Roach        }
25764d9078aSGreg Roach        $data = Repository::fetchGedcomRecord($xref, $tree_id);
258a25f0a04SGreg Roach        if ($data) {
259a25f0a04SGreg Roach            return $data;
260a25f0a04SGreg Roach        }
26164d9078aSGreg Roach        $data = Media::fetchGedcomRecord($xref, $tree_id);
262a25f0a04SGreg Roach        if ($data) {
263a25f0a04SGreg Roach            return $data;
264a25f0a04SGreg Roach        }
26564d9078aSGreg Roach        $data = Note::fetchGedcomRecord($xref, $tree_id);
266a25f0a04SGreg Roach        if ($data) {
267a25f0a04SGreg Roach            return $data;
268a25f0a04SGreg Roach        }
269c1010edaSGreg Roach
270a25f0a04SGreg Roach        // Some other type of record...
271a25f0a04SGreg Roach
27264d9078aSGreg Roach        return Database::prepare(
27364d9078aSGreg Roach            "SELECT o_gedcom FROM `##other` WHERE o_id = :xref AND o_file = :tree_id"
27413abd6f3SGreg Roach        )->execute([
27564d9078aSGreg Roach            'xref'    => $xref,
27664d9078aSGreg Roach            'tree_id' => $tree_id,
27713abd6f3SGreg Roach        ])->fetchOne();
278a25f0a04SGreg Roach    }
279a25f0a04SGreg Roach
280a25f0a04SGreg Roach    /**
281a25f0a04SGreg Roach     * Get the XREF for this record
282a25f0a04SGreg Roach     *
283a25f0a04SGreg Roach     * @return string
284a25f0a04SGreg Roach     */
2858f53f488SRico Sonntag    public function getXref(): string
286c1010edaSGreg Roach    {
287a25f0a04SGreg Roach        return $this->xref;
288a25f0a04SGreg Roach    }
289a25f0a04SGreg Roach
290a25f0a04SGreg Roach    /**
291000959d9SGreg Roach     * Get the tree to which this record belongs
292000959d9SGreg Roach     *
293000959d9SGreg Roach     * @return Tree
294000959d9SGreg Roach     */
2958f53f488SRico Sonntag    public function getTree(): Tree
296c1010edaSGreg Roach    {
297518bbdc1SGreg Roach        return $this->tree;
298000959d9SGreg Roach    }
299000959d9SGreg Roach
300000959d9SGreg Roach    /**
301a25f0a04SGreg Roach     * Application code should access data via Fact objects.
302a25f0a04SGreg Roach     * This function exists to support old code.
303a25f0a04SGreg Roach     *
304a25f0a04SGreg Roach     * @return string
305a25f0a04SGreg Roach     */
306c1010edaSGreg Roach    public function getGedcom()
307c1010edaSGreg Roach    {
308b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
309a25f0a04SGreg Roach    }
310a25f0a04SGreg Roach
311a25f0a04SGreg Roach    /**
312a25f0a04SGreg Roach     * Does this record have a pending change?
313a25f0a04SGreg Roach     *
314cbc1590aSGreg Roach     * @return bool
315a25f0a04SGreg Roach     */
3168f53f488SRico Sonntag    public function isPendingAddition(): bool
317c1010edaSGreg Roach    {
318a25f0a04SGreg Roach        return $this->pending !== null;
319a25f0a04SGreg Roach    }
320a25f0a04SGreg Roach
321a25f0a04SGreg Roach    /**
322a25f0a04SGreg Roach     * Does this record have a pending deletion?
323a25f0a04SGreg Roach     *
324cbc1590aSGreg Roach     * @return bool
325a25f0a04SGreg Roach     */
3268f53f488SRico Sonntag    public function isPendingDeletion(): bool
327c1010edaSGreg Roach    {
328a25f0a04SGreg Roach        return $this->pending === '';
329a25f0a04SGreg Roach    }
330a25f0a04SGreg Roach
331a25f0a04SGreg Roach    /**
332a25f0a04SGreg Roach     * Generate a URL to this record, suitable for use in HTML, etc.
333a25f0a04SGreg Roach     *
334b1f1e4efSGreg Roach     * @deprecated
335b1f1e4efSGreg Roach     *
336a25f0a04SGreg Roach     * @return string
337a25f0a04SGreg Roach     */
3388f53f488SRico Sonntag    public function getHtmlUrl(): string
339c1010edaSGreg Roach    {
340b1f1e4efSGreg Roach        return e($this->url());
341b1f1e4efSGreg Roach    }
342b1f1e4efSGreg Roach
343b1f1e4efSGreg Roach    /**
344225e381fSGreg Roach     * Generate a URL to this record.
345b1f1e4efSGreg Roach     *
346b1f1e4efSGreg Roach     * @deprecated
347b1f1e4efSGreg Roach     *
348b1f1e4efSGreg Roach     * @return string
349b1f1e4efSGreg Roach     */
3508f53f488SRico Sonntag    public function getRawUrl(): string
351c1010edaSGreg Roach    {
352b1f1e4efSGreg Roach        return $this->url();
353a25f0a04SGreg Roach    }
354a25f0a04SGreg Roach
355a25f0a04SGreg Roach    /**
356225e381fSGreg Roach     * Generate a URL to this record.
357a25f0a04SGreg Roach     *
358a25f0a04SGreg Roach     * @return string
359a25f0a04SGreg Roach     */
3608f53f488SRico Sonntag    public function url(): string
361c1010edaSGreg Roach    {
362225e381fSGreg Roach        return route(static::ROUTE_NAME, [
363225e381fSGreg Roach            'xref' => $this->getXref(),
364225e381fSGreg Roach            'ged'  => $this->tree->getName(),
365225e381fSGreg Roach        ]);
366a25f0a04SGreg Roach    }
367a25f0a04SGreg Roach
368a25f0a04SGreg Roach    /**
369a25f0a04SGreg Roach     * Work out whether this record can be shown to a user with a given access level
370a25f0a04SGreg Roach     *
371cbc1590aSGreg Roach     * @param int $access_level
372a25f0a04SGreg Roach     *
373cbc1590aSGreg Roach     * @return bool
374a25f0a04SGreg Roach     */
37576f666f4SGreg Roach    private function canShowRecord(int $access_level): bool
376c1010edaSGreg Roach    {
377a25f0a04SGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
378518bbdc1SGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
379a25f0a04SGreg Roach            return true;
380a25f0a04SGreg Roach        }
381a25f0a04SGreg Roach
382a25f0a04SGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
3834b9ff166SGreg Roach        if ($this->getXref() === $this->tree->getUserPreference(Auth::user(), 'gedcomid') && $access_level === Auth::accessLevel($this->tree)) {
384a25f0a04SGreg Roach            return true;
385a25f0a04SGreg Roach        }
386a25f0a04SGreg Roach
387a25f0a04SGreg Roach        // Does this record have a RESN?
38820ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
3894b9ff166SGreg Roach            return Auth::PRIV_NONE >= $access_level;
390a25f0a04SGreg Roach        }
39120ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
3924b9ff166SGreg Roach            return Auth::PRIV_USER >= $access_level;
393a25f0a04SGreg Roach        }
39420ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
395a25f0a04SGreg Roach            return true;
396a25f0a04SGreg Roach        }
397a25f0a04SGreg Roach
398a25f0a04SGreg Roach        // Does this record have a default RESN?
399518bbdc1SGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
400518bbdc1SGreg Roach        if (isset($individual_privacy[$this->getXref()])) {
401518bbdc1SGreg Roach            return $individual_privacy[$this->getXref()] >= $access_level;
402a25f0a04SGreg Roach        }
403a25f0a04SGreg Roach
404a25f0a04SGreg Roach        // Privacy rules do not apply to admins
4054b9ff166SGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
406a25f0a04SGreg Roach            return true;
407a25f0a04SGreg Roach        }
408a25f0a04SGreg Roach
409a25f0a04SGreg Roach        // Different types of record have different privacy rules
410a25f0a04SGreg Roach        return $this->canShowByType($access_level);
411a25f0a04SGreg Roach    }
412a25f0a04SGreg Roach
413a25f0a04SGreg Roach    /**
414a25f0a04SGreg Roach     * Each object type may have its own special rules, and re-implement this function.
415a25f0a04SGreg Roach     *
416cbc1590aSGreg Roach     * @param int $access_level
417a25f0a04SGreg Roach     *
418cbc1590aSGreg Roach     * @return bool
419a25f0a04SGreg Roach     */
42035584196SGreg Roach    protected function canShowByType(int $access_level): bool
421c1010edaSGreg Roach    {
422518bbdc1SGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
423a25f0a04SGreg Roach
424518bbdc1SGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
425a25f0a04SGreg Roach            // Restriction found
426518bbdc1SGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
427b2ce94c6SRico Sonntag        }
428b2ce94c6SRico Sonntag
429a25f0a04SGreg Roach        // No restriction found - must be public:
430a25f0a04SGreg Roach        return true;
431a25f0a04SGreg Roach    }
432a25f0a04SGreg Roach
433a25f0a04SGreg Roach    /**
434a25f0a04SGreg Roach     * Can the details of this record be shown?
435a25f0a04SGreg Roach     *
436cbc1590aSGreg Roach     * @param int|null $access_level
437a25f0a04SGreg Roach     *
438cbc1590aSGreg Roach     * @return bool
439a25f0a04SGreg Roach     */
44035584196SGreg Roach    public function canShow(int $access_level = null): bool
441c1010edaSGreg Roach    {
4424b9ff166SGreg Roach        if ($access_level === null) {
4434b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
4444b9ff166SGreg Roach        }
4454b9ff166SGreg Roach
446a25f0a04SGreg Roach        // CACHING: this function can take three different parameters,
447a25f0a04SGreg Roach        // and therefore needs three different caches for the result.
448a25f0a04SGreg Roach        switch ($access_level) {
4494b9ff166SGreg Roach            case Auth::PRIV_PRIVATE: // visitor
450a25f0a04SGreg Roach                if ($this->disp_public === null) {
4514b9ff166SGreg Roach                    $this->disp_public = $this->canShowRecord(Auth::PRIV_PRIVATE);
452a25f0a04SGreg Roach                }
453cbc1590aSGreg Roach
454a25f0a04SGreg Roach                return $this->disp_public;
4554b9ff166SGreg Roach            case Auth::PRIV_USER: // member
456a25f0a04SGreg Roach                if ($this->disp_user === null) {
4574b9ff166SGreg Roach                    $this->disp_user = $this->canShowRecord(Auth::PRIV_USER);
458a25f0a04SGreg Roach                }
459cbc1590aSGreg Roach
460a25f0a04SGreg Roach                return $this->disp_user;
4614b9ff166SGreg Roach            case Auth::PRIV_NONE: // admin
462a25f0a04SGreg Roach                if ($this->disp_none === null) {
4634b9ff166SGreg Roach                    $this->disp_none = $this->canShowRecord(Auth::PRIV_NONE);
464a25f0a04SGreg Roach                }
465cbc1590aSGreg Roach
466a25f0a04SGreg Roach                return $this->disp_none;
4674b9ff166SGreg Roach            case Auth::PRIV_HIDE: // hidden from admins
468a25f0a04SGreg Roach                // We use this value to bypass privacy checks. For example,
469a25f0a04SGreg Roach                // when downloading data or when calculating privacy itself.
470a25f0a04SGreg Roach                return true;
471a25f0a04SGreg Roach            default:
472a25f0a04SGreg Roach                // Should never get here.
473a25f0a04SGreg Roach                return false;
474a25f0a04SGreg Roach        }
475a25f0a04SGreg Roach    }
476a25f0a04SGreg Roach
477a25f0a04SGreg Roach    /**
478a25f0a04SGreg Roach     * Can the name of this record be shown?
479a25f0a04SGreg Roach     *
480cbc1590aSGreg Roach     * @param int|null $access_level
481a25f0a04SGreg Roach     *
482cbc1590aSGreg Roach     * @return bool
483a25f0a04SGreg Roach     */
48476f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
485c1010edaSGreg Roach    {
4864b9ff166SGreg Roach        if ($access_level === null) {
4874b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
4884b9ff166SGreg Roach        }
4894b9ff166SGreg Roach
490a25f0a04SGreg Roach        return $this->canShow($access_level);
491a25f0a04SGreg Roach    }
492a25f0a04SGreg Roach
493a25f0a04SGreg Roach    /**
494a25f0a04SGreg Roach     * Can we edit this record?
495a25f0a04SGreg Roach     *
496cbc1590aSGreg Roach     * @return bool
497a25f0a04SGreg Roach     */
4988f53f488SRico Sonntag    public function canEdit(): bool
499c1010edaSGreg Roach    {
5004b9ff166SGreg Roach        return Auth::isManager($this->tree) || Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
501a25f0a04SGreg Roach    }
502a25f0a04SGreg Roach
503a25f0a04SGreg Roach    /**
504a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
505a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
506a25f0a04SGreg Roach     *
507cbc1590aSGreg Roach     * @param int $access_level
508a25f0a04SGreg Roach     *
509a25f0a04SGreg Roach     * @return string
510a25f0a04SGreg Roach     */
51176f666f4SGreg Roach    public function privatizeGedcom(int $access_level)
512c1010edaSGreg Roach    {
5134b9ff166SGreg Roach        if ($access_level == Auth::PRIV_HIDE) {
514a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
515a25f0a04SGreg Roach            return $this->gedcom;
516b2ce94c6SRico Sonntag        }
517b2ce94c6SRico Sonntag
518b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
519a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
520a25f0a04SGreg Roach
521a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
522a25f0a04SGreg Roach            list($gedrec) = explode("\n", $this->gedcom, 2);
523a25f0a04SGreg Roach
524a25f0a04SGreg Roach            // Check each of the facts for access
525a25f0a04SGreg Roach            foreach ($this->getFacts(null, false, $access_level) as $fact) {
526a25f0a04SGreg Roach                $gedrec .= "\n" . $fact->getGedcom();
527a25f0a04SGreg Roach            }
528cbc1590aSGreg Roach
529a25f0a04SGreg Roach            return $gedrec;
530b2ce94c6SRico Sonntag        }
531b2ce94c6SRico Sonntag
532a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
533a25f0a04SGreg Roach        // limited data, such as links to other records.
534a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
535a25f0a04SGreg Roach    }
536a25f0a04SGreg Roach
537a25f0a04SGreg Roach    /**
538a25f0a04SGreg Roach     * Generate a private version of this record
539a25f0a04SGreg Roach     *
540cbc1590aSGreg Roach     * @param int $access_level
541a25f0a04SGreg Roach     *
542a25f0a04SGreg Roach     * @return string
543a25f0a04SGreg Roach     */
54476f666f4SGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
545c1010edaSGreg Roach    {
546a25f0a04SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
547a25f0a04SGreg Roach    }
548a25f0a04SGreg Roach
549a25f0a04SGreg Roach    /**
550a25f0a04SGreg Roach     * Convert a name record into sortable and full/display versions. This default
551a25f0a04SGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
552a25f0a04SGreg Roach     *
553a25f0a04SGreg Roach     * @param string $type
554a25f0a04SGreg Roach     * @param string $value
555a25f0a04SGreg Roach     * @param string $gedcom
5567e96c925SGreg Roach     *
5577e96c925SGreg Roach     * @return void
558a25f0a04SGreg Roach     */
55976f666f4SGreg Roach    protected function addName(string $type, string $value, string $gedcom)
560c1010edaSGreg Roach    {
561bdb3725aSGreg Roach        $this->getAllNames[] = [
562a25f0a04SGreg Roach            'type'   => $type,
5637e96c925SGreg Roach            'sort'   => preg_replace_callback('/([0-9]+)/', function (array $matches): string {
5648d68cabeSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
5658d68cabeSGreg Roach            }, $value),
566c1010edaSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
567c1010edaSGreg Roach            // This is used for display
568c1010edaSGreg Roach            'fullNN' => $value,
569c1010edaSGreg Roach            // This goes into the database
57013abd6f3SGreg Roach        ];
571a25f0a04SGreg Roach    }
572a25f0a04SGreg Roach
573a25f0a04SGreg Roach    /**
574a25f0a04SGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
575a25f0a04SGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
576a25f0a04SGreg Roach     * Parameters: the level 1 fact containing the name.
577a25f0a04SGreg Roach     * Return value: an array of name structures, each containing
578a25f0a04SGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
579a25f0a04SGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
580a25f0a04SGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
581a25f0a04SGreg Roach     *
582cbc1590aSGreg Roach     * @param int    $level
583a25f0a04SGreg Roach     * @param string $fact_type
584a25f0a04SGreg Roach     * @param Fact[] $facts
5857e96c925SGreg Roach     *
5867e96c925SGreg Roach     * @return void
587a25f0a04SGreg Roach     */
58876f666f4SGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, array $facts)
589c1010edaSGreg Roach    {
590a25f0a04SGreg Roach        $sublevel    = $level + 1;
591a25f0a04SGreg Roach        $subsublevel = $sublevel + 1;
592a25f0a04SGreg Roach        foreach ($facts as $fact) {
593a25f0a04SGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->getGedcom(), $matches, PREG_SET_ORDER)) {
594a25f0a04SGreg Roach                foreach ($matches as $match) {
595a25f0a04SGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
596a25f0a04SGreg Roach                    if ($match[1] == 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
597a25f0a04SGreg Roach                        $this->addName('_MARNM', $match[2], $fact->getGedcom());
598a25f0a04SGreg Roach                    } else {
599a25f0a04SGreg Roach                        $this->addName($match[1], $match[2], $fact->getGedcom());
600a25f0a04SGreg Roach                    }
601a25f0a04SGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
602a25f0a04SGreg Roach                        foreach ($submatches as $submatch) {
603a25f0a04SGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
604a25f0a04SGreg Roach                        }
605a25f0a04SGreg Roach                    }
606a25f0a04SGreg Roach                }
607a25f0a04SGreg Roach            }
608a25f0a04SGreg Roach        }
609a25f0a04SGreg Roach    }
610a25f0a04SGreg Roach
611a25f0a04SGreg Roach    /**
612a25f0a04SGreg Roach     * Default for "other" object types
613c7ff4153SGreg Roach     *
614c7ff4153SGreg Roach     * @return void
615a25f0a04SGreg Roach     */
616c1010edaSGreg Roach    public function extractNames()
617c1010edaSGreg Roach    {
61876f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
619a25f0a04SGreg Roach    }
620a25f0a04SGreg Roach
621a25f0a04SGreg Roach    /**
622a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
623a25f0a04SGreg Roach     *
624a25f0a04SGreg Roach     * @return string[][]
625a25f0a04SGreg Roach     */
6268f53f488SRico Sonntag    public function getAllNames(): array
627c1010edaSGreg Roach    {
628bdb3725aSGreg Roach        if ($this->getAllNames === null) {
629bdb3725aSGreg Roach            $this->getAllNames = [];
630a25f0a04SGreg Roach            if ($this->canShowName()) {
631a25f0a04SGreg Roach                // Ask the record to extract its names
632a25f0a04SGreg Roach                $this->extractNames();
633a25f0a04SGreg Roach                // No name found? Use a fallback.
634bdb3725aSGreg Roach                if (!$this->getAllNames) {
635db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
636a25f0a04SGreg Roach                }
637a25f0a04SGreg Roach            } else {
638db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
639a25f0a04SGreg Roach            }
640a25f0a04SGreg Roach        }
641cbc1590aSGreg Roach
642bdb3725aSGreg Roach        return $this->getAllNames;
643a25f0a04SGreg Roach    }
644a25f0a04SGreg Roach
645a25f0a04SGreg Roach    /**
646a25f0a04SGreg Roach     * If this object has no name, what do we call it?
647a25f0a04SGreg Roach     *
648a25f0a04SGreg Roach     * @return string
649a25f0a04SGreg Roach     */
6508f53f488SRico Sonntag    public function getFallBackName(): string
651c1010edaSGreg Roach    {
652d53324c9SGreg Roach        return e($this->getXref());
653a25f0a04SGreg Roach    }
654a25f0a04SGreg Roach
655a25f0a04SGreg Roach    /**
656a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
657a25f0a04SGreg Roach     *
658cbc1590aSGreg Roach     * @return int
659a25f0a04SGreg Roach     */
6608f53f488SRico Sonntag    public function getPrimaryName(): int
661c1010edaSGreg Roach    {
662a25f0a04SGreg Roach        static $language_script;
663a25f0a04SGreg Roach
664a25f0a04SGreg Roach        if ($language_script === null) {
665a25f0a04SGreg Roach            $language_script = I18N::languageScript(WT_LOCALE);
666a25f0a04SGreg Roach        }
667a25f0a04SGreg Roach
668bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
669a25f0a04SGreg Roach            // Generally, the first name is the primary one....
670bdb3725aSGreg Roach            $this->getPrimaryName = 0;
671a25f0a04SGreg Roach            // ...except when the language/name use different character sets
672a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
67369546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
674bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
675a25f0a04SGreg Roach                    break;
676a25f0a04SGreg Roach                }
677a25f0a04SGreg Roach            }
678a25f0a04SGreg Roach        }
679a25f0a04SGreg Roach
680bdb3725aSGreg Roach        return $this->getPrimaryName;
681a25f0a04SGreg Roach    }
682a25f0a04SGreg Roach
683a25f0a04SGreg Roach    /**
684a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
685a25f0a04SGreg Roach     *
686cbc1590aSGreg Roach     * @return int
687a25f0a04SGreg Roach     */
6888f53f488SRico Sonntag    public function getSecondaryName(): int
689c1010edaSGreg Roach    {
6908f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
691a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
692bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
693a25f0a04SGreg Roach            // ....except when there are names with different character sets
694a25f0a04SGreg Roach            $all_names = $this->getAllNames();
695a25f0a04SGreg Roach            if (count($all_names) > 1) {
696a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
697a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
698a25f0a04SGreg Roach                    if ($n != $this->getPrimaryName() && $name['type'] != '_MARNM' && I18N::textScript($name['sort']) != $primary_script) {
699bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
700a25f0a04SGreg Roach                        break;
701a25f0a04SGreg Roach                    }
702a25f0a04SGreg Roach                }
703a25f0a04SGreg Roach            }
704a25f0a04SGreg Roach        }
705cbc1590aSGreg Roach
706bdb3725aSGreg Roach        return $this->getSecondaryName;
707a25f0a04SGreg Roach    }
708a25f0a04SGreg Roach
709a25f0a04SGreg Roach    /**
710a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
711a25f0a04SGreg Roach     *
71276f666f4SGreg Roach     * @param int|null $n
7137e96c925SGreg Roach     *
7147e96c925SGreg Roach     * @return void
715a25f0a04SGreg Roach     */
716251a9de7SGreg Roach    public function setPrimaryName(int $n = null)
717c1010edaSGreg Roach    {
718bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
719bdb3725aSGreg Roach        $this->getSecondaryName = null;
720a25f0a04SGreg Roach    }
721a25f0a04SGreg Roach
722a25f0a04SGreg Roach    /**
723a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
724a25f0a04SGreg Roach     *
725a25f0a04SGreg Roach     * @return string
726a25f0a04SGreg Roach     */
727c1010edaSGreg Roach    public function __toString()
728c1010edaSGreg Roach    {
729518bbdc1SGreg Roach        return $this->xref . '@' . $this->tree->getTreeId();
730a25f0a04SGreg Roach    }
731a25f0a04SGreg Roach
732a25f0a04SGreg Roach    /**
733a25f0a04SGreg Roach     * Static helper function to sort an array of objects by name
734a25f0a04SGreg Roach     * Records whose names cannot be displayed are sorted at the end.
735a25f0a04SGreg Roach     *
736a25f0a04SGreg Roach     * @param GedcomRecord $x
737a25f0a04SGreg Roach     * @param GedcomRecord $y
738a25f0a04SGreg Roach     *
739cbc1590aSGreg Roach     * @return int
740a25f0a04SGreg Roach     */
741c1010edaSGreg Roach    public static function compare(GedcomRecord $x, GedcomRecord $y)
742c1010edaSGreg Roach    {
743a25f0a04SGreg Roach        if ($x->canShowName()) {
744a25f0a04SGreg Roach            if ($y->canShowName()) {
745a25f0a04SGreg Roach                return I18N::strcasecmp($x->getSortName(), $y->getSortName());
746b2ce94c6SRico Sonntag            }
747b2ce94c6SRico Sonntag
748a25f0a04SGreg Roach            return -1; // only $y is private
749a25f0a04SGreg Roach        }
750b2ce94c6SRico Sonntag
751a25f0a04SGreg Roach        if ($y->canShowName()) {
752a25f0a04SGreg Roach            return 1; // only $x is private
753b2ce94c6SRico Sonntag        }
754b2ce94c6SRico Sonntag
755a25f0a04SGreg Roach        return 0; // both $x and $y private
756a25f0a04SGreg Roach    }
757a25f0a04SGreg Roach
758a25f0a04SGreg Roach    /**
759a25f0a04SGreg Roach     * Get variants of the name
760a25f0a04SGreg Roach     *
761a25f0a04SGreg Roach     * @return string
762a25f0a04SGreg Roach     */
763c1010edaSGreg Roach    public function getFullName()
764c1010edaSGreg Roach    {
765a25f0a04SGreg Roach        if ($this->canShowName()) {
766a25f0a04SGreg Roach            $tmp = $this->getAllNames();
767cbc1590aSGreg Roach
768a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
769a25f0a04SGreg Roach        }
770b2ce94c6SRico Sonntag
771b2ce94c6SRico Sonntag        return I18N::translate('Private');
772a25f0a04SGreg Roach    }
773a25f0a04SGreg Roach
774a25f0a04SGreg Roach    /**
775a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
776a25f0a04SGreg Roach     *
777a25f0a04SGreg Roach     * @return string
778a25f0a04SGreg Roach     */
7798f53f488SRico Sonntag    public function getSortName(): string
780c1010edaSGreg Roach    {
781a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
782a25f0a04SGreg Roach        $tmp = $this->getAllNames();
783cbc1590aSGreg Roach
784a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
785a25f0a04SGreg Roach    }
786a25f0a04SGreg Roach
787a25f0a04SGreg Roach    /**
788a25f0a04SGreg Roach     * Get the full name in an alternative character set
789a25f0a04SGreg Roach     *
790a25f0a04SGreg Roach     * @return null|string
791a25f0a04SGreg Roach     */
792c1010edaSGreg Roach    public function getAddName()
793c1010edaSGreg Roach    {
794a25f0a04SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() != $this->getSecondaryName()) {
795a25f0a04SGreg Roach            $all_names = $this->getAllNames();
796cbc1590aSGreg Roach
797a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
798a25f0a04SGreg Roach        }
799b2ce94c6SRico Sonntag
800b2ce94c6SRico Sonntag        return null;
801a25f0a04SGreg Roach    }
802a25f0a04SGreg Roach
803a25f0a04SGreg Roach    /**
804a25f0a04SGreg Roach     * Format this object for display in a list
805a25f0a04SGreg Roach     *
806a25f0a04SGreg Roach     * @return string
807a25f0a04SGreg Roach     */
8088f53f488SRico Sonntag    public function formatList(): string
809c1010edaSGreg Roach    {
810b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
811b165e17cSGreg Roach        $html .= '<b>' . $this->getFullName() . '</b>';
812a25f0a04SGreg Roach        $html .= $this->formatListDetails();
813b165e17cSGreg Roach        $html .= '</a>';
814cbc1590aSGreg Roach
815a25f0a04SGreg Roach        return $html;
816a25f0a04SGreg Roach    }
817a25f0a04SGreg Roach
818a25f0a04SGreg Roach    /**
819a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
820a25f0a04SGreg Roach     * identifying characteristics of this record.
821a25f0a04SGreg Roach     *
822a25f0a04SGreg Roach     * @return string
823a25f0a04SGreg Roach     */
8248f53f488SRico Sonntag    public function formatListDetails(): string
825c1010edaSGreg Roach    {
826a25f0a04SGreg Roach        return '';
827a25f0a04SGreg Roach    }
828a25f0a04SGreg Roach
829a25f0a04SGreg Roach    /**
830a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
831a25f0a04SGreg Roach     *
832a25f0a04SGreg Roach     * @param string $facts
833cbc1590aSGreg Roach     * @param int    $style
834a25f0a04SGreg Roach     *
835a25f0a04SGreg Roach     * @return string
836a25f0a04SGreg Roach     */
83776f666f4SGreg Roach    public function formatFirstMajorFact(string $facts, int $style): string
838c1010edaSGreg Roach    {
839a25f0a04SGreg Roach        foreach ($this->getFacts($facts, true) as $event) {
840a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
841d93f11b5SGreg Roach            if ($event->getDate()->isOK() && !$event->getPlace()->isEmpty()) {
842d93f11b5SGreg Roach                $joiner = ' — ';
843d93f11b5SGreg Roach            } else {
844d93f11b5SGreg Roach                $joiner = '';
845d93f11b5SGreg Roach            }
846a25f0a04SGreg Roach            if ($event->getDate()->isOK() || !$event->getPlace()->isEmpty()) {
847a25f0a04SGreg Roach                switch ($style) {
848a25f0a04SGreg Roach                    case 1:
849d93f11b5SGreg Roach                        return '<br><em>' . $event->getLabel() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
850a25f0a04SGreg Roach                    case 2:
851d93f11b5SGreg Roach                        return '<dl><dt class="label">' . $event->getLabel() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
852a25f0a04SGreg Roach                }
853a25f0a04SGreg Roach            }
854a25f0a04SGreg Roach        }
855cbc1590aSGreg Roach
856a25f0a04SGreg Roach        return '';
857a25f0a04SGreg Roach    }
858a25f0a04SGreg Roach
859a25f0a04SGreg Roach    /**
860a25f0a04SGreg Roach     * Find individuals linked to this record.
861a25f0a04SGreg Roach     *
862a25f0a04SGreg Roach     * @param string $link
863a25f0a04SGreg Roach     *
864360dbd2cSGreg Roach     * @return Individual[]
865a25f0a04SGreg Roach     */
86676f666f4SGreg Roach    public function linkedIndividuals(string $link): array
867c1010edaSGreg Roach    {
868a25f0a04SGreg Roach        $rows = Database::prepare(
86924ec66ceSGreg Roach            "SELECT i_id AS xref, i_gedcom AS gedcom" .
870a25f0a04SGreg Roach            " FROM `##individuals`" .
87181088023SGreg Roach            " JOIN `##link` ON i_file = l_file AND i_id = l_from" .
87281088023SGreg Roach            " LEFT JOIN `##name` ON i_file = n_file AND i_id = n_id AND n_num = 0" .
87381088023SGreg Roach            " WHERE i_file = :tree_id AND l_type = :link AND l_to = :xref" .
87481088023SGreg Roach            " ORDER BY n_sort COLLATE :collation"
87513abd6f3SGreg Roach        )->execute([
87681088023SGreg Roach            'tree_id'   => $this->tree->getTreeId(),
87781088023SGreg Roach            'link'      => $link,
87881088023SGreg Roach            'xref'      => $this->xref,
87981088023SGreg Roach            'collation' => I18N::collation(),
88013abd6f3SGreg Roach        ])->fetchAll();
881a25f0a04SGreg Roach
88213abd6f3SGreg Roach        $list = [];
883a25f0a04SGreg Roach        foreach ($rows as $row) {
88424ec66ceSGreg Roach            $record = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
885a25f0a04SGreg Roach            if ($record->canShowName()) {
886a25f0a04SGreg Roach                $list[] = $record;
887a25f0a04SGreg Roach            }
888a25f0a04SGreg Roach        }
889cbc1590aSGreg Roach
890a25f0a04SGreg Roach        return $list;
891a25f0a04SGreg Roach    }
892a25f0a04SGreg Roach
893a25f0a04SGreg Roach    /**
894a25f0a04SGreg Roach     * Find families linked to this record.
895a25f0a04SGreg Roach     *
896a25f0a04SGreg Roach     * @param string $link
897a25f0a04SGreg Roach     *
898360dbd2cSGreg Roach     * @return Family[]
899a25f0a04SGreg Roach     */
90076f666f4SGreg Roach    public function linkedFamilies(string $link): array
901c1010edaSGreg Roach    {
902a25f0a04SGreg Roach        $rows = Database::prepare(
90324ec66ceSGreg Roach            "SELECT f_id AS xref, f_gedcom AS gedcom" .
904a25f0a04SGreg Roach            " FROM `##families`" .
90581088023SGreg Roach            " JOIN `##link` ON f_file = l_file AND f_id = l_from" .
90681088023SGreg Roach            " LEFT JOIN `##name` ON f_file = n_file AND f_id = n_id AND n_num = 0" .
90781088023SGreg Roach            " WHERE f_file = :tree_id AND l_type = :link AND l_to = :xref"
90813abd6f3SGreg Roach        )->execute([
90981088023SGreg Roach            'tree_id' => $this->tree->getTreeId(),
91081088023SGreg Roach            'link'    => $link,
91181088023SGreg Roach            'xref'    => $this->xref,
91213abd6f3SGreg Roach        ])->fetchAll();
913a25f0a04SGreg Roach
91413abd6f3SGreg Roach        $list = [];
915a25f0a04SGreg Roach        foreach ($rows as $row) {
91624ec66ceSGreg Roach            $record = Family::getInstance($row->xref, $this->tree, $row->gedcom);
917a25f0a04SGreg Roach            if ($record->canShowName()) {
918a25f0a04SGreg Roach                $list[] = $record;
919a25f0a04SGreg Roach            }
920a25f0a04SGreg Roach        }
921cbc1590aSGreg Roach
922a25f0a04SGreg Roach        return $list;
923a25f0a04SGreg Roach    }
924a25f0a04SGreg Roach
925a25f0a04SGreg Roach    /**
926a25f0a04SGreg Roach     * Find sources linked to this record.
927a25f0a04SGreg Roach     *
928a25f0a04SGreg Roach     * @param string $link
929a25f0a04SGreg Roach     *
930360dbd2cSGreg Roach     * @return Source[]
931a25f0a04SGreg Roach     */
93276f666f4SGreg Roach    public function linkedSources(string $link): array
933c1010edaSGreg Roach    {
934a25f0a04SGreg Roach        $rows = Database::prepare(
93524ec66ceSGreg Roach            "SELECT s_id AS xref, s_gedcom AS gedcom" .
936a25f0a04SGreg Roach            " FROM `##sources`" .
93781088023SGreg Roach            " JOIN `##link` ON s_file = l_file AND s_id = l_from" .
93881088023SGreg Roach            " WHERE s_file = :tree_id AND l_type = :link AND l_to = :xref" .
93981088023SGreg Roach            " ORDER BY s_name COLLATE :collation"
94013abd6f3SGreg Roach        )->execute([
94181088023SGreg Roach            'tree_id'   => $this->tree->getTreeId(),
94281088023SGreg Roach            'link'      => $link,
94381088023SGreg Roach            'xref'      => $this->xref,
94481088023SGreg Roach            'collation' => I18N::collation(),
94513abd6f3SGreg Roach        ])->fetchAll();
946a25f0a04SGreg Roach
94713abd6f3SGreg Roach        $list = [];
948a25f0a04SGreg Roach        foreach ($rows as $row) {
94924ec66ceSGreg Roach            $record = Source::getInstance($row->xref, $this->tree, $row->gedcom);
950a25f0a04SGreg Roach            if ($record->canShowName()) {
951a25f0a04SGreg Roach                $list[] = $record;
952a25f0a04SGreg Roach            }
953a25f0a04SGreg Roach        }
954cbc1590aSGreg Roach
955a25f0a04SGreg Roach        return $list;
956a25f0a04SGreg Roach    }
957a25f0a04SGreg Roach
958a25f0a04SGreg Roach    /**
959a25f0a04SGreg Roach     * Find media objects linked to this record.
960a25f0a04SGreg Roach     *
961a25f0a04SGreg Roach     * @param string $link
962a25f0a04SGreg Roach     *
963360dbd2cSGreg Roach     * @return Media[]
964a25f0a04SGreg Roach     */
96576f666f4SGreg Roach    public function linkedMedia(string $link): array
966c1010edaSGreg Roach    {
967a25f0a04SGreg Roach        $rows = Database::prepare(
96824ec66ceSGreg Roach            "SELECT m_id AS xref, m_gedcom AS gedcom" .
969a25f0a04SGreg Roach            " FROM `##media`" .
97081088023SGreg Roach            " JOIN `##link` ON m_file = l_file AND m_id = l_from" .
97164b90bf1SGreg Roach            " WHERE m_file = :tree_id AND l_type = :link AND l_to = :xref"
97213abd6f3SGreg Roach        )->execute([
97381088023SGreg Roach            'tree_id' => $this->tree->getTreeId(),
97481088023SGreg Roach            'link'    => $link,
97581088023SGreg Roach            'xref'    => $this->xref,
97613abd6f3SGreg Roach        ])->fetchAll();
977a25f0a04SGreg Roach
97813abd6f3SGreg Roach        $list = [];
979a25f0a04SGreg Roach        foreach ($rows as $row) {
98024ec66ceSGreg Roach            $record = Media::getInstance($row->xref, $this->tree, $row->gedcom);
981a25f0a04SGreg Roach            if ($record->canShowName()) {
982a25f0a04SGreg Roach                $list[] = $record;
983a25f0a04SGreg Roach            }
984a25f0a04SGreg Roach        }
985cbc1590aSGreg Roach
986a25f0a04SGreg Roach        return $list;
987a25f0a04SGreg Roach    }
988a25f0a04SGreg Roach
989a25f0a04SGreg Roach    /**
990a25f0a04SGreg Roach     * Find notes linked to this record.
991a25f0a04SGreg Roach     *
992a25f0a04SGreg Roach     * @param string $link
993a25f0a04SGreg Roach     *
994a25f0a04SGreg Roach     * @return Note[]
995a25f0a04SGreg Roach     */
99676f666f4SGreg Roach    public function linkedNotes(string $link): array
997c1010edaSGreg Roach    {
998a25f0a04SGreg Roach        $rows = Database::prepare(
99924ec66ceSGreg Roach            "SELECT o_id AS xref, o_gedcom AS gedcom" .
1000a25f0a04SGreg Roach            " FROM `##other`" .
100181088023SGreg Roach            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
100281088023SGreg Roach            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
100381088023SGreg Roach            " WHERE o_file = :tree_id AND o_type = 'NOTE' AND l_type = :link AND l_to = :xref" .
100481088023SGreg Roach            " ORDER BY n_sort COLLATE :collation"
100513abd6f3SGreg Roach        )->execute([
100681088023SGreg Roach            'tree_id'   => $this->tree->getTreeId(),
100781088023SGreg Roach            'link'      => $link,
100881088023SGreg Roach            'xref'      => $this->xref,
100981088023SGreg Roach            'collation' => I18N::collation(),
101013abd6f3SGreg Roach        ])->fetchAll();
1011a25f0a04SGreg Roach
101213abd6f3SGreg Roach        $list = [];
1013a25f0a04SGreg Roach        foreach ($rows as $row) {
101424ec66ceSGreg Roach            $record = Note::getInstance($row->xref, $this->tree, $row->gedcom);
1015a25f0a04SGreg Roach            if ($record->canShowName()) {
1016a25f0a04SGreg Roach                $list[] = $record;
1017a25f0a04SGreg Roach            }
1018a25f0a04SGreg Roach        }
1019cbc1590aSGreg Roach
1020a25f0a04SGreg Roach        return $list;
1021a25f0a04SGreg Roach    }
1022a25f0a04SGreg Roach
1023a25f0a04SGreg Roach    /**
1024a25f0a04SGreg Roach     * Find repositories linked to this record.
1025a25f0a04SGreg Roach     *
1026a25f0a04SGreg Roach     * @param string $link
1027a25f0a04SGreg Roach     *
1028360dbd2cSGreg Roach     * @return Repository[]
1029a25f0a04SGreg Roach     */
103076f666f4SGreg Roach    public function linkedRepositories(string $link): array
1031c1010edaSGreg Roach    {
1032a25f0a04SGreg Roach        $rows = Database::prepare(
103324ec66ceSGreg Roach            "SELECT o_id AS xref, o_gedcom AS gedcom" .
1034a25f0a04SGreg Roach            " FROM `##other`" .
103581088023SGreg Roach            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
103681088023SGreg Roach            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
103781088023SGreg Roach            " WHERE o_file = :tree_id AND o_type = 'REPO' AND l_type = :link AND l_to = :xref" .
103851a671c6SGreg Roach            " ORDER BY n_sort COLLATE :collation"
103913abd6f3SGreg Roach        )->execute([
104081088023SGreg Roach            'tree_id'   => $this->tree->getTreeId(),
104181088023SGreg Roach            'link'      => $link,
104281088023SGreg Roach            'xref'      => $this->xref,
104381088023SGreg Roach            'collation' => I18N::collation(),
104413abd6f3SGreg Roach        ])->fetchAll();
1045a25f0a04SGreg Roach
104613abd6f3SGreg Roach        $list = [];
1047a25f0a04SGreg Roach        foreach ($rows as $row) {
104824ec66ceSGreg Roach            $record = Repository::getInstance($row->xref, $this->tree, $row->gedcom);
1049a25f0a04SGreg Roach            if ($record->canShowName()) {
1050a25f0a04SGreg Roach                $list[] = $record;
1051a25f0a04SGreg Roach            }
1052a25f0a04SGreg Roach        }
1053cbc1590aSGreg Roach
1054a25f0a04SGreg Roach        return $list;
1055a25f0a04SGreg Roach    }
1056a25f0a04SGreg Roach
1057a25f0a04SGreg Roach    /**
1058a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
1059a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
1060a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
1061a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
1062a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
1063a25f0a04SGreg Roach     *
1064a25f0a04SGreg Roach     * @param string $event_type
1065a25f0a04SGreg Roach     *
1066a25f0a04SGreg Roach     * @return Date[]
1067a25f0a04SGreg Roach     */
106876f666f4SGreg Roach    public function getAllEventDates(string $event_type): array
1069c1010edaSGreg Roach    {
107013abd6f3SGreg Roach        $dates = [];
1071a25f0a04SGreg Roach        foreach ($this->getFacts($event_type) as $event) {
1072a25f0a04SGreg Roach            if ($event->getDate()->isOK()) {
1073a25f0a04SGreg Roach                $dates[] = $event->getDate();
1074a25f0a04SGreg Roach            }
1075a25f0a04SGreg Roach        }
1076a25f0a04SGreg Roach
1077a25f0a04SGreg Roach        return $dates;
1078a25f0a04SGreg Roach    }
1079a25f0a04SGreg Roach
1080a25f0a04SGreg Roach    /**
1081a25f0a04SGreg Roach     * Get all the places for a particular type of event
1082a25f0a04SGreg Roach     *
1083a25f0a04SGreg Roach     * @param string $event_type
1084a25f0a04SGreg Roach     *
10854080d558SGreg Roach     * @return Place[]
1086a25f0a04SGreg Roach     */
108776f666f4SGreg Roach    public function getAllEventPlaces(string $event_type): array
1088c1010edaSGreg Roach    {
108913abd6f3SGreg Roach        $places = [];
1090a25f0a04SGreg Roach        foreach ($this->getFacts($event_type) as $event) {
1091a25f0a04SGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->getGedcom(), $ged_places)) {
1092a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
109316d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
1094a25f0a04SGreg Roach                }
1095a25f0a04SGreg Roach            }
1096a25f0a04SGreg Roach        }
1097a25f0a04SGreg Roach
1098a25f0a04SGreg Roach        return $places;
1099a25f0a04SGreg Roach    }
1100a25f0a04SGreg Roach
1101a25f0a04SGreg Roach    /**
1102a25f0a04SGreg Roach     * Get the first (i.e. prefered) Fact for the given fact type
1103a25f0a04SGreg Roach     *
1104a25f0a04SGreg Roach     * @param string $tag
1105a25f0a04SGreg Roach     *
1106a25f0a04SGreg Roach     * @return Fact|null
1107a25f0a04SGreg Roach     */
110876f666f4SGreg Roach    public function getFirstFact(string $tag)
1109c1010edaSGreg Roach    {
1110a25f0a04SGreg Roach        foreach ($this->getFacts() as $fact) {
1111a25f0a04SGreg Roach            if ($fact->getTag() === $tag) {
1112a25f0a04SGreg Roach                return $fact;
1113a25f0a04SGreg Roach            }
1114a25f0a04SGreg Roach        }
1115a25f0a04SGreg Roach
1116a25f0a04SGreg Roach        return null;
1117a25f0a04SGreg Roach    }
1118a25f0a04SGreg Roach
1119a25f0a04SGreg Roach    /**
1120a25f0a04SGreg Roach     * The facts and events for this record.
1121a25f0a04SGreg Roach     *
1122a25f0a04SGreg Roach     * @param string   $filter
1123cbc1590aSGreg Roach     * @param bool     $sort
1124cbc1590aSGreg Roach     * @param int|null $access_level
1125cbc1590aSGreg Roach     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1126a25f0a04SGreg Roach     *
1127a25f0a04SGreg Roach     * @return Fact[]
1128a25f0a04SGreg Roach     */
112976f666f4SGreg Roach    public function getFacts(string $filter = null, bool $sort = false, int $access_level = null, bool $override = false): array
1130c1010edaSGreg Roach    {
11314b9ff166SGreg Roach        if ($access_level === null) {
11324b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
11334b9ff166SGreg Roach        }
11344b9ff166SGreg Roach
113513abd6f3SGreg Roach        $facts = [];
1136a25f0a04SGreg Roach        if ($this->canShow($access_level) || $override) {
1137a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
11383a7d762dSGreg Roach                if (($filter === null || preg_match('/^' . $filter . '$/', $fact->getTag())) && $fact->canShow($access_level)) {
1139a25f0a04SGreg Roach                    $facts[] = $fact;
1140a25f0a04SGreg Roach                }
1141a25f0a04SGreg Roach            }
1142a25f0a04SGreg Roach        }
1143a25f0a04SGreg Roach        if ($sort) {
11443d7a8a4cSGreg Roach            Functions::sortFacts($facts);
1145a25f0a04SGreg Roach        }
1146cbc1590aSGreg Roach
1147a25f0a04SGreg Roach        return $facts;
1148a25f0a04SGreg Roach    }
1149a25f0a04SGreg Roach
1150a25f0a04SGreg Roach    /**
1151a25f0a04SGreg Roach     * Get the last-change timestamp for this record, either as a formatted string
1152a25f0a04SGreg Roach     * (for display) or as a unix timestamp (for sorting)
1153a25f0a04SGreg Roach     *
1154cbc1590aSGreg Roach     * @param bool $sorting
1155a25f0a04SGreg Roach     *
1156*589feda3SGreg Roach     * @return string|int
1157a25f0a04SGreg Roach     */
115876f666f4SGreg Roach    public function lastChangeTimestamp(bool $sorting = false)
1159c1010edaSGreg Roach    {
1160a25f0a04SGreg Roach        $chan = $this->getFirstFact('CHAN');
1161a25f0a04SGreg Roach
1162a25f0a04SGreg Roach        if ($chan) {
1163a25f0a04SGreg Roach            // The record does have a CHAN event
1164f5b60decSGreg Roach            $d = $chan->getDate()->minimumDate();
1165a25f0a04SGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->getGedcom(), $match)) {
1166a25f0a04SGreg Roach                $t = mktime((int) $match[1], (int) $match[2], (int) $match[3], (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1167a25f0a04SGreg Roach            } elseif (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->getGedcom(), $match)) {
1168a25f0a04SGreg Roach                $t = mktime((int) $match[1], (int) $match[2], 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1169a25f0a04SGreg Roach            } else {
1170a25f0a04SGreg Roach                $t = mktime(0, 0, 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1171a25f0a04SGreg Roach            }
1172a25f0a04SGreg Roach            if ($sorting) {
1173a25f0a04SGreg Roach                return $t;
1174b2ce94c6SRico Sonntag            }
1175b2ce94c6SRico Sonntag
11763d7a8a4cSGreg Roach            return strip_tags(FunctionsDate::formatTimestamp($t));
1177a25f0a04SGreg Roach        }
1178b2ce94c6SRico Sonntag
1179a25f0a04SGreg Roach        // The record does not have a CHAN event
1180a25f0a04SGreg Roach        if ($sorting) {
1181a25f0a04SGreg Roach            return '0';
1182b2ce94c6SRico Sonntag        }
1183b2ce94c6SRico Sonntag
118466b90994SGreg Roach        return '';
1185a25f0a04SGreg Roach    }
1186a25f0a04SGreg Roach
1187a25f0a04SGreg Roach    /**
1188a25f0a04SGreg Roach     * Get the last-change user for this record
1189a25f0a04SGreg Roach     *
1190a25f0a04SGreg Roach     * @return string
1191a25f0a04SGreg Roach     */
1192c1010edaSGreg Roach    public function lastChangeUser()
1193c1010edaSGreg Roach    {
1194a25f0a04SGreg Roach        $chan = $this->getFirstFact('CHAN');
1195a25f0a04SGreg Roach
1196a25f0a04SGreg Roach        if ($chan === null) {
1197a25f0a04SGreg Roach            return I18N::translate('Unknown');
1198b2ce94c6SRico Sonntag        }
1199b2ce94c6SRico Sonntag
1200a25f0a04SGreg Roach        $chan_user = $chan->getAttribute('_WT_USER');
1201baacc364SGreg Roach        if ($chan_user === '') {
1202a25f0a04SGreg Roach            return I18N::translate('Unknown');
1203b2ce94c6SRico Sonntag        }
1204b2ce94c6SRico Sonntag
1205a25f0a04SGreg Roach        return $chan_user;
1206a25f0a04SGreg Roach    }
1207a25f0a04SGreg Roach
1208a25f0a04SGreg Roach    /**
1209a25f0a04SGreg Roach     * Add a new fact to this record
1210a25f0a04SGreg Roach     *
1211a25f0a04SGreg Roach     * @param string $gedcom
1212cbc1590aSGreg Roach     * @param bool   $update_chan
12137e96c925SGreg Roach     *
12147e96c925SGreg Roach     * @return void
1215a25f0a04SGreg Roach     */
121676f666f4SGreg Roach    public function createFact(string $gedcom, bool $update_chan)
1217c1010edaSGreg Roach    {
1218a25f0a04SGreg Roach        $this->updateFact(null, $gedcom, $update_chan);
1219a25f0a04SGreg Roach    }
1220a25f0a04SGreg Roach
1221a25f0a04SGreg Roach    /**
1222a25f0a04SGreg Roach     * Delete a fact from this record
1223a25f0a04SGreg Roach     *
1224a25f0a04SGreg Roach     * @param string $fact_id
1225cbc1590aSGreg Roach     * @param bool   $update_chan
12267e96c925SGreg Roach     *
12277e96c925SGreg Roach     * @return void
1228a25f0a04SGreg Roach     */
122976f666f4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan)
1230c1010edaSGreg Roach    {
1231db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
1232a25f0a04SGreg Roach    }
1233a25f0a04SGreg Roach
1234a25f0a04SGreg Roach    /**
1235a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
1236a25f0a04SGreg Roach     *
1237a25f0a04SGreg Roach     * @param string $fact_id
1238a25f0a04SGreg Roach     * @param string $gedcom
1239cbc1590aSGreg Roach     * @param bool   $update_chan
1240a25f0a04SGreg Roach     *
12417e96c925SGreg Roach     * @return void
12427e96c925SGreg Roach     * @throws Exception
1243a25f0a04SGreg Roach     */
124476f666f4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan)
1245c1010edaSGreg Roach    {
1246a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1247a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1248a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1249a25f0a04SGreg Roach
1250a25f0a04SGreg Roach        if ($this->pending === '') {
12517e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
1252a25f0a04SGreg Roach        }
1253db7bb364SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . WT_REGEX_TAG . '/', $gedcom)) {
12547e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1255a25f0a04SGreg Roach        }
1256a25f0a04SGreg Roach
1257a25f0a04SGreg Roach        if ($this->pending) {
1258a25f0a04SGreg Roach            $old_gedcom = $this->pending;
1259a25f0a04SGreg Roach        } else {
1260a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
1261a25f0a04SGreg Roach        }
1262a25f0a04SGreg Roach
1263a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
1264a25f0a04SGreg Roach        list($new_gedcom) = explode("\n", $old_gedcom, 2);
1265a25f0a04SGreg Roach
1266a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
12674b9ff166SGreg Roach        foreach ($this->getFacts(null, false, Auth::PRIV_HIDE) as $fact) {
1268a25f0a04SGreg Roach            if (!$fact->isPendingDeletion()) {
1269a25f0a04SGreg Roach                if ($fact->getFactId() === $fact_id) {
1270db7bb364SGreg Roach                    if ($gedcom !== '') {
1271a25f0a04SGreg Roach                        $new_gedcom .= "\n" . $gedcom;
1272a25f0a04SGreg Roach                    }
1273a25f0a04SGreg Roach                    $fact_id = true; // Only replace/delete one copy of a duplicate fact
1274a25f0a04SGreg Roach                } elseif ($fact->getTag() != 'CHAN' || !$update_chan) {
1275a25f0a04SGreg Roach                    $new_gedcom .= "\n" . $fact->getGedcom();
1276a25f0a04SGreg Roach                }
1277a25f0a04SGreg Roach            }
1278a25f0a04SGreg Roach        }
1279a25f0a04SGreg Roach        if ($update_chan) {
12804e9cf5abSGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1281a25f0a04SGreg Roach        }
1282a25f0a04SGreg Roach
1283a25f0a04SGreg Roach        // Adding a new fact
1284a25f0a04SGreg Roach        if (!$fact_id) {
1285a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
1286a25f0a04SGreg Roach        }
1287a25f0a04SGreg Roach
1288a25f0a04SGreg Roach        if ($new_gedcom != $old_gedcom) {
1289a25f0a04SGreg Roach            // Save the changes
1290a25f0a04SGreg Roach            Database::prepare(
1291a25f0a04SGreg Roach                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
129213abd6f3SGreg Roach            )->execute([
1293518bbdc1SGreg Roach                $this->tree->getTreeId(),
1294a25f0a04SGreg Roach                $this->xref,
1295a25f0a04SGreg Roach                $old_gedcom,
1296a25f0a04SGreg Roach                $new_gedcom,
1297cbc1590aSGreg Roach                Auth::id(),
129813abd6f3SGreg Roach            ]);
1299a25f0a04SGreg Roach
1300a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1301a25f0a04SGreg Roach
1302a25f0a04SGreg Roach            if (Auth::user()->getPreference('auto_accept')) {
1303cc5684fdSGreg Roach                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1304a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1305a25f0a04SGreg Roach                $this->pending = null;
1306a25f0a04SGreg Roach            }
1307a25f0a04SGreg Roach        }
1308a25f0a04SGreg Roach        $this->parseFacts();
1309a25f0a04SGreg Roach    }
1310a25f0a04SGreg Roach
1311a25f0a04SGreg Roach    /**
1312a25f0a04SGreg Roach     * Update this record
1313a25f0a04SGreg Roach     *
1314a25f0a04SGreg Roach     * @param string $gedcom
1315cbc1590aSGreg Roach     * @param bool   $update_chan
13167e96c925SGreg Roach     *
13177e96c925SGreg Roach     * @return void
1318a25f0a04SGreg Roach     */
131976f666f4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan)
1320c1010edaSGreg Roach    {
1321a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1322a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1323a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1324a25f0a04SGreg Roach
1325a25f0a04SGreg Roach        // Update the CHAN record
1326a25f0a04SGreg Roach        if ($update_chan) {
1327a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1328a25f0a04SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1329a25f0a04SGreg Roach        }
1330a25f0a04SGreg Roach
1331a25f0a04SGreg Roach        // Create a pending change
1332a25f0a04SGreg Roach        Database::prepare(
1333a25f0a04SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
133413abd6f3SGreg Roach        )->execute([
1335518bbdc1SGreg Roach            $this->tree->getTreeId(),
1336a25f0a04SGreg Roach            $this->xref,
1337a25f0a04SGreg Roach            $this->getGedcom(),
1338a25f0a04SGreg Roach            $gedcom,
1339cbc1590aSGreg Roach            Auth::id(),
134013abd6f3SGreg Roach        ]);
1341a25f0a04SGreg Roach
1342a25f0a04SGreg Roach        // Clear the cache
1343a25f0a04SGreg Roach        $this->pending = $gedcom;
1344a25f0a04SGreg Roach
1345a25f0a04SGreg Roach        // Accept this pending change
1346a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1347cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1348a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1349a25f0a04SGreg Roach            $this->pending = null;
1350a25f0a04SGreg Roach        }
1351a25f0a04SGreg Roach
1352a25f0a04SGreg Roach        $this->parseFacts();
1353a25f0a04SGreg Roach
1354847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1355a25f0a04SGreg Roach    }
1356a25f0a04SGreg Roach
1357a25f0a04SGreg Roach    /**
1358a25f0a04SGreg Roach     * Delete this record
1359b874da82SGreg Roach     *
1360b874da82SGreg Roach     * @return void
1361a25f0a04SGreg Roach     */
1362c1010edaSGreg Roach    public function deleteRecord()
1363c1010edaSGreg Roach    {
1364a25f0a04SGreg Roach        // Create a pending change
13654c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1366a25f0a04SGreg Roach            Database::prepare(
1367a25f0a04SGreg Roach                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, '', ?)"
136813abd6f3SGreg Roach            )->execute([
1369518bbdc1SGreg Roach                $this->tree->getTreeId(),
1370a25f0a04SGreg Roach                $this->xref,
1371a25f0a04SGreg Roach                $this->getGedcom(),
1372a25f0a04SGreg Roach                Auth::id(),
137313abd6f3SGreg Roach            ]);
13744c0b5256SGreg Roach        }
1375a25f0a04SGreg Roach
13764c0b5256SGreg Roach        // Auto-accept this pending change
1377a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1378cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1379a25f0a04SGreg Roach        }
1380a25f0a04SGreg Roach
1381a25f0a04SGreg Roach        // Clear the cache
1382a25f0a04SGreg Roach        self::$gedcom_record_cache  = null;
1383a25f0a04SGreg Roach        self::$pending_record_cache = null;
1384a25f0a04SGreg Roach
1385847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1386a25f0a04SGreg Roach    }
1387a25f0a04SGreg Roach
1388a25f0a04SGreg Roach    /**
1389a25f0a04SGreg Roach     * Remove all links from this record to $xref
1390a25f0a04SGreg Roach     *
1391a25f0a04SGreg Roach     * @param string $xref
1392cbc1590aSGreg Roach     * @param bool   $update_chan
13937e96c925SGreg Roach     *
13947e96c925SGreg Roach     * @return void
1395a25f0a04SGreg Roach     */
139676f666f4SGreg Roach    public function removeLinks(string $xref, bool $update_chan)
1397c1010edaSGreg Roach    {
1398a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1399a25f0a04SGreg Roach
1400a25f0a04SGreg Roach        foreach ($this->getFacts() as $fact) {
1401baacc364SGreg Roach            if ($fact->getValue() === $value) {
1402a25f0a04SGreg Roach                $this->deleteFact($fact->getFactId(), $update_chan);
1403a25f0a04SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . WT_REGEX_TAG . ' ' . $value . '/', $fact->getGedcom(), $matches, PREG_SET_ORDER)) {
1404a25f0a04SGreg Roach                $gedcom = $fact->getGedcom();
1405a25f0a04SGreg Roach                foreach ($matches as $match) {
1406a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1407a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1408a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1409a25f0a04SGreg Roach                }
1410a25f0a04SGreg Roach                $this->updateFact($fact->getFactId(), $gedcom, $update_chan);
1411a25f0a04SGreg Roach            }
1412a25f0a04SGreg Roach        }
1413a25f0a04SGreg Roach    }
1414a25f0a04SGreg Roach}
1415