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