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