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