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