xref: /webtrees/app/Family.php (revision 8898179db9ee9ab76e7912468223d7b1fdcddfbc)
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
248     * @return Individual[]
249     */
250    public function spouses($access_level = null): Collection
251    {
252        $spouses = new Collection([
253            $this->husband($access_level),
254            $this->wife($access_level),
255        ]);
256
257        return $spouses->filter();
258    }
259
260    /**
261     * Get a list of this family’s children.
262     *
263     * @param int|null $access_level
264     *
265     * @return Collection
266     * @return Individual[]
267     */
268    public function children($access_level = null): Collection
269    {
270        if ($access_level === null) {
271            $access_level = Auth::accessLevel($this->tree);
272        }
273
274        $SHOW_PRIVATE_RELATIONSHIPS = (bool) $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
275
276        $children = new Collection();
277
278        foreach ($this->facts(['CHIL'], false, $access_level, $SHOW_PRIVATE_RELATIONSHIPS) as $fact) {
279            $child = $fact->target();
280
281            if ($child instanceof Individual && ($SHOW_PRIVATE_RELATIONSHIPS || $child->canShowName($access_level))) {
282                $children->push($child);
283            }
284        }
285
286        return $children;
287    }
288
289    /**
290     * Number of children - for the individual list
291     *
292     * @return int
293     */
294    public function numberOfChildren(): int
295    {
296        $nchi = $this->children()->count();
297
298        foreach ($this->facts(['NCHI']) as $fact) {
299            $nchi = max($nchi, (int) $fact->value());
300        }
301
302        return $nchi;
303    }
304
305    /**
306     * get the marriage event
307     *
308     * @return Fact|null
309     */
310    public function getMarriage(): ?Fact
311    {
312        return $this->facts(['MARR'])->first();
313    }
314
315    /**
316     * Get marriage date
317     *
318     * @return Date
319     */
320    public function getMarriageDate(): Date
321    {
322        $marriage = $this->getMarriage();
323        if ($marriage) {
324            return $marriage->date();
325        }
326
327        return new Date('');
328    }
329
330    /**
331     * Get the marriage year - displayed on lists of families
332     *
333     * @return int
334     */
335    public function getMarriageYear(): int
336    {
337        return $this->getMarriageDate()->minimumDate()->year;
338    }
339
340    /**
341     * Get the marriage place
342     *
343     * @return Place
344     */
345    public function getMarriagePlace(): Place
346    {
347        $marriage = $this->getMarriage();
348
349        return $marriage->place();
350    }
351
352    /**
353     * Get a list of all marriage dates - for the family lists.
354     *
355     * @return Date[]
356     */
357    public function getAllMarriageDates(): array
358    {
359        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
360            if ($array = $this->getAllEventDates([$event])) {
361                return $array;
362            }
363        }
364
365        return [];
366    }
367
368    /**
369     * Get a list of all marriage places - for the family lists.
370     *
371     * @return Place[]
372     */
373    public function getAllMarriagePlaces(): array
374    {
375        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
376            $places = $this->getAllEventPlaces([$event]);
377            if (!empty($places)) {
378                return $places;
379            }
380        }
381
382        return [];
383    }
384
385    /**
386     * Derived classes should redefine this function, otherwise the object will have no name
387     *
388     * @return string[][]
389     */
390    public function getAllNames(): array
391    {
392        if ($this->getAllNames === null) {
393            // Check the script used by each name, so we can match cyrillic with cyrillic, greek with greek, etc.
394            $husb_names = [];
395            if ($this->husb) {
396                $husb_names = array_filter($this->husb->getAllNames(), function (array $x): bool {
397                    return $x['type'] !== '_MARNM';
398                });
399            }
400            // If the individual only has married names, create a dummy birth name.
401            if (empty($husb_names)) {
402                $husb_names[] = [
403                    'type' => 'BIRT',
404                    'sort' => '@N.N.',
405                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
406                ];
407            }
408            foreach ($husb_names as $n => $husb_name) {
409                $husb_names[$n]['script'] = I18N::textScript($husb_name['full']);
410            }
411
412            $wife_names = [];
413            if ($this->wife) {
414                $wife_names = array_filter($this->wife->getAllNames(), function (array $x): bool {
415                    return $x['type'] !== '_MARNM';
416                });
417            }
418            // If the individual only has married names, create a dummy birth name.
419            if (empty($wife_names)) {
420                $wife_names[] = [
421                    'type' => 'BIRT',
422                    'sort' => '@N.N.',
423                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
424                ];
425            }
426            foreach ($wife_names as $n => $wife_name) {
427                $wife_names[$n]['script'] = I18N::textScript($wife_name['full']);
428            }
429
430            // Add the matched names first
431            foreach ($husb_names as $husb_name) {
432                foreach ($wife_names as $wife_name) {
433                    if ($husb_name['script'] == $wife_name['script']) {
434                        $this->getAllNames[] = [
435                            'type' => $husb_name['type'],
436                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
437                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
438                            // No need for a fullNN entry - we do not currently store FAM names in the database
439                        ];
440                    }
441                }
442            }
443
444            // Add the unmatched names second (there may be no matched names)
445            foreach ($husb_names as $husb_name) {
446                foreach ($wife_names as $wife_name) {
447                    if ($husb_name['script'] != $wife_name['script']) {
448                        $this->getAllNames[] = [
449                            'type' => $husb_name['type'],
450                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
451                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
452                            // No need for a fullNN entry - we do not currently store FAM names in the database
453                        ];
454                    }
455                }
456            }
457        }
458
459        return $this->getAllNames;
460    }
461
462    /**
463     * This function should be redefined in derived classes to show any major
464     * identifying characteristics of this record.
465     *
466     * @return string
467     */
468    public function formatListDetails(): string
469    {
470        return
471            $this->formatFirstMajorFact(Gedcom::MARRIAGE_EVENTS, 1) .
472            $this->formatFirstMajorFact(Gedcom::DIVORCE_EVENTS, 1);
473    }
474}
475