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