xref: /webtrees/app/GedcomRecord.php (revision 8f53f488f13e53e44dc48778e8f51ec9f91352dd)
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 */
1676692c8bSGreg Roachnamespace Fisharebest\Webtrees;
1776692c8bSGreg Roach
183d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\Functions;
193d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsDate;
203d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
213d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsPrint;
2279529c87SGreg Roachuse stdClass;
23a25f0a04SGreg Roach
24a25f0a04SGreg Roach/**
2576692c8bSGreg Roach * A GEDCOM object.
26a25f0a04SGreg Roach */
27c1010edaSGreg Roachclass GedcomRecord
28c1010edaSGreg Roach{
29a25f0a04SGreg Roach    const RECORD_TYPE = 'UNKNOWN';
30225e381fSGreg Roach    const ROUTE_NAME  = 'record';
31a25f0a04SGreg Roach
32a25f0a04SGreg Roach    /** @var string The record identifier */
33a25f0a04SGreg Roach    protected $xref;
34a25f0a04SGreg Roach
35000959d9SGreg Roach    /** @var Tree  The family tree to which this record belongs */
36000959d9SGreg Roach    protected $tree;
37a25f0a04SGreg Roach
38a25f0a04SGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
39a25f0a04SGreg Roach    protected $gedcom;
40a25f0a04SGreg Roach
41a25f0a04SGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
42a25f0a04SGreg Roach    protected $pending;
43a25f0a04SGreg Roach
44a25f0a04SGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
45a25f0a04SGreg Roach    protected $facts;
46a25f0a04SGreg Roach
47cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_PRIVATE */
48a25f0a04SGreg Roach    private $disp_public;
49a25f0a04SGreg Roach
50cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_USER */
51a25f0a04SGreg Roach    private $disp_user;
52a25f0a04SGreg Roach
53cbc1590aSGreg Roach    /** @var bool Can we display details of this record to Auth::PRIV_NONE */
54a25f0a04SGreg Roach    private $disp_none;
55a25f0a04SGreg Roach
56a25f0a04SGreg Roach    /** @var string[][] All the names of this individual */
57bdb3725aSGreg Roach    protected $getAllNames;
58a25f0a04SGreg Roach
59cbc1590aSGreg Roach    /** @var int Cached result */
60bdb3725aSGreg Roach    protected $getPrimaryName;
61a25f0a04SGreg Roach
62cbc1590aSGreg Roach    /** @var int Cached result */
63bdb3725aSGreg Roach    protected $getSecondaryName;
64a25f0a04SGreg Roach
6576692c8bSGreg Roach    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
66395f0fe0SGreg Roach    protected static $gedcom_record_cache;
671ae87ce5SGreg Roach
6879529c87SGreg Roach    /** @var stdClass[][] Fetch all pending edits in one database query */
69a25f0a04SGreg Roach    private static $pending_record_cache;
70a25f0a04SGreg Roach
71a25f0a04SGreg Roach    /**
72a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
73a25f0a04SGreg Roach     *
74a25f0a04SGreg Roach     * @param string      $xref
75a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
76a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
77a25f0a04SGreg Roach     *                             empty string for records with pending deletions
7824ec66ceSGreg Roach     * @param Tree        $tree
79a25f0a04SGreg Roach     */
80c1010edaSGreg Roach    public function __construct($xref, $gedcom, $pending, $tree)
81c1010edaSGreg Roach    {
82a25f0a04SGreg Roach        $this->xref    = $xref;
83a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
84a25f0a04SGreg Roach        $this->pending = $pending;
8524ec66ceSGreg Roach        $this->tree    = $tree;
86a25f0a04SGreg Roach
87a25f0a04SGreg Roach        $this->parseFacts();
88a25f0a04SGreg Roach    }
89a25f0a04SGreg Roach
90a25f0a04SGreg Roach    /**
91a25f0a04SGreg Roach     * Split the record into facts
92a25f0a04SGreg Roach     */
93c1010edaSGreg Roach    private function parseFacts()
94c1010edaSGreg Roach    {
95a25f0a04SGreg Roach        // Split the record into facts
96a25f0a04SGreg Roach        if ($this->gedcom) {
97a25f0a04SGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
98a25f0a04SGreg Roach            array_shift($gedcom_facts);
99a25f0a04SGreg Roach        } else {
10013abd6f3SGreg Roach            $gedcom_facts = [];
101a25f0a04SGreg Roach        }
102a25f0a04SGreg Roach        if ($this->pending) {
103a25f0a04SGreg Roach            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
104a25f0a04SGreg Roach            array_shift($pending_facts);
105a25f0a04SGreg Roach        } else {
10613abd6f3SGreg Roach            $pending_facts = [];
107a25f0a04SGreg Roach        }
108a25f0a04SGreg Roach
10913abd6f3SGreg Roach        $this->facts = [];
110a25f0a04SGreg Roach
111a25f0a04SGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
112a25f0a04SGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
113a25f0a04SGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts)) {
114a25f0a04SGreg Roach                $fact->setPendingDeletion();
115a25f0a04SGreg Roach            }
116a25f0a04SGreg Roach            $this->facts[] = $fact;
117a25f0a04SGreg Roach        }
118a25f0a04SGreg Roach        foreach ($pending_facts as $pending_fact) {
119a25f0a04SGreg Roach            if (!in_array($pending_fact, $gedcom_facts)) {
120a25f0a04SGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
121a25f0a04SGreg Roach                $fact->setPendingAddition();
122a25f0a04SGreg Roach                $this->facts[] = $fact;
123a25f0a04SGreg Roach            }
124a25f0a04SGreg Roach        }
125a25f0a04SGreg Roach    }
126a25f0a04SGreg Roach
127a25f0a04SGreg Roach    /**
128a25f0a04SGreg Roach     * Get an instance of a GedcomRecord object. For single records,
129a25f0a04SGreg Roach     * we just receive the XREF. For bulk records (such as lists
130a25f0a04SGreg Roach     * and search results) we can receive the GEDCOM data as well.
131a25f0a04SGreg Roach     *
132a25f0a04SGreg Roach     * @param string      $xref
13324ec66ceSGreg Roach     * @param Tree        $tree
134a25f0a04SGreg Roach     * @param string|null $gedcom
135a25f0a04SGreg Roach     *
136a25f0a04SGreg Roach     * @throws \Exception
137cbc1590aSGreg Roach     *
13884658595SGreg Roach     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|null
139a25f0a04SGreg Roach     */
140c1010edaSGreg Roach    public static function getInstance($xref, Tree $tree, $gedcom = null)
141c1010edaSGreg Roach    {
14224ec66ceSGreg Roach        $tree_id = $tree->getTreeId();
14324ec66ceSGreg Roach
144e71ef9d2SGreg Roach        // Is this record already in the cache?
14524ec66ceSGreg Roach        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
146e71ef9d2SGreg Roach            return self::$gedcom_record_cache[$xref][$tree_id];
147a25f0a04SGreg Roach        }
148a25f0a04SGreg Roach
149a25f0a04SGreg Roach        // Do we need to fetch the record from the database?
150a25f0a04SGreg Roach        if ($gedcom === null) {
15124ec66ceSGreg Roach            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
152a25f0a04SGreg Roach        }
153a25f0a04SGreg Roach
154a25f0a04SGreg Roach        // If we can edit, then we also need to be able to see pending records.
15594075df0SGreg Roach        if (Auth::isEditor($tree)) {
15624ec66ceSGreg Roach            if (!isset(self::$pending_record_cache[$tree_id])) {
157a25f0a04SGreg Roach                // Fetch all pending records in one database query
15813abd6f3SGreg Roach                self::$pending_record_cache[$tree_id] = [];
159a25f0a04SGreg Roach                $rows                                 = Database::prepare(
16094075df0SGreg Roach                    "SELECT xref, new_gedcom FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id ORDER BY change_id"
16113abd6f3SGreg Roach                )->execute([
162cbc1590aSGreg Roach                    'tree_id' => $tree_id,
16313abd6f3SGreg Roach                ])->fetchAll();
164a25f0a04SGreg Roach                foreach ($rows as $row) {
16524ec66ceSGreg Roach                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
166a25f0a04SGreg Roach                }
167a25f0a04SGreg Roach            }
168a25f0a04SGreg Roach
16924ec66ceSGreg Roach            if (isset(self::$pending_record_cache[$tree_id][$xref])) {
170a25f0a04SGreg Roach                // A pending edit exists for this record
17124ec66ceSGreg Roach                $pending = self::$pending_record_cache[$tree_id][$xref];
172a25f0a04SGreg Roach            } else {
173a25f0a04SGreg Roach                $pending = null;
174a25f0a04SGreg Roach            }
175a25f0a04SGreg Roach        } else {
176a25f0a04SGreg Roach            // There are no pending changes for this record
177a25f0a04SGreg Roach            $pending = null;
178a25f0a04SGreg Roach        }
179a25f0a04SGreg Roach
180a25f0a04SGreg Roach        // No such record exists
181a25f0a04SGreg Roach        if ($gedcom === null && $pending === null) {
182a25f0a04SGreg Roach            return null;
183a25f0a04SGreg Roach        }
184a25f0a04SGreg Roach
185a25f0a04SGreg Roach        // Create the object
186a25f0a04SGreg Roach        if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom . $pending, $match)) {
187a25f0a04SGreg Roach            $xref = $match[1]; // Collation - we may have requested I123 and found i123
188a25f0a04SGreg Roach            $type = $match[2];
189a25f0a04SGreg Roach        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
190a25f0a04SGreg Roach            $xref = $match[1];
191a25f0a04SGreg Roach            $type = $match[1];
192a25f0a04SGreg Roach        } elseif ($gedcom . $pending) {
193a25f0a04SGreg Roach            throw new \Exception('Unrecognized GEDCOM record: ' . $gedcom);
194a25f0a04SGreg Roach        } else {
195a25f0a04SGreg Roach            // A record with both pending creation and pending deletion
196a25f0a04SGreg Roach            $type = static::RECORD_TYPE;
197a25f0a04SGreg Roach        }
198a25f0a04SGreg Roach
199a25f0a04SGreg Roach        switch ($type) {
200a25f0a04SGreg Roach            case 'INDI':
20124ec66ceSGreg Roach                $record = new Individual($xref, $gedcom, $pending, $tree);
202a25f0a04SGreg Roach                break;
203a25f0a04SGreg Roach            case 'FAM':
20424ec66ceSGreg Roach                $record = new Family($xref, $gedcom, $pending, $tree);
205a25f0a04SGreg Roach                break;
206a25f0a04SGreg Roach            case 'SOUR':
20724ec66ceSGreg Roach                $record = new Source($xref, $gedcom, $pending, $tree);
208a25f0a04SGreg Roach                break;
209a25f0a04SGreg Roach            case 'OBJE':
21024ec66ceSGreg Roach                $record = new Media($xref, $gedcom, $pending, $tree);
211a25f0a04SGreg Roach                break;
212a25f0a04SGreg Roach            case 'REPO':
21324ec66ceSGreg Roach                $record = new Repository($xref, $gedcom, $pending, $tree);
214a25f0a04SGreg Roach                break;
215a25f0a04SGreg Roach            case 'NOTE':
21624ec66ceSGreg Roach                $record = new Note($xref, $gedcom, $pending, $tree);
217a25f0a04SGreg Roach                break;
218a25f0a04SGreg Roach            default:
21906ef8e02SGreg Roach                $record = new self($xref, $gedcom, $pending, $tree);
220a25f0a04SGreg Roach                break;
221a25f0a04SGreg Roach        }
222a25f0a04SGreg Roach
223a25f0a04SGreg Roach        // Store it in the cache
22424ec66ceSGreg Roach        self::$gedcom_record_cache[$xref][$tree_id] = $record;
225a25f0a04SGreg Roach
226a25f0a04SGreg Roach        return $record;
227a25f0a04SGreg Roach    }
228a25f0a04SGreg Roach
229a25f0a04SGreg Roach    /**
230a25f0a04SGreg Roach     * Fetch data from the database
231a25f0a04SGreg Roach     *
232a25f0a04SGreg Roach     * @param string $xref
233cbc1590aSGreg Roach     * @param int    $tree_id
234a25f0a04SGreg Roach     *
235a25f0a04SGreg Roach     * @return null|string
236a25f0a04SGreg Roach     */
237c1010edaSGreg Roach    protected static function fetchGedcomRecord($xref, $tree_id)
238c1010edaSGreg Roach    {
239a25f0a04SGreg Roach        // We don't know what type of object this is. Try each one in turn.
24064d9078aSGreg Roach        $data = Individual::fetchGedcomRecord($xref, $tree_id);
241a25f0a04SGreg Roach        if ($data) {
242a25f0a04SGreg Roach            return $data;
243a25f0a04SGreg Roach        }
24464d9078aSGreg Roach        $data = Family::fetchGedcomRecord($xref, $tree_id);
245a25f0a04SGreg Roach        if ($data) {
246a25f0a04SGreg Roach            return $data;
247a25f0a04SGreg Roach        }
24864d9078aSGreg Roach        $data = Source::fetchGedcomRecord($xref, $tree_id);
249a25f0a04SGreg Roach        if ($data) {
250a25f0a04SGreg Roach            return $data;
251a25f0a04SGreg Roach        }
25264d9078aSGreg Roach        $data = Repository::fetchGedcomRecord($xref, $tree_id);
253a25f0a04SGreg Roach        if ($data) {
254a25f0a04SGreg Roach            return $data;
255a25f0a04SGreg Roach        }
25664d9078aSGreg Roach        $data = Media::fetchGedcomRecord($xref, $tree_id);
257a25f0a04SGreg Roach        if ($data) {
258a25f0a04SGreg Roach            return $data;
259a25f0a04SGreg Roach        }
26064d9078aSGreg Roach        $data = Note::fetchGedcomRecord($xref, $tree_id);
261a25f0a04SGreg Roach        if ($data) {
262a25f0a04SGreg Roach            return $data;
263a25f0a04SGreg Roach        }
264c1010edaSGreg Roach
265a25f0a04SGreg Roach        // Some other type of record...
266a25f0a04SGreg Roach
26764d9078aSGreg Roach        return Database::prepare(
26864d9078aSGreg Roach            "SELECT o_gedcom FROM `##other` WHERE o_id = :xref AND o_file = :tree_id"
26913abd6f3SGreg Roach        )->execute([
27064d9078aSGreg Roach            'xref'    => $xref,
27164d9078aSGreg Roach            'tree_id' => $tree_id,
27213abd6f3SGreg Roach        ])->fetchOne();
273a25f0a04SGreg Roach    }
274a25f0a04SGreg Roach
275a25f0a04SGreg Roach    /**
276a25f0a04SGreg Roach     * Get the XREF for this record
277a25f0a04SGreg Roach     *
278a25f0a04SGreg Roach     * @return string
279a25f0a04SGreg Roach     */
280*8f53f488SRico Sonntag    public function getXref(): string
281c1010edaSGreg Roach    {
282a25f0a04SGreg Roach        return $this->xref;
283a25f0a04SGreg Roach    }
284a25f0a04SGreg Roach
285a25f0a04SGreg Roach    /**
286000959d9SGreg Roach     * Get the tree to which this record belongs
287000959d9SGreg Roach     *
288000959d9SGreg Roach     * @return Tree
289000959d9SGreg Roach     */
290*8f53f488SRico Sonntag    public function getTree(): Tree
291c1010edaSGreg Roach    {
292518bbdc1SGreg Roach        return $this->tree;
293000959d9SGreg Roach    }
294000959d9SGreg Roach
295000959d9SGreg Roach    /**
296a25f0a04SGreg Roach     * Application code should access data via Fact objects.
297a25f0a04SGreg Roach     * This function exists to support old code.
298a25f0a04SGreg Roach     *
299a25f0a04SGreg Roach     * @return string
300a25f0a04SGreg Roach     */
301c1010edaSGreg Roach    public function getGedcom()
302c1010edaSGreg Roach    {
303a25f0a04SGreg Roach        if ($this->pending === null) {
304a25f0a04SGreg Roach            return $this->gedcom;
305a25f0a04SGreg Roach        } else {
306a25f0a04SGreg Roach            return $this->pending;
307a25f0a04SGreg Roach        }
308a25f0a04SGreg Roach    }
309a25f0a04SGreg Roach
310a25f0a04SGreg Roach    /**
311a25f0a04SGreg Roach     * Does this record have a pending change?
312a25f0a04SGreg Roach     *
313cbc1590aSGreg Roach     * @return bool
314a25f0a04SGreg Roach     */
315*8f53f488SRico Sonntag    public function isPendingAddition(): bool
316c1010edaSGreg Roach    {
317a25f0a04SGreg Roach        return $this->pending !== null;
318a25f0a04SGreg Roach    }
319a25f0a04SGreg Roach
320a25f0a04SGreg Roach    /**
321a25f0a04SGreg Roach     * Does this record have a pending deletion?
322a25f0a04SGreg Roach     *
323cbc1590aSGreg Roach     * @return bool
324a25f0a04SGreg Roach     */
325*8f53f488SRico Sonntag    public function isPendingDeletion(): bool
326c1010edaSGreg Roach    {
327a25f0a04SGreg Roach        return $this->pending === '';
328a25f0a04SGreg Roach    }
329a25f0a04SGreg Roach
330a25f0a04SGreg Roach    /**
331a25f0a04SGreg Roach     * Generate a URL to this record, suitable for use in HTML, etc.
332a25f0a04SGreg Roach     *
333b1f1e4efSGreg Roach     * @deprecated
334b1f1e4efSGreg Roach     *
335a25f0a04SGreg Roach     * @return string
336a25f0a04SGreg Roach     */
337*8f53f488SRico Sonntag    public function getHtmlUrl(): string
338c1010edaSGreg Roach    {
339b1f1e4efSGreg Roach        return e($this->url());
340b1f1e4efSGreg Roach    }
341b1f1e4efSGreg Roach
342b1f1e4efSGreg Roach    /**
343225e381fSGreg Roach     * Generate a URL to this record.
344b1f1e4efSGreg Roach     *
345b1f1e4efSGreg Roach     * @deprecated
346b1f1e4efSGreg Roach     *
347b1f1e4efSGreg Roach     * @return string
348b1f1e4efSGreg Roach     */
349*8f53f488SRico Sonntag    public function getRawUrl(): string
350c1010edaSGreg Roach    {
351b1f1e4efSGreg Roach        return $this->url();
352a25f0a04SGreg Roach    }
353a25f0a04SGreg Roach
354a25f0a04SGreg Roach    /**
355225e381fSGreg Roach     * Generate a URL to this record.
356a25f0a04SGreg Roach     *
357a25f0a04SGreg Roach     * @return string
358a25f0a04SGreg Roach     */
359*8f53f488SRico Sonntag    public function url(): string
360c1010edaSGreg Roach    {
361225e381fSGreg Roach        return route(static::ROUTE_NAME, [
362225e381fSGreg Roach            'xref' => $this->getXref(),
363225e381fSGreg Roach            'ged'  => $this->tree->getName(),
364225e381fSGreg Roach        ]);
365a25f0a04SGreg Roach    }
366a25f0a04SGreg Roach
367a25f0a04SGreg Roach    /**
368a25f0a04SGreg Roach     * Work out whether this record can be shown to a user with a given access level
369a25f0a04SGreg Roach     *
370cbc1590aSGreg Roach     * @param int $access_level
371a25f0a04SGreg Roach     *
372cbc1590aSGreg Roach     * @return bool
373a25f0a04SGreg Roach     */
374*8f53f488SRico Sonntag    private function canShowRecord($access_level): bool
375c1010edaSGreg Roach    {
376a25f0a04SGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
377518bbdc1SGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
378a25f0a04SGreg Roach            return true;
379a25f0a04SGreg Roach        }
380a25f0a04SGreg Roach
381a25f0a04SGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
3824b9ff166SGreg Roach        if ($this->getXref() === $this->tree->getUserPreference(Auth::user(), 'gedcomid') && $access_level === Auth::accessLevel($this->tree)) {
383a25f0a04SGreg Roach            return true;
384a25f0a04SGreg Roach        }
385a25f0a04SGreg Roach
386a25f0a04SGreg Roach        // Does this record have a RESN?
38720ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
3884b9ff166SGreg Roach            return Auth::PRIV_NONE >= $access_level;
389a25f0a04SGreg Roach        }
39020ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
3914b9ff166SGreg Roach            return Auth::PRIV_USER >= $access_level;
392a25f0a04SGreg Roach        }
39320ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
394a25f0a04SGreg Roach            return true;
395a25f0a04SGreg Roach        }
396a25f0a04SGreg Roach
397a25f0a04SGreg Roach        // Does this record have a default RESN?
398518bbdc1SGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
399518bbdc1SGreg Roach        if (isset($individual_privacy[$this->getXref()])) {
400518bbdc1SGreg Roach            return $individual_privacy[$this->getXref()] >= $access_level;
401a25f0a04SGreg Roach        }
402a25f0a04SGreg Roach
403a25f0a04SGreg Roach        // Privacy rules do not apply to admins
4044b9ff166SGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
405a25f0a04SGreg Roach            return true;
406a25f0a04SGreg Roach        }
407a25f0a04SGreg Roach
408a25f0a04SGreg Roach        // Different types of record have different privacy rules
409a25f0a04SGreg Roach        return $this->canShowByType($access_level);
410a25f0a04SGreg Roach    }
411a25f0a04SGreg Roach
412a25f0a04SGreg Roach    /**
413a25f0a04SGreg Roach     * Each object type may have its own special rules, and re-implement this function.
414a25f0a04SGreg Roach     *
415cbc1590aSGreg Roach     * @param int $access_level
416a25f0a04SGreg Roach     *
417cbc1590aSGreg Roach     * @return bool
418a25f0a04SGreg Roach     */
419c1010edaSGreg Roach    protected function canShowByType($access_level)
420c1010edaSGreg Roach    {
421518bbdc1SGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
422a25f0a04SGreg Roach
423518bbdc1SGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
424a25f0a04SGreg Roach            // Restriction found
425518bbdc1SGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
426a25f0a04SGreg Roach        } else {
427a25f0a04SGreg Roach            // No restriction found - must be public:
428a25f0a04SGreg Roach            return true;
429a25f0a04SGreg Roach        }
430a25f0a04SGreg Roach    }
431a25f0a04SGreg Roach
432a25f0a04SGreg Roach    /**
433a25f0a04SGreg Roach     * Can the details of this record be shown?
434a25f0a04SGreg Roach     *
435cbc1590aSGreg Roach     * @param int|null $access_level
436a25f0a04SGreg Roach     *
437cbc1590aSGreg Roach     * @return bool
438a25f0a04SGreg Roach     */
439c1010edaSGreg Roach    public function canShow($access_level = null)
440c1010edaSGreg Roach    {
4414b9ff166SGreg Roach        if ($access_level === null) {
4424b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
4434b9ff166SGreg Roach        }
4444b9ff166SGreg Roach
445a25f0a04SGreg Roach        // CACHING: this function can take three different parameters,
446a25f0a04SGreg Roach        // and therefore needs three different caches for the result.
447a25f0a04SGreg Roach        switch ($access_level) {
4484b9ff166SGreg Roach            case Auth::PRIV_PRIVATE: // visitor
449a25f0a04SGreg Roach                if ($this->disp_public === null) {
4504b9ff166SGreg Roach                    $this->disp_public = $this->canShowRecord(Auth::PRIV_PRIVATE);
451a25f0a04SGreg Roach                }
452cbc1590aSGreg Roach
453a25f0a04SGreg Roach                return $this->disp_public;
4544b9ff166SGreg Roach            case Auth::PRIV_USER: // member
455a25f0a04SGreg Roach                if ($this->disp_user === null) {
4564b9ff166SGreg Roach                    $this->disp_user = $this->canShowRecord(Auth::PRIV_USER);
457a25f0a04SGreg Roach                }
458cbc1590aSGreg Roach
459a25f0a04SGreg Roach                return $this->disp_user;
4604b9ff166SGreg Roach            case Auth::PRIV_NONE: // admin
461a25f0a04SGreg Roach                if ($this->disp_none === null) {
4624b9ff166SGreg Roach                    $this->disp_none = $this->canShowRecord(Auth::PRIV_NONE);
463a25f0a04SGreg Roach                }
464cbc1590aSGreg Roach
465a25f0a04SGreg Roach                return $this->disp_none;
4664b9ff166SGreg Roach            case Auth::PRIV_HIDE: // hidden from admins
467a25f0a04SGreg Roach                // We use this value to bypass privacy checks. For example,
468a25f0a04SGreg Roach                // when downloading data or when calculating privacy itself.
469a25f0a04SGreg Roach                return true;
470a25f0a04SGreg Roach            default:
471a25f0a04SGreg Roach                // Should never get here.
472a25f0a04SGreg Roach                return false;
473a25f0a04SGreg Roach        }
474a25f0a04SGreg Roach    }
475a25f0a04SGreg Roach
476a25f0a04SGreg Roach    /**
477a25f0a04SGreg Roach     * Can the name of this record be shown?
478a25f0a04SGreg Roach     *
479cbc1590aSGreg Roach     * @param int|null $access_level
480a25f0a04SGreg Roach     *
481cbc1590aSGreg Roach     * @return bool
482a25f0a04SGreg Roach     */
483*8f53f488SRico Sonntag    public function canShowName($access_level = null): bool
484c1010edaSGreg Roach    {
4854b9ff166SGreg Roach        if ($access_level === null) {
4864b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
4874b9ff166SGreg Roach        }
4884b9ff166SGreg Roach
489a25f0a04SGreg Roach        return $this->canShow($access_level);
490a25f0a04SGreg Roach    }
491a25f0a04SGreg Roach
492a25f0a04SGreg Roach    /**
493a25f0a04SGreg Roach     * Can we edit this record?
494a25f0a04SGreg Roach     *
495cbc1590aSGreg Roach     * @return bool
496a25f0a04SGreg Roach     */
497*8f53f488SRico Sonntag    public function canEdit(): bool
498c1010edaSGreg Roach    {
4994b9ff166SGreg Roach        return Auth::isManager($this->tree) || Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
500a25f0a04SGreg Roach    }
501a25f0a04SGreg Roach
502a25f0a04SGreg Roach    /**
503a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
504a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
505a25f0a04SGreg Roach     *
506cbc1590aSGreg Roach     * @param int $access_level
507a25f0a04SGreg Roach     *
508a25f0a04SGreg Roach     * @return string
509a25f0a04SGreg Roach     */
510c1010edaSGreg Roach    public function privatizeGedcom($access_level)
511c1010edaSGreg Roach    {
5124b9ff166SGreg Roach        if ($access_level == Auth::PRIV_HIDE) {
513a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
514a25f0a04SGreg Roach            return $this->gedcom;
515a25f0a04SGreg Roach        } elseif ($this->canShow($access_level)) {
516a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
517a25f0a04SGreg Roach
518a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
519a25f0a04SGreg Roach            list($gedrec) = explode("\n", $this->gedcom, 2);
520a25f0a04SGreg Roach
521a25f0a04SGreg Roach            // Check each of the facts for access
522a25f0a04SGreg Roach            foreach ($this->getFacts(null, false, $access_level) as $fact) {
523a25f0a04SGreg Roach                $gedrec .= "\n" . $fact->getGedcom();
524a25f0a04SGreg Roach            }
525cbc1590aSGreg Roach
526a25f0a04SGreg Roach            return $gedrec;
527a25f0a04SGreg Roach        } else {
528a25f0a04SGreg Roach            // We cannot display the details, but we may be able to display
529a25f0a04SGreg Roach            // limited data, such as links to other records.
530a25f0a04SGreg Roach            return $this->createPrivateGedcomRecord($access_level);
531a25f0a04SGreg Roach        }
532a25f0a04SGreg Roach    }
533a25f0a04SGreg Roach
534a25f0a04SGreg Roach    /**
535a25f0a04SGreg Roach     * Generate a private version of this record
536a25f0a04SGreg Roach     *
537cbc1590aSGreg Roach     * @param int $access_level
538a25f0a04SGreg Roach     *
539a25f0a04SGreg Roach     * @return string
540a25f0a04SGreg Roach     */
541*8f53f488SRico Sonntag    protected function createPrivateGedcomRecord($access_level): string
542c1010edaSGreg Roach    {
543a25f0a04SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
544a25f0a04SGreg Roach    }
545a25f0a04SGreg Roach
546a25f0a04SGreg Roach    /**
547a25f0a04SGreg Roach     * Convert a name record into sortable and full/display versions. This default
548a25f0a04SGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
549a25f0a04SGreg Roach     *
550a25f0a04SGreg Roach     * @param string $type
551a25f0a04SGreg Roach     * @param string $value
552a25f0a04SGreg Roach     * @param string $gedcom
553a25f0a04SGreg Roach     */
554c1010edaSGreg Roach    protected function addName($type, $value, $gedcom)
555c1010edaSGreg Roach    {
556bdb3725aSGreg Roach        $this->getAllNames[] = [
557a25f0a04SGreg Roach            'type'   => $type,
5588d68cabeSGreg Roach            'sort'   => preg_replace_callback('/([0-9]+)/', function ($matches) {
5598d68cabeSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
5608d68cabeSGreg Roach            }, $value),
561c1010edaSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
562c1010edaSGreg Roach            // This is used for display
563c1010edaSGreg Roach            'fullNN' => $value,
564c1010edaSGreg Roach            // This goes into the database
56513abd6f3SGreg Roach        ];
566a25f0a04SGreg Roach    }
567a25f0a04SGreg Roach
568a25f0a04SGreg Roach    /**
569a25f0a04SGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
570a25f0a04SGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
571a25f0a04SGreg Roach     * Parameters: the level 1 fact containing the name.
572a25f0a04SGreg Roach     * Return value: an array of name structures, each containing
573a25f0a04SGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
574a25f0a04SGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
575a25f0a04SGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
576a25f0a04SGreg Roach     *
577cbc1590aSGreg Roach     * @param int    $level
578a25f0a04SGreg Roach     * @param string $fact_type
579a25f0a04SGreg Roach     * @param Fact[] $facts
580a25f0a04SGreg Roach     */
581c1010edaSGreg Roach    protected function extractNamesFromFacts($level, $fact_type, $facts)
582c1010edaSGreg Roach    {
583a25f0a04SGreg Roach        $sublevel    = $level + 1;
584a25f0a04SGreg Roach        $subsublevel = $sublevel + 1;
585a25f0a04SGreg Roach        foreach ($facts as $fact) {
586a25f0a04SGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->getGedcom(), $matches, PREG_SET_ORDER)) {
587a25f0a04SGreg Roach                foreach ($matches as $match) {
588a25f0a04SGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
589a25f0a04SGreg Roach                    if ($match[1] == 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
590a25f0a04SGreg Roach                        $this->addName('_MARNM', $match[2], $fact->getGedcom());
591a25f0a04SGreg Roach                    } else {
592a25f0a04SGreg Roach                        $this->addName($match[1], $match[2], $fact->getGedcom());
593a25f0a04SGreg Roach                    }
594a25f0a04SGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
595a25f0a04SGreg Roach                        foreach ($submatches as $submatch) {
596a25f0a04SGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
597a25f0a04SGreg Roach                        }
598a25f0a04SGreg Roach                    }
599a25f0a04SGreg Roach                }
600a25f0a04SGreg Roach            }
601a25f0a04SGreg Roach        }
602a25f0a04SGreg Roach    }
603a25f0a04SGreg Roach
604a25f0a04SGreg Roach    /**
605a25f0a04SGreg Roach     * Default for "other" object types
606a25f0a04SGreg Roach     */
607c1010edaSGreg Roach    public function extractNames()
608c1010edaSGreg Roach    {
609a25f0a04SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), null);
610a25f0a04SGreg Roach    }
611a25f0a04SGreg Roach
612a25f0a04SGreg Roach    /**
613a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
614a25f0a04SGreg Roach     *
615a25f0a04SGreg Roach     * @return string[][]
616a25f0a04SGreg Roach     */
617*8f53f488SRico Sonntag    public function getAllNames(): array
618c1010edaSGreg Roach    {
619bdb3725aSGreg Roach        if ($this->getAllNames === null) {
620bdb3725aSGreg Roach            $this->getAllNames = [];
621a25f0a04SGreg Roach            if ($this->canShowName()) {
622a25f0a04SGreg Roach                // Ask the record to extract its names
623a25f0a04SGreg Roach                $this->extractNames();
624a25f0a04SGreg Roach                // No name found? Use a fallback.
625bdb3725aSGreg Roach                if (!$this->getAllNames) {
626a25f0a04SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), null);
627a25f0a04SGreg Roach                }
628a25f0a04SGreg Roach            } else {
629a25f0a04SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), null);
630a25f0a04SGreg Roach            }
631a25f0a04SGreg Roach        }
632cbc1590aSGreg Roach
633bdb3725aSGreg Roach        return $this->getAllNames;
634a25f0a04SGreg Roach    }
635a25f0a04SGreg Roach
636a25f0a04SGreg Roach    /**
637a25f0a04SGreg Roach     * If this object has no name, what do we call it?
638a25f0a04SGreg Roach     *
639a25f0a04SGreg Roach     * @return string
640a25f0a04SGreg Roach     */
641*8f53f488SRico Sonntag    public function getFallBackName(): string
642c1010edaSGreg Roach    {
643d53324c9SGreg Roach        return e($this->getXref());
644a25f0a04SGreg Roach    }
645a25f0a04SGreg Roach
646a25f0a04SGreg Roach    /**
647a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
648a25f0a04SGreg Roach     *
649cbc1590aSGreg Roach     * @return int
650a25f0a04SGreg Roach     */
651*8f53f488SRico Sonntag    public function getPrimaryName(): int
652c1010edaSGreg Roach    {
653a25f0a04SGreg Roach        static $language_script;
654a25f0a04SGreg Roach
655a25f0a04SGreg Roach        if ($language_script === null) {
656a25f0a04SGreg Roach            $language_script = I18N::languageScript(WT_LOCALE);
657a25f0a04SGreg Roach        }
658a25f0a04SGreg Roach
659bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
660a25f0a04SGreg Roach            // Generally, the first name is the primary one....
661bdb3725aSGreg Roach            $this->getPrimaryName = 0;
662a25f0a04SGreg Roach            // ...except when the language/name use different character sets
663a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
66469546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
665bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
666a25f0a04SGreg Roach                    break;
667a25f0a04SGreg Roach                }
668a25f0a04SGreg Roach            }
669a25f0a04SGreg Roach        }
670a25f0a04SGreg Roach
671bdb3725aSGreg Roach        return $this->getPrimaryName;
672a25f0a04SGreg Roach    }
673a25f0a04SGreg Roach
674a25f0a04SGreg Roach    /**
675a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
676a25f0a04SGreg Roach     *
677cbc1590aSGreg Roach     * @return int
678a25f0a04SGreg Roach     */
679*8f53f488SRico Sonntag    public function getSecondaryName(): int
680c1010edaSGreg Roach    {
681bdb3725aSGreg Roach        if (is_null($this->getSecondaryName)) {
682a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
683bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
684a25f0a04SGreg Roach            // ....except when there are names with different character sets
685a25f0a04SGreg Roach            $all_names = $this->getAllNames();
686a25f0a04SGreg Roach            if (count($all_names) > 1) {
687a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
688a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
689a25f0a04SGreg Roach                    if ($n != $this->getPrimaryName() && $name['type'] != '_MARNM' && I18N::textScript($name['sort']) != $primary_script) {
690bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
691a25f0a04SGreg Roach                        break;
692a25f0a04SGreg Roach                    }
693a25f0a04SGreg Roach                }
694a25f0a04SGreg Roach            }
695a25f0a04SGreg Roach        }
696cbc1590aSGreg Roach
697bdb3725aSGreg Roach        return $this->getSecondaryName;
698a25f0a04SGreg Roach    }
699a25f0a04SGreg Roach
700a25f0a04SGreg Roach    /**
701a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
702a25f0a04SGreg Roach     *
703cbc1590aSGreg Roach     * @param int $n
704a25f0a04SGreg Roach     */
705c1010edaSGreg Roach    public function setPrimaryName($n)
706c1010edaSGreg Roach    {
707bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
708bdb3725aSGreg Roach        $this->getSecondaryName = null;
709a25f0a04SGreg Roach    }
710a25f0a04SGreg Roach
711a25f0a04SGreg Roach    /**
712a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
713a25f0a04SGreg Roach     *
714a25f0a04SGreg Roach     * @return string
715a25f0a04SGreg Roach     */
716c1010edaSGreg Roach    public function __toString()
717c1010edaSGreg Roach    {
718518bbdc1SGreg Roach        return $this->xref . '@' . $this->tree->getTreeId();
719a25f0a04SGreg Roach    }
720a25f0a04SGreg Roach
721a25f0a04SGreg Roach    /**
722a25f0a04SGreg Roach     * Static helper function to sort an array of objects by name
723a25f0a04SGreg Roach     * Records whose names cannot be displayed are sorted at the end.
724a25f0a04SGreg Roach     *
725a25f0a04SGreg Roach     * @param GedcomRecord $x
726a25f0a04SGreg Roach     * @param GedcomRecord $y
727a25f0a04SGreg Roach     *
728cbc1590aSGreg Roach     * @return int
729a25f0a04SGreg Roach     */
730c1010edaSGreg Roach    public static function compare(GedcomRecord $x, GedcomRecord $y)
731c1010edaSGreg Roach    {
732a25f0a04SGreg Roach        if ($x->canShowName()) {
733a25f0a04SGreg Roach            if ($y->canShowName()) {
734a25f0a04SGreg Roach                return I18N::strcasecmp($x->getSortName(), $y->getSortName());
735a25f0a04SGreg Roach            } else {
736a25f0a04SGreg Roach                return -1; // only $y is private
737a25f0a04SGreg Roach            }
738a25f0a04SGreg Roach        } else {
739a25f0a04SGreg Roach            if ($y->canShowName()) {
740a25f0a04SGreg Roach                return 1; // only $x is private
741a25f0a04SGreg Roach            } else {
742a25f0a04SGreg Roach                return 0; // both $x and $y private
743a25f0a04SGreg Roach            }
744a25f0a04SGreg Roach        }
745a25f0a04SGreg Roach    }
746a25f0a04SGreg Roach
747a25f0a04SGreg Roach    /**
748a25f0a04SGreg Roach     * Get variants of the name
749a25f0a04SGreg Roach     *
750a25f0a04SGreg Roach     * @return string
751a25f0a04SGreg Roach     */
752c1010edaSGreg Roach    public function getFullName()
753c1010edaSGreg Roach    {
754a25f0a04SGreg Roach        if ($this->canShowName()) {
755a25f0a04SGreg Roach            $tmp = $this->getAllNames();
756cbc1590aSGreg Roach
757a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
758a25f0a04SGreg Roach        } else {
759a25f0a04SGreg Roach            return I18N::translate('Private');
760a25f0a04SGreg Roach        }
761a25f0a04SGreg Roach    }
762a25f0a04SGreg Roach
763a25f0a04SGreg Roach    /**
764a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
765a25f0a04SGreg Roach     *
766a25f0a04SGreg Roach     * @return string
767a25f0a04SGreg Roach     */
768*8f53f488SRico Sonntag    public function getSortName(): string
769c1010edaSGreg Roach    {
770a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
771a25f0a04SGreg Roach        $tmp = $this->getAllNames();
772cbc1590aSGreg Roach
773a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
774a25f0a04SGreg Roach    }
775a25f0a04SGreg Roach
776a25f0a04SGreg Roach    /**
777a25f0a04SGreg Roach     * Get the full name in an alternative character set
778a25f0a04SGreg Roach     *
779a25f0a04SGreg Roach     * @return null|string
780a25f0a04SGreg Roach     */
781c1010edaSGreg Roach    public function getAddName()
782c1010edaSGreg Roach    {
783a25f0a04SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() != $this->getSecondaryName()) {
784a25f0a04SGreg Roach            $all_names = $this->getAllNames();
785cbc1590aSGreg Roach
786a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
787a25f0a04SGreg Roach        } else {
788a25f0a04SGreg Roach            return null;
789a25f0a04SGreg Roach        }
790a25f0a04SGreg Roach    }
791a25f0a04SGreg Roach
792a25f0a04SGreg Roach    /**
793a25f0a04SGreg Roach     * Format this object for display in a list
794a25f0a04SGreg Roach     *
795a25f0a04SGreg Roach     * @return string
796a25f0a04SGreg Roach     */
797*8f53f488SRico Sonntag    public function formatList(): string
798c1010edaSGreg Roach    {
799b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
800b165e17cSGreg Roach        $html .= '<b>' . $this->getFullName() . '</b>';
801a25f0a04SGreg Roach        $html .= $this->formatListDetails();
802b165e17cSGreg Roach        $html .= '</a>';
803cbc1590aSGreg Roach
804a25f0a04SGreg Roach        return $html;
805a25f0a04SGreg Roach    }
806a25f0a04SGreg Roach
807a25f0a04SGreg Roach    /**
808a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
809a25f0a04SGreg Roach     * identifying characteristics of this record.
810a25f0a04SGreg Roach     *
811a25f0a04SGreg Roach     * @return string
812a25f0a04SGreg Roach     */
813*8f53f488SRico Sonntag    public function formatListDetails(): string
814c1010edaSGreg Roach    {
815a25f0a04SGreg Roach        return '';
816a25f0a04SGreg Roach    }
817a25f0a04SGreg Roach
818a25f0a04SGreg Roach    /**
819a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
820a25f0a04SGreg Roach     *
821a25f0a04SGreg Roach     * @param string $facts
822cbc1590aSGreg Roach     * @param int    $style
823a25f0a04SGreg Roach     *
824a25f0a04SGreg Roach     * @return string
825a25f0a04SGreg Roach     */
826*8f53f488SRico Sonntag    public function formatFirstMajorFact($facts, $style): string
827c1010edaSGreg Roach    {
828a25f0a04SGreg Roach        foreach ($this->getFacts($facts, true) as $event) {
829a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
830d93f11b5SGreg Roach            if ($event->getDate()->isOK() && !$event->getPlace()->isEmpty()) {
831d93f11b5SGreg Roach                $joiner = ' — ';
832d93f11b5SGreg Roach            } else {
833d93f11b5SGreg Roach                $joiner = '';
834d93f11b5SGreg Roach            }
835a25f0a04SGreg Roach            if ($event->getDate()->isOK() || !$event->getPlace()->isEmpty()) {
836a25f0a04SGreg Roach                switch ($style) {
837a25f0a04SGreg Roach                    case 1:
838d93f11b5SGreg Roach                        return '<br><em>' . $event->getLabel() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
839a25f0a04SGreg Roach                    case 2:
840d93f11b5SGreg Roach                        return '<dl><dt class="label">' . $event->getLabel() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
841a25f0a04SGreg Roach                }
842a25f0a04SGreg Roach            }
843a25f0a04SGreg Roach        }
844cbc1590aSGreg Roach
845a25f0a04SGreg Roach        return '';
846a25f0a04SGreg Roach    }
847a25f0a04SGreg Roach
848a25f0a04SGreg Roach    /**
849a25f0a04SGreg Roach     * Find individuals linked to this record.
850a25f0a04SGreg Roach     *
851a25f0a04SGreg Roach     * @param string $link
852a25f0a04SGreg Roach     *
853360dbd2cSGreg Roach     * @return Individual[]
854a25f0a04SGreg Roach     */
855*8f53f488SRico Sonntag    public function linkedIndividuals($link): array
856c1010edaSGreg Roach    {
857a25f0a04SGreg Roach        $rows = Database::prepare(
85824ec66ceSGreg Roach            "SELECT i_id AS xref, i_gedcom AS gedcom" .
859a25f0a04SGreg Roach            " FROM `##individuals`" .
86081088023SGreg Roach            " JOIN `##link` ON i_file = l_file AND i_id = l_from" .
86181088023SGreg Roach            " LEFT JOIN `##name` ON i_file = n_file AND i_id = n_id AND n_num = 0" .
86281088023SGreg Roach            " WHERE i_file = :tree_id AND l_type = :link AND l_to = :xref" .
86381088023SGreg Roach            " ORDER BY n_sort COLLATE :collation"
86413abd6f3SGreg Roach        )->execute([
86581088023SGreg Roach            'tree_id'   => $this->tree->getTreeId(),
86681088023SGreg Roach            'link'      => $link,
86781088023SGreg Roach            'xref'      => $this->xref,
86881088023SGreg Roach            'collation' => I18N::collation(),
86913abd6f3SGreg Roach        ])->fetchAll();
870a25f0a04SGreg Roach
87113abd6f3SGreg Roach        $list = [];
872a25f0a04SGreg Roach        foreach ($rows as $row) {
87324ec66ceSGreg Roach            $record = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
874a25f0a04SGreg Roach            if ($record->canShowName()) {
875a25f0a04SGreg Roach                $list[] = $record;
876a25f0a04SGreg Roach            }
877a25f0a04SGreg Roach        }
878cbc1590aSGreg Roach
879a25f0a04SGreg Roach        return $list;
880a25f0a04SGreg Roach    }
881a25f0a04SGreg Roach
882a25f0a04SGreg Roach    /**
883a25f0a04SGreg Roach     * Find families linked to this record.
884a25f0a04SGreg Roach     *
885a25f0a04SGreg Roach     * @param string $link
886a25f0a04SGreg Roach     *
887360dbd2cSGreg Roach     * @return Family[]
888a25f0a04SGreg Roach     */
889*8f53f488SRico Sonntag    public function linkedFamilies($link): array
890c1010edaSGreg Roach    {
891a25f0a04SGreg Roach        $rows = Database::prepare(
89224ec66ceSGreg Roach            "SELECT f_id AS xref, f_gedcom AS gedcom" .
893a25f0a04SGreg Roach            " FROM `##families`" .
89481088023SGreg Roach            " JOIN `##link` ON f_file = l_file AND f_id = l_from" .
89581088023SGreg Roach            " LEFT JOIN `##name` ON f_file = n_file AND f_id = n_id AND n_num = 0" .
89681088023SGreg Roach            " WHERE f_file = :tree_id AND l_type = :link AND l_to = :xref"
89713abd6f3SGreg Roach        )->execute([
89881088023SGreg Roach            'tree_id' => $this->tree->getTreeId(),
89981088023SGreg Roach            'link'    => $link,
90081088023SGreg Roach            'xref'    => $this->xref,
90113abd6f3SGreg Roach        ])->fetchAll();
902a25f0a04SGreg Roach
90313abd6f3SGreg Roach        $list = [];
904a25f0a04SGreg Roach        foreach ($rows as $row) {
90524ec66ceSGreg Roach            $record = Family::getInstance($row->xref, $this->tree, $row->gedcom);
906a25f0a04SGreg Roach            if ($record->canShowName()) {
907a25f0a04SGreg Roach                $list[] = $record;
908a25f0a04SGreg Roach            }
909a25f0a04SGreg Roach        }
910cbc1590aSGreg Roach
911a25f0a04SGreg Roach        return $list;
912a25f0a04SGreg Roach    }
913a25f0a04SGreg Roach
914a25f0a04SGreg Roach    /**
915a25f0a04SGreg Roach     * Find sources linked to this record.
916a25f0a04SGreg Roach     *
917a25f0a04SGreg Roach     * @param string $link
918a25f0a04SGreg Roach     *
919360dbd2cSGreg Roach     * @return Source[]
920a25f0a04SGreg Roach     */
921*8f53f488SRico Sonntag    public function linkedSources($link): array
922c1010edaSGreg Roach    {
923a25f0a04SGreg Roach        $rows = Database::prepare(
92424ec66ceSGreg Roach            "SELECT s_id AS xref, s_gedcom AS gedcom" .
925a25f0a04SGreg Roach            " FROM `##sources`" .
92681088023SGreg Roach            " JOIN `##link` ON s_file = l_file AND s_id = l_from" .
92781088023SGreg Roach            " WHERE s_file = :tree_id AND l_type = :link AND l_to = :xref" .
92881088023SGreg Roach            " ORDER BY s_name COLLATE :collation"
92913abd6f3SGreg Roach        )->execute([
93081088023SGreg Roach            'tree_id'   => $this->tree->getTreeId(),
93181088023SGreg Roach            'link'      => $link,
93281088023SGreg Roach            'xref'      => $this->xref,
93381088023SGreg Roach            'collation' => I18N::collation(),
93413abd6f3SGreg Roach        ])->fetchAll();
935a25f0a04SGreg Roach
93613abd6f3SGreg Roach        $list = [];
937a25f0a04SGreg Roach        foreach ($rows as $row) {
93824ec66ceSGreg Roach            $record = Source::getInstance($row->xref, $this->tree, $row->gedcom);
939a25f0a04SGreg Roach            if ($record->canShowName()) {
940a25f0a04SGreg Roach                $list[] = $record;
941a25f0a04SGreg Roach            }
942a25f0a04SGreg Roach        }
943cbc1590aSGreg Roach
944a25f0a04SGreg Roach        return $list;
945a25f0a04SGreg Roach    }
946a25f0a04SGreg Roach
947a25f0a04SGreg Roach    /**
948a25f0a04SGreg Roach     * Find media objects linked to this record.
949a25f0a04SGreg Roach     *
950a25f0a04SGreg Roach     * @param string $link
951a25f0a04SGreg Roach     *
952360dbd2cSGreg Roach     * @return Media[]
953a25f0a04SGreg Roach     */
954*8f53f488SRico Sonntag    public function linkedMedia($link): array
955c1010edaSGreg Roach    {
956a25f0a04SGreg Roach        $rows = Database::prepare(
95724ec66ceSGreg Roach            "SELECT m_id AS xref, m_gedcom AS gedcom" .
958a25f0a04SGreg Roach            " FROM `##media`" .
95981088023SGreg Roach            " JOIN `##link` ON m_file = l_file AND m_id = l_from" .
96064b90bf1SGreg Roach            " WHERE m_file = :tree_id AND l_type = :link AND l_to = :xref"
96113abd6f3SGreg Roach        )->execute([
96281088023SGreg Roach            'tree_id' => $this->tree->getTreeId(),
96381088023SGreg Roach            'link'    => $link,
96481088023SGreg Roach            'xref'    => $this->xref,
96513abd6f3SGreg Roach        ])->fetchAll();
966a25f0a04SGreg Roach
96713abd6f3SGreg Roach        $list = [];
968a25f0a04SGreg Roach        foreach ($rows as $row) {
96924ec66ceSGreg Roach            $record = Media::getInstance($row->xref, $this->tree, $row->gedcom);
970a25f0a04SGreg Roach            if ($record->canShowName()) {
971a25f0a04SGreg Roach                $list[] = $record;
972a25f0a04SGreg Roach            }
973a25f0a04SGreg Roach        }
974cbc1590aSGreg Roach
975a25f0a04SGreg Roach        return $list;
976a25f0a04SGreg Roach    }
977a25f0a04SGreg Roach
978a25f0a04SGreg Roach    /**
979a25f0a04SGreg Roach     * Find notes linked to this record.
980a25f0a04SGreg Roach     *
981a25f0a04SGreg Roach     * @param string $link
982a25f0a04SGreg Roach     *
983a25f0a04SGreg Roach     * @return Note[]
984a25f0a04SGreg Roach     */
985*8f53f488SRico Sonntag    public function linkedNotes($link): array
986c1010edaSGreg Roach    {
987a25f0a04SGreg Roach        $rows = Database::prepare(
98824ec66ceSGreg Roach            "SELECT o_id AS xref, o_gedcom AS gedcom" .
989a25f0a04SGreg Roach            " FROM `##other`" .
99081088023SGreg Roach            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
99181088023SGreg Roach            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
99281088023SGreg Roach            " WHERE o_file = :tree_id AND o_type = 'NOTE' AND l_type = :link AND l_to = :xref" .
99381088023SGreg Roach            " ORDER BY n_sort COLLATE :collation"
99413abd6f3SGreg Roach        )->execute([
99581088023SGreg Roach            'tree_id'   => $this->tree->getTreeId(),
99681088023SGreg Roach            'link'      => $link,
99781088023SGreg Roach            'xref'      => $this->xref,
99881088023SGreg Roach            'collation' => I18N::collation(),
99913abd6f3SGreg Roach        ])->fetchAll();
1000a25f0a04SGreg Roach
100113abd6f3SGreg Roach        $list = [];
1002a25f0a04SGreg Roach        foreach ($rows as $row) {
100324ec66ceSGreg Roach            $record = Note::getInstance($row->xref, $this->tree, $row->gedcom);
1004a25f0a04SGreg Roach            if ($record->canShowName()) {
1005a25f0a04SGreg Roach                $list[] = $record;
1006a25f0a04SGreg Roach            }
1007a25f0a04SGreg Roach        }
1008cbc1590aSGreg Roach
1009a25f0a04SGreg Roach        return $list;
1010a25f0a04SGreg Roach    }
1011a25f0a04SGreg Roach
1012a25f0a04SGreg Roach    /**
1013a25f0a04SGreg Roach     * Find repositories linked to this record.
1014a25f0a04SGreg Roach     *
1015a25f0a04SGreg Roach     * @param string $link
1016a25f0a04SGreg Roach     *
1017360dbd2cSGreg Roach     * @return Repository[]
1018a25f0a04SGreg Roach     */
1019*8f53f488SRico Sonntag    public function linkedRepositories($link): array
1020c1010edaSGreg Roach    {
1021a25f0a04SGreg Roach        $rows = Database::prepare(
102224ec66ceSGreg Roach            "SELECT o_id AS xref, o_gedcom AS gedcom" .
1023a25f0a04SGreg Roach            " FROM `##other`" .
102481088023SGreg Roach            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
102581088023SGreg Roach            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
102681088023SGreg Roach            " WHERE o_file = :tree_id AND o_type = 'REPO' AND l_type = :link AND l_to = :xref" .
102751a671c6SGreg Roach            " ORDER BY n_sort COLLATE :collation"
102813abd6f3SGreg Roach        )->execute([
102981088023SGreg Roach            'tree_id'   => $this->tree->getTreeId(),
103081088023SGreg Roach            'link'      => $link,
103181088023SGreg Roach            'xref'      => $this->xref,
103281088023SGreg Roach            'collation' => I18N::collation(),
103313abd6f3SGreg Roach        ])->fetchAll();
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     *
1053a25f0a04SGreg Roach     * @param string $event_type
1054a25f0a04SGreg Roach     *
1055a25f0a04SGreg Roach     * @return Date[]
1056a25f0a04SGreg Roach     */
1057*8f53f488SRico Sonntag    public function getAllEventDates($event_type): array
1058c1010edaSGreg Roach    {
105913abd6f3SGreg Roach        $dates = [];
1060a25f0a04SGreg Roach        foreach ($this->getFacts($event_type) as $event) {
1061a25f0a04SGreg Roach            if ($event->getDate()->isOK()) {
1062a25f0a04SGreg Roach                $dates[] = $event->getDate();
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     *
1072a25f0a04SGreg Roach     * @param string $event_type
1073a25f0a04SGreg Roach     *
10744080d558SGreg Roach     * @return Place[]
1075a25f0a04SGreg Roach     */
1076*8f53f488SRico Sonntag    public function getAllEventPlaces($event_type): array
1077c1010edaSGreg Roach    {
107813abd6f3SGreg Roach        $places = [];
1079a25f0a04SGreg Roach        foreach ($this->getFacts($event_type) as $event) {
1080a25f0a04SGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->getGedcom(), $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     */
1097c1010edaSGreg Roach    public function getFirstFact($tag)
1098c1010edaSGreg Roach    {
1099a25f0a04SGreg Roach        foreach ($this->getFacts() 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     *
1111a25f0a04SGreg 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     */
1118*8f53f488SRico Sonntag    public function getFacts($filter = null, $sort = false, $access_level = null, $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) {
11273a7d762dSGreg Roach                if (($filter === null || preg_match('/^' . $filter . '$/', $fact->getTag())) && $fact->canShow($access_level)) {
1128a25f0a04SGreg Roach                    $facts[] = $fact;
1129a25f0a04SGreg Roach                }
1130a25f0a04SGreg Roach            }
1131a25f0a04SGreg Roach        }
1132a25f0a04SGreg Roach        if ($sort) {
11333d7a8a4cSGreg Roach            Functions::sortFacts($facts);
1134a25f0a04SGreg Roach        }
1135cbc1590aSGreg Roach
1136a25f0a04SGreg Roach        return $facts;
1137a25f0a04SGreg Roach    }
1138a25f0a04SGreg Roach
1139a25f0a04SGreg Roach    /**
1140a25f0a04SGreg Roach     * Get the last-change timestamp for this record, either as a formatted string
1141a25f0a04SGreg Roach     * (for display) or as a unix timestamp (for sorting)
1142a25f0a04SGreg Roach     *
1143cbc1590aSGreg Roach     * @param bool $sorting
1144a25f0a04SGreg Roach     *
1145a25f0a04SGreg Roach     * @return string
1146a25f0a04SGreg Roach     */
1147c1010edaSGreg Roach    public function lastChangeTimestamp($sorting = false)
1148c1010edaSGreg Roach    {
1149a25f0a04SGreg Roach        $chan = $this->getFirstFact('CHAN');
1150a25f0a04SGreg Roach
1151a25f0a04SGreg Roach        if ($chan) {
1152a25f0a04SGreg Roach            // The record does have a CHAN event
1153f5b60decSGreg Roach            $d = $chan->getDate()->minimumDate();
1154a25f0a04SGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->getGedcom(), $match)) {
1155a25f0a04SGreg Roach                $t = mktime((int)$match[1], (int)$match[2], (int)$match[3], (int)$d->format('%n'), (int)$d->format('%j'), (int)$d->format('%Y'));
1156a25f0a04SGreg Roach            } elseif (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->getGedcom(), $match)) {
1157a25f0a04SGreg Roach                $t = mktime((int)$match[1], (int)$match[2], 0, (int)$d->format('%n'), (int)$d->format('%j'), (int)$d->format('%Y'));
1158a25f0a04SGreg Roach            } else {
1159a25f0a04SGreg Roach                $t = mktime(0, 0, 0, (int)$d->format('%n'), (int)$d->format('%j'), (int)$d->format('%Y'));
1160a25f0a04SGreg Roach            }
1161a25f0a04SGreg Roach            if ($sorting) {
1162a25f0a04SGreg Roach                return $t;
1163a25f0a04SGreg Roach            } else {
11643d7a8a4cSGreg Roach                return strip_tags(FunctionsDate::formatTimestamp($t));
1165a25f0a04SGreg Roach            }
1166a25f0a04SGreg Roach        } else {
1167a25f0a04SGreg Roach            // The record does not have a CHAN event
1168a25f0a04SGreg Roach            if ($sorting) {
1169a25f0a04SGreg Roach                return '0';
1170a25f0a04SGreg Roach            } else {
117166b90994SGreg Roach                return '';
1172a25f0a04SGreg Roach            }
1173a25f0a04SGreg Roach        }
1174a25f0a04SGreg Roach    }
1175a25f0a04SGreg Roach
1176a25f0a04SGreg Roach    /**
1177a25f0a04SGreg Roach     * Get the last-change user for this record
1178a25f0a04SGreg Roach     *
1179a25f0a04SGreg Roach     * @return string
1180a25f0a04SGreg Roach     */
1181c1010edaSGreg Roach    public function lastChangeUser()
1182c1010edaSGreg Roach    {
1183a25f0a04SGreg Roach        $chan = $this->getFirstFact('CHAN');
1184a25f0a04SGreg Roach
1185a25f0a04SGreg Roach        if ($chan === null) {
1186a25f0a04SGreg Roach            return I18N::translate('Unknown');
1187a25f0a04SGreg Roach        } else {
1188a25f0a04SGreg Roach            $chan_user = $chan->getAttribute('_WT_USER');
1189baacc364SGreg Roach            if ($chan_user === '') {
1190a25f0a04SGreg Roach                return I18N::translate('Unknown');
1191a25f0a04SGreg Roach            } else {
1192a25f0a04SGreg Roach                return $chan_user;
1193a25f0a04SGreg Roach            }
1194a25f0a04SGreg Roach        }
1195a25f0a04SGreg Roach    }
1196a25f0a04SGreg Roach
1197a25f0a04SGreg Roach    /**
1198a25f0a04SGreg Roach     * Add a new fact to this record
1199a25f0a04SGreg Roach     *
1200a25f0a04SGreg Roach     * @param string $gedcom
1201cbc1590aSGreg Roach     * @param bool   $update_chan
1202a25f0a04SGreg Roach     */
1203c1010edaSGreg Roach    public function createFact($gedcom, $update_chan)
1204c1010edaSGreg Roach    {
1205a25f0a04SGreg Roach        $this->updateFact(null, $gedcom, $update_chan);
1206a25f0a04SGreg Roach    }
1207a25f0a04SGreg Roach
1208a25f0a04SGreg Roach    /**
1209a25f0a04SGreg Roach     * Delete a fact from this record
1210a25f0a04SGreg Roach     *
1211a25f0a04SGreg Roach     * @param string $fact_id
1212cbc1590aSGreg Roach     * @param bool   $update_chan
1213a25f0a04SGreg Roach     */
1214c1010edaSGreg Roach    public function deleteFact($fact_id, $update_chan)
1215c1010edaSGreg Roach    {
1216a25f0a04SGreg Roach        $this->updateFact($fact_id, null, $update_chan);
1217a25f0a04SGreg Roach    }
1218a25f0a04SGreg Roach
1219a25f0a04SGreg Roach    /**
1220a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
1221a25f0a04SGreg Roach     *
1222a25f0a04SGreg Roach     * @param string $fact_id
1223a25f0a04SGreg Roach     * @param string $gedcom
1224cbc1590aSGreg Roach     * @param bool   $update_chan
1225a25f0a04SGreg Roach     *
1226a25f0a04SGreg Roach     * @throws \Exception
1227a25f0a04SGreg Roach     */
1228c1010edaSGreg Roach    public function updateFact($fact_id, $gedcom, $update_chan)
1229c1010edaSGreg Roach    {
1230a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1231a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1232a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1233a25f0a04SGreg Roach
1234a25f0a04SGreg Roach        if ($this->pending === '') {
1235a25f0a04SGreg Roach            throw new \Exception('Cannot edit a deleted record');
1236a25f0a04SGreg Roach        }
1237a25f0a04SGreg Roach        if ($gedcom && !preg_match('/^1 ' . WT_REGEX_TAG . '/', $gedcom)) {
1238a25f0a04SGreg Roach            throw new \Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1239a25f0a04SGreg Roach        }
1240a25f0a04SGreg Roach
1241a25f0a04SGreg Roach        if ($this->pending) {
1242a25f0a04SGreg Roach            $old_gedcom = $this->pending;
1243a25f0a04SGreg Roach        } else {
1244a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
1245a25f0a04SGreg Roach        }
1246a25f0a04SGreg Roach
1247a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
1248a25f0a04SGreg Roach        list($new_gedcom) = explode("\n", $old_gedcom, 2);
1249a25f0a04SGreg Roach
1250a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
12514b9ff166SGreg Roach        foreach ($this->getFacts(null, false, Auth::PRIV_HIDE) as $fact) {
1252a25f0a04SGreg Roach            if (!$fact->isPendingDeletion()) {
1253a25f0a04SGreg Roach                if ($fact->getFactId() === $fact_id) {
1254a25f0a04SGreg Roach                    if ($gedcom) {
1255a25f0a04SGreg Roach                        $new_gedcom .= "\n" . $gedcom;
1256a25f0a04SGreg Roach                    }
1257a25f0a04SGreg Roach                    $fact_id = true; // Only replace/delete one copy of a duplicate fact
1258a25f0a04SGreg Roach                } elseif ($fact->getTag() != 'CHAN' || !$update_chan) {
1259a25f0a04SGreg Roach                    $new_gedcom .= "\n" . $fact->getGedcom();
1260a25f0a04SGreg Roach                }
1261a25f0a04SGreg Roach            }
1262a25f0a04SGreg Roach        }
1263a25f0a04SGreg Roach        if ($update_chan) {
12644e9cf5abSGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1265a25f0a04SGreg Roach        }
1266a25f0a04SGreg Roach
1267a25f0a04SGreg Roach        // Adding a new fact
1268a25f0a04SGreg Roach        if (!$fact_id) {
1269a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
1270a25f0a04SGreg Roach        }
1271a25f0a04SGreg Roach
1272a25f0a04SGreg Roach        if ($new_gedcom != $old_gedcom) {
1273a25f0a04SGreg Roach            // Save the changes
1274a25f0a04SGreg Roach            Database::prepare(
1275a25f0a04SGreg Roach                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
127613abd6f3SGreg Roach            )->execute([
1277518bbdc1SGreg Roach                $this->tree->getTreeId(),
1278a25f0a04SGreg Roach                $this->xref,
1279a25f0a04SGreg Roach                $old_gedcom,
1280a25f0a04SGreg Roach                $new_gedcom,
1281cbc1590aSGreg Roach                Auth::id(),
128213abd6f3SGreg Roach            ]);
1283a25f0a04SGreg Roach
1284a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1285a25f0a04SGreg Roach
1286a25f0a04SGreg Roach            if (Auth::user()->getPreference('auto_accept')) {
1287cc5684fdSGreg Roach                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1288a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1289a25f0a04SGreg Roach                $this->pending = null;
1290a25f0a04SGreg Roach            }
1291a25f0a04SGreg Roach        }
1292a25f0a04SGreg Roach        $this->parseFacts();
1293a25f0a04SGreg Roach    }
1294a25f0a04SGreg Roach
1295a25f0a04SGreg Roach    /**
1296a25f0a04SGreg Roach     * Update this record
1297a25f0a04SGreg Roach     *
1298a25f0a04SGreg Roach     * @param string $gedcom
1299cbc1590aSGreg Roach     * @param bool   $update_chan
1300a25f0a04SGreg Roach     */
1301c1010edaSGreg Roach    public function updateRecord($gedcom, $update_chan)
1302c1010edaSGreg Roach    {
1303a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1304a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1305a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1306a25f0a04SGreg Roach
1307a25f0a04SGreg Roach        // Update the CHAN record
1308a25f0a04SGreg Roach        if ($update_chan) {
1309a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1310a25f0a04SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1311a25f0a04SGreg Roach        }
1312a25f0a04SGreg Roach
1313a25f0a04SGreg Roach        // Create a pending change
1314a25f0a04SGreg Roach        Database::prepare(
1315a25f0a04SGreg Roach            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
131613abd6f3SGreg Roach        )->execute([
1317518bbdc1SGreg Roach            $this->tree->getTreeId(),
1318a25f0a04SGreg Roach            $this->xref,
1319a25f0a04SGreg Roach            $this->getGedcom(),
1320a25f0a04SGreg Roach            $gedcom,
1321cbc1590aSGreg Roach            Auth::id(),
132213abd6f3SGreg Roach        ]);
1323a25f0a04SGreg Roach
1324a25f0a04SGreg Roach        // Clear the cache
1325a25f0a04SGreg Roach        $this->pending = $gedcom;
1326a25f0a04SGreg Roach
1327a25f0a04SGreg Roach        // Accept this pending change
1328a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1329cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1330a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1331a25f0a04SGreg Roach            $this->pending = null;
1332a25f0a04SGreg Roach        }
1333a25f0a04SGreg Roach
1334a25f0a04SGreg Roach        $this->parseFacts();
1335a25f0a04SGreg Roach
1336847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1337a25f0a04SGreg Roach    }
1338a25f0a04SGreg Roach
1339a25f0a04SGreg Roach    /**
1340a25f0a04SGreg Roach     * Delete this record
1341a25f0a04SGreg Roach     */
1342c1010edaSGreg Roach    public function deleteRecord()
1343c1010edaSGreg Roach    {
1344a25f0a04SGreg Roach        // Create a pending change
13454c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1346a25f0a04SGreg Roach            Database::prepare(
1347a25f0a04SGreg Roach                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, '', ?)"
134813abd6f3SGreg Roach            )->execute([
1349518bbdc1SGreg Roach                $this->tree->getTreeId(),
1350a25f0a04SGreg Roach                $this->xref,
1351a25f0a04SGreg Roach                $this->getGedcom(),
1352a25f0a04SGreg Roach                Auth::id(),
135313abd6f3SGreg Roach            ]);
13544c0b5256SGreg Roach        }
1355a25f0a04SGreg Roach
13564c0b5256SGreg Roach        // Auto-accept this pending change
1357a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1358cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1359a25f0a04SGreg Roach        }
1360a25f0a04SGreg Roach
1361a25f0a04SGreg Roach        // Clear the cache
1362a25f0a04SGreg Roach        self::$gedcom_record_cache  = null;
1363a25f0a04SGreg Roach        self::$pending_record_cache = null;
1364a25f0a04SGreg Roach
1365847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1366a25f0a04SGreg Roach    }
1367a25f0a04SGreg Roach
1368a25f0a04SGreg Roach    /**
1369a25f0a04SGreg Roach     * Remove all links from this record to $xref
1370a25f0a04SGreg Roach     *
1371a25f0a04SGreg Roach     * @param string $xref
1372cbc1590aSGreg Roach     * @param bool   $update_chan
1373a25f0a04SGreg Roach     */
1374c1010edaSGreg Roach    public function removeLinks($xref, $update_chan)
1375c1010edaSGreg Roach    {
1376a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1377a25f0a04SGreg Roach
1378a25f0a04SGreg Roach        foreach ($this->getFacts() as $fact) {
1379baacc364SGreg Roach            if ($fact->getValue() === $value) {
1380a25f0a04SGreg Roach                $this->deleteFact($fact->getFactId(), $update_chan);
1381a25f0a04SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . WT_REGEX_TAG . ' ' . $value . '/', $fact->getGedcom(), $matches, PREG_SET_ORDER)) {
1382a25f0a04SGreg Roach                $gedcom = $fact->getGedcom();
1383a25f0a04SGreg Roach                foreach ($matches as $match) {
1384a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1385a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1386a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1387a25f0a04SGreg Roach                }
1388a25f0a04SGreg Roach                $this->updateFact($fact->getFactId(), $gedcom, $update_chan);
1389a25f0a04SGreg Roach            }
1390a25f0a04SGreg Roach        }
1391a25f0a04SGreg Roach    }
1392a25f0a04SGreg Roach}
1393