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