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