Issues (165)

app/Family.php (1 issue)

Labels
Severity
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2023 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 <https://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees;
21
22
use Closure;
23
use Fisharebest\Webtrees\Http\RequestHandlers\FamilyPage;
24
use Illuminate\Support\Collection;
25
26
/**
27
 * A GEDCOM family (FAM) object.
28
 */
29
class Family extends GedcomRecord
30
{
31
    public const RECORD_TYPE = 'FAM';
32
33
    protected const ROUTE_NAME = FamilyPage::class;
34
35
    // The husband (or first spouse for same-sex couples)
36
    private Individual|null $husb = null;
37
38
    // The wife (or second spouse for same-sex couples)
39
    private Individual|null $wife = null;
40
41
    /**
42
     * Create a GedcomRecord object from raw GEDCOM data.
43
     *
44
     * @param string      $xref
45
     * @param string      $gedcom  an empty string for new/pending records
46
     * @param string|null $pending null for a record with no pending edits,
47
     *                             empty string for records with pending deletions
48
     * @param Tree        $tree
49
     */
50
    public function __construct(string $xref, string $gedcom, string|null $pending, Tree $tree)
51
    {
52
        parent::__construct($xref, $gedcom, $pending, $tree);
53
54
        // Make sure we find records in pending records.
55
        $gedcom_pending = $gedcom . "\n" . $pending;
56
57
        if (preg_match('/\n1 HUSB @(.+)@/', $gedcom_pending, $match)) {
58
            $this->husb = Registry::individualFactory()->make($match[1], $tree);
59
        }
60
        if (preg_match('/\n1 WIFE @(.+)@/', $gedcom_pending, $match)) {
61
            $this->wife = Registry::individualFactory()->make($match[1], $tree);
62
        }
63
    }
64
65
    /**
66
     * A closure which will compare families by marriage date.
67
     *
68
     * @return Closure(Family,Family):int
69
     */
70
    public static function marriageDateComparator(): Closure
71
    {
72
        return static fn (Family $x, Family $y): int => Date::compare($x->getMarriageDate(), $y->getMarriageDate());
73
    }
74
75
    /**
76
     * Generate a private version of this record
77
     *
78
     * @param int $access_level
79
     *
80
     * @return string
81
     */
82
    protected function createPrivateGedcomRecord(int $access_level): string
83
    {
84
        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
85
            $access_level = Auth::PRIV_HIDE;
86
        }
87
88
        $rec = '0 @' . $this->xref . '@ FAM';
89
        // Just show the 1 CHIL/HUSB/WIFE tag, not any subtags, which may contain private data
90
        preg_match_all('/\n1 (?:CHIL|HUSB|WIFE) @(' . Gedcom::REGEX_XREF . ')@/', $this->gedcom, $matches, PREG_SET_ORDER);
91
        foreach ($matches as $match) {
92
            $rela = Registry::individualFactory()->make($match[1], $this->tree);
93
            if ($rela instanceof Individual && $rela->canShow($access_level)) {
94
                $rec .= $match[0];
95
            }
96
        }
97
98
        return $rec;
99
    }
100
101
    /**
102
     * Get the male (or first female) partner of the family
103
     *
104
     * @param int|null $access_level
105
     *
106
     * @return Individual|null
107
     */
108
    public function husband(int|null $access_level = null): Individual|null
109
    {
110
        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
111
            $access_level = Auth::PRIV_HIDE;
112
        }
113
114
        if ($this->husb instanceof Individual && $this->husb->canShowName($access_level)) {
115
            return $this->husb;
116
        }
117
118
        return null;
119
    }
120
121
    /**
122
     * Get the female (or second male) partner of the family
123
     *
124
     * @param int|null $access_level
125
     *
126
     * @return Individual|null
127
     */
128
    public function wife(int|null $access_level = null): Individual|null
129
    {
130
        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
131
            $access_level = Auth::PRIV_HIDE;
132
        }
133
134
        if ($this->wife instanceof Individual && $this->wife->canShowName($access_level)) {
135
            return $this->wife;
136
        }
137
138
        return null;
139
    }
140
141
    /**
142
     * Each object type may have its own special rules, and re-implement this function.
143
     *
144
     * @param int $access_level
145
     *
146
     * @return bool
147
     */
148
    protected function canShowByType(int $access_level): bool
149
    {
150
        // Hide a family if any member is private
151
        preg_match_all('/\n1 (?:CHIL|HUSB|WIFE) @(' . Gedcom::REGEX_XREF . ')@/', $this->gedcom, $matches);
152
        foreach ($matches[1] as $match) {
153
            $person = Registry::individualFactory()->make($match, $this->tree);
154
            if ($person && !$person->canShow($access_level)) {
155
                return false;
156
            }
157
        }
158
159
        return true;
160
    }
161
162
    /**
163
     * Can the name of this record be shown?
164
     *
165
     * @param int|null $access_level
166
     *
167
     * @return bool
168
     */
169
    public function canShowName(int|null $access_level = null): bool
170
    {
171
        // We can always see the name (Husband-name + Wife-name), however,
172
        // the name will often be "private + private"
173
        return true;
174
    }
175
176
    /**
177
     * Find the spouse of a person.
178
     *
179
     * @param Individual $person
180
     * @param int|null   $access_level
181
     *
182
     * @return Individual|null
183
     */
184
    public function spouse(Individual $person, int|null $access_level = null): Individual|null
185
    {
186
        if ($person === $this->wife) {
187
            return $this->husband($access_level);
188
        }
189
190
        return $this->wife($access_level);
191
    }
192
193
    /**
194
     * Get the (zero, one or two) spouses from this family.
195
     *
196
     * @param int|null $access_level
197
     *
198
     * @return Collection<int,Individual>
199
     */
200
    public function spouses(int|null $access_level = null): Collection
201
    {
202
        $spouses = new Collection([
0 ignored issues
show
array($this->husband($ac...s->wife($access_level)) of type array<integer,Fisharebes...btrees\Individual|null> is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $items of Illuminate\Support\Collection::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

202
        $spouses = new Collection(/** @scrutinizer ignore-type */ [
Loading history...
203
            $this->husband($access_level),
204
            $this->wife($access_level),
205
        ]);
206
207
        return $spouses->filter();
208
    }
209
210
    /**
211
     * Get a list of this family’s children.
212
     *
213
     * @param int|null $access_level
214
     *
215
     * @return Collection<int,Individual>
216
     */
217
    public function children(int|null $access_level = null): Collection
218
    {
219
        $access_level ??= Auth::accessLevel($this->tree);
220
221
        if ($this->tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') === '1') {
222
            $access_level = Auth::PRIV_HIDE;
223
        }
224
225
        $children = new Collection();
226
227
        foreach ($this->facts(['CHIL'], false, $access_level) as $fact) {
228
            $child = $fact->target();
229
230
            if ($child instanceof Individual && $child->canShowName($access_level)) {
231
                $children->push($child);
232
            }
233
        }
234
235
        return $children;
236
    }
237
238
    /**
239
     * Number of children - for the individual list
240
     *
241
     * @return int
242
     */
243
    public function numberOfChildren(): int
244
    {
245
        $nchi = $this->children()->count();
246
247
        foreach ($this->facts(['NCHI']) as $fact) {
248
            $nchi = max($nchi, (int) $fact->value());
249
        }
250
251
        return $nchi;
252
    }
253
254
    /**
255
     * get the marriage event
256
     */
257
    public function getMarriage(): Fact|null
258
    {
259
        return $this->facts(['MARR'])->first();
260
    }
261
262
    /**
263
     * Get marriage date
264
     *
265
     * @return Date
266
     */
267
    public function getMarriageDate(): Date
268
    {
269
        $marriage = $this->getMarriage();
270
        if ($marriage instanceof Fact) {
271
            return $marriage->date();
272
        }
273
274
        return new Date('');
275
    }
276
277
    /**
278
     * Get the marriage year - displayed on lists of families
279
     *
280
     * @return int
281
     */
282
    public function getMarriageYear(): int
283
    {
284
        return $this->getMarriageDate()->minimumDate()->year;
285
    }
286
287
    /**
288
     * Get the marriage place
289
     *
290
     * @return Place
291
     */
292
    public function getMarriagePlace(): Place
293
    {
294
        $marriage = $this->getMarriage();
295
296
        if ($marriage instanceof Fact) {
297
            return $marriage->place();
298
        }
299
300
        return new Place('', $this->tree);
301
    }
302
303
    /**
304
     * Get a list of all marriage dates - for the family lists.
305
     *
306
     * @return array<Date>
307
     */
308
    public function getAllMarriageDates(): array
309
    {
310
        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
311
            $array = $this->getAllEventDates([$event]);
312
313
            if ($array !== []) {
314
                return $array;
315
            }
316
        }
317
318
        return [];
319
    }
320
321
    /**
322
     * Get a list of all marriage places - for the family lists.
323
     *
324
     * @return array<Place>
325
     */
326
    public function getAllMarriagePlaces(): array
327
    {
328
        foreach (Gedcom::MARRIAGE_EVENTS as $event) {
329
            $places = $this->getAllEventPlaces([$event]);
330
            if ($places !== []) {
331
                return $places;
332
            }
333
        }
334
335
        return [];
336
    }
337
338
    /**
339
     * Derived classes should redefine this function, otherwise the object will have no name
340
     *
341
     * @return array<int,array<string,string>>
342
     */
343
    public function getAllNames(): array
344
    {
345
        if ($this->getAllNames === []) {
346
            // Check the script used by each name, so we can match cyrillic with cyrillic, greek with greek, etc.
347
            $husb_names = [];
348
            if ($this->husb instanceof Individual) {
349
                $husb_names = array_filter($this->husb->getAllNames(), static fn (array $x): bool => $x['type'] !== '_MARNM');
350
            }
351
            // If the individual only has married names, create a fake birth name.
352
            if ($husb_names === []) {
353
                $husb_names[] = [
354
                    'type' => 'BIRT',
355
                    'sort' => Individual::NOMEN_NESCIO,
356
                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
357
                ];
358
            }
359
            foreach ($husb_names as $n => $husb_name) {
360
                $husb_names[$n]['script'] = I18N::textScript($husb_name['full']);
361
            }
362
363
            $wife_names = [];
364
            if ($this->wife instanceof Individual) {
365
                $wife_names = array_filter($this->wife->getAllNames(), static fn (array $x): bool => $x['type'] !== '_MARNM');
366
            }
367
            // If the individual only has married names, create a fake birth name.
368
            if ($wife_names === []) {
369
                $wife_names[] = [
370
                    'type' => 'BIRT',
371
                    'sort' => Individual::NOMEN_NESCIO,
372
                    'full' => I18N::translateContext('Unknown given name', '…') . ' ' . I18N::translateContext('Unknown surname', '…'),
373
                ];
374
            }
375
            foreach ($wife_names as $n => $wife_name) {
376
                $wife_names[$n]['script'] = I18N::textScript($wife_name['full']);
377
            }
378
379
            // Add the matched names first
380
            foreach ($husb_names as $husb_name) {
381
                foreach ($wife_names as $wife_name) {
382
                    if ($husb_name['script'] === $wife_name['script']) {
383
                        $this->getAllNames[] = [
384
                            'type' => $husb_name['type'],
385
                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
386
                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
387
                            // No need for a fullNN entry - we do not currently store FAM names in the database
388
                        ];
389
                    }
390
                }
391
            }
392
393
            // Add the unmatched names second (there may be no matched names)
394
            foreach ($husb_names as $husb_name) {
395
                foreach ($wife_names as $wife_name) {
396
                    if ($husb_name['script'] !== $wife_name['script']) {
397
                        $this->getAllNames[] = [
398
                            'type' => $husb_name['type'],
399
                            'sort' => $husb_name['sort'] . ' + ' . $wife_name['sort'],
400
                            'full' => $husb_name['full'] . ' + ' . $wife_name['full'],
401
                            // No need for a fullNN entry - we do not currently store FAM names in the database
402
                        ];
403
                    }
404
                }
405
            }
406
        }
407
408
        return $this->getAllNames;
409
    }
410
411
    /**
412
     * This function should be redefined in derived classes to show any major
413
     * identifying characteristics of this record.
414
     *
415
     * @return string
416
     */
417
    public function formatListDetails(): string
418
    {
419
        return
420
            $this->formatFirstMajorFact(Gedcom::MARRIAGE_EVENTS, 1) .
421
            $this->formatFirstMajorFact(Gedcom::DIVORCE_EVENTS, 1);
422
    }
423
424
    /**
425
     * Lock the database row, to prevent concurrent edits.
426
     */
427
    public function lock(): void
428
    {
429
        DB::table('families')
430
            ->where('f_file', '=', $this->tree->id())
431
            ->where('f_id', '=', $this->xref())
432
            ->lockForUpdate()
433
            ->get();
434
    }
435
}
436