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