xref: /webtrees/app/Family.php (revision eaf6176917d65962efb940f4ca71c92d33ea9f35)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2018 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16namespace Fisharebest\Webtrees;
17
18/**
19 * A GEDCOM family (FAM) object.
20 */
21class Family extends GedcomRecord {
22	const RECORD_TYPE = 'FAM';
23	const ROUTE_NAME  = 'family';
24
25	/** @var Individual|null The husband (or first spouse for same-sex couples) */
26	private $husb;
27
28	/** @var Individual|null The wife (or second spouse for same-sex couples) */
29	private $wife;
30
31	/**
32	 * Create a GedcomRecord object from raw GEDCOM data.
33	 *
34	 * @param string      $xref
35	 * @param string      $gedcom  an empty string for new/pending records
36	 * @param string|null $pending null for a record with no pending edits,
37	 *                             empty string for records with pending deletions
38	 * @param Tree        $tree
39	 */
40	public function __construct($xref, $gedcom, $pending, $tree) {
41		parent::__construct($xref, $gedcom, $pending, $tree);
42
43		// Fetch family members
44		if (preg_match_all('/^1 (?:HUSB|WIFE|CHIL) @(.+)@/m', $gedcom . $pending, $match)) {
45			Individual::load($tree, $match[1]);
46		}
47
48		if (preg_match('/^1 HUSB @(.+)@/m', $gedcom . $pending, $match)) {
49			$this->husb = Individual::getInstance($match[1], $tree);
50		}
51		if (preg_match('/^1 WIFE @(.+)@/m', $gedcom . $pending, $match)) {
52			$this->wife = Individual::getInstance($match[1], $tree);
53		}
54
55		// Make sure husb/wife are the right way round.
56		if ($this->husb && $this->husb->getSex() === 'F' || $this->wife && $this->wife->getSex() === 'M') {
57			list($this->husb, $this->wife) = [$this->wife, $this->husb];
58		}
59	}
60
61	/**
62	 * Get an instance of a family object. For single records,
63	 * we just receive the XREF. For bulk records (such as lists
64	 * and search results) we can receive the GEDCOM data as well.
65	 *
66	 * @param string      $xref
67	 * @param Tree        $tree
68	 * @param string|null $gedcom
69	 *
70	 * @throws \Exception
71	 *
72	 * @return Family|null
73	 */
74	public static function getInstance($xref, Tree $tree, $gedcom = null) {
75		$record = parent::getInstance($xref, $tree, $gedcom);
76
77		if ($record instanceof Family) {
78			return $record;
79		} else {
80			return null;
81		}
82	}
83
84	/**
85	 * Generate a private version of this record
86	 *
87	 * @param int $access_level
88	 *
89	 * @return string
90	 */
91	protected function createPrivateGedcomRecord($access_level) {
92		$SHOW_PRIVATE_RELATIONSHIPS = $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
93
94		$rec = '0 @' . $this->xref . '@ FAM';
95		// Just show the 1 CHIL/HUSB/WIFE tag, not any subtags, which may contain private data
96		preg_match_all('/\n1 (?:CHIL|HUSB|WIFE) @(' . WT_REGEX_XREF . ')@/', $this->gedcom, $matches, PREG_SET_ORDER);
97		foreach ($matches as $match) {
98			$rela = Individual::getInstance($match[1], $this->tree);
99			if ($rela && ($SHOW_PRIVATE_RELATIONSHIPS || $rela->canShow($access_level))) {
100				$rec .= $match[0];
101			}
102		}
103
104		return $rec;
105	}
106
107	/**
108	 * Fetch data from the database
109	 *
110	 * @param string $xref
111	 * @param int    $tree_id
112	 *
113	 * @return null|string
114	 */
115	protected static function fetchGedcomRecord($xref, $tree_id) {
116		return Database::prepare(
117			"SELECT f_gedcom FROM `##families` WHERE f_id = :xref AND f_file = :tree_id"
118		)->execute([
119			'xref'    => $xref,
120			'tree_id' => $tree_id,
121		])->fetchOne();
122	}
123
124	/**
125	 * Get the male (or first female) partner of the family
126	 *
127	 * @param $access_level int|null
128	 *
129	 * @return Individual|null
130	 */
131	public function getHusband($access_level = null) {
132		$SHOW_PRIVATE_RELATIONSHIPS = $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
133
134		if ($this->husb && ($SHOW_PRIVATE_RELATIONSHIPS || $this->husb->canShowName($access_level))) {
135			return $this->husb;
136		} else {
137			return null;
138		}
139	}
140
141	/**
142	 * Get the female (or second male) partner of the family
143	 *
144	 * @param $access_level int|null
145	 *
146	 * @return Individual|null
147	 */
148	public function getWife($access_level = null) {
149		$SHOW_PRIVATE_RELATIONSHIPS = $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
150
151		if ($this->wife && ($SHOW_PRIVATE_RELATIONSHIPS || $this->wife->canShowName($access_level))) {
152			return $this->wife;
153		} else {
154			return null;
155		}
156	}
157
158	/**
159	 * Each object type may have its own special rules, and re-implement this function.
160	 *
161	 * @param int $access_level
162	 *
163	 * @return bool
164	 */
165	protected function canShowByType($access_level) {
166		// Hide a family if any member is private
167		preg_match_all('/\n1 (?:CHIL|HUSB|WIFE) @(' . WT_REGEX_XREF . ')@/', $this->gedcom, $matches);
168		foreach ($matches[1] as $match) {
169			$person = Individual::getInstance($match, $this->tree);
170			if ($person && !$person->canShow($access_level)) {
171				return false;
172			}
173		}
174
175		return true;
176	}
177
178	/**
179	 * Can the name of this record be shown?
180	 *
181	 * @param int|null $access_level
182	 *
183	 * @return bool
184	 */
185	public function canShowName($access_level = null) {
186		// We can always see the name (Husband-name + Wife-name), however,
187		// the name will often be "private + private"
188		return true;
189	}
190
191	/**
192	 * Find the spouse of a person.
193	 *
194	 * @param Individual $person
195	 * @param int|null   $access_level
196	 *
197	 * @return Individual|null
198	 */
199	public function getSpouse(Individual $person, $access_level = null) {
200		if ($person === $this->wife) {
201			return $this->getHusband($access_level);
202		} else {
203			return $this->getWife($access_level);
204		}
205	}
206
207	/**
208	 * Get the (zero, one or two) spouses from this family.
209	 *
210	 * @param int|null $access_level
211	 *
212	 * @return Individual[]
213	 */
214	public function getSpouses($access_level = null) {
215		return array_filter([
216			$this->getHusband($access_level),
217			$this->getWife($access_level),
218		]);
219	}
220
221	/**
222	 * Get a list of this family’s children.
223	 *
224	 * @param int|null $access_level
225	 *
226	 * @return Individual[]
227	 */
228	public function getChildren($access_level = null) {
229		if ($access_level === null) {
230			$access_level = Auth::accessLevel($this->tree);
231		}
232
233		$SHOW_PRIVATE_RELATIONSHIPS = $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
234
235		$children = [];
236		foreach ($this->getFacts('CHIL', false, $access_level, $SHOW_PRIVATE_RELATIONSHIPS) as $fact) {
237			$child = $fact->getTarget();
238			if ($child && ($SHOW_PRIVATE_RELATIONSHIPS || $child->canShowName($access_level))) {
239				$children[] = $child;
240			}
241		}
242
243		return $children;
244	}
245
246	/**
247	 * Static helper function to sort an array of families by marriage date
248	 *
249	 * @param Family $x
250	 * @param Family $y
251	 *
252	 * @return int
253	 */
254	public static function compareMarrDate(Family $x, Family $y) {
255		return Date::compare($x->getMarriageDate(), $y->getMarriageDate());
256	}
257
258	/**
259	 * Number of children - for the individual list
260	 *
261	 * @return int
262	 */
263	public function getNumberOfChildren() {
264		$nchi = count($this->getChildren());
265		foreach ($this->getFacts('NCHI') as $fact) {
266			$nchi = max($nchi, (int) $fact->getValue());
267		}
268
269		return $nchi;
270	}
271
272	/**
273	 * get the marriage event
274	 *
275	 * @return Fact
276	 */
277	public function getMarriage() {
278		return $this->getFirstFact('MARR');
279	}
280
281	/**
282	 * Get marriage date
283	 *
284	 * @return Date
285	 */
286	public function getMarriageDate() {
287		$marriage = $this->getMarriage();
288		if ($marriage) {
289			return $marriage->getDate();
290		} else {
291			return new Date('');
292		}
293	}
294
295	/**
296	 * Get the marriage year - displayed on lists of families
297	 *
298	 * @return int
299	 */
300	public function getMarriageYear() {
301		return $this->getMarriageDate()->minimumDate()->y;
302	}
303
304	/**
305	 * Get the marriage place
306	 *
307	 * @return Place
308	 */
309	public function getMarriagePlace() {
310		$marriage = $this->getMarriage();
311
312		return $marriage->getPlace();
313	}
314
315	/**
316	 * Get a list of all marriage dates - for the family lists.
317	 *
318	 * @return Date[]
319	 */
320	public function getAllMarriageDates() {
321		foreach (explode('|', WT_EVENTS_MARR) as $event) {
322			if ($array = $this->getAllEventDates($event)) {
323				return $array;
324			}
325		}
326
327		return [];
328	}
329
330	/**
331	 * Get a list of all marriage places - for the family lists.
332	 *
333	 * @return Place[]
334	 */
335	public function getAllMarriagePlaces() {
336		foreach (explode('|', WT_EVENTS_MARR) as $event) {
337			$places = $this->getAllEventPlaces($event);
338			if (!empty($places)) {
339				return $places;
340			}
341		}
342
343		return [];
344	}
345
346	/**
347	 * Derived classes should redefine this function, otherwise the object will have no name
348	 *
349	 * @return string[][]
350	 */
351	public function getAllNames() {
352		if (is_null($this->_getAllNames)) {
353			// Check the script used by each name, so we can match cyrillic with cyrillic, greek with greek, etc.
354			$husb_names = [];
355			if ($this->husb) {
356				$husb_names = array_filter($this->husb->getAllNames(), function (array $x) {
357					return $x['type'] !== '_MARNM';
358				} );
359			}
360			// If the individual only has married names, create a dummy birth name.
361			if (empty($husb_names)) {
362				$husb_names[] = [
363					'type' => 'BIRT',
364					'sort' => '@N.N.',
365					'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
366				];
367			}
368			foreach ($husb_names as $n => $husb_name) {
369				$husb_names[$n]['script'] = I18N::textScript($husb_name['full']);
370			}
371
372			$wife_names = [];
373			if ($this->wife) {
374				$wife_names = array_filter($this->wife->getAllNames(), function (array $x) {
375					return $x['type'] !== '_MARNM';
376				} );
377			}
378			// If the individual only has married names, create a dummy birth name.
379			if (empty($wife_names)) {
380				$wife_names[] = [
381					'type' => 'BIRT',
382					'sort' => '@N.N.',
383					'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
384				];
385			}
386			foreach ($wife_names as $n => $wife_name) {
387				$wife_names[$n]['script'] = I18N::textScript($wife_name['full']);
388			}
389
390			// Add the matched names first
391			foreach ($husb_names as $husb_name) {
392				foreach ($wife_names as $wife_name) {
393					if ($husb_name['script'] == $wife_name['script']) {
394						$this->_getAllNames[] = [
395							'type' => $husb_name['type'],
396							'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
397							'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
398							// No need for a fullNN entry - we do not currently store FAM names in the database
399						];
400					}
401				}
402			}
403
404			// Add the unmatched names second (there may be no matched names)
405			foreach ($husb_names as $husb_name) {
406				foreach ($wife_names as $wife_name) {
407					if ($husb_name['script'] != $wife_name['script']) {
408						$this->_getAllNames[] = [
409							'type' => $husb_name['type'],
410							'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
411							'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
412							// No need for a fullNN entry - we do not currently store FAM names in the database
413						];
414					}
415				}
416			}
417		}
418
419		return $this->_getAllNames;
420	}
421
422	/**
423	 * This function should be redefined in derived classes to show any major
424	 * identifying characteristics of this record.
425	 *
426	 * @return string
427	 */
428	public function formatListDetails() {
429		return
430			$this->formatFirstMajorFact(WT_EVENTS_MARR, 1) .
431			$this->formatFirstMajorFact(WT_EVENTS_DIV, 1);
432	}
433}
434