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