xref: /webtrees/app/GedcomRecord.php (revision 3be3dabd99a20c9582afa24d09fbb2e9485d1a9e)
1<?php
2namespace 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 int  The gedcom file */
30	protected $gedcom_id;
31
32	/** @var string  GEDCOM data (before any pending edits) */
33	protected $gedcom;
34
35	/** @var string|null  GEDCOM data (after any pending edits) */
36	protected $pending;
37
38	/** @var Fact[] facts extracted from $gedcom/$pending */
39	protected $facts;
40
41	/** @var bool Can we display details of this record to WT_PRIV_PUBLIC */
42	private   $disp_public;
43
44	/** @var bool Can we display details of this record to WT_PRIV_USER */
45	private   $disp_user;
46
47	/** @var bool Can we display details of this record to WT_PRIV_NONE */
48	private   $disp_none;
49
50	/** @var string[][] All the names of this individual */
51	protected $_getAllNames;
52
53	/** @var int Cached result */
54	protected $_getPrimaryName;
55
56	/** @var int Cached result */
57	protected $_getSecondaryName;
58
59	// Allow getInstance() to return references to existing objects
60	private static $gedcom_record_cache;
61	// Fetch all pending edits in one database query
62	private static $pending_record_cache;
63
64	/**
65	 * Create a GedcomRecord object from raw GEDCOM data.
66	 *
67	 * @param string      $xref
68	 * @param string      $gedcom  an empty string for new/pending records
69	 * @param string|null $pending null for a record with no pending edits,
70	 *                             empty string for records with pending deletions
71	 * @param integer     $gedcom_id
72	 */
73	public function __construct($xref, $gedcom, $pending, $gedcom_id) {
74		$this->xref      = $xref;
75		$this->gedcom    = $gedcom;
76		$this->pending   = $pending;
77		$this->gedcom_id = $gedcom_id;
78
79		$this->parseFacts();
80	}
81
82	/**
83	 * Split the record into facts
84	 */
85	private function parseFacts() {
86		// Split the record into facts
87		if ($this->gedcom) {
88			$gedcom_facts = preg_split('/\n(?=1)/s', $this->gedcom);
89			array_shift($gedcom_facts);
90		} else {
91			$gedcom_facts = array();
92		}
93		if ($this->pending) {
94			$pending_facts = preg_split('/\n(?=1)/s', $this->pending);
95			array_shift($pending_facts);
96		} else {
97			$pending_facts = array();
98		}
99
100		$this->facts = array();
101
102		foreach ($gedcom_facts as $gedcom_fact) {
103			$fact = new Fact($gedcom_fact, $this, md5($gedcom_fact));
104			if ($this->pending !== null && !in_array($gedcom_fact, $pending_facts)) {
105				$fact->setPendingDeletion();
106			}
107			$this->facts[] = $fact;
108		}
109		foreach ($pending_facts as $pending_fact) {
110			if (!in_array($pending_fact, $gedcom_facts)) {
111				$fact = new Fact($pending_fact, $this, md5($pending_fact));
112				$fact->setPendingAddition();
113				$this->facts[] = $fact;
114			}
115		}
116	}
117
118	/**
119	 * Get an instance of a GedcomRecord object.  For single records,
120	 * we just receive the XREF.  For bulk records (such as lists
121	 * and search results) we can receive the GEDCOM data as well.
122	 *
123	 * @param string       $xref
124	 * @param integer|null $gedcom_id
125	 * @param string|null  $gedcom
126	 *
127	 * @return GedcomRecord|null
128	 * @throws \Exception
129	 */
130	public static function getInstance($xref, $gedcom_id = WT_GED_ID, $gedcom = null) {
131		// Is this record already in the cache?
132		if (isset(self::$gedcom_record_cache[$xref][$gedcom_id])) {
133			return self::$gedcom_record_cache[$xref][$gedcom_id];
134		}
135
136		// Do we need to fetch the record from the database?
137		if ($gedcom === null) {
138			$gedcom = static::fetchGedcomRecord($xref, $gedcom_id);
139		}
140
141		// If we can edit, then we also need to be able to see pending records.
142		if (WT_USER_CAN_EDIT) {
143			if (!isset(self::$pending_record_cache[$gedcom_id])) {
144				// Fetch all pending records in one database query
145				self::$pending_record_cache[$gedcom_id] = array();
146				$rows = Database::prepare(
147					"SELECT xref, new_gedcom FROM `##change` WHERE status='pending' AND gedcom_id=?"
148				)->execute(array($gedcom_id))->fetchAll();
149				foreach ($rows as $row) {
150					self::$pending_record_cache[$gedcom_id][$row->xref] = $row->new_gedcom;
151				}
152			}
153
154			if (isset(self::$pending_record_cache[$gedcom_id][$xref])) {
155				// A pending edit exists for this record
156				$pending = self::$pending_record_cache[$gedcom_id][$xref];
157			} else {
158				$pending = null;
159			}
160		} else {
161			// There are no pending changes for this record
162			$pending = null;
163		}
164
165		// No such record exists
166		if ($gedcom === null && $pending === null) {
167			return null;
168		}
169
170		// Create the object
171		if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom . $pending, $match)) {
172			$xref = $match[1]; // Collation - we may have requested I123 and found i123
173			$type = $match[2];
174		} elseif (preg_match('/^0 (HEAD|TRLR)/', $gedcom . $pending, $match)) {
175			$xref = $match[1];
176			$type = $match[1];
177		} elseif ($gedcom . $pending) {
178			throw new \Exception('Unrecognized GEDCOM record: ' . $gedcom);
179		} else {
180			// A record with both pending creation and pending deletion
181			$type = static::RECORD_TYPE;
182		}
183
184		switch ($type) {
185		case 'INDI':
186			$record = new Individual($xref, $gedcom, $pending, $gedcom_id);
187			break;
188		case 'FAM':
189			$record = new Family($xref, $gedcom, $pending, $gedcom_id);
190			break;
191		case 'SOUR':
192			$record = new Source($xref, $gedcom, $pending, $gedcom_id);
193			break;
194		case 'OBJE':
195			$record = new Media($xref, $gedcom, $pending, $gedcom_id);
196			break;
197		case 'REPO':
198			$record = new Repository($xref, $gedcom, $pending, $gedcom_id);
199			break;
200		case 'NOTE':
201			$record = new Note($xref, $gedcom, $pending, $gedcom_id);
202			break;
203		default:
204			$record = new GedcomRecord($xref, $gedcom, $pending, $gedcom_id);
205			break;
206		}
207
208		// Store it in the cache
209		self::$gedcom_record_cache[$xref][$gedcom_id] = $record;
210
211		return $record;
212	}
213
214	/**
215	 * Fetch data from the database
216	 *
217	 * @param string  $xref
218	 * @param integer $gedcom_id
219	 *
220	 * @return null|string
221	 */
222	protected static function fetchGedcomRecord($xref, $gedcom_id) {
223		static $statement = null;
224
225		// We don't know what type of object this is.  Try each one in turn.
226		$data = Individual::fetchGedcomRecord($xref, $gedcom_id);
227		if ($data) {
228			return $data;
229		}
230		$data = Family::fetchGedcomRecord($xref, $gedcom_id);
231		if ($data) {
232			return $data;
233		}
234		$data = Source::fetchGedcomRecord($xref, $gedcom_id);
235		if ($data) {
236			return $data;
237		}
238		$data = Repository::fetchGedcomRecord($xref, $gedcom_id);
239		if ($data) {
240			return $data;
241		}
242		$data = Media::fetchGedcomRecord($xref, $gedcom_id);
243		if ($data) {
244			return $data;
245		}
246		$data = Note::fetchGedcomRecord($xref, $gedcom_id);
247		if ($data) {
248			return $data;
249		}
250		// Some other type of record...
251		if (is_null($statement)) {
252			$statement = Database::prepare("SELECT o_gedcom FROM `##other` WHERE o_id=? AND o_file=?");
253		}
254		return $statement->execute(array($xref, $gedcom_id))->fetchOne();
255
256	}
257
258	/**
259	 * Get the XREF for this record
260	 *
261	 * @return string
262	 */
263	public function getXref() {
264		return $this->xref;
265	}
266
267	/**
268	 * Get the tree ID for this record
269	 *
270	 * @return integer
271	 */
272	public function getGedcomId() {
273		return $this->gedcom_id;
274	}
275
276	/**
277	 * Application code should access data via Fact objects.
278	 * This function exists to support old code.
279	 *
280	 * @return string
281	 */
282	public function getGedcom() {
283		if ($this->pending === null) {
284			return $this->gedcom;
285		} else {
286			return $this->pending;
287		}
288	}
289
290	/**
291	 * Does this record have a pending change?
292	 *
293	 * @return boolean
294	 */
295	public function isPendingAddtion() {
296		return $this->pending !== null;
297	}
298
299	/**
300	 * Does this record have a pending deletion?
301	 *
302	 * @return boolean
303	 */
304	public function isPendingDeletion() {
305		return $this->pending === '';
306	}
307
308	/**
309	 * Generate a URL to this record, suitable for use in HTML, etc.
310	 *
311	 * @return string
312	 */
313	public function getHtmlUrl() {
314		return $this->getLinkUrl(static::URL_PREFIX, '&amp;');
315	}
316
317	/**
318	 * Generate a URL to this record, suitable for use in javascript, HTTP headers, etc.
319	 *
320	 * @return string
321	 */
322	public function getRawUrl() {
323		return $this->getLinkUrl(static::URL_PREFIX, '&');
324	}
325
326	/**
327	 * Generate an absolute URL for this record, suitable for sitemap.xml, RSS feeds, etc.
328	 *
329	 * @return string
330	 */
331	public function getAbsoluteLinkUrl() {
332		return WT_BASE_URL . $this->getHtmlUrl();
333	}
334
335	/**
336	 * Generate a URL to this record.
337	 *
338	 * @param string $link
339	 * @param string $separator
340	 *
341	 * @return string
342	 */
343	private function getLinkUrl($link, $separator) {
344		if ($this->gedcom_id == WT_GED_ID) {
345			return $link . $this->getXref() . $separator . 'ged=' . WT_GEDURL;
346		} elseif ($this->gedcom_id == 0) {
347			return '#';
348		} else {
349			return $link . $this->getXref() . $separator . 'ged=' . rawurlencode(get_gedcom_from_id($this->gedcom_id));
350		}
351	}
352
353	/**
354	 * Work out whether this record can be shown to a user with a given access level
355	 *
356	 * @param integer $access_level
357	 *
358	 * @return boolean
359	 */
360	private function _canShow($access_level) {
361		global $person_privacy, $HIDE_LIVE_PEOPLE;
362
363		// This setting would better be called "$ENABLE_PRIVACY"
364		if (!$HIDE_LIVE_PEOPLE) {
365			return true;
366		}
367
368		// We should always be able to see our own record (unless an admin is applying download restrictions)
369		if ($this->getXref() == WT_USER_GEDCOM_ID && $this->getGedcomId() == WT_GED_ID && $access_level == WT_USER_ACCESS_LEVEL) {
370			return true;
371		}
372
373		// Does this record have a RESN?
374		if (strpos($this->gedcom, "\n1 RESN confidential")) {
375			return WT_PRIV_NONE >= $access_level;
376		}
377		if (strpos($this->gedcom, "\n1 RESN privacy")) {
378			return WT_PRIV_USER >= $access_level;
379		}
380		if (strpos($this->gedcom, "\n1 RESN none")) {
381			return true;
382		}
383
384		// Does this record have a default RESN?
385		if (isset($person_privacy[$this->getXref()])) {
386			return $person_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		global $global_facts;
407
408		if (isset($global_facts[static::RECORD_TYPE])) {
409			// Restriction found
410			return $global_facts[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->gedcom_id;
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->gedcom_id, $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->gedcom_id, $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->gedcom_id, $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->gedcom_id, $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->gedcom_id, $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->gedcom_id, $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->gedcom_id,
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->gedcom_id);
1185				$this->gedcom  = $new_gedcom;
1186				$this->pending = null;
1187			}
1188		}
1189		$this->parseFacts();
1190	}
1191
1192	/**
1193	 * Create a new record from GEDCOM data.
1194	 *
1195	 * @param string  $gedcom
1196	 * @param integer $gedcom_id
1197	 *
1198	 * @return GedcomRecord
1199	 * @throws \Exception
1200	 */
1201	static public function createRecord($gedcom, $gedcom_id) {
1202		if (preg_match('/^0 @(' . WT_REGEX_XREF . ')@ (' . WT_REGEX_TAG . ')/', $gedcom, $match)) {
1203			$xref = $match[1];
1204			$type = $match[2];
1205		} else {
1206			throw new \Exception('Invalid argument to GedcomRecord::createRecord(' . $gedcom . ')');
1207		}
1208		if (strpos("\r", $gedcom) !== false) {
1209			// MSDOS line endings will break things in horrible ways
1210			throw new \Exception('Evil line endings found in GedcomRecord::createRecord(' . $gedcom . ')');
1211		}
1212
1213		// webtrees creates XREFs containing digits.  Anything else (e.g. “new”) is just a placeholder.
1214		if (!preg_match('/\d/', $xref)) {
1215			$xref   = get_new_xref($type);
1216			$gedcom = preg_replace('/^0 @(' . WT_REGEX_XREF . ')@/', '0 @' . $xref . '@', $gedcom);
1217		}
1218
1219		// Create a change record, if not already present
1220		if (!preg_match('/\n1 CHAN/', $gedcom)) {
1221			$gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1222		}
1223
1224		// Create a pending change
1225		Database::prepare(
1226			"INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, '', ?, ?)"
1227		)->execute(array(
1228			$gedcom_id,
1229			$xref,
1230			$gedcom,
1231			Auth::id()
1232		));
1233
1234		// Accept this pending change
1235		if (Auth::user()->getPreference('auto_accept')) {
1236			accept_all_changes($xref, $gedcom_id);
1237		}
1238
1239		// Clear this record from the cache
1240		self::$pending_record_cache = null;
1241
1242		Log::addEditLog('Create: ' . $type . ' ' . $xref);
1243
1244		// Return the newly created record
1245		return GedcomRecord::getInstance($xref);
1246	}
1247
1248	/**
1249	 * Update this record
1250	 *
1251	 * @param string  $gedcom
1252	 * @param boolean $update_chan
1253	 */
1254	public function updateRecord($gedcom, $update_chan) {
1255		// MSDOS line endings will break things in horrible ways
1256		$gedcom = preg_replace('/[\r\n]+/', "\n", $gedcom);
1257		$gedcom = trim($gedcom);
1258
1259		// Update the CHAN record
1260		if ($update_chan) {
1261			$gedcom = preg_replace('/\n1 CHAN(\n[2-9].*)*/', '', $gedcom);
1262			$gedcom .= "\n1 CHAN\n2 DATE " . date('d M Y') . "\n3 TIME " . date('H:i:s') . "\n2 _WT_USER " . Auth::user()->getUserName();
1263		}
1264
1265		// Create a pending change
1266		Database::prepare(
1267			"INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, ?, ?)"
1268		)->execute(array(
1269			$this->gedcom_id,
1270			$this->xref,
1271			$this->getGedcom(),
1272			$gedcom,
1273			Auth::id()
1274		));
1275
1276		// Clear the cache
1277		$this->pending = $gedcom;
1278
1279		// Accept this pending change
1280		if (Auth::user()->getPreference('auto_accept')) {
1281			accept_all_changes($this->xref, $this->gedcom_id);
1282			$this->gedcom  = $gedcom;
1283			$this->pending = null;
1284		}
1285
1286		$this->parseFacts();
1287
1288		Log::addEditLog('Update: ' . static::RECORD_TYPE . ' ' . $this->xref);
1289	}
1290
1291	/**
1292	 * Delete this record
1293	 */
1294	public function deleteRecord() {
1295		// Create a pending change
1296		Database::prepare(
1297			"INSERT INTO `##change` (gedcom_id, xref, old_gedcom, new_gedcom, user_id) VALUES (?, ?, ?, '', ?)"
1298		)->execute(array(
1299			$this->gedcom_id,
1300			$this->xref,
1301			$this->getGedcom(),
1302			Auth::id(),
1303		));
1304
1305		// Accept this pending change
1306		if (Auth::user()->getPreference('auto_accept')) {
1307			accept_all_changes($this->xref, $this->gedcom_id);
1308		}
1309
1310		// Clear the cache
1311		self::$gedcom_record_cache = null;
1312		self::$pending_record_cache = null;
1313
1314		Log::addEditLog('Delete: ' . static::RECORD_TYPE . ' ' . $this->xref);
1315	}
1316
1317	/**
1318	 * Remove all links from this record to $xref
1319	 *
1320	 * @param string  $xref
1321	 * @param boolean $update_chan
1322	 */
1323	public function removeLinks($xref, $update_chan) {
1324		$value = '@' . $xref . '@';
1325
1326		foreach ($this->getFacts() as $fact) {
1327			if ($fact->getValue() == $value) {
1328				$this->deleteFact($fact->getFactId(), $update_chan);
1329			} elseif (preg_match_all('/\n(\d) ' . WT_REGEX_TAG . ' ' . $value . '/', $fact->getGedcom(), $matches, PREG_SET_ORDER)) {
1330				$gedcom = $fact->getGedcom();
1331				foreach ($matches as $match) {
1332					$next_level = $match[1] + 1;
1333					$next_levels = '[' . $next_level . '-9]';
1334					$gedcom = preg_replace('/' . $match[0] . '(\n' . $next_levels . '.*)*/', '', $gedcom);
1335				}
1336				$this->updateFact($fact->getFactId(), $gedcom, $update_chan);
1337			}
1338		}
1339	}
1340}
1341