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