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