xref: /webtrees/app/Family.php (revision 0c0910bf0f275a14f35d2ccdf698f91f79e269d4)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17declare(strict_types=1);
18
19namespace Fisharebest\Webtrees;
20
21use Closure;
22use Exception;
23use Illuminate\Database\Capsule\Manager as DB;
24use Illuminate\Support\Collection;
25use stdClass;
26
27/**
28 * A GEDCOM family (FAM) object.
29 */
30class Family extends GedcomRecord
31{
32    public const RECORD_TYPE = 'FAM';
33
34    protected const ROUTE_NAME = 'family';
35
36    /** @var Individual|null The husband (or first spouse for same-sex couples) */
37    private $husb;
38
39    /** @var Individual|null The wife (or second spouse for same-sex couples) */
40    private $wife;
41
42    /**
43     * Create a GedcomRecord object from raw GEDCOM data.
44     *
45     * @param string      $xref
46     * @param string      $gedcom  an empty string for new/pending records
47     * @param string|null $pending null for a record with no pending edits,
48     *                             empty string for records with pending deletions
49     * @param Tree        $tree
50     */
51    public function __construct(string $xref, string $gedcom, ?string $pending, Tree $tree)
52    {
53        parent::__construct($xref, $gedcom, $pending, $tree);
54
55        // Fetch family members
56        if (preg_match_all('/^1 (?:HUSB|WIFE|CHIL) @(.+)@/m', $gedcom . $pending, $match)) {
57            Individual::load($tree, $match[1]);
58        }
59
60        if (preg_match('/^1 HUSB @(.+)@/m', $gedcom . $pending, $match)) {
61            $this->husb = Individual::getInstance($match[1], $tree);
62        }
63        if (preg_match('/^1 WIFE @(.+)@/m', $gedcom . $pending, $match)) {
64            $this->wife = Individual::getInstance($match[1], $tree);
65        }
66    }
67
68    /**
69     * A closure which will create a record from a database row.
70     *
71     * @return Closure
72     */
73    public static function rowMapper(): Closure
74    {
75        return static function (stdClass $row): Family {
76            return Family::getInstance($row->f_id, Tree::findById((int) $row->f_file), $row->f_gedcom);
77        };
78    }
79
80    /**
81     * A closure which will compare families by marriage date.
82     *
83     * @return Closure
84     */
85    public static function marriageDateComparator(): Closure
86    {
87        return static function (Family $x, Family $y): int {
88            return Date::compare($x->getMarriageDate(), $y->getMarriageDate());
89        };
90    }
91
92    /**
93     * Get an instance of a family object. For single records,
94     * we just receive the XREF. For bulk records (such as lists
95     * and search results) we can receive the GEDCOM data as well.
96     *
97     * @param string      $xref
98     * @param Tree        $tree
99     * @param string|null $gedcom
100     *
101     * @throws Exception
102     *
103     * @return Family|null
104     */
105    public static function getInstance(string $xref, Tree $tree, string $gedcom = null): ?self
106    {
107        $record = parent::getInstance($xref, $tree, $gedcom);
108
109        if ($record instanceof self) {
110            return $record;
111        }
112
113        return null;
114    }
115
116    /**
117     * Generate a private version of this record
118     *
119     * @param int $access_level
120     *
121     * @return string
122     */
123    protected function createPrivateGedcomRecord(int $access_level): string
124    {
125        $SHOW_PRIVATE_RELATIONSHIPS = $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
126
127        $rec = '0 @' . $this->xref . '@ FAM';
128        // Just show the 1 CHIL/HUSB/WIFE tag, not any subtags, which may contain private data
129        preg_match_all('/\n1 (?:CHIL|HUSB|WIFE) @(' . Gedcom::REGEX_XREF . ')@/', $this->gedcom, $matches, PREG_SET_ORDER);
130        foreach ($matches as $match) {
131            $rela = Individual::getInstance($match[1], $this->tree);
132            if ($rela && ($SHOW_PRIVATE_RELATIONSHIPS || $rela->canShow($access_level))) {
133                $rec .= $match[0];
134            }
135        }
136
137        return $rec;
138    }
139
140    /**
141     * Fetch data from the database
142     *
143     * @param string $xref
144     * @param int    $tree_id
145     *
146     * @return string|null
147     */
148    protected static function fetchGedcomRecord(string $xref, int $tree_id): ?string
149    {
150        return DB::table('families')
151            ->where('f_id', '=', $xref)
152            ->where('f_file', '=', $tree_id)
153            ->value('f_gedcom');
154    }
155
156    /**
157     * Get the male (or first female) partner of the family
158     *
159     * @param int|null $access_level
160     *
161     * @return Individual|null
162     */
163    public function husband($access_level = null): ?Individual
164    {
165        $SHOW_PRIVATE_RELATIONSHIPS = $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
166
167        if ($this->husb && ($SHOW_PRIVATE_RELATIONSHIPS || $this->husb->canShowName($access_level))) {
168            return $this->husb;
169        }
170
171        return null;
172    }
173
174    /**
175     * Get the female (or second male) partner of the family
176     *
177     * @param int|null $access_level
178     *
179     * @return Individual|null
180     */
181    public function wife($access_level = null): ?Individual
182    {
183        $SHOW_PRIVATE_RELATIONSHIPS = $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
184
185        if ($this->wife && ($SHOW_PRIVATE_RELATIONSHIPS || $this->wife->canShowName($access_level))) {
186            return $this->wife;
187        }
188
189        return null;
190    }
191
192    /**
193     * Each object type may have its own special rules, and re-implement this function.
194     *
195     * @param int $access_level
196     *
197     * @return bool
198     */
199    protected function canShowByType(int $access_level): bool
200    {
201        // Hide a family if any member is private
202        preg_match_all('/\n1 (?:CHIL|HUSB|WIFE) @(' . Gedcom::REGEX_XREF . ')@/', $this->gedcom, $matches);
203        foreach ($matches[1] as $match) {
204            $person = Individual::getInstance($match, $this->tree);
205            if ($person && !$person->canShow($access_level)) {
206                return false;
207            }
208        }
209
210        return true;
211    }
212
213    /**
214     * Can the name of this record be shown?
215     *
216     * @param int|null $access_level
217     *
218     * @return bool
219     */
220    public function canShowName(int $access_level = null): bool
221    {
222        // We can always see the name (Husband-name + Wife-name), however,
223        // the name will often be "private + private"
224        return true;
225    }
226
227    /**
228     * Find the spouse of a person.
229     *
230     * @param Individual $person
231     * @param int|null   $access_level
232     *
233     * @return Individual|null
234     */
235    public function spouse(Individual $person, $access_level = null): ?Individual
236    {
237        if ($person === $this->wife) {
238            return $this->husband($access_level);
239        }
240
241        return $this->wife($access_level);
242    }
243
244    /**
245     * Get the (zero, one or two) spouses from this family.
246     *
247     * @param int|null $access_level
248     *
249     * @return Collection
250     */
251    public function spouses($access_level = null): Collection
252    {
253        $spouses = new Collection([
254            $this->husband($access_level),
255            $this->wife($access_level),
256        ]);
257
258        return $spouses->filter();
259    }
260
261    /**
262     * Get a list of this family’s children.
263     *
264     * @param int|null $access_level
265     *
266     * @return Collection
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        if ($marriage instanceof Fact) {
350            return $marriage->place();
351        }
352
353        return new Place('', $this->tree);
354    }
355
356    /**
357     * Get a list of all marriage dates - for the family lists.
358     *
359     * @return Date[]
360     */
361    public function getAllMarriageDates(): array
362    {
363        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
364            $array = $this->getAllEventDates([$event]);
365
366            if (!empty($array)) {
367                return $array;
368            }
369        }
370
371        return [];
372    }
373
374    /**
375     * Get a list of all marriage places - for the family lists.
376     *
377     * @return Place[]
378     */
379    public function getAllMarriagePlaces(): array
380    {
381        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
382            $places = $this->getAllEventPlaces([$event]);
383            if (!empty($places)) {
384                return $places;
385            }
386        }
387
388        return [];
389    }
390
391    /**
392     * Derived classes should redefine this function, otherwise the object will have no name
393     *
394     * @return string[][]
395     */
396    public function getAllNames(): array
397    {
398        if ($this->getAllNames === null) {
399            // Check the script used by each name, so we can match cyrillic with cyrillic, greek with greek, etc.
400            $husb_names = [];
401            if ($this->husb) {
402                $husb_names = array_filter($this->husb->getAllNames(), static function (array $x): bool {
403                    return $x['type'] !== '_MARNM';
404                });
405            }
406            // If the individual only has married names, create a dummy birth name.
407            if (empty($husb_names)) {
408                $husb_names[] = [
409                    'type' => 'BIRT',
410                    'sort' => '@N.N.',
411                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
412                ];
413            }
414            foreach ($husb_names as $n => $husb_name) {
415                $husb_names[$n]['script'] = I18N::textScript($husb_name['full']);
416            }
417
418            $wife_names = [];
419            if ($this->wife) {
420                $wife_names = array_filter($this->wife->getAllNames(), static function (array $x): bool {
421                    return $x['type'] !== '_MARNM';
422                });
423            }
424            // If the individual only has married names, create a dummy birth name.
425            if (empty($wife_names)) {
426                $wife_names[] = [
427                    'type' => 'BIRT',
428                    'sort' => '@N.N.',
429                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
430                ];
431            }
432            foreach ($wife_names as $n => $wife_name) {
433                $wife_names[$n]['script'] = I18N::textScript($wife_name['full']);
434            }
435
436            // Add the matched names first
437            foreach ($husb_names as $husb_name) {
438                foreach ($wife_names as $wife_name) {
439                    if ($husb_name['script'] === $wife_name['script']) {
440                        $this->getAllNames[] = [
441                            'type' => $husb_name['type'],
442                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
443                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
444                            // No need for a fullNN entry - we do not currently store FAM names in the database
445                        ];
446                    }
447                }
448            }
449
450            // Add the unmatched names second (there may be no matched names)
451            foreach ($husb_names as $husb_name) {
452                foreach ($wife_names as $wife_name) {
453                    if ($husb_name['script'] !== $wife_name['script']) {
454                        $this->getAllNames[] = [
455                            'type' => $husb_name['type'],
456                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
457                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
458                            // No need for a fullNN entry - we do not currently store FAM names in the database
459                        ];
460                    }
461                }
462            }
463        }
464
465        return $this->getAllNames;
466    }
467
468    /**
469     * This function should be redefined in derived classes to show any major
470     * identifying characteristics of this record.
471     *
472     * @return string
473     */
474    public function formatListDetails(): string
475    {
476        return
477            $this->formatFirstMajorFact(Gedcom::MARRIAGE_EVENTS, 1) .
478            $this->formatFirstMajorFact(Gedcom::DIVORCE_EVENTS, 1);
479    }
480}
481