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