xref: /webtrees/app/Family.php (revision 6f56d8e2d285e2b1bc4277945ca29e6fc4d6e4c7)
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 stdClass;
23
24/**
25 * A GEDCOM family (FAM) object.
26 */
27class Family extends GedcomRecord
28{
29    public const RECORD_TYPE = 'FAM';
30
31    protected const ROUTE_NAME = 'family';
32
33    /** @var Individual|null The husband (or first spouse for same-sex couples) */
34    private $husb;
35
36    /** @var Individual|null The wife (or second spouse for same-sex couples) */
37    private $wife;
38
39    /**
40     * Create a GedcomRecord object from raw GEDCOM data.
41     *
42     * @param string      $xref
43     * @param string      $gedcom  an empty string for new/pending records
44     * @param string|null $pending null for a record with no pending edits,
45     *                             empty string for records with pending deletions
46     * @param Tree        $tree
47     */
48    public function __construct(string $xref, string $gedcom, $pending, Tree $tree)
49    {
50        parent::__construct($xref, $gedcom, $pending, $tree);
51
52        // Fetch family members
53        if (preg_match_all('/^1 (?:HUSB|WIFE|CHIL) @(.+)@/m', $gedcom . $pending, $match)) {
54            Individual::load($tree, $match[1]);
55        }
56
57        if (preg_match('/^1 HUSB @(.+)@/m', $gedcom . $pending, $match)) {
58            $this->husb = Individual::getInstance($match[1], $tree);
59        }
60        if (preg_match('/^1 WIFE @(.+)@/m', $gedcom . $pending, $match)) {
61            $this->wife = Individual::getInstance($match[1], $tree);
62        }
63    }
64
65    /**
66     * A closure which will create a record from a database row.
67     *
68     * @param Tree $tree
69     *
70     * @return Closure
71     */
72    public static function rowMapper(Tree $tree): Closure
73    {
74        return function (stdClass $row) use ($tree): Family {
75            return Family::getInstance($row->f_id, $tree, $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 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)
105    {
106        $record = parent::getInstance($xref, $tree, $gedcom);
107
108        if ($record instanceof Family) {
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 null|string
146     */
147    protected static function fetchGedcomRecord(string $xref, int $tree_id)
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 getHusband($access_level = null)
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 getWife($access_level = null)
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 getSpouse(Individual $person, $access_level = null)
235    {
236        if ($person === $this->wife) {
237            return $this->getHusband($access_level);
238        }
239
240        return $this->getWife($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 Individual[]
249     */
250    public function getSpouses($access_level = null): array
251    {
252        return array_filter([
253            $this->getHusband($access_level),
254            $this->getWife($access_level),
255        ]);
256    }
257
258    /**
259     * Get a list of this family’s children.
260     *
261     * @param int|null $access_level
262     *
263     * @return Individual[]
264     */
265    public function getChildren($access_level = null): array
266    {
267        if ($access_level === null) {
268            $access_level = Auth::accessLevel($this->tree);
269        }
270
271        $SHOW_PRIVATE_RELATIONSHIPS = (bool) $this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS');
272
273        $children = [];
274        foreach ($this->facts(['CHIL'], false, $access_level, $SHOW_PRIVATE_RELATIONSHIPS) as $fact) {
275            $child = $fact->target();
276            if ($child instanceof Individual && ($SHOW_PRIVATE_RELATIONSHIPS || $child->canShowName($access_level))) {
277                $children[] = $child;
278            }
279        }
280
281        return $children;
282    }
283
284    /**
285     * Number of children - for the individual list
286     *
287     * @return int
288     */
289    public function getNumberOfChildren(): int
290    {
291        $nchi = count($this->getChildren());
292        foreach ($this->facts(['NCHI']) as $fact) {
293            $nchi = max($nchi, (int) $fact->value());
294        }
295
296        return $nchi;
297    }
298
299    /**
300     * get the marriage event
301     *
302     * @return Fact|null
303     */
304    public function getMarriage()
305    {
306        return $this->getFirstFact('MARR');
307    }
308
309    /**
310     * Get marriage date
311     *
312     * @return Date
313     */
314    public function getMarriageDate()
315    {
316        $marriage = $this->getMarriage();
317        if ($marriage) {
318            return $marriage->date();
319        }
320
321        return new Date('');
322    }
323
324    /**
325     * Get the marriage year - displayed on lists of families
326     *
327     * @return int
328     */
329    public function getMarriageYear(): int
330    {
331        return $this->getMarriageDate()->minimumDate()->year;
332    }
333
334    /**
335     * Get the marriage place
336     *
337     * @return Place
338     */
339    public function getMarriagePlace(): Place
340    {
341        $marriage = $this->getMarriage();
342
343        return $marriage->place();
344    }
345
346    /**
347     * Get a list of all marriage dates - for the family lists.
348     *
349     * @return Date[]
350     */
351    public function getAllMarriageDates(): array
352    {
353        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
354            if ($array = $this->getAllEventDates([$event])) {
355                return $array;
356            }
357        }
358
359        return [];
360    }
361
362    /**
363     * Get a list of all marriage places - for the family lists.
364     *
365     * @return Place[]
366     */
367    public function getAllMarriagePlaces(): array
368    {
369        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
370            $places = $this->getAllEventPlaces([$event]);
371            if (!empty($places)) {
372                return $places;
373            }
374        }
375
376        return [];
377    }
378
379    /**
380     * Derived classes should redefine this function, otherwise the object will have no name
381     *
382     * @return string[][]
383     */
384    public function getAllNames(): array
385    {
386        if ($this->getAllNames === null) {
387            // Check the script used by each name, so we can match cyrillic with cyrillic, greek with greek, etc.
388            $husb_names = [];
389            if ($this->husb) {
390                $husb_names = array_filter($this->husb->getAllNames(), function (array $x): bool {
391                    return $x['type'] !== '_MARNM';
392                });
393            }
394            // If the individual only has married names, create a dummy birth name.
395            if (empty($husb_names)) {
396                $husb_names[] = [
397                    'type' => 'BIRT',
398                    'sort' => '@N.N.',
399                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
400                ];
401            }
402            foreach ($husb_names as $n => $husb_name) {
403                $husb_names[$n]['script'] = I18N::textScript($husb_name['full']);
404            }
405
406            $wife_names = [];
407            if ($this->wife) {
408                $wife_names = array_filter($this->wife->getAllNames(), function (array $x): bool {
409                    return $x['type'] !== '_MARNM';
410                });
411            }
412            // If the individual only has married names, create a dummy birth name.
413            if (empty($wife_names)) {
414                $wife_names[] = [
415                    'type' => 'BIRT',
416                    'sort' => '@N.N.',
417                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
418                ];
419            }
420            foreach ($wife_names as $n => $wife_name) {
421                $wife_names[$n]['script'] = I18N::textScript($wife_name['full']);
422            }
423
424            // Add the matched names first
425            foreach ($husb_names as $husb_name) {
426                foreach ($wife_names as $wife_name) {
427                    if ($husb_name['script'] == $wife_name['script']) {
428                        $this->getAllNames[] = [
429                            'type' => $husb_name['type'],
430                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
431                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
432                            // No need for a fullNN entry - we do not currently store FAM names in the database
433                        ];
434                    }
435                }
436            }
437
438            // Add the unmatched names second (there may be no matched names)
439            foreach ($husb_names as $husb_name) {
440                foreach ($wife_names as $wife_name) {
441                    if ($husb_name['script'] != $wife_name['script']) {
442                        $this->getAllNames[] = [
443                            'type' => $husb_name['type'],
444                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
445                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
446                            // No need for a fullNN entry - we do not currently store FAM names in the database
447                        ];
448                    }
449                }
450            }
451        }
452
453        return $this->getAllNames;
454    }
455
456    /**
457     * This function should be redefined in derived classes to show any major
458     * identifying characteristics of this record.
459     *
460     * @return string
461     */
462    public function formatListDetails(): string
463    {
464        return
465            $this->formatFirstMajorFact(Gedcom::MARRIAGE_EVENTS, 1) .
466            $this->formatFirstMajorFact(Gedcom::DIVORCE_EVENTS, 1);
467    }
468}
469