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