xref: /webtrees/app/GedcomRecord.php (revision afa9f52a203237c67caf58d7b2920e1417a057bd)
1a25f0a04SGreg Roach<?php
23976b470SGreg Roach
3a25f0a04SGreg Roach/**
4a25f0a04SGreg Roach * webtrees: online genealogy
58fcd0d32SGreg Roach * Copyright (C) 2019 webtrees development team
6a25f0a04SGreg Roach * This program is free software: you can redistribute it and/or modify
7a25f0a04SGreg Roach * it under the terms of the GNU General Public License as published by
8a25f0a04SGreg Roach * the Free Software Foundation, either version 3 of the License, or
9a25f0a04SGreg Roach * (at your option) any later version.
10a25f0a04SGreg Roach * This program is distributed in the hope that it will be useful,
11a25f0a04SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
12a25f0a04SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13a25f0a04SGreg Roach * GNU General Public License for more details.
14a25f0a04SGreg Roach * You should have received a copy of the GNU General Public License
15a25f0a04SGreg Roach * along with this program. If not, see <http://www.gnu.org/licenses/>.
16a25f0a04SGreg Roach */
17e7f56f2aSGreg Roachdeclare(strict_types=1);
18e7f56f2aSGreg Roach
1976692c8bSGreg Roachnamespace Fisharebest\Webtrees;
2076692c8bSGreg Roach
21886b77daSGreg Roachuse Closure;
227e96c925SGreg Roachuse Exception;
233d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
243d7a8a4cSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsPrint;
25bf4eb542SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
2683242252SGreg Roachuse Illuminate\Database\Query\Builder;
2783242252SGreg Roachuse Illuminate\Database\Query\Expression;
28ba1c12e8SGreg Roachuse Illuminate\Database\Query\JoinClause;
2939ca88baSGreg Roachuse Illuminate\Support\Collection;
30ee4364daSGreg Roachuse Illuminate\Support\Str;
3179529c87SGreg Roachuse stdClass;
32a25f0a04SGreg Roach
33a25f0a04SGreg Roach/**
3476692c8bSGreg Roach * A GEDCOM object.
35a25f0a04SGreg Roach */
36c1010edaSGreg Roachclass GedcomRecord
37c1010edaSGreg Roach{
3816d6367aSGreg Roach    public const RECORD_TYPE = 'UNKNOWN';
3916d6367aSGreg Roach
4016d6367aSGreg Roach    protected const ROUTE_NAME = 'record';
41a25f0a04SGreg Roach
42a25f0a04SGreg Roach    /** @var string The record identifier */
43a25f0a04SGreg Roach    protected $xref;
44a25f0a04SGreg Roach
45000959d9SGreg Roach    /** @var Tree  The family tree to which this record belongs */
46000959d9SGreg Roach    protected $tree;
47a25f0a04SGreg Roach
48a25f0a04SGreg Roach    /** @var string  GEDCOM data (before any pending edits) */
49a25f0a04SGreg Roach    protected $gedcom;
50a25f0a04SGreg Roach
51a25f0a04SGreg Roach    /** @var string|null  GEDCOM data (after any pending edits) */
52a25f0a04SGreg Roach    protected $pending;
53a25f0a04SGreg Roach
54a25f0a04SGreg Roach    /** @var Fact[] facts extracted from $gedcom/$pending */
55a25f0a04SGreg Roach    protected $facts;
56a25f0a04SGreg Roach
57a25f0a04SGreg Roach    /** @var string[][] All the names of this individual */
58bdb3725aSGreg Roach    protected $getAllNames;
59a25f0a04SGreg Roach
60d17d7b9eSGreg Roach    /** @var int|null Cached result */
61bdb3725aSGreg Roach    protected $getPrimaryName;
62a25f0a04SGreg Roach
63d17d7b9eSGreg Roach    /** @var int|null Cached result */
64bdb3725aSGreg Roach    protected $getSecondaryName;
65a25f0a04SGreg Roach
6676692c8bSGreg Roach    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
67bec87e94SGreg Roach    public static $gedcom_record_cache;
681ae87ce5SGreg Roach
6979529c87SGreg Roach    /** @var stdClass[][] Fetch all pending edits in one database query */
70bec87e94SGreg Roach    public static $pending_record_cache;
71a25f0a04SGreg Roach
72a25f0a04SGreg Roach    /**
73a25f0a04SGreg Roach     * Create a GedcomRecord object from raw GEDCOM data.
74a25f0a04SGreg Roach     *
75a25f0a04SGreg Roach     * @param string      $xref
76a25f0a04SGreg Roach     * @param string      $gedcom  an empty string for new/pending records
77a25f0a04SGreg Roach     * @param string|null $pending null for a record with no pending edits,
78a25f0a04SGreg Roach     *                             empty string for records with pending deletions
7924ec66ceSGreg Roach     * @param Tree        $tree
80a25f0a04SGreg Roach     */
81e364afe4SGreg Roach    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
82c1010edaSGreg Roach    {
83a25f0a04SGreg Roach        $this->xref    = $xref;
84a25f0a04SGreg Roach        $this->gedcom  = $gedcom;
85a25f0a04SGreg Roach        $this->pending = $pending;
8624ec66ceSGreg Roach        $this->tree    = $tree;
87a25f0a04SGreg Roach
88a25f0a04SGreg Roach        $this->parseFacts();
89a25f0a04SGreg Roach    }
90a25f0a04SGreg Roach
91a25f0a04SGreg Roach    /**
92886b77daSGreg Roach     * A closure which will create a record from a database row.
93886b77daSGreg Roach     *
94886b77daSGreg Roach     * @return Closure
95886b77daSGreg Roach     */
96c0804649SGreg Roach    public static function rowMapper(): Closure
97886b77daSGreg Roach    {
986c2179e2SGreg Roach        return static function (stdClass $row): GedcomRecord {
99e3bddf11SGreg Roach            return GedcomRecord::getInstance($row->o_id, Tree::findById((int) $row->o_file), $row->o_gedcom);
100886b77daSGreg Roach        };
101886b77daSGreg Roach    }
102886b77daSGreg Roach
103886b77daSGreg Roach    /**
104886b77daSGreg Roach     * A closure which will filter out private records.
105886b77daSGreg Roach     *
106886b77daSGreg Roach     * @return Closure
107886b77daSGreg Roach     */
1084146fabcSGreg Roach    public static function accessFilter(): Closure
109886b77daSGreg Roach    {
1106c2179e2SGreg Roach        return static function (GedcomRecord $record): bool {
111886b77daSGreg Roach            return $record->canShow();
112886b77daSGreg Roach        };
113886b77daSGreg Roach    }
114886b77daSGreg Roach
115886b77daSGreg Roach    /**
116c156e8f5SGreg Roach     * A closure which will compare records by name.
117c156e8f5SGreg Roach     *
118c156e8f5SGreg Roach     * @return Closure
119c156e8f5SGreg Roach     */
120c156e8f5SGreg Roach    public static function nameComparator(): Closure
121c156e8f5SGreg Roach    {
1226c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y): int {
123c156e8f5SGreg Roach            if ($x->canShowName()) {
124c156e8f5SGreg Roach                if ($y->canShowName()) {
12539ca88baSGreg Roach                    return I18N::strcasecmp($x->sortName(), $y->sortName());
126c156e8f5SGreg Roach                }
127c156e8f5SGreg Roach
128c156e8f5SGreg Roach                return -1; // only $y is private
129c156e8f5SGreg Roach            }
130c156e8f5SGreg Roach
131c156e8f5SGreg Roach            if ($y->canShowName()) {
132c156e8f5SGreg Roach                return 1; // only $x is private
133c156e8f5SGreg Roach            }
134c156e8f5SGreg Roach
135c156e8f5SGreg Roach            return 0; // both $x and $y private
136c156e8f5SGreg Roach        };
137c156e8f5SGreg Roach    }
138c156e8f5SGreg Roach
139c156e8f5SGreg Roach    /**
140c156e8f5SGreg Roach     * A closure which will compare records by change time.
141c156e8f5SGreg Roach     *
142c156e8f5SGreg Roach     * @param int $direction +1 to sort ascending, -1 to sort descending
143c156e8f5SGreg Roach     *
144c156e8f5SGreg Roach     * @return Closure
145c156e8f5SGreg Roach     */
146c156e8f5SGreg Roach    public static function lastChangeComparator(int $direction = 1): Closure
147c156e8f5SGreg Roach    {
1486c2179e2SGreg Roach        return static function (GedcomRecord $x, GedcomRecord $y) use ($direction): int {
1494459dc9aSGreg Roach            return $direction * ($x->lastChangeTimestamp() <=> $y->lastChangeTimestamp());
150c156e8f5SGreg Roach        };
151c156e8f5SGreg Roach    }
152c156e8f5SGreg Roach
153c156e8f5SGreg Roach    /**
154a25f0a04SGreg Roach     * Split the record into facts
1557e96c925SGreg Roach     *
1567e96c925SGreg Roach     * @return void
157a25f0a04SGreg Roach     */
158e364afe4SGreg Roach    private function parseFacts(): void
159c1010edaSGreg Roach    {
160a25f0a04SGreg Roach        // Split the record into facts
161a25f0a04SGreg Roach        if ($this->gedcom) {
162a25f0a04SGreg Roach            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
163a25f0a04SGreg Roach            array_shift($gedcom_facts);
164a25f0a04SGreg Roach        } else {
16513abd6f3SGreg Roach            $gedcom_facts = [];
166a25f0a04SGreg Roach        }
167a25f0a04SGreg Roach        if ($this->pending) {
168a25f0a04SGreg Roach            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
169a25f0a04SGreg Roach            array_shift($pending_facts);
170a25f0a04SGreg Roach        } else {
17113abd6f3SGreg Roach            $pending_facts = [];
172a25f0a04SGreg Roach        }
173a25f0a04SGreg Roach
17413abd6f3SGreg Roach        $this->facts = [];
175a25f0a04SGreg Roach
176a25f0a04SGreg Roach        foreach ($gedcom_facts as $gedcom_fact) {
177a25f0a04SGreg Roach            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
17822d65e5aSGreg Roach            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts, true)) {
179a25f0a04SGreg Roach                $fact->setPendingDeletion();
180a25f0a04SGreg Roach            }
181a25f0a04SGreg Roach            $this->facts[] = $fact;
182a25f0a04SGreg Roach        }
183a25f0a04SGreg Roach        foreach ($pending_facts as $pending_fact) {
18422d65e5aSGreg Roach            if (!in_array($pending_fact, $gedcom_facts, true)) {
185a25f0a04SGreg Roach                $fact = new Fact($pending_fact, $this, md5($pending_fact));
186a25f0a04SGreg Roach                $fact->setPendingAddition();
187a25f0a04SGreg Roach                $this->facts[] = $fact;
188a25f0a04SGreg Roach            }
189a25f0a04SGreg Roach        }
190a25f0a04SGreg Roach    }
191a25f0a04SGreg Roach
192a25f0a04SGreg Roach    /**
193a25f0a04SGreg Roach     * Get an instance of a GedcomRecord object. For single records,
194a25f0a04SGreg Roach     * we just receive the XREF. For bulk records (such as lists
195a25f0a04SGreg Roach     * and search results) we can receive the GEDCOM data as well.
196a25f0a04SGreg Roach     *
197a25f0a04SGreg Roach     * @param string      $xref
19824ec66ceSGreg Roach     * @param Tree        $tree
199a25f0a04SGreg Roach     * @param string|null $gedcom
200a25f0a04SGreg Roach     *
2017e96c925SGreg Roach     * @throws Exception
20284658595SGreg Roach     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|null
203a25f0a04SGreg Roach     */
20476f666f4SGreg Roach    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
205c1010edaSGreg Roach    {
20672cf66d4SGreg Roach        $tree_id = $tree->id();
20724ec66ceSGreg Roach
208e71ef9d2SGreg Roach        // Is this record already in the cache?
20924ec66ceSGreg Roach        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
210e71ef9d2SGreg Roach            return self::$gedcom_record_cache[$xref][$tree_id];
211a25f0a04SGreg Roach        }
212a25f0a04SGreg Roach
213a25f0a04SGreg Roach        // Do we need to fetch the record from the database?
214a25f0a04SGreg Roach        if ($gedcom === null) {
21524ec66ceSGreg Roach            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
216a25f0a04SGreg Roach        }
217a25f0a04SGreg Roach
218a25f0a04SGreg Roach        // If we can edit, then we also need to be able to see pending records.
21994075df0SGreg Roach        if (Auth::isEditor($tree)) {
22024ec66ceSGreg Roach            if (!isset(self::$pending_record_cache[$tree_id])) {
221a25f0a04SGreg Roach                // Fetch all pending records in one database query
22213abd6f3SGreg Roach                self::$pending_record_cache[$tree_id] = [];
22385fc8064SGreg Roach                $rows                                 = DB::table('change')
22485fc8064SGreg Roach                    ->where('gedcom_id', '=', $tree_id)
22585fc8064SGreg Roach                    ->where('status', '=', 'pending')
22685fc8064SGreg Roach                    ->orderBy('change_id')
22785fc8064SGreg Roach                    ->select(['xref', 'new_gedcom'])
22885fc8064SGreg Roach                    ->get();
229d17d7b9eSGreg Roach
230a25f0a04SGreg Roach                foreach ($rows as $row) {
23124ec66ceSGreg Roach                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
232a25f0a04SGreg Roach                }
233a25f0a04SGreg Roach            }
234a25f0a04SGreg Roach
235d17d7b9eSGreg Roach            $pending = self::$pending_record_cache[$tree_id][$xref] ?? null;
236a25f0a04SGreg Roach        } else {
237a25f0a04SGreg Roach            // There are no pending changes for this record
238a25f0a04SGreg Roach            $pending = null;
239a25f0a04SGreg Roach        }
240a25f0a04SGreg Roach
241a25f0a04SGreg Roach        // No such record exists
242a25f0a04SGreg Roach        if ($gedcom === null && $pending === null) {
243a25f0a04SGreg Roach            return null;
244a25f0a04SGreg Roach        }
245a25f0a04SGreg Roach
246fc3ccce4SGreg Roach        // No such record, but a pending creation exists
247fc3ccce4SGreg Roach        if ($gedcom === null) {
248fc3ccce4SGreg Roach            $gedcom = '';
249fc3ccce4SGreg Roach        }
250fc3ccce4SGreg Roach
251a25f0a04SGreg Roach        // Create the object
2528d0ebef0SGreg Roach        if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedcom . $pending, $match)) {
253a25f0a04SGreg Roach            $xref = $match[1]; // Collation - we may have requested I123 and found i123
254a25f0a04SGreg Roach            $type = $match[2];
255a25f0a04SGreg Roach        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
256a25f0a04SGreg Roach            $xref = $match[1];
257a25f0a04SGreg Roach            $type = $match[1];
258a25f0a04SGreg Roach        } elseif ($gedcom . $pending) {
2597e96c925SGreg Roach            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
260a25f0a04SGreg Roach        } else {
261a25f0a04SGreg Roach            // A record with both pending creation and pending deletion
262a25f0a04SGreg Roach            $type = static::RECORD_TYPE;
263a25f0a04SGreg Roach        }
264a25f0a04SGreg Roach
265a25f0a04SGreg Roach        switch ($type) {
266a25f0a04SGreg Roach            case 'INDI':
26724ec66ceSGreg Roach                $record = new Individual($xref, $gedcom, $pending, $tree);
268a25f0a04SGreg Roach                break;
269a25f0a04SGreg Roach            case 'FAM':
27024ec66ceSGreg Roach                $record = new Family($xref, $gedcom, $pending, $tree);
271a25f0a04SGreg Roach                break;
272a25f0a04SGreg Roach            case 'SOUR':
27324ec66ceSGreg Roach                $record = new Source($xref, $gedcom, $pending, $tree);
274a25f0a04SGreg Roach                break;
275a25f0a04SGreg Roach            case 'OBJE':
27624ec66ceSGreg Roach                $record = new Media($xref, $gedcom, $pending, $tree);
277a25f0a04SGreg Roach                break;
278a25f0a04SGreg Roach            case 'REPO':
27924ec66ceSGreg Roach                $record = new Repository($xref, $gedcom, $pending, $tree);
280a25f0a04SGreg Roach                break;
281a25f0a04SGreg Roach            case 'NOTE':
28224ec66ceSGreg Roach                $record = new Note($xref, $gedcom, $pending, $tree);
283a25f0a04SGreg Roach                break;
284a25f0a04SGreg Roach            default:
28506ef8e02SGreg Roach                $record = new self($xref, $gedcom, $pending, $tree);
286a25f0a04SGreg Roach                break;
287a25f0a04SGreg Roach        }
288a25f0a04SGreg Roach
289a25f0a04SGreg Roach        // Store it in the cache
29024ec66ceSGreg Roach        self::$gedcom_record_cache[$xref][$tree_id] = $record;
291a25f0a04SGreg Roach
292a25f0a04SGreg Roach        return $record;
293a25f0a04SGreg Roach    }
294a25f0a04SGreg Roach
295a25f0a04SGreg Roach    /**
296a25f0a04SGreg Roach     * Fetch data from the database
297a25f0a04SGreg Roach     *
298a25f0a04SGreg Roach     * @param string $xref
299cbc1590aSGreg Roach     * @param int    $tree_id
300a25f0a04SGreg Roach     *
301e364afe4SGreg Roach     * @return string|null
302a25f0a04SGreg Roach     */
303e364afe4SGreg Roach    protected static function fetchGedcomRecord(string $xref, int $tree_id): ?string
304c1010edaSGreg Roach    {
305a25f0a04SGreg Roach        // We don't know what type of object this is. Try each one in turn.
30664d9078aSGreg Roach        $data = Individual::fetchGedcomRecord($xref, $tree_id);
30785fc8064SGreg Roach        if ($data !== null) {
308a25f0a04SGreg Roach            return $data;
309a25f0a04SGreg Roach        }
31064d9078aSGreg Roach        $data = Family::fetchGedcomRecord($xref, $tree_id);
31185fc8064SGreg Roach        if ($data !== null) {
312a25f0a04SGreg Roach            return $data;
313a25f0a04SGreg Roach        }
31464d9078aSGreg Roach        $data = Source::fetchGedcomRecord($xref, $tree_id);
31585fc8064SGreg Roach        if ($data !== null) {
316a25f0a04SGreg Roach            return $data;
317a25f0a04SGreg Roach        }
31864d9078aSGreg Roach        $data = Repository::fetchGedcomRecord($xref, $tree_id);
31985fc8064SGreg Roach        if ($data !== null) {
320a25f0a04SGreg Roach            return $data;
321a25f0a04SGreg Roach        }
32264d9078aSGreg Roach        $data = Media::fetchGedcomRecord($xref, $tree_id);
32385fc8064SGreg Roach        if ($data !== null) {
324a25f0a04SGreg Roach            return $data;
325a25f0a04SGreg Roach        }
32664d9078aSGreg Roach        $data = Note::fetchGedcomRecord($xref, $tree_id);
32785fc8064SGreg Roach        if ($data !== null) {
328a25f0a04SGreg Roach            return $data;
329a25f0a04SGreg Roach        }
330c1010edaSGreg Roach
331a25f0a04SGreg Roach        // Some other type of record...
332d09b6323SGreg Roach        return DB::table('other')
33385fc8064SGreg Roach            ->where('o_file', '=', $tree_id)
33485fc8064SGreg Roach            ->where('o_id', '=', $xref)
33585fc8064SGreg Roach            ->value('o_gedcom');
336a25f0a04SGreg Roach    }
337a25f0a04SGreg Roach
338a25f0a04SGreg Roach    /**
339a25f0a04SGreg Roach     * Get the XREF for this record
340a25f0a04SGreg Roach     *
341a25f0a04SGreg Roach     * @return string
342a25f0a04SGreg Roach     */
343c0935879SGreg Roach    public function xref(): string
344c1010edaSGreg Roach    {
345a25f0a04SGreg Roach        return $this->xref;
346a25f0a04SGreg Roach    }
347a25f0a04SGreg Roach
348a25f0a04SGreg Roach    /**
349000959d9SGreg Roach     * Get the tree to which this record belongs
350000959d9SGreg Roach     *
351000959d9SGreg Roach     * @return Tree
352000959d9SGreg Roach     */
353f4afa648SGreg Roach    public function tree(): Tree
354c1010edaSGreg Roach    {
355518bbdc1SGreg Roach        return $this->tree;
356000959d9SGreg Roach    }
357000959d9SGreg Roach
358000959d9SGreg Roach    /**
359a25f0a04SGreg Roach     * Application code should access data via Fact objects.
360a25f0a04SGreg Roach     * This function exists to support old code.
361a25f0a04SGreg Roach     *
362a25f0a04SGreg Roach     * @return string
363a25f0a04SGreg Roach     */
364e364afe4SGreg Roach    public function gedcom(): string
365c1010edaSGreg Roach    {
366b2ce94c6SRico Sonntag        return $this->pending ?? $this->gedcom;
367a25f0a04SGreg Roach    }
368a25f0a04SGreg Roach
369a25f0a04SGreg Roach    /**
370a25f0a04SGreg Roach     * Does this record have a pending change?
371a25f0a04SGreg Roach     *
372cbc1590aSGreg Roach     * @return bool
373a25f0a04SGreg Roach     */
3748f53f488SRico Sonntag    public function isPendingAddition(): bool
375c1010edaSGreg Roach    {
376a25f0a04SGreg Roach        return $this->pending !== null;
377a25f0a04SGreg Roach    }
378a25f0a04SGreg Roach
379a25f0a04SGreg Roach    /**
380a25f0a04SGreg Roach     * Does this record have a pending deletion?
381a25f0a04SGreg Roach     *
382cbc1590aSGreg Roach     * @return bool
383a25f0a04SGreg Roach     */
3848f53f488SRico Sonntag    public function isPendingDeletion(): bool
385c1010edaSGreg Roach    {
386a25f0a04SGreg Roach        return $this->pending === '';
387a25f0a04SGreg Roach    }
388a25f0a04SGreg Roach
389a25f0a04SGreg Roach    /**
390ee4364daSGreg Roach     * Generate a "slug" to use in pretty URLs.
391ee4364daSGreg Roach     *
392ee4364daSGreg Roach     * @return string
393ee4364daSGreg Roach     */
394ee4364daSGreg Roach    public function slug(): string
395ee4364daSGreg Roach    {
396*afa9f52aSGreg Roach        return strip_tags($this->fullName());
397ee4364daSGreg Roach    }
398ee4364daSGreg Roach
399ee4364daSGreg Roach    /**
400225e381fSGreg Roach     * Generate a URL to this record.
401a25f0a04SGreg Roach     *
402a25f0a04SGreg Roach     * @return string
403a25f0a04SGreg Roach     */
4048f53f488SRico Sonntag    public function url(): string
405c1010edaSGreg Roach    {
406225e381fSGreg Roach        return route(static::ROUTE_NAME, [
407c0935879SGreg Roach            'xref' => $this->xref(),
408ee4364daSGreg Roach            'tree' => $this->tree->name(),
409ee4364daSGreg Roach            'slug' => $this->slug(),
410225e381fSGreg Roach        ]);
411a25f0a04SGreg Roach    }
412a25f0a04SGreg Roach
413a25f0a04SGreg Roach    /**
414a25f0a04SGreg Roach     * Work out whether this record can be shown to a user with a given access level
415a25f0a04SGreg Roach     *
416cbc1590aSGreg Roach     * @param int $access_level
417a25f0a04SGreg Roach     *
418cbc1590aSGreg Roach     * @return bool
419a25f0a04SGreg Roach     */
42076f666f4SGreg Roach    private function canShowRecord(int $access_level): bool
421c1010edaSGreg Roach    {
422a25f0a04SGreg Roach        // This setting would better be called "$ENABLE_PRIVACY"
423518bbdc1SGreg Roach        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
424a25f0a04SGreg Roach            return true;
425a25f0a04SGreg Roach        }
426a25f0a04SGreg Roach
427a25f0a04SGreg Roach        // We should always be able to see our own record (unless an admin is applying download restrictions)
428c0935879SGreg Roach        if ($this->xref() === $this->tree->getUserPreference(Auth::user(), 'gedcomid') && $access_level === Auth::accessLevel($this->tree)) {
429a25f0a04SGreg Roach            return true;
430a25f0a04SGreg Roach        }
431a25f0a04SGreg Roach
432a25f0a04SGreg Roach        // Does this record have a RESN?
43320ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
4344b9ff166SGreg Roach            return Auth::PRIV_NONE >= $access_level;
435a25f0a04SGreg Roach        }
43620ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
4374b9ff166SGreg Roach            return Auth::PRIV_USER >= $access_level;
438a25f0a04SGreg Roach        }
43920ff464cSGreg Roach        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
440a25f0a04SGreg Roach            return true;
441a25f0a04SGreg Roach        }
442a25f0a04SGreg Roach
443a25f0a04SGreg Roach        // Does this record have a default RESN?
444518bbdc1SGreg Roach        $individual_privacy = $this->tree->getIndividualPrivacy();
445c0935879SGreg Roach        if (isset($individual_privacy[$this->xref()])) {
446c0935879SGreg Roach            return $individual_privacy[$this->xref()] >= $access_level;
447a25f0a04SGreg Roach        }
448a25f0a04SGreg Roach
449a25f0a04SGreg Roach        // Privacy rules do not apply to admins
4504b9ff166SGreg Roach        if (Auth::PRIV_NONE >= $access_level) {
451a25f0a04SGreg Roach            return true;
452a25f0a04SGreg Roach        }
453a25f0a04SGreg Roach
454a25f0a04SGreg Roach        // Different types of record have different privacy rules
455a25f0a04SGreg Roach        return $this->canShowByType($access_level);
456a25f0a04SGreg Roach    }
457a25f0a04SGreg Roach
458a25f0a04SGreg Roach    /**
459a25f0a04SGreg Roach     * Each object type may have its own special rules, and re-implement this function.
460a25f0a04SGreg Roach     *
461cbc1590aSGreg Roach     * @param int $access_level
462a25f0a04SGreg Roach     *
463cbc1590aSGreg Roach     * @return bool
464a25f0a04SGreg Roach     */
46535584196SGreg Roach    protected function canShowByType(int $access_level): bool
466c1010edaSGreg Roach    {
467518bbdc1SGreg Roach        $fact_privacy = $this->tree->getFactPrivacy();
468a25f0a04SGreg Roach
469518bbdc1SGreg Roach        if (isset($fact_privacy[static::RECORD_TYPE])) {
470a25f0a04SGreg Roach            // Restriction found
471518bbdc1SGreg Roach            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
472b2ce94c6SRico Sonntag        }
473b2ce94c6SRico Sonntag
474a25f0a04SGreg Roach        // No restriction found - must be public:
475a25f0a04SGreg Roach        return true;
476a25f0a04SGreg Roach    }
477a25f0a04SGreg Roach
478a25f0a04SGreg Roach    /**
479a25f0a04SGreg Roach     * Can the details of this record be shown?
480a25f0a04SGreg Roach     *
481cbc1590aSGreg Roach     * @param int|null $access_level
482a25f0a04SGreg Roach     *
483cbc1590aSGreg Roach     * @return bool
484a25f0a04SGreg Roach     */
48535584196SGreg Roach    public function canShow(int $access_level = null): bool
486c1010edaSGreg Roach    {
487f0b9c048SGreg Roach        $access_level = $access_level ?? Auth::accessLevel($this->tree);
4884b9ff166SGreg Roach
489a25f0a04SGreg Roach        // We use this value to bypass privacy checks. For example,
490a25f0a04SGreg Roach        // when downloading data or when calculating privacy itself.
491f0b9c048SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
492a25f0a04SGreg Roach            return true;
493a25f0a04SGreg Roach        }
494f0b9c048SGreg Roach
495f0b9c048SGreg Roach        $cache_key = 'canShow' . $this->xref . ':' . $this->tree->id() . ':' . $access_level;
496f0b9c048SGreg Roach
497f0b9c048SGreg Roach        return app('cache.array')->rememberForever($cache_key, function () use ($access_level) {
498f0b9c048SGreg Roach            return $this->canShowRecord($access_level);
499f0b9c048SGreg Roach        });
500a25f0a04SGreg Roach    }
501a25f0a04SGreg Roach
502a25f0a04SGreg Roach    /**
503a25f0a04SGreg Roach     * Can the name of this record be shown?
504a25f0a04SGreg Roach     *
505cbc1590aSGreg Roach     * @param int|null $access_level
506a25f0a04SGreg Roach     *
507cbc1590aSGreg Roach     * @return bool
508a25f0a04SGreg Roach     */
50976f666f4SGreg Roach    public function canShowName(int $access_level = null): bool
510c1010edaSGreg Roach    {
511a25f0a04SGreg Roach        return $this->canShow($access_level);
512a25f0a04SGreg Roach    }
513a25f0a04SGreg Roach
514a25f0a04SGreg Roach    /**
515a25f0a04SGreg Roach     * Can we edit this record?
516a25f0a04SGreg Roach     *
517cbc1590aSGreg Roach     * @return bool
518a25f0a04SGreg Roach     */
5198f53f488SRico Sonntag    public function canEdit(): bool
520c1010edaSGreg Roach    {
5211450f098SGreg Roach        if ($this->isPendingDeletion()) {
5221450f098SGreg Roach            return false;
5231450f098SGreg Roach        }
5241450f098SGreg Roach
5251450f098SGreg Roach        if (Auth::isManager($this->tree)) {
5261450f098SGreg Roach            return true;
5271450f098SGreg Roach        }
5281450f098SGreg Roach
5291450f098SGreg Roach        return Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
530a25f0a04SGreg Roach    }
531a25f0a04SGreg Roach
532a25f0a04SGreg Roach    /**
533a25f0a04SGreg Roach     * Remove private data from the raw gedcom record.
534a25f0a04SGreg Roach     * Return both the visible and invisible data. We need the invisible data when editing.
535a25f0a04SGreg Roach     *
536cbc1590aSGreg Roach     * @param int $access_level
537a25f0a04SGreg Roach     *
538a25f0a04SGreg Roach     * @return string
539a25f0a04SGreg Roach     */
540e364afe4SGreg Roach    public function privatizeGedcom(int $access_level): string
541c1010edaSGreg Roach    {
542e364afe4SGreg Roach        if ($access_level === Auth::PRIV_HIDE) {
543a25f0a04SGreg Roach            // We may need the original record, for example when downloading a GEDCOM or clippings cart
544a25f0a04SGreg Roach            return $this->gedcom;
545b2ce94c6SRico Sonntag        }
546b2ce94c6SRico Sonntag
547b2ce94c6SRico Sonntag        if ($this->canShow($access_level)) {
548a25f0a04SGreg Roach            // The record is not private, but the individual facts may be.
549a25f0a04SGreg Roach
550a25f0a04SGreg Roach            // Include the entire first line (for NOTE records)
55165e02381SGreg Roach            [$gedrec] = explode("\n", $this->gedcom, 2);
552a25f0a04SGreg Roach
553a25f0a04SGreg Roach            // Check each of the facts for access
5548d0ebef0SGreg Roach            foreach ($this->facts([], false, $access_level) as $fact) {
555138ca96cSGreg Roach                $gedrec .= "\n" . $fact->gedcom();
556a25f0a04SGreg Roach            }
557cbc1590aSGreg Roach
558a25f0a04SGreg Roach            return $gedrec;
559b2ce94c6SRico Sonntag        }
560b2ce94c6SRico Sonntag
561a25f0a04SGreg Roach        // We cannot display the details, but we may be able to display
562a25f0a04SGreg Roach        // limited data, such as links to other records.
563a25f0a04SGreg Roach        return $this->createPrivateGedcomRecord($access_level);
564a25f0a04SGreg Roach    }
565a25f0a04SGreg Roach
566a25f0a04SGreg Roach    /**
567a25f0a04SGreg Roach     * Generate a private version of this record
568a25f0a04SGreg Roach     *
569cbc1590aSGreg Roach     * @param int $access_level
570a25f0a04SGreg Roach     *
571a25f0a04SGreg Roach     * @return string
572a25f0a04SGreg Roach     */
57376f666f4SGreg Roach    protected function createPrivateGedcomRecord(int $access_level): string
574c1010edaSGreg Roach    {
575a25f0a04SGreg Roach        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
576a25f0a04SGreg Roach    }
577a25f0a04SGreg Roach
578a25f0a04SGreg Roach    /**
579a25f0a04SGreg Roach     * Convert a name record into sortable and full/display versions. This default
580a25f0a04SGreg Roach     * should be OK for simple record types. INDI/FAM records will need to redefine it.
581a25f0a04SGreg Roach     *
582a25f0a04SGreg Roach     * @param string $type
583a25f0a04SGreg Roach     * @param string $value
584a25f0a04SGreg Roach     * @param string $gedcom
5857e96c925SGreg Roach     *
5867e96c925SGreg Roach     * @return void
587a25f0a04SGreg Roach     */
588e364afe4SGreg Roach    protected function addName(string $type, string $value, string $gedcom): void
589c1010edaSGreg Roach    {
590bdb3725aSGreg Roach        $this->getAllNames[] = [
591a25f0a04SGreg Roach            'type'   => $type,
5920b5fd0a6SGreg Roach            'sort'   => preg_replace_callback('/([0-9]+)/', static function (array $matches): string {
5938d68cabeSGreg Roach                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
5948d68cabeSGreg Roach            }, $value),
595c1010edaSGreg Roach            'full'   => '<span dir="auto">' . e($value) . '</span>',
596c1010edaSGreg Roach            // This is used for display
597c1010edaSGreg Roach            'fullNN' => $value,
598c1010edaSGreg Roach            // This goes into the database
59913abd6f3SGreg Roach        ];
600a25f0a04SGreg Roach    }
601a25f0a04SGreg Roach
602a25f0a04SGreg Roach    /**
603a25f0a04SGreg Roach     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
604a25f0a04SGreg Roach     * Records without a name (e.g. FAM) will need to redefine this function.
605a25f0a04SGreg Roach     * Parameters: the level 1 fact containing the name.
606a25f0a04SGreg Roach     * Return value: an array of name structures, each containing
607a25f0a04SGreg Roach     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
608a25f0a04SGreg Roach     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
609a25f0a04SGreg Roach     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
610a25f0a04SGreg Roach     *
611cbc1590aSGreg Roach     * @param int        $level
612a25f0a04SGreg Roach     * @param string     $fact_type
61354c7f8dfSGreg Roach     * @param Collection $facts
6147e96c925SGreg Roach     *
6157e96c925SGreg Roach     * @return void
616a25f0a04SGreg Roach     */
617e364afe4SGreg Roach    protected function extractNamesFromFacts(int $level, string $fact_type, Collection $facts): void
618c1010edaSGreg Roach    {
619a25f0a04SGreg Roach        $sublevel    = $level + 1;
620a25f0a04SGreg Roach        $subsublevel = $sublevel + 1;
621a25f0a04SGreg Roach        foreach ($facts as $fact) {
622138ca96cSGreg Roach            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->gedcom(), $matches, PREG_SET_ORDER)) {
623a25f0a04SGreg Roach                foreach ($matches as $match) {
624a25f0a04SGreg Roach                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
625e364afe4SGreg Roach                    if ($match[1] === 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
626138ca96cSGreg Roach                        $this->addName('_MARNM', $match[2], $fact->gedcom());
627a25f0a04SGreg Roach                    } else {
628138ca96cSGreg Roach                        $this->addName($match[1], $match[2], $fact->gedcom());
629a25f0a04SGreg Roach                    }
630a25f0a04SGreg Roach                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
631a25f0a04SGreg Roach                        foreach ($submatches as $submatch) {
632a25f0a04SGreg Roach                            $this->addName($submatch[1], $submatch[2], $match[3]);
633a25f0a04SGreg Roach                        }
634a25f0a04SGreg Roach                    }
635a25f0a04SGreg Roach                }
636a25f0a04SGreg Roach            }
637a25f0a04SGreg Roach        }
638a25f0a04SGreg Roach    }
639a25f0a04SGreg Roach
640a25f0a04SGreg Roach    /**
641a25f0a04SGreg Roach     * Default for "other" object types
642c7ff4153SGreg Roach     *
643c7ff4153SGreg Roach     * @return void
644a25f0a04SGreg Roach     */
645e364afe4SGreg Roach    public function extractNames(): void
646c1010edaSGreg Roach    {
64776f666f4SGreg Roach        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
648a25f0a04SGreg Roach    }
649a25f0a04SGreg Roach
650a25f0a04SGreg Roach    /**
651a25f0a04SGreg Roach     * Derived classes should redefine this function, otherwise the object will have no name
652a25f0a04SGreg Roach     *
653a25f0a04SGreg Roach     * @return string[][]
654a25f0a04SGreg Roach     */
6558f53f488SRico Sonntag    public function getAllNames(): array
656c1010edaSGreg Roach    {
657bdb3725aSGreg Roach        if ($this->getAllNames === null) {
658bdb3725aSGreg Roach            $this->getAllNames = [];
659a25f0a04SGreg Roach            if ($this->canShowName()) {
660a25f0a04SGreg Roach                // Ask the record to extract its names
661a25f0a04SGreg Roach                $this->extractNames();
662a25f0a04SGreg Roach                // No name found? Use a fallback.
663bdb3725aSGreg Roach                if (!$this->getAllNames) {
664db7bb364SGreg Roach                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
665a25f0a04SGreg Roach                }
666a25f0a04SGreg Roach            } else {
667db7bb364SGreg Roach                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
668a25f0a04SGreg Roach            }
669a25f0a04SGreg Roach        }
670cbc1590aSGreg Roach
671bdb3725aSGreg Roach        return $this->getAllNames;
672a25f0a04SGreg Roach    }
673a25f0a04SGreg Roach
674a25f0a04SGreg Roach    /**
675a25f0a04SGreg Roach     * If this object has no name, what do we call it?
676a25f0a04SGreg Roach     *
677a25f0a04SGreg Roach     * @return string
678a25f0a04SGreg Roach     */
6798f53f488SRico Sonntag    public function getFallBackName(): string
680c1010edaSGreg Roach    {
681c0935879SGreg Roach        return e($this->xref());
682a25f0a04SGreg Roach    }
683a25f0a04SGreg Roach
684a25f0a04SGreg Roach    /**
685a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the primary one.
686a25f0a04SGreg Roach     *
687cbc1590aSGreg Roach     * @return int
688a25f0a04SGreg Roach     */
6898f53f488SRico Sonntag    public function getPrimaryName(): int
690c1010edaSGreg Roach    {
691a25f0a04SGreg Roach        static $language_script;
692a25f0a04SGreg Roach
693a25f0a04SGreg Roach        if ($language_script === null) {
694a25f0a04SGreg Roach            $language_script = I18N::languageScript(WT_LOCALE);
695a25f0a04SGreg Roach        }
696a25f0a04SGreg Roach
697bdb3725aSGreg Roach        if ($this->getPrimaryName === null) {
698a25f0a04SGreg Roach            // Generally, the first name is the primary one....
699bdb3725aSGreg Roach            $this->getPrimaryName = 0;
700a25f0a04SGreg Roach            // ...except when the language/name use different character sets
701a25f0a04SGreg Roach            foreach ($this->getAllNames() as $n => $name) {
70269546be1SGreg Roach                if (I18N::textScript($name['sort']) === $language_script) {
703bdb3725aSGreg Roach                    $this->getPrimaryName = $n;
704a25f0a04SGreg Roach                    break;
705a25f0a04SGreg Roach                }
706a25f0a04SGreg Roach            }
707a25f0a04SGreg Roach        }
708a25f0a04SGreg Roach
709bdb3725aSGreg Roach        return $this->getPrimaryName;
710a25f0a04SGreg Roach    }
711a25f0a04SGreg Roach
712a25f0a04SGreg Roach    /**
713a25f0a04SGreg Roach     * Which of the (possibly several) names of this record is the secondary one.
714a25f0a04SGreg Roach     *
715cbc1590aSGreg Roach     * @return int
716a25f0a04SGreg Roach     */
7178f53f488SRico Sonntag    public function getSecondaryName(): int
718c1010edaSGreg Roach    {
7198f038c36SRico Sonntag        if ($this->getSecondaryName === null) {
720a25f0a04SGreg Roach            // Generally, the primary and secondary names are the same
721bdb3725aSGreg Roach            $this->getSecondaryName = $this->getPrimaryName();
722a25f0a04SGreg Roach            // ....except when there are names with different character sets
723a25f0a04SGreg Roach            $all_names = $this->getAllNames();
724a25f0a04SGreg Roach            if (count($all_names) > 1) {
725a25f0a04SGreg Roach                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
726a25f0a04SGreg Roach                foreach ($all_names as $n => $name) {
727e364afe4SGreg Roach                    if ($n !== $this->getPrimaryName() && $name['type'] !== '_MARNM' && I18N::textScript($name['sort']) !== $primary_script) {
728bdb3725aSGreg Roach                        $this->getSecondaryName = $n;
729a25f0a04SGreg Roach                        break;
730a25f0a04SGreg Roach                    }
731a25f0a04SGreg Roach                }
732a25f0a04SGreg Roach            }
733a25f0a04SGreg Roach        }
734cbc1590aSGreg Roach
735bdb3725aSGreg Roach        return $this->getSecondaryName;
736a25f0a04SGreg Roach    }
737a25f0a04SGreg Roach
738a25f0a04SGreg Roach    /**
739a25f0a04SGreg Roach     * Allow the choice of primary name to be overidden, e.g. in a search result
740a25f0a04SGreg Roach     *
74176f666f4SGreg Roach     * @param int|null $n
7427e96c925SGreg Roach     *
7437e96c925SGreg Roach     * @return void
744a25f0a04SGreg Roach     */
745e364afe4SGreg Roach    public function setPrimaryName(int $n = null): void
746c1010edaSGreg Roach    {
747bdb3725aSGreg Roach        $this->getPrimaryName   = $n;
748bdb3725aSGreg Roach        $this->getSecondaryName = null;
749a25f0a04SGreg Roach    }
750a25f0a04SGreg Roach
751a25f0a04SGreg Roach    /**
752a25f0a04SGreg Roach     * Allow native PHP functions such as array_unique() to work with objects
753a25f0a04SGreg Roach     *
754a25f0a04SGreg Roach     * @return string
755a25f0a04SGreg Roach     */
756c1010edaSGreg Roach    public function __toString()
757c1010edaSGreg Roach    {
75872cf66d4SGreg Roach        return $this->xref . '@' . $this->tree->id();
759a25f0a04SGreg Roach    }
760a25f0a04SGreg Roach
761a25f0a04SGreg Roach    /**
762c156e8f5SGreg Roach     * /**
763a25f0a04SGreg Roach     * Get variants of the name
764a25f0a04SGreg Roach     *
765a25f0a04SGreg Roach     * @return string
766a25f0a04SGreg Roach     */
767e364afe4SGreg Roach    public function fullName(): string
768c1010edaSGreg Roach    {
769a25f0a04SGreg Roach        if ($this->canShowName()) {
770a25f0a04SGreg Roach            $tmp = $this->getAllNames();
771cbc1590aSGreg Roach
772a25f0a04SGreg Roach            return $tmp[$this->getPrimaryName()]['full'];
773a25f0a04SGreg Roach        }
774b2ce94c6SRico Sonntag
775b2ce94c6SRico Sonntag        return I18N::translate('Private');
776a25f0a04SGreg Roach    }
777a25f0a04SGreg Roach
778a25f0a04SGreg Roach    /**
779a25f0a04SGreg Roach     * Get a sortable version of the name. Do not display this!
780a25f0a04SGreg Roach     *
781a25f0a04SGreg Roach     * @return string
782a25f0a04SGreg Roach     */
78339ca88baSGreg Roach    public function sortName(): string
784c1010edaSGreg Roach    {
785a25f0a04SGreg Roach        // The sortable name is never displayed, no need to call canShowName()
786a25f0a04SGreg Roach        $tmp = $this->getAllNames();
787cbc1590aSGreg Roach
788a25f0a04SGreg Roach        return $tmp[$this->getPrimaryName()]['sort'];
789a25f0a04SGreg Roach    }
790a25f0a04SGreg Roach
791a25f0a04SGreg Roach    /**
792a25f0a04SGreg Roach     * Get the full name in an alternative character set
793a25f0a04SGreg Roach     *
794e364afe4SGreg Roach     * @return string|null
795a25f0a04SGreg Roach     */
796e364afe4SGreg Roach    public function alternateName(): ?string
797c1010edaSGreg Roach    {
798e364afe4SGreg Roach        if ($this->canShowName() && $this->getPrimaryName() !== $this->getSecondaryName()) {
799a25f0a04SGreg Roach            $all_names = $this->getAllNames();
800cbc1590aSGreg Roach
801a25f0a04SGreg Roach            return $all_names[$this->getSecondaryName()]['full'];
802a25f0a04SGreg Roach        }
803b2ce94c6SRico Sonntag
804b2ce94c6SRico Sonntag        return null;
805a25f0a04SGreg Roach    }
806a25f0a04SGreg Roach
807a25f0a04SGreg Roach    /**
808a25f0a04SGreg Roach     * Format this object for display in a list
809a25f0a04SGreg Roach     *
810a25f0a04SGreg Roach     * @return string
811a25f0a04SGreg Roach     */
8128f53f488SRico Sonntag    public function formatList(): string
813c1010edaSGreg Roach    {
814b165e17cSGreg Roach        $html = '<a href="' . e($this->url()) . '" class="list_item">';
81539ca88baSGreg Roach        $html .= '<b>' . $this->fullName() . '</b>';
816a25f0a04SGreg Roach        $html .= $this->formatListDetails();
817b165e17cSGreg Roach        $html .= '</a>';
818cbc1590aSGreg Roach
819a25f0a04SGreg Roach        return $html;
820a25f0a04SGreg Roach    }
821a25f0a04SGreg Roach
822a25f0a04SGreg Roach    /**
823a25f0a04SGreg Roach     * This function should be redefined in derived classes to show any major
824a25f0a04SGreg Roach     * identifying characteristics of this record.
825a25f0a04SGreg Roach     *
826a25f0a04SGreg Roach     * @return string
827a25f0a04SGreg Roach     */
8288f53f488SRico Sonntag    public function formatListDetails(): string
829c1010edaSGreg Roach    {
830a25f0a04SGreg Roach        return '';
831a25f0a04SGreg Roach    }
832a25f0a04SGreg Roach
833a25f0a04SGreg Roach    /**
834a25f0a04SGreg Roach     * Extract/format the first fact from a list of facts.
835a25f0a04SGreg Roach     *
8368d0ebef0SGreg Roach     * @param string[] $facts
837cbc1590aSGreg Roach     * @param int      $style
838a25f0a04SGreg Roach     *
839a25f0a04SGreg Roach     * @return string
840a25f0a04SGreg Roach     */
8418d0ebef0SGreg Roach    public function formatFirstMajorFact(array $facts, int $style): string
842c1010edaSGreg Roach    {
84330158ae7SGreg Roach        foreach ($this->facts($facts, true) as $event) {
844a25f0a04SGreg Roach            // Only display if it has a date or place (or both)
845e364afe4SGreg Roach            if ($event->date()->isOK() && $event->place()->gedcomName() !== '') {
846d93f11b5SGreg Roach                $joiner = ' — ';
847d93f11b5SGreg Roach            } else {
848d93f11b5SGreg Roach                $joiner = '';
849d93f11b5SGreg Roach            }
850e364afe4SGreg Roach            if ($event->date()->isOK() || $event->place()->gedcomName() !== '') {
851a25f0a04SGreg Roach                switch ($style) {
852a25f0a04SGreg Roach                    case 1:
8537b7d8067SGreg Roach                        return '<br><em>' . $event->label() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
854a25f0a04SGreg Roach                    case 2:
8557b7d8067SGreg Roach                        return '<dl><dt class="label">' . $event->label() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
856a25f0a04SGreg Roach                }
857a25f0a04SGreg Roach            }
858a25f0a04SGreg Roach        }
859cbc1590aSGreg Roach
860a25f0a04SGreg Roach        return '';
861a25f0a04SGreg Roach    }
862a25f0a04SGreg Roach
863a25f0a04SGreg Roach    /**
864a25f0a04SGreg Roach     * Find individuals linked to this record.
865a25f0a04SGreg Roach     *
866a25f0a04SGreg Roach     * @param string $link
867a25f0a04SGreg Roach     *
868907c1109SGreg Roach     * @return Collection
869a25f0a04SGreg Roach     */
870907c1109SGreg Roach    public function linkedIndividuals(string $link): Collection
871c1010edaSGreg Roach    {
872907c1109SGreg Roach        return DB::table('individuals')
8730b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
874907c1109SGreg Roach                $join
875907c1109SGreg Roach                    ->on('l_file', '=', 'i_file')
876907c1109SGreg Roach                    ->on('l_from', '=', 'i_id');
877ba1c12e8SGreg Roach            })
878ba1c12e8SGreg Roach            ->where('i_file', '=', $this->tree->id())
879ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
880ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
881907c1109SGreg Roach            ->select(['individuals.*'])
882907c1109SGreg Roach            ->get()
883907c1109SGreg Roach            ->map(Individual::rowMapper())
884907c1109SGreg Roach            ->filter(self::accessFilter());
885a25f0a04SGreg Roach    }
886a25f0a04SGreg Roach
887a25f0a04SGreg Roach    /**
888a25f0a04SGreg Roach     * Find families linked to this record.
889a25f0a04SGreg Roach     *
890a25f0a04SGreg Roach     * @param string $link
891a25f0a04SGreg Roach     *
892907c1109SGreg Roach     * @return Collection
893a25f0a04SGreg Roach     */
894907c1109SGreg Roach    public function linkedFamilies(string $link): Collection
895c1010edaSGreg Roach    {
896907c1109SGreg Roach        return DB::table('families')
8970b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
898907c1109SGreg Roach                $join
899907c1109SGreg Roach                    ->on('l_file', '=', 'f_file')
900907c1109SGreg Roach                    ->on('l_from', '=', 'f_id');
901ba1c12e8SGreg Roach            })
902ba1c12e8SGreg Roach            ->where('f_file', '=', $this->tree->id())
903ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
904ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
905907c1109SGreg Roach            ->select(['families.*'])
906907c1109SGreg Roach            ->get()
907907c1109SGreg Roach            ->map(Family::rowMapper())
908907c1109SGreg Roach            ->filter(self::accessFilter());
909a25f0a04SGreg Roach    }
910a25f0a04SGreg Roach
911a25f0a04SGreg Roach    /**
912a25f0a04SGreg Roach     * Find sources linked to this record.
913a25f0a04SGreg Roach     *
914a25f0a04SGreg Roach     * @param string $link
915a25f0a04SGreg Roach     *
916907c1109SGreg Roach     * @return Collection
917a25f0a04SGreg Roach     */
918907c1109SGreg Roach    public function linkedSources(string $link): Collection
919c1010edaSGreg Roach    {
920907c1109SGreg Roach        return DB::table('sources')
9210b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
922907c1109SGreg Roach                $join
923907c1109SGreg Roach                    ->on('l_file', '=', 's_file')
924907c1109SGreg Roach                    ->on('l_from', '=', 's_id');
925ba1c12e8SGreg Roach            })
926ba1c12e8SGreg Roach            ->where('s_file', '=', $this->tree->id())
927ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
928ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
929907c1109SGreg Roach            ->select(['sources.*'])
930907c1109SGreg Roach            ->get()
931907c1109SGreg Roach            ->map(Source::rowMapper())
932907c1109SGreg Roach            ->filter(self::accessFilter());
933a25f0a04SGreg Roach    }
934a25f0a04SGreg Roach
935a25f0a04SGreg Roach    /**
936a25f0a04SGreg Roach     * Find media objects linked to this record.
937a25f0a04SGreg Roach     *
938a25f0a04SGreg Roach     * @param string $link
939a25f0a04SGreg Roach     *
940907c1109SGreg Roach     * @return Collection
941a25f0a04SGreg Roach     */
942907c1109SGreg Roach    public function linkedMedia(string $link): Collection
943c1010edaSGreg Roach    {
944907c1109SGreg Roach        return DB::table('media')
9450b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
946907c1109SGreg Roach                $join
947907c1109SGreg Roach                    ->on('l_file', '=', 'm_file')
948907c1109SGreg Roach                    ->on('l_from', '=', 'm_id');
949ba1c12e8SGreg Roach            })
950ba1c12e8SGreg Roach            ->where('m_file', '=', $this->tree->id())
951ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
952ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
953907c1109SGreg Roach            ->select(['media.*'])
954907c1109SGreg Roach            ->get()
955907c1109SGreg Roach            ->map(Media::rowMapper())
956907c1109SGreg Roach            ->filter(self::accessFilter());
957a25f0a04SGreg Roach    }
958a25f0a04SGreg Roach
959a25f0a04SGreg Roach    /**
960a25f0a04SGreg Roach     * Find notes linked to this record.
961a25f0a04SGreg Roach     *
962a25f0a04SGreg Roach     * @param string $link
963a25f0a04SGreg Roach     *
964907c1109SGreg Roach     * @return Collection
965a25f0a04SGreg Roach     */
966907c1109SGreg Roach    public function linkedNotes(string $link): Collection
967c1010edaSGreg Roach    {
968907c1109SGreg Roach        return DB::table('other')
9690b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
970907c1109SGreg Roach                $join
971907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
972907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
973ba1c12e8SGreg Roach            })
974ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
975ba1c12e8SGreg Roach            ->where('o_type', '=', 'NOTE')
976ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
977ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
978907c1109SGreg Roach            ->select(['other.*'])
979907c1109SGreg Roach            ->get()
980907c1109SGreg Roach            ->map(Note::rowMapper())
981907c1109SGreg Roach            ->filter(self::accessFilter());
982a25f0a04SGreg Roach    }
983a25f0a04SGreg Roach
984a25f0a04SGreg Roach    /**
985a25f0a04SGreg Roach     * Find repositories linked to this record.
986a25f0a04SGreg Roach     *
987a25f0a04SGreg Roach     * @param string $link
988a25f0a04SGreg Roach     *
989907c1109SGreg Roach     * @return Collection
990a25f0a04SGreg Roach     */
991907c1109SGreg Roach    public function linkedRepositories(string $link): Collection
992c1010edaSGreg Roach    {
993907c1109SGreg Roach        return DB::table('other')
9940b5fd0a6SGreg Roach            ->join('link', static function (JoinClause $join): void {
995907c1109SGreg Roach                $join
996907c1109SGreg Roach                    ->on('l_file', '=', 'o_file')
997907c1109SGreg Roach                    ->on('l_from', '=', 'o_id');
998ba1c12e8SGreg Roach            })
999ba1c12e8SGreg Roach            ->where('o_file', '=', $this->tree->id())
1000ba1c12e8SGreg Roach            ->where('o_type', '=', 'REPO')
1001ba1c12e8SGreg Roach            ->where('l_type', '=', $link)
1002ba1c12e8SGreg Roach            ->where('l_to', '=', $this->xref)
1003907c1109SGreg Roach            ->select(['other.*'])
1004907c1109SGreg Roach            ->get()
1005907c1109SGreg Roach            ->map(Individual::rowMapper())
1006907c1109SGreg Roach            ->filter(self::accessFilter());
1007a25f0a04SGreg Roach    }
1008a25f0a04SGreg Roach
1009a25f0a04SGreg Roach    /**
1010a25f0a04SGreg Roach     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
1011a25f0a04SGreg Roach     * This is used to display multiple events on the individual/family lists.
1012a25f0a04SGreg Roach     * Multiple events can exist because of uncertainty in dates, dates in different
1013a25f0a04SGreg Roach     * calendars, place-names in both latin and hebrew character sets, etc.
1014a25f0a04SGreg Roach     * It also allows us to combine dates/places from different events in the summaries.
1015a25f0a04SGreg Roach     *
10168d0ebef0SGreg Roach     * @param string[] $events
1017a25f0a04SGreg Roach     *
1018a25f0a04SGreg Roach     * @return Date[]
1019a25f0a04SGreg Roach     */
10208d0ebef0SGreg Roach    public function getAllEventDates(array $events): array
1021c1010edaSGreg Roach    {
102213abd6f3SGreg Roach        $dates = [];
10238d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
10242decada7SGreg Roach            if ($event->date()->isOK()) {
10252decada7SGreg Roach                $dates[] = $event->date();
1026a25f0a04SGreg Roach            }
1027a25f0a04SGreg Roach        }
1028a25f0a04SGreg Roach
1029a25f0a04SGreg Roach        return $dates;
1030a25f0a04SGreg Roach    }
1031a25f0a04SGreg Roach
1032a25f0a04SGreg Roach    /**
1033a25f0a04SGreg Roach     * Get all the places for a particular type of event
1034a25f0a04SGreg Roach     *
10358d0ebef0SGreg Roach     * @param string[] $events
1036a25f0a04SGreg Roach     *
10374080d558SGreg Roach     * @return Place[]
1038a25f0a04SGreg Roach     */
10398d0ebef0SGreg Roach    public function getAllEventPlaces(array $events): array
1040c1010edaSGreg Roach    {
104113abd6f3SGreg Roach        $places = [];
10428d0ebef0SGreg Roach        foreach ($this->facts($events) as $event) {
1043138ca96cSGreg Roach            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->gedcom(), $ged_places)) {
1044a25f0a04SGreg Roach                foreach ($ged_places[1] as $ged_place) {
104516d0b7f7SRico Sonntag                    $places[] = new Place($ged_place, $this->tree);
1046a25f0a04SGreg Roach                }
1047a25f0a04SGreg Roach            }
1048a25f0a04SGreg Roach        }
1049a25f0a04SGreg Roach
1050a25f0a04SGreg Roach        return $places;
1051a25f0a04SGreg Roach    }
1052a25f0a04SGreg Roach
1053a25f0a04SGreg Roach    /**
1054a25f0a04SGreg Roach     * The facts and events for this record.
1055a25f0a04SGreg Roach     *
10568d0ebef0SGreg Roach     * @param string[] $filter
1057cbc1590aSGreg Roach     * @param bool     $sort
1058cbc1590aSGreg Roach     * @param int|null $access_level
1059cbc1590aSGreg Roach     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1060a25f0a04SGreg Roach     *
106154c7f8dfSGreg Roach     * @return Collection
1062a25f0a04SGreg Roach     */
106339ca88baSGreg Roach    public function facts(array $filter = [], bool $sort = false, int $access_level = null, bool $override = false): Collection
1064c1010edaSGreg Roach    {
10654b9ff166SGreg Roach        if ($access_level === null) {
10664b9ff166SGreg Roach            $access_level = Auth::accessLevel($this->tree);
10674b9ff166SGreg Roach        }
10684b9ff166SGreg Roach
10698af3e5c1SGreg Roach        $facts = new Collection();
1070a25f0a04SGreg Roach        if ($this->canShow($access_level) || $override) {
1071a25f0a04SGreg Roach            foreach ($this->facts as $fact) {
107222d65e5aSGreg Roach                if (($filter === [] || in_array($fact->getTag(), $filter, true)) && $fact->canShow($access_level)) {
10738af3e5c1SGreg Roach                    $facts->push($fact);
1074a25f0a04SGreg Roach                }
1075a25f0a04SGreg Roach            }
1076a25f0a04SGreg Roach        }
1077d17d7b9eSGreg Roach
1078a25f0a04SGreg Roach        if ($sort) {
1079580a4d11SGreg Roach            $facts = Fact::sortFacts($facts);
1080a25f0a04SGreg Roach        }
1081cbc1590aSGreg Roach
108239ca88baSGreg Roach        return new Collection($facts);
1083a25f0a04SGreg Roach    }
1084a25f0a04SGreg Roach
1085a25f0a04SGreg Roach    /**
10864459dc9aSGreg Roach     * Get the last-change timestamp for this record
1087a25f0a04SGreg Roach     *
10884459dc9aSGreg Roach     * @return Carbon
1089a25f0a04SGreg Roach     */
10904459dc9aSGreg Roach    public function lastChangeTimestamp(): Carbon
1091c1010edaSGreg Roach    {
10924459dc9aSGreg Roach        /** @var Fact|null $chan */
1093820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
1094a25f0a04SGreg Roach
10954459dc9aSGreg Roach        if ($chan instanceof Fact) {
1096a25f0a04SGreg Roach            // The record does have a CHAN event
10972decada7SGreg Roach            $d = $chan->date()->minimumDate();
10984459dc9aSGreg Roach
1099138ca96cSGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->gedcom(), $match)) {
11004459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2], (int) $match[3]);
1101e364afe4SGreg Roach            }
1102e364afe4SGreg Roach
1103e364afe4SGreg Roach            if (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->gedcom(), $match)) {
11044459dc9aSGreg Roach                return Carbon::create($d->year(), $d->month(), $d->day(), (int) $match[1], (int) $match[2]);
1105b2ce94c6SRico Sonntag            }
1106b2ce94c6SRico Sonntag
11074459dc9aSGreg Roach            return Carbon::create($d->year(), $d->month(), $d->day());
1108a25f0a04SGreg Roach        }
1109b2ce94c6SRico Sonntag
1110a25f0a04SGreg Roach        // The record does not have a CHAN event
11114459dc9aSGreg Roach        return Carbon::createFromTimestamp(0);
1112a25f0a04SGreg Roach    }
1113a25f0a04SGreg Roach
1114a25f0a04SGreg Roach    /**
1115a25f0a04SGreg Roach     * Get the last-change user for this record
1116a25f0a04SGreg Roach     *
1117a25f0a04SGreg Roach     * @return string
1118a25f0a04SGreg Roach     */
1119e364afe4SGreg Roach    public function lastChangeUser(): string
1120c1010edaSGreg Roach    {
1121820b62dfSGreg Roach        $chan = $this->facts(['CHAN'])->first();
1122a25f0a04SGreg Roach
1123a25f0a04SGreg Roach        if ($chan === null) {
1124a25f0a04SGreg Roach            return I18N::translate('Unknown');
1125b2ce94c6SRico Sonntag        }
1126b2ce94c6SRico Sonntag
11273425616eSGreg Roach        $chan_user = $chan->attribute('_WT_USER');
1128baacc364SGreg Roach        if ($chan_user === '') {
1129a25f0a04SGreg Roach            return I18N::translate('Unknown');
1130b2ce94c6SRico Sonntag        }
1131b2ce94c6SRico Sonntag
1132a25f0a04SGreg Roach        return $chan_user;
1133a25f0a04SGreg Roach    }
1134a25f0a04SGreg Roach
1135a25f0a04SGreg Roach    /**
1136a25f0a04SGreg Roach     * Add a new fact to this record
1137a25f0a04SGreg Roach     *
1138a25f0a04SGreg Roach     * @param string $gedcom
1139cbc1590aSGreg Roach     * @param bool   $update_chan
11407e96c925SGreg Roach     *
11417e96c925SGreg Roach     * @return void
1142a25f0a04SGreg Roach     */
1143e364afe4SGreg Roach    public function createFact(string $gedcom, bool $update_chan): void
1144c1010edaSGreg Roach    {
1145fc3ccce4SGreg Roach        $this->updateFact('', $gedcom, $update_chan);
1146a25f0a04SGreg Roach    }
1147a25f0a04SGreg Roach
1148a25f0a04SGreg Roach    /**
1149a25f0a04SGreg Roach     * Delete a fact from this record
1150a25f0a04SGreg Roach     *
1151a25f0a04SGreg Roach     * @param string $fact_id
1152cbc1590aSGreg Roach     * @param bool   $update_chan
11537e96c925SGreg Roach     *
11547e96c925SGreg Roach     * @return void
1155a25f0a04SGreg Roach     */
1156e364afe4SGreg Roach    public function deleteFact(string $fact_id, bool $update_chan): void
1157c1010edaSGreg Roach    {
1158db7bb364SGreg Roach        $this->updateFact($fact_id, '', $update_chan);
1159a25f0a04SGreg Roach    }
1160a25f0a04SGreg Roach
1161a25f0a04SGreg Roach    /**
1162a25f0a04SGreg Roach     * Replace a fact with a new gedcom data.
1163a25f0a04SGreg Roach     *
1164a25f0a04SGreg Roach     * @param string $fact_id
1165a25f0a04SGreg Roach     * @param string $gedcom
1166cbc1590aSGreg Roach     * @param bool   $update_chan
1167a25f0a04SGreg Roach     *
11687e96c925SGreg Roach     * @return void
11697e96c925SGreg Roach     * @throws Exception
1170a25f0a04SGreg Roach     */
1171e364afe4SGreg Roach    public function updateFact(string $fact_id, string $gedcom, bool $update_chan): void
1172c1010edaSGreg Roach    {
1173a25f0a04SGreg Roach        // MSDOS line endings will break things in horrible ways
1174a25f0a04SGreg Roach        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1175a25f0a04SGreg Roach        $gedcom = trim($gedcom);
1176a25f0a04SGreg Roach
1177a25f0a04SGreg Roach        if ($this->pending === '') {
11787e96c925SGreg Roach            throw new Exception('Cannot edit a deleted record');
1179a25f0a04SGreg Roach        }
11808d0ebef0SGreg Roach        if ($gedcom !== '' && !preg_match('/^1 ' . Gedcom::REGEX_TAG . '/', $gedcom)) {
11817e96c925SGreg Roach            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1182a25f0a04SGreg Roach        }
1183a25f0a04SGreg Roach
1184a25f0a04SGreg Roach        if ($this->pending) {
1185a25f0a04SGreg Roach            $old_gedcom = $this->pending;
1186a25f0a04SGreg Roach        } else {
1187a25f0a04SGreg Roach            $old_gedcom = $this->gedcom;
1188a25f0a04SGreg Roach        }
1189a25f0a04SGreg Roach
1190a25f0a04SGreg Roach        // First line of record may contain data - e.g. NOTE records.
119165e02381SGreg Roach        [$new_gedcom] = explode("\n", $old_gedcom, 2);
1192a25f0a04SGreg Roach
1193a25f0a04SGreg Roach        // Replacing (or deleting) an existing fact
11948d0ebef0SGreg Roach        foreach ($this->facts([], false, Auth::PRIV_HIDE) as $fact) {
1195a25f0a04SGreg Roach            if (!$fact->isPendingDeletion()) {
1196905ab80aSGreg Roach                if ($fact->id() === $fact_id) {
1197db7bb364SGreg Roach                    if ($gedcom !== '') {
1198a25f0a04SGreg Roach                        $new_gedcom .= "\n" . $gedcom;
1199a25f0a04SGreg Roach                    }
1200fc3ccce4SGreg Roach                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1201e364afe4SGreg Roach                } elseif ($fact->getTag() !== 'CHAN' || !$update_chan) {
1202138ca96cSGreg Roach                    $new_gedcom .= "\n" . $fact->gedcom();
1203a25f0a04SGreg Roach                }
1204a25f0a04SGreg Roach            }
1205a25f0a04SGreg Roach        }
1206a25f0a04SGreg Roach        if ($update_chan) {
1207e5a6b4d4SGreg Roach            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1208a25f0a04SGreg Roach        }
1209a25f0a04SGreg Roach
1210a25f0a04SGreg Roach        // Adding a new fact
1211fc3ccce4SGreg Roach        if ($fact_id === '') {
1212a25f0a04SGreg Roach            $new_gedcom .= "\n" . $gedcom;
1213a25f0a04SGreg Roach        }
1214a25f0a04SGreg Roach
1215e364afe4SGreg Roach        if ($new_gedcom !== $old_gedcom) {
1216a25f0a04SGreg Roach            // Save the changes
1217d09b6323SGreg Roach            DB::table('change')->insert([
1218d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1219d09b6323SGreg Roach                'xref'       => $this->xref,
1220d09b6323SGreg Roach                'old_gedcom' => $old_gedcom,
1221d09b6323SGreg Roach                'new_gedcom' => $new_gedcom,
1222d09b6323SGreg Roach                'user_id'    => Auth::id(),
122313abd6f3SGreg Roach            ]);
1224a25f0a04SGreg Roach
1225a25f0a04SGreg Roach            $this->pending = $new_gedcom;
1226a25f0a04SGreg Roach
1227a25f0a04SGreg Roach            if (Auth::user()->getPreference('auto_accept')) {
1228cc5684fdSGreg Roach                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1229a25f0a04SGreg Roach                $this->gedcom  = $new_gedcom;
1230a25f0a04SGreg Roach                $this->pending = null;
1231a25f0a04SGreg Roach            }
1232a25f0a04SGreg Roach        }
1233a25f0a04SGreg Roach        $this->parseFacts();
1234a25f0a04SGreg Roach    }
1235a25f0a04SGreg Roach
1236a25f0a04SGreg Roach    /**
1237a25f0a04SGreg Roach     * Update this record
1238a25f0a04SGreg Roach     *
1239a25f0a04SGreg Roach     * @param string $gedcom
1240cbc1590aSGreg Roach     * @param bool   $update_chan
12417e96c925SGreg Roach     *
12427e96c925SGreg Roach     * @return void
1243a25f0a04SGreg Roach     */
1244e364afe4SGreg Roach    public function updateRecord(string $gedcom, bool $update_chan): void
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        // Update the CHAN record
1251a25f0a04SGreg Roach        if ($update_chan) {
1252a25f0a04SGreg Roach            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1253e5a6b4d4SGreg Roach            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->userName();
1254a25f0a04SGreg Roach        }
1255a25f0a04SGreg Roach
1256a25f0a04SGreg Roach        // Create a pending change
1257d09b6323SGreg Roach        DB::table('change')->insert([
1258d09b6323SGreg Roach            'gedcom_id'  => $this->tree->id(),
1259d09b6323SGreg Roach            'xref'       => $this->xref,
1260d09b6323SGreg Roach            'old_gedcom' => $this->gedcom(),
1261d09b6323SGreg Roach            'new_gedcom' => $gedcom,
1262d09b6323SGreg Roach            'user_id'    => Auth::id(),
126313abd6f3SGreg Roach        ]);
1264a25f0a04SGreg Roach
1265a25f0a04SGreg Roach        // Clear the cache
1266a25f0a04SGreg Roach        $this->pending = $gedcom;
1267a25f0a04SGreg Roach
1268a25f0a04SGreg Roach        // Accept this pending change
1269a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1270cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1271a25f0a04SGreg Roach            $this->gedcom  = $gedcom;
1272a25f0a04SGreg Roach            $this->pending = null;
1273a25f0a04SGreg Roach        }
1274a25f0a04SGreg Roach
1275a25f0a04SGreg Roach        $this->parseFacts();
1276a25f0a04SGreg Roach
1277847d5489SGreg Roach        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1278a25f0a04SGreg Roach    }
1279a25f0a04SGreg Roach
1280a25f0a04SGreg Roach    /**
1281a25f0a04SGreg Roach     * Delete this record
1282b874da82SGreg Roach     *
1283b874da82SGreg Roach     * @return void
1284a25f0a04SGreg Roach     */
1285e364afe4SGreg Roach    public function deleteRecord(): void
1286c1010edaSGreg Roach    {
1287a25f0a04SGreg Roach        // Create a pending change
12884c0b5256SGreg Roach        if (!$this->isPendingDeletion()) {
1289d09b6323SGreg Roach            DB::table('change')->insert([
1290d09b6323SGreg Roach                'gedcom_id'  => $this->tree->id(),
1291d09b6323SGreg Roach                'xref'       => $this->xref,
1292d09b6323SGreg Roach                'old_gedcom' => $this->gedcom(),
1293d09b6323SGreg Roach                'new_gedcom' => '',
1294d09b6323SGreg Roach                'user_id'    => Auth::id(),
129513abd6f3SGreg Roach            ]);
12964c0b5256SGreg Roach        }
1297a25f0a04SGreg Roach
12984c0b5256SGreg Roach        // Auto-accept this pending change
1299a25f0a04SGreg Roach        if (Auth::user()->getPreference('auto_accept')) {
1300cc5684fdSGreg Roach            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1301a25f0a04SGreg Roach        }
1302a25f0a04SGreg Roach
1303a25f0a04SGreg Roach        // Clear the cache
1304d17d7b9eSGreg Roach        self::$gedcom_record_cache  = [];
1305d17d7b9eSGreg Roach        self::$pending_record_cache = [];
1306a25f0a04SGreg Roach
1307847d5489SGreg Roach        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1308a25f0a04SGreg Roach    }
1309a25f0a04SGreg Roach
1310a25f0a04SGreg Roach    /**
1311a25f0a04SGreg Roach     * Remove all links from this record to $xref
1312a25f0a04SGreg Roach     *
1313a25f0a04SGreg Roach     * @param string $xref
1314cbc1590aSGreg Roach     * @param bool   $update_chan
13157e96c925SGreg Roach     *
13167e96c925SGreg Roach     * @return void
1317a25f0a04SGreg Roach     */
1318e364afe4SGreg Roach    public function removeLinks(string $xref, bool $update_chan): void
1319c1010edaSGreg Roach    {
1320a25f0a04SGreg Roach        $value = '@' . $xref . '@';
1321a25f0a04SGreg Roach
132230158ae7SGreg Roach        foreach ($this->facts() as $fact) {
132384586c02SGreg Roach            if ($fact->value() === $value) {
1324905ab80aSGreg Roach                $this->deleteFact($fact->id(), $update_chan);
13258d0ebef0SGreg Roach            } elseif (preg_match_all('/\n(\d) ' . Gedcom::REGEX_TAG . ' ' . $value . '/', $fact->gedcom(), $matches, PREG_SET_ORDER)) {
1326138ca96cSGreg Roach                $gedcom = $fact->gedcom();
1327a25f0a04SGreg Roach                foreach ($matches as $match) {
1328a25f0a04SGreg Roach                    $next_level  = $match[1] + 1;
1329a25f0a04SGreg Roach                    $next_levels = '[' . $next_level . '-9]';
1330a25f0a04SGreg Roach                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1331a25f0a04SGreg Roach                }
1332905ab80aSGreg Roach                $this->updateFact($fact->id(), $gedcom, $update_chan);
1333a25f0a04SGreg Roach            }
1334a25f0a04SGreg Roach        }
1335a25f0a04SGreg Roach    }
1336bf4eb542SGreg Roach
1337bf4eb542SGreg Roach    /**
1338bf4eb542SGreg Roach     * Fetch XREFs of all records linked to a record - when deleting an object, we must
1339bf4eb542SGreg Roach     * also delete all links to it.
1340bf4eb542SGreg Roach     *
1341bf4eb542SGreg Roach     * @return GedcomRecord[]
1342bf4eb542SGreg Roach     */
1343bf4eb542SGreg Roach    public function linkingRecords(): array
1344bf4eb542SGreg Roach    {
1345bf4eb542SGreg Roach        $union = DB::table('change')
1346bf4eb542SGreg Roach            ->where('gedcom_id', '=', $this->tree()->id())
1347fbbe964bSGreg Roach            ->whereContains('new_gedcom', '@' . $this->xref() . '@')
1348bf4eb542SGreg Roach            ->where('new_gedcom', 'NOT LIKE', '0 @' . $this->xref() . '@%')
134983242252SGreg Roach            ->whereIn('change_id', function (Builder $query): void {
135083242252SGreg Roach                $query->select(new Expression('MAX(change_id)'))
135183242252SGreg Roach                    ->from('change')
135283242252SGreg Roach                    ->where('gedcom_id', '=', $this->tree->id())
135383242252SGreg Roach                    ->where('status', '=', 'pending')
13547f5c2944SGreg Roach                    ->groupBy(['xref']);
135583242252SGreg Roach            })
1356bf4eb542SGreg Roach            ->select(['xref']);
1357bf4eb542SGreg Roach
1358bf4eb542SGreg Roach        $xrefs = DB::table('link')
1359bf4eb542SGreg Roach            ->where('l_file', '=', $this->tree()->id())
1360bf4eb542SGreg Roach            ->where('l_to', '=', $this->xref())
136147256fc5SGreg Roach            ->select(['l_from'])
1362bf4eb542SGreg Roach            ->union($union)
1363bf4eb542SGreg Roach            ->pluck('l_from');
1364bf4eb542SGreg Roach
1365bf4eb542SGreg Roach        return $xrefs->map(function (string $xref): GedcomRecord {
1366bf4eb542SGreg Roach            return GedcomRecord::getInstance($xref, $this->tree);
1367bf4eb542SGreg Roach        })->all();
1368bf4eb542SGreg Roach    }
1369a25f0a04SGreg Roach}
1370