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