summaryrefslogtreecommitdiff
path: root/app/Family.php
blob: a59bc27d864b59d1a94e281d242a142093be0867 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
<?php

/**
 * webtrees: online genealogy
 * Copyright (C) 2026 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

declare(strict_types=1);

namespace Fisharebest\Webtrees;

use Closure;
use Fisharebest\Webtrees\Http\RequestHandlers\FamilyPage;
use Illuminate\Support\Collection;

/**
 * A GEDCOM family (FAM) object.
 */
class Family extends GedcomRecord
{
    public const string RECORD_TYPE = 'FAM';

    protected const string ROUTE_NAME = FamilyPage::class;

    // The husband (or first spouse for same-sex couples)
    private Individual|null $husb = null;

    // The wife (or second spouse for same-sex couples)
    private Individual|null $wife = null;

    /**
     * Create a GedcomRecord object from raw GEDCOM data.
     *
     * @param string      $xref
     * @param string      $gedcom  an empty string for new/pending records
     * @param string|null $pending null for a record with no pending edits,
     *                             empty string for records with pending deletions
     * @param Tree        $tree
     */
    public function __construct(string $xref, string $gedcom, string|null $pending, Tree $tree)
    {
        parent::__construct($xref, $gedcom, $pending, $tree);

        // Make sure we find records in pending records.
        $gedcom_pending = $gedcom . "\n" . $pending;

        if (preg_match('/\n1 HUSB @(.+)@/', $gedcom_pending, $match)) {
            $this->husb = Registry::individualFactory()->make($match[1], $tree);
        }
        if (preg_match('/\n1 WIFE @(.+)@/', $gedcom_pending, $match)) {
            $this->wife = Registry::individualFactory()->make($match[1], $tree);
        }
    }

    /**
     * A closure which will compare families by marriage date.
     *
     * @return Closure(Family,Family):int
     */
    public static function marriageDateComparator(): Closure
    {
        return static fn (Family $x, Family $y): int => Date::compare($x->getMarriageDate(), $y->getMarriageDate());
    }

    /**
     * Get the male (or first female) partner of the family
     *
     * @param int|null $access_level
     *
     * @return Individual|null
     */
    public function husband(int|null $access_level = null): Individual|null
    {
        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
            $access_level = Auth::PRIV_HIDE;
        }

        if ($this->husb instanceof Individual && $this->husb->canShowName($access_level)) {
            return $this->husb;
        }

        return null;
    }

    /**
     * Get the female (or second male) partner of the family
     *
     * @param int|null $access_level
     *
     * @return Individual|null
     */
    public function wife(int|null $access_level = null): Individual|null
    {
        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
            $access_level = Auth::PRIV_HIDE;
        }

        if ($this->wife instanceof Individual && $this->wife->canShowName($access_level)) {
            return $this->wife;
        }

        return null;
    }

    /**
     * Each object type may have its own special rules, and re-implement this function.
     *
     * @param int $access_level
     *
     * @return bool
     */
    protected function canShowByType(int $access_level): bool
    {
        // Hide a family if any member is private
        preg_match_all('/\n1 (?:CHIL|HUSB|WIFE) @(' . Gedcom::REGEX_XREF . ')@/', $this->gedcom, $matches);
        foreach ($matches[1] as $match) {
            $individual = Registry::individualFactory()->make($match, $this->tree);

            if ($individual instanceof Individual && !$individual->canShow($access_level)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Can the name of this record be shown?
     *
     * @param int|null $access_level
     *
     * @return bool
     */
    public function canShowName(int|null $access_level = null): bool
    {
        // We can always see the name (Husband-name + Wife-name), however,
        // the name will often be "private + private"
        return true;
    }

    /**
     * Find the spouse of a person.
     *
     * @param Individual $person
     * @param int|null   $access_level
     *
     * @return Individual|null
     */
    public function spouse(Individual $person, int|null $access_level = null): Individual|null
    {
        if ($person === $this->wife) {
            return $this->husband($access_level);
        }

        return $this->wife($access_level);
    }

    /**
     * Get the (zero, one or two) spouses from this family.
     *
     * @param int|null $access_level
     *
     * @return Collection<int,Individual>
     */
    public function spouses(int|null $access_level = null): Collection
    {
        $spouses = new Collection([
            $this->husband($access_level),
            $this->wife($access_level),
        ]);

        return $spouses->filter();
    }

    /**
     * Get a list of this family’s children.
     *
     * @param int|null $access_level
     *
     * @return Collection<int,Individual>
     */
    public function children(int|null $access_level = null): Collection
    {
        $access_level ??= Auth::accessLevel($this->tree);

        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
            $access_level = Auth::PRIV_HIDE;
        }

        $children = new Collection();

        foreach ($this->facts(['CHIL'], false, $access_level) as $fact) {
            $child = $fact->target();

            if ($child instanceof Individual && $child->canShowName($access_level)) {
                $children->push($child);
            }
        }

        return $children;
    }

    /**
     * Number of children - for the individual list
     *
     * @return int
     */
    public function numberOfChildren(): int
    {
        $nchi = $this->children()->count();

        foreach ($this->facts(['NCHI']) as $fact) {
            $nchi = max($nchi, (int) $fact->value());
        }

        return $nchi;
    }

    /**
     * get the marriage event
     */
    public function getMarriage(): Fact|null
    {
        return $this->facts(['MARR'])->first();
    }

    /**
     * Get marriage date
     *
     * @return Date
     */
    public function getMarriageDate(): Date
    {
        $marriage = $this->getMarriage();
        if ($marriage instanceof Fact) {
            return $marriage->date();
        }

        return new Date('');
    }

    /**
     * Get the marriage year - displayed on lists of families
     *
     * @return int
     */
    public function getMarriageYear(): int
    {
        return $this->getMarriageDate()->minimumDate()->year;
    }

    /**
     * Get the marriage place
     *
     * @return Place
     */
    public function getMarriagePlace(): Place
    {
        $marriage = $this->getMarriage();

        if ($marriage instanceof Fact) {
            return $marriage->place();
        }

        return new Place('', $this->tree);
    }

    /**
     * Get a list of all marriage dates - for the family lists.
     *
     * @return array<Date>
     */
    public function getAllMarriageDates(): array
    {
        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
            $array = $this->getAllEventDates([$event]);

            if ($array !== []) {
                return $array;
            }
        }

        return [];
    }

    /**
     * Get a list of all marriage places - for the family lists.
     *
     * @return array<Place>
     */
    public function getAllMarriagePlaces(): array
    {
        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
            $places = $this->getAllEventPlaces([$event]);
            if ($places !== []) {
                return $places;
            }
        }

        return [];
    }

    /**
     * Derived classes should redefine this function, otherwise the object will have no name
     *
     * @return array<int,array<string,string>>
     */
    public function getAllNames(): array
    {
        if ($this->getAllNames === []) {
            // Check the script used by each name, so we can match cyrillic with cyrillic, greek with greek, etc.
            $husb_names = [];
            if ($this->husb instanceof Individual) {
                $husb_names = $this->husb->getAllNames();
            }
            // use Nomen Nescio when no name is known
            if ($husb_names === []) {
                $husb_names[] = [
                    'type' => 'BIRT',
                    'sort' => Individual::NOMEN_NESCIO,
                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
                ];
            }
            foreach ($husb_names as $n => $husb_name) {
                $husb_names[$n]['script'] = I18N::textScript($husb_name['full']);
            }

            $wife_names = [];
            if ($this->wife instanceof Individual) {
                $wife_names = $this->wife->getAllNames();
            }
            // use Nomen Nescio when no name is known
            if ($wife_names === []) {
                $wife_names[] = [
                    'type' => 'BIRT',
                    'sort' => Individual::NOMEN_NESCIO,
                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
                ];
            }
            foreach ($wife_names as $n => $wife_name) {
                $wife_names[$n]['script'] = I18N::textScript($wife_name['full']);
            }

            // Add the matched names first
            foreach ($husb_names as $husb_name) {
                foreach ($wife_names as $wife_name) {
                    if ($husb_name['script'] === $wife_name['script']) {
                        $this->getAllNames[] = [
                            'type' => $husb_name['type'],
                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
                            // No need for a fullNN entry - we do not currently store FAM names in the database
                        ];
                    }
                }
            }

            // Add the unmatched names second (there may be no matched names)
            foreach ($husb_names as $husb_name) {
                foreach ($wife_names as $wife_name) {
                    if ($husb_name['script'] !== $wife_name['script']) {
                        $this->getAllNames[] = [
                            'type' => $husb_name['type'],
                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
                            // No need for a fullNN entry - we do not currently store FAM names in the database
                        ];
                    }
                }
            }
        }

        return $this->getAllNames;
    }

    /**
     * This function should be redefined in derived classes to show any major
     * identifying characteristics of this record.
     *
     * @return string
     */
    public function formatListDetails(): string
    {
        return
            $this->formatFirstMajorFact(Gedcom::MARRIAGE_EVENTS, 1) .
            $this->formatFirstMajorFact(Gedcom::DIVORCE_EVENTS, 1);
    }

    /**
     * Lock the database row, to prevent concurrent edits.
     */
    public function lock(): void
    {
        DB::table('families')
            ->where('f_file', '=', $this->tree->id())
            ->where('f_id', '=', $this->xref())
            ->lockForUpdate()
            ->get();
    }
}