xref: /webtrees/app/GedcomRecord.php (revision 67994fb087e1b24564a780e4ae8aeff801733e35)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees;
19
20use Exception;
21use Fisharebest\Webtrees\Functions\Functions;
22use Fisharebest\Webtrees\Functions\FunctionsDate;
23use Fisharebest\Webtrees\Functions\FunctionsImport;
24use Fisharebest\Webtrees\Functions\FunctionsPrint;
25use stdClass;
26
27/**
28 * A GEDCOM object.
29 */
30class GedcomRecord
31{
32    const RECORD_TYPE = 'UNKNOWN';
33    const ROUTE_NAME  = 'record';
34
35    /** @var string The record identifier */
36    protected $xref;
37
38    /** @var Tree  The family tree to which this record belongs */
39    protected $tree;
40
41    /** @var string  GEDCOM data (before any pending edits) */
42    protected $gedcom;
43
44    /** @var string|null  GEDCOM data (after any pending edits) */
45    protected $pending;
46
47    /** @var Fact[] facts extracted from $gedcom/$pending */
48    protected $facts;
49
50    /** @var bool Can we display details of this record to Auth::PRIV_PRIVATE */
51    private $disp_public;
52
53    /** @var bool Can we display details of this record to Auth::PRIV_USER */
54    private $disp_user;
55
56    /** @var bool Can we display details of this record to Auth::PRIV_NONE */
57    private $disp_none;
58
59    /** @var string[][] All the names of this individual */
60    protected $getAllNames;
61
62    /** @var int Cached result */
63    protected $getPrimaryName;
64
65    /** @var int Cached result */
66    protected $getSecondaryName;
67
68    /** @var GedcomRecord[][] Allow getInstance() to return references to existing objects */
69    protected static $gedcom_record_cache;
70
71    /** @var stdClass[][] Fetch all pending edits in one database query */
72    private static $pending_record_cache;
73
74    /**
75     * Create a GedcomRecord object from raw GEDCOM data.
76     *
77     * @param string      $xref
78     * @param string      $gedcom  an empty string for new/pending records
79     * @param string|null $pending null for a record with no pending edits,
80     *                             empty string for records with pending deletions
81     * @param Tree        $tree
82     */
83    public function __construct(string $xref, string $gedcom, $pending, Tree $tree)
84    {
85        $this->xref    = $xref;
86        $this->gedcom  = $gedcom;
87        $this->pending = $pending;
88        $this->tree    = $tree;
89
90        $this->parseFacts();
91    }
92
93    /**
94     * Split the record into facts
95     *
96     * @return void
97     */
98    private function parseFacts()
99    {
100        // Split the record into facts
101        if ($this->gedcom) {
102            $gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
103            array_shift($gedcom_facts);
104        } else {
105            $gedcom_facts = [];
106        }
107        if ($this->pending) {
108            $pending_facts = preg_split('/\n(?=1)/s', $this->pending);
109            array_shift($pending_facts);
110        } else {
111            $pending_facts = [];
112        }
113
114        $this->facts = [];
115
116        foreach ($gedcom_facts as $gedcom_fact) {
117            $fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
118            if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts)) {
119                $fact->setPendingDeletion();
120            }
121            $this->facts[] = $fact;
122        }
123        foreach ($pending_facts as $pending_fact) {
124            if (!in_array($pending_fact, $gedcom_facts)) {
125                $fact = new Fact($pending_fact, $this, md5($pending_fact));
126                $fact->setPendingAddition();
127                $this->facts[] = $fact;
128            }
129        }
130    }
131
132    /**
133     * Get an instance of a GedcomRecord object. For single records,
134     * we just receive the XREF. For bulk records (such as lists
135     * and search results) we can receive the GEDCOM data as well.
136     *
137     * @param string      $xref
138     * @param Tree        $tree
139     * @param string|null $gedcom
140     *
141     * @throws Exception
142     *
143     * @return GedcomRecord|Individual|Family|Source|Repository|Media|Note|null
144     */
145    public static function getInstance(string $xref, Tree $tree, string $gedcom = null)
146    {
147        $tree_id = $tree->getTreeId();
148
149        // Is this record already in the cache?
150        if (isset(self::$gedcom_record_cache[$xref][$tree_id])) {
151            return self::$gedcom_record_cache[$xref][$tree_id];
152        }
153
154        // Do we need to fetch the record from the database?
155        if ($gedcom === null) {
156            $gedcom = static::fetchGedcomRecord($xref, $tree_id);
157        }
158
159        // If we can edit, then we also need to be able to see pending records.
160        if (Auth::isEditor($tree)) {
161            if (!isset(self::$pending_record_cache[$tree_id])) {
162                // Fetch all pending records in one database query
163                self::$pending_record_cache[$tree_id] = [];
164                $rows                                 = Database::prepare(
165                    "SELECT xref, new_gedcom FROM `##change` WHERE status = 'pending' AND gedcom_id = :tree_id ORDER BY change_id"
166                )->execute([
167                    'tree_id' => $tree_id,
168                ])->fetchAll();
169                foreach ($rows as $row) {
170                    self::$pending_record_cache[$tree_id][$row->xref] = $row->new_gedcom;
171                }
172            }
173
174            if (isset(self::$pending_record_cache[$tree_id][$xref])) {
175                // A pending edit exists for this record
176                $pending = self::$pending_record_cache[$tree_id][$xref];
177            } else {
178                $pending = null;
179            }
180        } else {
181            // There are no pending changes for this record
182            $pending = null;
183        }
184
185        // No such record exists
186        if ($gedcom === null && $pending === null) {
187            return null;
188        }
189
190        // No such record, but a pending creation exists
191        if ($gedcom === null) {
192            $gedcom = '';
193        }
194
195        // Create the object
196        if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom . $pending, $match)) {
197            $xref = $match[1]; // Collation - we may have requested I123 and found i123
198            $type = $match[2];
199        } elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
200            $xref = $match[1];
201            $type = $match[1];
202        } elseif ($gedcom . $pending) {
203            throw new Exception('Unrecognized GEDCOM record: ' . $gedcom);
204        } else {
205            // A record with both pending creation and pending deletion
206            $type = static::RECORD_TYPE;
207        }
208
209        switch ($type) {
210            case 'INDI':
211                $record = new Individual($xref, $gedcom, $pending, $tree);
212                break;
213            case 'FAM':
214                $record = new Family($xref, $gedcom, $pending, $tree);
215                break;
216            case 'SOUR':
217                $record = new Source($xref, $gedcom, $pending, $tree);
218                break;
219            case 'OBJE':
220                $record = new Media($xref, $gedcom, $pending, $tree);
221                break;
222            case 'REPO':
223                $record = new Repository($xref, $gedcom, $pending, $tree);
224                break;
225            case 'NOTE':
226                $record = new Note($xref, $gedcom, $pending, $tree);
227                break;
228            default:
229                $record = new self($xref, $gedcom, $pending, $tree);
230                break;
231        }
232
233        // Store it in the cache
234        self::$gedcom_record_cache[$xref][$tree_id] = $record;
235
236        return $record;
237    }
238
239    /**
240     * Fetch data from the database
241     *
242     * @param string $xref
243     * @param int    $tree_id
244     *
245     * @return null|string
246     */
247    protected static function fetchGedcomRecord(string $xref, int $tree_id)
248    {
249        // We don't know what type of object this is. Try each one in turn.
250        $data = Individual::fetchGedcomRecord($xref, $tree_id);
251        if ($data) {
252            return $data;
253        }
254        $data = Family::fetchGedcomRecord($xref, $tree_id);
255        if ($data) {
256            return $data;
257        }
258        $data = Source::fetchGedcomRecord($xref, $tree_id);
259        if ($data) {
260            return $data;
261        }
262        $data = Repository::fetchGedcomRecord($xref, $tree_id);
263        if ($data) {
264            return $data;
265        }
266        $data = Media::fetchGedcomRecord($xref, $tree_id);
267        if ($data) {
268            return $data;
269        }
270        $data = Note::fetchGedcomRecord($xref, $tree_id);
271        if ($data) {
272            return $data;
273        }
274
275        // Some other type of record...
276
277        return Database::prepare(
278            "SELECT o_gedcom FROM `##other` WHERE o_id = :xref AND o_file = :tree_id"
279        )->execute([
280            'xref'    => $xref,
281            'tree_id' => $tree_id,
282        ])->fetchOne();
283    }
284
285    /**
286     * Get the XREF for this record
287     *
288     * @return string
289     */
290    public function getXref(): string
291    {
292        return $this->xref;
293    }
294
295    /**
296     * Get the tree to which this record belongs
297     *
298     * @return Tree
299     */
300    public function getTree(): Tree
301    {
302        return $this->tree;
303    }
304
305    /**
306     * Application code should access data via Fact objects.
307     * This function exists to support old code.
308     *
309     * @return string
310     */
311    public function getGedcom()
312    {
313        return $this->pending ?? $this->gedcom;
314    }
315
316    /**
317     * Does this record have a pending change?
318     *
319     * @return bool
320     */
321    public function isPendingAddition(): bool
322    {
323        return $this->pending !== null;
324    }
325
326    /**
327     * Does this record have a pending deletion?
328     *
329     * @return bool
330     */
331    public function isPendingDeletion(): bool
332    {
333        return $this->pending === '';
334    }
335
336    /**
337     * Generate a URL to this record, suitable for use in HTML, etc.
338     *
339     * @deprecated
340     *
341     * @return string
342     */
343    public function getHtmlUrl(): string
344    {
345        return e($this->url());
346    }
347
348    /**
349     * Generate a URL to this record.
350     *
351     * @deprecated
352     *
353     * @return string
354     */
355    public function getRawUrl(): string
356    {
357        return $this->url();
358    }
359
360    /**
361     * Generate a URL to this record.
362     *
363     * @return string
364     */
365    public function url(): string
366    {
367        return route(static::ROUTE_NAME, [
368            'xref' => $this->getXref(),
369            'ged'  => $this->tree->getName(),
370        ]);
371    }
372
373    /**
374     * Work out whether this record can be shown to a user with a given access level
375     *
376     * @param int $access_level
377     *
378     * @return bool
379     */
380    private function canShowRecord(int $access_level): bool
381    {
382        // This setting would better be called "$ENABLE_PRIVACY"
383        if (!$this->tree->getPreference('HIDE_LIVE_PEOPLE')) {
384            return true;
385        }
386
387        // We should always be able to see our own record (unless an admin is applying download restrictions)
388        if ($this->getXref() === $this->tree->getUserPreference(Auth::user(), 'gedcomid') && $access_level === Auth::accessLevel($this->tree)) {
389            return true;
390        }
391
392        // Does this record have a RESN?
393        if (strpos($this->gedcom, "\n1 RESN confidential") !== false) {
394            return Auth::PRIV_NONE >= $access_level;
395        }
396        if (strpos($this->gedcom, "\n1 RESN privacy") !== false) {
397            return Auth::PRIV_USER >= $access_level;
398        }
399        if (strpos($this->gedcom, "\n1 RESN none") !== false) {
400            return true;
401        }
402
403        // Does this record have a default RESN?
404        $individual_privacy = $this->tree->getIndividualPrivacy();
405        if (isset($individual_privacy[$this->getXref()])) {
406            return $individual_privacy[$this->getXref()] >= $access_level;
407        }
408
409        // Privacy rules do not apply to admins
410        if (Auth::PRIV_NONE >= $access_level) {
411            return true;
412        }
413
414        // Different types of record have different privacy rules
415        return $this->canShowByType($access_level);
416    }
417
418    /**
419     * Each object type may have its own special rules, and re-implement this function.
420     *
421     * @param int $access_level
422     *
423     * @return bool
424     */
425    protected function canShowByType(int $access_level): bool
426    {
427        $fact_privacy = $this->tree->getFactPrivacy();
428
429        if (isset($fact_privacy[static::RECORD_TYPE])) {
430            // Restriction found
431            return $fact_privacy[static::RECORD_TYPE] >= $access_level;
432        }
433
434        // No restriction found - must be public:
435        return true;
436    }
437
438    /**
439     * Can the details of this record be shown?
440     *
441     * @param int|null $access_level
442     *
443     * @return bool
444     */
445    public function canShow(int $access_level = null): bool
446    {
447        if ($access_level === null) {
448            $access_level = Auth::accessLevel($this->tree);
449        }
450
451        // CACHING: this function can take three different parameters,
452        // and therefore needs three different caches for the result.
453        switch ($access_level) {
454            case Auth::PRIV_PRIVATE: // visitor
455                if ($this->disp_public === null) {
456                    $this->disp_public = $this->canShowRecord(Auth::PRIV_PRIVATE);
457                }
458
459                return $this->disp_public;
460            case Auth::PRIV_USER: // member
461                if ($this->disp_user === null) {
462                    $this->disp_user = $this->canShowRecord(Auth::PRIV_USER);
463                }
464
465                return $this->disp_user;
466            case Auth::PRIV_NONE: // admin
467                if ($this->disp_none === null) {
468                    $this->disp_none = $this->canShowRecord(Auth::PRIV_NONE);
469                }
470
471                return $this->disp_none;
472            case Auth::PRIV_HIDE: // hidden from admins
473                // We use this value to bypass privacy checks. For example,
474                // when downloading data or when calculating privacy itself.
475                return true;
476            default:
477                // Should never get here.
478                return false;
479        }
480    }
481
482    /**
483     * Can the name of this record be shown?
484     *
485     * @param int|null $access_level
486     *
487     * @return bool
488     */
489    public function canShowName(int $access_level = null): bool
490    {
491        if ($access_level === null) {
492            $access_level = Auth::accessLevel($this->tree);
493        }
494
495        return $this->canShow($access_level);
496    }
497
498    /**
499     * Can we edit this record?
500     *
501     * @return bool
502     */
503    public function canEdit(): bool
504    {
505        return Auth::isManager($this->tree) || Auth::isEditor($this->tree) && strpos($this->gedcom, "\n1 RESN locked") === false;
506    }
507
508    /**
509     * Remove private data from the raw gedcom record.
510     * Return both the visible and invisible data. We need the invisible data when editing.
511     *
512     * @param int $access_level
513     *
514     * @return string
515     */
516    public function privatizeGedcom(int $access_level)
517    {
518        if ($access_level == Auth::PRIV_HIDE) {
519            // We may need the original record, for example when downloading a GEDCOM or clippings cart
520            return $this->gedcom;
521        }
522
523        if ($this->canShow($access_level)) {
524            // The record is not private, but the individual facts may be.
525
526            // Include the entire first line (for NOTE records)
527            list($gedrec) = explode("\n", $this->gedcom, 2);
528
529            // Check each of the facts for access
530            foreach ($this->getFacts(null, false, $access_level) as $fact) {
531                $gedrec .= "\n" . $fact->getGedcom();
532            }
533
534            return $gedrec;
535        }
536
537        // We cannot display the details, but we may be able to display
538        // limited data, such as links to other records.
539        return $this->createPrivateGedcomRecord($access_level);
540    }
541
542    /**
543     * Generate a private version of this record
544     *
545     * @param int $access_level
546     *
547     * @return string
548     */
549    protected function createPrivateGedcomRecord(int $access_level): string
550    {
551        return '0 @' . $this->xref . '@ ' . static::RECORD_TYPE . "\n1 NOTE " . I18N::translate('Private');
552    }
553
554    /**
555     * Convert a name record into sortable and full/display versions. This default
556     * should be OK for simple record types. INDI/FAM records will need to redefine it.
557     *
558     * @param string $type
559     * @param string $value
560     * @param string $gedcom
561     *
562     * @return void
563     */
564    protected function addName(string $type, string $value, string $gedcom)
565    {
566        $this->getAllNames[] = [
567            'type'   => $type,
568            'sort'   => preg_replace_callback('/([0-9]+)/', function (array $matches): string {
569                return str_pad($matches[0], 10, '0', STR_PAD_LEFT);
570            }, $value),
571            'full'   => '<span dir="auto">' . e($value) . '</span>',
572            // This is used for display
573            'fullNN' => $value,
574            // This goes into the database
575        ];
576    }
577
578    /**
579     * Get all the names of a record, including ROMN, FONE and _HEB alternatives.
580     * Records without a name (e.g. FAM) will need to redefine this function.
581     * Parameters: the level 1 fact containing the name.
582     * Return value: an array of name structures, each containing
583     * ['type'] = the gedcom fact, e.g. NAME, TITL, FONE, _HEB, etc.
584     * ['full'] = the name as specified in the record, e.g. 'Vincent van Gogh' or 'John Unknown'
585     * ['sort'] = a sortable version of the name (not for display), e.g. 'Gogh, Vincent' or '@N.N., John'
586     *
587     * @param int    $level
588     * @param string $fact_type
589     * @param Fact[] $facts
590     *
591     * @return void
592     */
593    protected function extractNamesFromFacts(int $level, string $fact_type, array $facts)
594    {
595        $sublevel    = $level + 1;
596        $subsublevel = $sublevel + 1;
597        foreach ($facts as $fact) {
598            if (preg_match_all("/^{$level} ({$fact_type}) (.+)((\n[{$sublevel}-9].+)*)/m", $fact->getGedcom(), $matches, PREG_SET_ORDER)) {
599                foreach ($matches as $match) {
600                    // Treat 1 NAME / 2 TYPE married the same as _MARNM
601                    if ($match[1] == 'NAME' && strpos($match[3], "\n2 TYPE married") !== false) {
602                        $this->addName('_MARNM', $match[2], $fact->getGedcom());
603                    } else {
604                        $this->addName($match[1], $match[2], $fact->getGedcom());
605                    }
606                    if ($match[3] && preg_match_all("/^{$sublevel} (ROMN|FONE|_\w+) (.+)((\n[{$subsublevel}-9].+)*)/m", $match[3], $submatches, PREG_SET_ORDER)) {
607                        foreach ($submatches as $submatch) {
608                            $this->addName($submatch[1], $submatch[2], $match[3]);
609                        }
610                    }
611                }
612            }
613        }
614    }
615
616    /**
617     * Default for "other" object types
618     *
619     * @return void
620     */
621    public function extractNames()
622    {
623        $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
624    }
625
626    /**
627     * Derived classes should redefine this function, otherwise the object will have no name
628     *
629     * @return string[][]
630     */
631    public function getAllNames(): array
632    {
633        if ($this->getAllNames === null) {
634            $this->getAllNames = [];
635            if ($this->canShowName()) {
636                // Ask the record to extract its names
637                $this->extractNames();
638                // No name found? Use a fallback.
639                if (!$this->getAllNames) {
640                    $this->addName(static::RECORD_TYPE, $this->getFallBackName(), '');
641                }
642            } else {
643                $this->addName(static::RECORD_TYPE, I18N::translate('Private'), '');
644            }
645        }
646
647        return $this->getAllNames;
648    }
649
650    /**
651     * If this object has no name, what do we call it?
652     *
653     * @return string
654     */
655    public function getFallBackName(): string
656    {
657        return e($this->getXref());
658    }
659
660    /**
661     * Which of the (possibly several) names of this record is the primary one.
662     *
663     * @return int
664     */
665    public function getPrimaryName(): int
666    {
667        static $language_script;
668
669        if ($language_script === null) {
670            $language_script = I18N::languageScript(WT_LOCALE);
671        }
672
673        if ($this->getPrimaryName === null) {
674            // Generally, the first name is the primary one....
675            $this->getPrimaryName = 0;
676            // ...except when the language/name use different character sets
677            foreach ($this->getAllNames() as $n => $name) {
678                if (I18N::textScript($name['sort']) === $language_script) {
679                    $this->getPrimaryName = $n;
680                    break;
681                }
682            }
683        }
684
685        return $this->getPrimaryName;
686    }
687
688    /**
689     * Which of the (possibly several) names of this record is the secondary one.
690     *
691     * @return int
692     */
693    public function getSecondaryName(): int
694    {
695        if ($this->getSecondaryName === null) {
696            // Generally, the primary and secondary names are the same
697            $this->getSecondaryName = $this->getPrimaryName();
698            // ....except when there are names with different character sets
699            $all_names = $this->getAllNames();
700            if (count($all_names) > 1) {
701                $primary_script = I18N::textScript($all_names[$this->getPrimaryName()]['sort']);
702                foreach ($all_names as $n => $name) {
703                    if ($n != $this->getPrimaryName() && $name['type'] != '_MARNM' && I18N::textScript($name['sort']) != $primary_script) {
704                        $this->getSecondaryName = $n;
705                        break;
706                    }
707                }
708            }
709        }
710
711        return $this->getSecondaryName;
712    }
713
714    /**
715     * Allow the choice of primary name to be overidden, e.g. in a search result
716     *
717     * @param int|null $n
718     *
719     * @return void
720     */
721    public function setPrimaryName(int $n = null)
722    {
723        $this->getPrimaryName   = $n;
724        $this->getSecondaryName = null;
725    }
726
727    /**
728     * Allow native PHP functions such as array_unique() to work with objects
729     *
730     * @return string
731     */
732    public function __toString()
733    {
734        return $this->xref . '@' . $this->tree->getTreeId();
735    }
736
737    /**
738     * Static helper function to sort an array of objects by name
739     * Records whose names cannot be displayed are sorted at the end.
740     *
741     * @param GedcomRecord $x
742     * @param GedcomRecord $y
743     *
744     * @return int
745     */
746    public static function compare(GedcomRecord $x, GedcomRecord $y)
747    {
748        if ($x->canShowName()) {
749            if ($y->canShowName()) {
750                return I18N::strcasecmp($x->getSortName(), $y->getSortName());
751            }
752
753            return -1; // only $y is private
754        }
755
756        if ($y->canShowName()) {
757            return 1; // only $x is private
758        }
759
760        return 0; // both $x and $y private
761    }
762
763    /**
764     * Get variants of the name
765     *
766     * @return string
767     */
768    public function getFullName()
769    {
770        if ($this->canShowName()) {
771            $tmp = $this->getAllNames();
772
773            return $tmp[$this->getPrimaryName()]['full'];
774        }
775
776        return I18N::translate('Private');
777    }
778
779    /**
780     * Get a sortable version of the name. Do not display this!
781     *
782     * @return string
783     */
784    public function getSortName(): string
785    {
786        // The sortable name is never displayed, no need to call canShowName()
787        $tmp = $this->getAllNames();
788
789        return $tmp[$this->getPrimaryName()]['sort'];
790    }
791
792    /**
793     * Get the full name in an alternative character set
794     *
795     * @return null|string
796     */
797    public function getAddName()
798    {
799        if ($this->canShowName() && $this->getPrimaryName() != $this->getSecondaryName()) {
800            $all_names = $this->getAllNames();
801
802            return $all_names[$this->getSecondaryName()]['full'];
803        }
804
805        return null;
806    }
807
808    /**
809     * Format this object for display in a list
810     *
811     * @return string
812     */
813    public function formatList(): string
814    {
815        $html = '<a href="' . e($this->url()) . '" class="list_item">';
816        $html .= '<b>' . $this->getFullName() . '</b>';
817        $html .= $this->formatListDetails();
818        $html .= '</a>';
819
820        return $html;
821    }
822
823    /**
824     * This function should be redefined in derived classes to show any major
825     * identifying characteristics of this record.
826     *
827     * @return string
828     */
829    public function formatListDetails(): string
830    {
831        return '';
832    }
833
834    /**
835     * Extract/format the first fact from a list of facts.
836     *
837     * @param string $facts
838     * @param int    $style
839     *
840     * @return string
841     */
842    public function formatFirstMajorFact(string $facts, int $style): string
843    {
844        foreach ($this->getFacts($facts, true) as $event) {
845            // Only display if it has a date or place (or both)
846            if ($event->getDate()->isOK() && !$event->getPlace()->isEmpty()) {
847                $joiner = ' — ';
848            } else {
849                $joiner = '';
850            }
851            if ($event->getDate()->isOK() || !$event->getPlace()->isEmpty()) {
852                switch ($style) {
853                    case 1:
854                        return '<br><em>' . $event->getLabel() . ' ' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</em>';
855                    case 2:
856                        return '<dl><dt class="label">' . $event->getLabel() . '</dt><dd class="field">' . FunctionsPrint::formatFactDate($event, $this, false, false) . $joiner . FunctionsPrint::formatFactPlace($event) . '</dd></dl>';
857                }
858            }
859        }
860
861        return '';
862    }
863
864    /**
865     * Find individuals linked to this record.
866     *
867     * @param string $link
868     *
869     * @return Individual[]
870     */
871    public function linkedIndividuals(string $link): array
872    {
873        $rows = Database::prepare(
874            "SELECT i_id AS xref, i_gedcom AS gedcom" .
875            " FROM `##individuals`" .
876            " JOIN `##link` ON i_file = l_file AND i_id = l_from" .
877            " LEFT JOIN `##name` ON i_file = n_file AND i_id = n_id AND n_num = 0" .
878            " WHERE i_file = :tree_id AND l_type = :link AND l_to = :xref" .
879            " ORDER BY n_sort COLLATE :collation"
880        )->execute([
881            'tree_id'   => $this->tree->getTreeId(),
882            'link'      => $link,
883            'xref'      => $this->xref,
884            'collation' => I18N::collation(),
885        ])->fetchAll();
886
887        $list = [];
888        foreach ($rows as $row) {
889            $record = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
890            if ($record->canShowName()) {
891                $list[] = $record;
892            }
893        }
894
895        return $list;
896    }
897
898    /**
899     * Find families linked to this record.
900     *
901     * @param string $link
902     *
903     * @return Family[]
904     */
905    public function linkedFamilies(string $link): array
906    {
907        $rows = Database::prepare(
908            "SELECT f_id AS xref, f_gedcom AS gedcom" .
909            " FROM `##families`" .
910            " JOIN `##link` ON f_file = l_file AND f_id = l_from" .
911            " LEFT JOIN `##name` ON f_file = n_file AND f_id = n_id AND n_num = 0" .
912            " WHERE f_file = :tree_id AND l_type = :link AND l_to = :xref"
913        )->execute([
914            'tree_id' => $this->tree->getTreeId(),
915            'link'    => $link,
916            'xref'    => $this->xref,
917        ])->fetchAll();
918
919        $list = [];
920        foreach ($rows as $row) {
921            $record = Family::getInstance($row->xref, $this->tree, $row->gedcom);
922            if ($record->canShowName()) {
923                $list[] = $record;
924            }
925        }
926
927        return $list;
928    }
929
930    /**
931     * Find sources linked to this record.
932     *
933     * @param string $link
934     *
935     * @return Source[]
936     */
937    public function linkedSources(string $link): array
938    {
939        $rows = Database::prepare(
940            "SELECT s_id AS xref, s_gedcom AS gedcom" .
941            " FROM `##sources`" .
942            " JOIN `##link` ON s_file = l_file AND s_id = l_from" .
943            " WHERE s_file = :tree_id AND l_type = :link AND l_to = :xref" .
944            " ORDER BY s_name COLLATE :collation"
945        )->execute([
946            'tree_id'   => $this->tree->getTreeId(),
947            'link'      => $link,
948            'xref'      => $this->xref,
949            'collation' => I18N::collation(),
950        ])->fetchAll();
951
952        $list = [];
953        foreach ($rows as $row) {
954            $record = Source::getInstance($row->xref, $this->tree, $row->gedcom);
955            if ($record->canShowName()) {
956                $list[] = $record;
957            }
958        }
959
960        return $list;
961    }
962
963    /**
964     * Find media objects linked to this record.
965     *
966     * @param string $link
967     *
968     * @return Media[]
969     */
970    public function linkedMedia(string $link): array
971    {
972        $rows = Database::prepare(
973            "SELECT m_id AS xref, m_gedcom AS gedcom" .
974            " FROM `##media`" .
975            " JOIN `##link` ON m_file = l_file AND m_id = l_from" .
976            " WHERE m_file = :tree_id AND l_type = :link AND l_to = :xref"
977        )->execute([
978            'tree_id' => $this->tree->getTreeId(),
979            'link'    => $link,
980            'xref'    => $this->xref,
981        ])->fetchAll();
982
983        $list = [];
984        foreach ($rows as $row) {
985            $record = Media::getInstance($row->xref, $this->tree, $row->gedcom);
986            if ($record->canShowName()) {
987                $list[] = $record;
988            }
989        }
990
991        return $list;
992    }
993
994    /**
995     * Find notes linked to this record.
996     *
997     * @param string $link
998     *
999     * @return Note[]
1000     */
1001    public function linkedNotes(string $link): array
1002    {
1003        $rows = Database::prepare(
1004            "SELECT o_id AS xref, o_gedcom AS gedcom" .
1005            " FROM `##other`" .
1006            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
1007            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
1008            " WHERE o_file = :tree_id AND o_type = 'NOTE' AND l_type = :link AND l_to = :xref" .
1009            " ORDER BY n_sort COLLATE :collation"
1010        )->execute([
1011            'tree_id'   => $this->tree->getTreeId(),
1012            'link'      => $link,
1013            'xref'      => $this->xref,
1014            'collation' => I18N::collation(),
1015        ])->fetchAll();
1016
1017        $list = [];
1018        foreach ($rows as $row) {
1019            $record = Note::getInstance($row->xref, $this->tree, $row->gedcom);
1020            if ($record->canShowName()) {
1021                $list[] = $record;
1022            }
1023        }
1024
1025        return $list;
1026    }
1027
1028    /**
1029     * Find repositories linked to this record.
1030     *
1031     * @param string $link
1032     *
1033     * @return Repository[]
1034     */
1035    public function linkedRepositories(string $link): array
1036    {
1037        $rows = Database::prepare(
1038            "SELECT o_id AS xref, o_gedcom AS gedcom" .
1039            " FROM `##other`" .
1040            " JOIN `##link` ON o_file = l_file AND o_id = l_from" .
1041            " LEFT JOIN `##name` ON o_file = n_file AND o_id = n_id AND n_num = 0" .
1042            " WHERE o_file = :tree_id AND o_type = 'REPO' AND l_type = :link AND l_to = :xref" .
1043            " ORDER BY n_sort COLLATE :collation"
1044        )->execute([
1045            'tree_id'   => $this->tree->getTreeId(),
1046            'link'      => $link,
1047            'xref'      => $this->xref,
1048            'collation' => I18N::collation(),
1049        ])->fetchAll();
1050
1051        $list = [];
1052        foreach ($rows as $row) {
1053            $record = Repository::getInstance($row->xref, $this->tree, $row->gedcom);
1054            if ($record->canShowName()) {
1055                $list[] = $record;
1056            }
1057        }
1058
1059        return $list;
1060    }
1061
1062    /**
1063     * Get all attributes (e.g. DATE or PLAC) from an event (e.g. BIRT or MARR).
1064     * This is used to display multiple events on the individual/family lists.
1065     * Multiple events can exist because of uncertainty in dates, dates in different
1066     * calendars, place-names in both latin and hebrew character sets, etc.
1067     * It also allows us to combine dates/places from different events in the summaries.
1068     *
1069     * @param string $event_type
1070     *
1071     * @return Date[]
1072     */
1073    public function getAllEventDates(string $event_type): array
1074    {
1075        $dates = [];
1076        foreach ($this->getFacts($event_type) as $event) {
1077            if ($event->getDate()->isOK()) {
1078                $dates[] = $event->getDate();
1079            }
1080        }
1081
1082        return $dates;
1083    }
1084
1085    /**
1086     * Get all the places for a particular type of event
1087     *
1088     * @param string $event_type
1089     *
1090     * @return Place[]
1091     */
1092    public function getAllEventPlaces(string $event_type): array
1093    {
1094        $places = [];
1095        foreach ($this->getFacts($event_type) as $event) {
1096            if (preg_match_all('/\n(?:2 PLAC|3 (?:ROMN|FONE|_HEB)) +(.+)/', $event->getGedcom(), $ged_places)) {
1097                foreach ($ged_places[1] as $ged_place) {
1098                    $places[] = new Place($ged_place, $this->tree);
1099                }
1100            }
1101        }
1102
1103        return $places;
1104    }
1105
1106    /**
1107     * Get the first (i.e. prefered) Fact for the given fact type
1108     *
1109     * @param string $tag
1110     *
1111     * @return Fact|null
1112     */
1113    public function getFirstFact(string $tag)
1114    {
1115        foreach ($this->getFacts() as $fact) {
1116            if ($fact->getTag() === $tag) {
1117                return $fact;
1118            }
1119        }
1120
1121        return null;
1122    }
1123
1124    /**
1125     * The facts and events for this record.
1126     *
1127     * @param string   $filter
1128     * @param bool     $sort
1129     * @param int|null $access_level
1130     * @param bool     $override Include private records, to allow us to implement $SHOW_PRIVATE_RELATIONSHIPS and $SHOW_LIVING_NAMES.
1131     *
1132     * @return Fact[]
1133     */
1134    public function getFacts(string $filter = null, bool $sort = false, int $access_level = null, bool $override = false): array
1135    {
1136        if ($access_level === null) {
1137            $access_level = Auth::accessLevel($this->tree);
1138        }
1139
1140        $facts = [];
1141        if ($this->canShow($access_level) || $override) {
1142            foreach ($this->facts as $fact) {
1143                if (($filter === null || preg_match('/^' . $filter . '$/', $fact->getTag())) && $fact->canShow($access_level)) {
1144                    $facts[] = $fact;
1145                }
1146            }
1147        }
1148        if ($sort) {
1149            Functions::sortFacts($facts);
1150        }
1151
1152        return $facts;
1153    }
1154
1155    /**
1156     * Get the last-change timestamp for this record, either as a formatted string
1157     * (for display) or as a unix timestamp (for sorting)
1158     *
1159     * @param bool $sorting
1160     *
1161     * @return string|int
1162     */
1163    public function lastChangeTimestamp(bool $sorting = false)
1164    {
1165        $chan = $this->getFirstFact('CHAN');
1166
1167        if ($chan) {
1168            // The record does have a CHAN event
1169            $d = $chan->getDate()->minimumDate();
1170            if (preg_match('/\n3 TIME (\d\d):(\d\d):(\d\d)/', $chan->getGedcom(), $match)) {
1171                $t = mktime((int) $match[1], (int) $match[2], (int) $match[3], (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1172            } elseif (preg_match('/\n3 TIME (\d\d):(\d\d)/', $chan->getGedcom(), $match)) {
1173                $t = mktime((int) $match[1], (int) $match[2], 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1174            } else {
1175                $t = mktime(0, 0, 0, (int) $d->format('%n'), (int) $d->format('%j'), (int) $d->format('%Y'));
1176            }
1177            if ($sorting) {
1178                return $t;
1179            }
1180
1181            return strip_tags(FunctionsDate::formatTimestamp($t));
1182        }
1183
1184        // The record does not have a CHAN event
1185        if ($sorting) {
1186            return '0';
1187        }
1188
1189        return '';
1190    }
1191
1192    /**
1193     * Get the last-change user for this record
1194     *
1195     * @return string
1196     */
1197    public function lastChangeUser()
1198    {
1199        $chan = $this->getFirstFact('CHAN');
1200
1201        if ($chan === null) {
1202            return I18N::translate('Unknown');
1203        }
1204
1205        $chan_user = $chan->getAttribute('_WT_USER');
1206        if ($chan_user === '') {
1207            return I18N::translate('Unknown');
1208        }
1209
1210        return $chan_user;
1211    }
1212
1213    /**
1214     * Add a new fact to this record
1215     *
1216     * @param string $gedcom
1217     * @param bool   $update_chan
1218     *
1219     * @return void
1220     */
1221    public function createFact(string $gedcom, bool $update_chan)
1222    {
1223        $this->updateFact('', $gedcom, $update_chan);
1224    }
1225
1226    /**
1227     * Delete a fact from this record
1228     *
1229     * @param string $fact_id
1230     * @param bool   $update_chan
1231     *
1232     * @return void
1233     */
1234    public function deleteFact(string $fact_id, bool $update_chan)
1235    {
1236        $this->updateFact($fact_id, '', $update_chan);
1237    }
1238
1239    /**
1240     * Replace a fact with a new gedcom data.
1241     *
1242     * @param string $fact_id
1243     * @param string $gedcom
1244     * @param bool   $update_chan
1245     *
1246     * @return void
1247     * @throws Exception
1248     */
1249    public function updateFact(string $fact_id, string $gedcom, bool $update_chan)
1250    {
1251        // MSDOS line endings will break things in horrible ways
1252        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1253        $gedcom = trim($gedcom);
1254
1255        if ($this->pending === '') {
1256            throw new Exception('Cannot edit a deleted record');
1257        }
1258        if ($gedcom !== '' && !preg_match('/^1 ' . WT_REGEX_TAG . '/', $gedcom)) {
1259            throw new Exception('Invalid GEDCOM data passed to GedcomRecord::updateFact(' . $gedcom . ')');
1260        }
1261
1262        if ($this->pending) {
1263            $old_gedcom = $this->pending;
1264        } else {
1265            $old_gedcom = $this->gedcom;
1266        }
1267
1268        // First line of record may contain data - e.g. NOTE records.
1269        list($new_gedcom) = explode("\n", $old_gedcom, 2);
1270
1271        // Replacing (or deleting) an existing fact
1272        foreach ($this->getFacts(null, false, Auth::PRIV_HIDE) as $fact) {
1273            if (!$fact->isPendingDeletion()) {
1274                if ($fact->getFactId() === $fact_id) {
1275                    if ($gedcom !== '') {
1276                        $new_gedcom .= "\n" . $gedcom;
1277                    }
1278                    $fact_id = 'NOT A VALID FACT ID'; // Only replace/delete one copy of a duplicate fact
1279                } elseif ($fact->getTag() != 'CHAN' || !$update_chan) {
1280                    $new_gedcom .= "\n" . $fact->getGedcom();
1281                }
1282            }
1283        }
1284        if ($update_chan) {
1285            $new_gedcom .= "\n1 CHAN\n2 DATE " . strtoupper(date('d M Y')) . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1286        }
1287
1288        // Adding a new fact
1289        if ($fact_id === '') {
1290            $new_gedcom .= "\n" . $gedcom;
1291        }
1292
1293        if ($new_gedcom != $old_gedcom) {
1294            // Save the changes
1295            Database::prepare(
1296                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
1297            )->execute([
1298                $this->tree->getTreeId(),
1299                $this->xref,
1300                $old_gedcom,
1301                $new_gedcom,
1302                Auth::id(),
1303            ]);
1304
1305            $this->pending = $new_gedcom;
1306
1307            if (Auth::user()->getPreference('auto_accept')) {
1308                FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1309                $this->gedcom  = $new_gedcom;
1310                $this->pending = null;
1311            }
1312        }
1313        $this->parseFacts();
1314    }
1315
1316    /**
1317     * Update this record
1318     *
1319     * @param string $gedcom
1320     * @param bool   $update_chan
1321     *
1322     * @return void
1323     */
1324    public function updateRecord(string $gedcom, bool $update_chan)
1325    {
1326        // MSDOS line endings will break things in horrible ways
1327        $gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1328        $gedcom = trim($gedcom);
1329
1330        // Update the CHAN record
1331        if ($update_chan) {
1332            $gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1333            $gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1334        }
1335
1336        // Create a pending change
1337        Database::prepare(
1338            "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
1339        )->execute([
1340            $this->tree->getTreeId(),
1341            $this->xref,
1342            $this->getGedcom(),
1343            $gedcom,
1344            Auth::id(),
1345        ]);
1346
1347        // Clear the cache
1348        $this->pending = $gedcom;
1349
1350        // Accept this pending change
1351        if (Auth::user()->getPreference('auto_accept')) {
1352            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1353            $this->gedcom  = $gedcom;
1354            $this->pending = null;
1355        }
1356
1357        $this->parseFacts();
1358
1359        Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1360    }
1361
1362    /**
1363     * Delete this record
1364     *
1365     * @return void
1366     */
1367    public function deleteRecord()
1368    {
1369        // Create a pending change
1370        if (!$this->isPendingDeletion()) {
1371            Database::prepare(
1372                "INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, '', ?)"
1373            )->execute([
1374                $this->tree->getTreeId(),
1375                $this->xref,
1376                $this->getGedcom(),
1377                Auth::id(),
1378            ]);
1379        }
1380
1381        // Auto-accept this pending change
1382        if (Auth::user()->getPreference('auto_accept')) {
1383            FunctionsImport::acceptAllChanges($this->xref, $this->tree);
1384        }
1385
1386        // Clear the cache
1387        self::$gedcom_record_cache  = null;
1388        self::$pending_record_cache = null;
1389
1390        Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref, $this->tree);
1391    }
1392
1393    /**
1394     * Remove all links from this record to $xref
1395     *
1396     * @param string $xref
1397     * @param bool   $update_chan
1398     *
1399     * @return void
1400     */
1401    public function removeLinks(string $xref, bool $update_chan)
1402    {
1403        $value = '@' . $xref . '@';
1404
1405        foreach ($this->getFacts() as $fact) {
1406            if ($fact->getValue() === $value) {
1407                $this->deleteFact($fact->getFactId(), $update_chan);
1408            } elseif (preg_match_all('/\n(\d) ' . WT_REGEX_TAG . ' ' . $value . '/', $fact->getGedcom(), $matches, PREG_SET_ORDER)) {
1409                $gedcom = $fact->getGedcom();
1410                foreach ($matches as $match) {
1411                    $next_level  = $match[1] + 1;
1412                    $next_levels = '[' . $next_level . '-9]';
1413                    $gedcom      = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1414                }
1415                $this->updateFact($fact->getFactId(), $gedcom, $update_chan);
1416            }
1417        }
1418    }
1419}
1420