xref: /webtrees/app/Tree.php (revision eed04cf92eb519b30002669d271d3ec8fc215449)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Closure;
23use Fisharebest\Flysystem\Adapter\ChrootAdapter;
24use Fisharebest\Webtrees\Contracts\UserInterface;
25use Fisharebest\Webtrees\Services\PendingChangesService;
26use Illuminate\Database\Capsule\Manager as DB;
27use InvalidArgumentException;
28use League\Flysystem\Filesystem;
29use League\Flysystem\FilesystemOperator;
30
31use function app;
32use function array_key_exists;
33use function assert;
34use function date;
35use function is_string;
36use function str_starts_with;
37use function strtoupper;
38use function substr_replace;
39
40/**
41 * Provide an interface to the wt_gedcom table.
42 */
43class Tree
44{
45    private const RESN_PRIVACY = [
46        'none'         => Auth::PRIV_PRIVATE,
47        'privacy'      => Auth::PRIV_USER,
48        'confidential' => Auth::PRIV_NONE,
49        'hidden'       => Auth::PRIV_HIDE,
50    ];
51
52
53    // Default values for some tree preferences.
54    protected const DEFAULT_PREFERENCES = [
55        'CALENDAR_FORMAT'              => 'gregorian',
56        'CHART_BOX_TAGS'               => '',
57        'EXPAND_SOURCES'               => '0',
58        'FAM_FACTS_QUICK'              => 'ENGA,MARR,DIV',
59        'FORMAT_TEXT'                  => 'markdown',
60        'FULL_SOURCES'                 => '0',
61        'GEDCOM_MEDIA_PATH'            => '',
62        'GENERATE_UIDS'                => '0',
63        'HIDE_GEDCOM_ERRORS'           => '1',
64        'HIDE_LIVE_PEOPLE'             => '1',
65        'INDI_FACTS_QUICK'             => 'BIRT,BURI,BAPM,CENS,DEAT,OCCU,RESI',
66        'KEEP_ALIVE_YEARS_BIRTH'       => '',
67        'KEEP_ALIVE_YEARS_DEATH'       => '',
68        'LANGUAGE'                     => 'en-US',
69        'MAX_ALIVE_AGE'                => '120',
70        'MEDIA_DIRECTORY'              => 'media/',
71        'MEDIA_UPLOAD'                 => '1', // Auth::PRIV_USER
72        'META_DESCRIPTION'             => '',
73        'META_TITLE'                   => Webtrees::NAME,
74        'NO_UPDATE_CHAN'               => '0',
75        'PEDIGREE_ROOT_ID'             => '',
76        'PREFER_LEVEL2_SOURCES'        => '1',
77        'QUICK_REQUIRED_FACTS'         => 'BIRT,DEAT',
78        'QUICK_REQUIRED_FAMFACTS'      => 'MARR',
79        'REQUIRE_AUTHENTICATION'       => '0',
80        'SAVE_WATERMARK_IMAGE'         => '0',
81        'SHOW_AGE_DIFF'                => '0',
82        'SHOW_COUNTER'                 => '1',
83        'SHOW_DEAD_PEOPLE'             => '2', // Auth::PRIV_PRIVATE
84        'SHOW_EST_LIST_DATES'          => '0',
85        'SHOW_FACT_ICONS'              => '1',
86        'SHOW_GEDCOM_RECORD'           => '0',
87        'SHOW_HIGHLIGHT_IMAGES'        => '1',
88        'SHOW_LEVEL2_NOTES'            => '1',
89        'SHOW_LIVING_NAMES'            => '1', // Auth::PRIV_USER
90        'SHOW_MEDIA_DOWNLOAD'          => '0',
91        'SHOW_NO_WATERMARK'            => '1', // Auth::PRIV_USER
92        'SHOW_PARENTS_AGE'             => '1',
93        'SHOW_PEDIGREE_PLACES'         => '9',
94        'SHOW_PEDIGREE_PLACES_SUFFIX'  => '0',
95        'SHOW_PRIVATE_RELATIONSHIPS'   => '1',
96        'SHOW_RELATIVES_EVENTS'        => '_BIRT_CHIL,_BIRT_SIBL,_MARR_CHIL,_MARR_PARE,_DEAT_CHIL,_DEAT_PARE,_DEAT_GPAR,_DEAT_SIBL,_DEAT_SPOU',
97        'SUBLIST_TRIGGER_I'            => '200',
98        'SURNAME_LIST_STYLE'           => 'style2',
99        'SURNAME_TRADITION'            => 'paternal',
100        'USE_SILHOUETTE'               => '1',
101        'WORD_WRAPPED_NOTES'           => '0',
102    ];
103
104    private int $id;
105
106    private string $name;
107
108    private string $title;
109
110    /** @var array<int> Default access rules for facts in this tree */
111    private array $fact_privacy;
112
113    /** @var array<int> Default access rules for individuals in this tree */
114    private array $individual_privacy;
115
116    /** @var array<array<int>> Default access rules for individual facts in this tree */
117    private array $individual_fact_privacy;
118
119    /** @var array<string> Cached copy of the wt_gedcom_setting table. */
120    private $preferences = [];
121
122    /** @var array<array<string>> Cached copy of the wt_user_gedcom_setting table. */
123    private array $user_preferences = [];
124
125    /**
126     * Create a tree object.
127     *
128     * @param int    $id
129     * @param string $name
130     * @param string $title
131     */
132    public function __construct(int $id, string $name, string $title)
133    {
134        $this->id                      = $id;
135        $this->name                    = $name;
136        $this->title                   = $title;
137        $this->fact_privacy            = [];
138        $this->individual_privacy      = [];
139        $this->individual_fact_privacy = [];
140
141        // Load the privacy settings for this tree
142        $rows = DB::table('default_resn')
143            ->where('gedcom_id', '=', $this->id)
144            ->get();
145
146        foreach ($rows as $row) {
147            // Convert GEDCOM privacy restriction to a webtrees access level.
148            $row->resn = self::RESN_PRIVACY[$row->resn];
149
150            if ($row->xref !== null) {
151                if ($row->tag_type !== null) {
152                    $this->individual_fact_privacy[$row->xref][$row->tag_type] = $row->resn;
153                } else {
154                    $this->individual_privacy[$row->xref] = $row->resn;
155                }
156            } else {
157                $this->fact_privacy[$row->tag_type] = $row->resn;
158            }
159        }
160    }
161
162    /**
163     * A closure which will create a record from a database row.
164     *
165     * @return Closure
166     */
167    public static function rowMapper(): Closure
168    {
169        return static fn (object $row): Tree => new Tree((int) $row->tree_id, $row->tree_name, $row->tree_title);
170    }
171
172    /**
173     * Set the tree’s configuration settings.
174     *
175     * @param string $setting_name
176     * @param string $setting_value
177     *
178     * @return self
179     */
180    public function setPreference(string $setting_name, string $setting_value): Tree
181    {
182        if ($setting_value !== $this->getPreference($setting_name)) {
183            DB::table('gedcom_setting')->updateOrInsert([
184                'gedcom_id'    => $this->id,
185                'setting_name' => $setting_name,
186            ], [
187                'setting_value' => $setting_value,
188            ]);
189
190            $this->preferences[$setting_name] = $setting_value;
191
192            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '"', $this);
193        }
194
195        return $this;
196    }
197
198    /**
199     * Get the tree’s configuration settings.
200     *
201     * @param string      $setting_name
202     * @param string|null $default
203     *
204     * @return string
205     */
206    public function getPreference(string $setting_name, string $default = null): string
207    {
208        if ($this->preferences === []) {
209            $this->preferences = DB::table('gedcom_setting')
210                ->where('gedcom_id', '=', $this->id)
211                ->pluck('setting_value', 'setting_name')
212                ->all();
213        }
214
215        return $this->preferences[$setting_name] ?? $default ?? self::DEFAULT_PREFERENCES[$setting_name] ?? '';
216    }
217
218    /**
219     * The name of this tree
220     *
221     * @return string
222     */
223    public function name(): string
224    {
225        return $this->name;
226    }
227
228    /**
229     * The title of this tree
230     *
231     * @return string
232     */
233    public function title(): string
234    {
235        return $this->title;
236    }
237
238    /**
239     * The fact-level privacy for this tree.
240     *
241     * @return array<int>
242     */
243    public function getFactPrivacy(): array
244    {
245        return $this->fact_privacy;
246    }
247
248    /**
249     * The individual-level privacy for this tree.
250     *
251     * @return array<int>
252     */
253    public function getIndividualPrivacy(): array
254    {
255        return $this->individual_privacy;
256    }
257
258    /**
259     * The individual-fact-level privacy for this tree.
260     *
261     * @return array<array<int>>
262     */
263    public function getIndividualFactPrivacy(): array
264    {
265        return $this->individual_fact_privacy;
266    }
267
268    /**
269     * Set the tree’s user-configuration settings.
270     *
271     * @param UserInterface $user
272     * @param string        $setting_name
273     * @param string        $setting_value
274     *
275     * @return self
276     */
277    public function setUserPreference(UserInterface $user, string $setting_name, string $setting_value): Tree
278    {
279        if ($this->getUserPreference($user, $setting_name) !== $setting_value) {
280            // Update the database
281            DB::table('user_gedcom_setting')->updateOrInsert([
282                'gedcom_id'    => $this->id(),
283                'user_id'      => $user->id(),
284                'setting_name' => $setting_name,
285            ], [
286                'setting_value' => $setting_value,
287            ]);
288
289            // Update the cache
290            $this->user_preferences[$user->id()][$setting_name] = $setting_value;
291            // Audit log of changes
292            Log::addConfigurationLog('Tree preference "' . $setting_name . '" set to "' . $setting_value . '" for user "' . $user->userName() . '"', $this);
293        }
294
295        return $this;
296    }
297
298    /**
299     * Get the tree’s user-configuration settings.
300     *
301     * @param UserInterface $user
302     * @param string        $setting_name
303     * @param string        $default
304     *
305     * @return string
306     */
307    public function getUserPreference(UserInterface $user, string $setting_name, string $default = ''): string
308    {
309        // There are lots of settings, and we need to fetch lots of them on every page
310        // so it is quicker to fetch them all in one go.
311        if (!array_key_exists($user->id(), $this->user_preferences)) {
312            $this->user_preferences[$user->id()] = DB::table('user_gedcom_setting')
313                ->where('user_id', '=', $user->id())
314                ->where('gedcom_id', '=', $this->id)
315                ->pluck('setting_value', 'setting_name')
316                ->all();
317        }
318
319        return $this->user_preferences[$user->id()][$setting_name] ?? $default;
320    }
321
322    /**
323     * The ID of this tree
324     *
325     * @return int
326     */
327    public function id(): int
328    {
329        return $this->id;
330    }
331
332    /**
333     * Can a user accept changes for this tree?
334     *
335     * @param UserInterface $user
336     *
337     * @return bool
338     */
339    public function canAcceptChanges(UserInterface $user): bool
340    {
341        return Auth::isModerator($this, $user);
342    }
343
344    /**
345     * Are there any pending edits for this tree, that need reviewing by a moderator.
346     *
347     * @return bool
348     */
349    public function hasPendingEdit(): bool
350    {
351        return DB::table('change')
352            ->where('gedcom_id', '=', $this->id)
353            ->where('status', '=', 'pending')
354            ->exists();
355    }
356
357    /**
358     * Create a new record from GEDCOM data.
359     *
360     * @param string $gedcom
361     *
362     * @return GedcomRecord|Individual|Family|Location|Note|Source|Repository|Media|Submitter|Submission
363     * @throws InvalidArgumentException
364     */
365    public function createRecord(string $gedcom): GedcomRecord
366    {
367        if (!preg_match('/^0 @@ ([_A-Z]+)/', $gedcom, $match)) {
368            throw new InvalidArgumentException('GedcomRecord::createRecord(' . $gedcom . ') does not begin 0 @@');
369        }
370
371        $xref   = Registry::xrefFactory()->make($match[1]);
372        $gedcom = substr_replace($gedcom, $xref, 3, 0);
373
374        // Create a change record
375        $today = strtoupper(date('d M Y'));
376        $now   = date('H:i:s');
377        $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
378
379        // Create a pending change
380        DB::table('change')->insert([
381            'gedcom_id'  => $this->id,
382            'xref'       => $xref,
383            'old_gedcom' => '',
384            'new_gedcom' => $gedcom,
385            'user_id'    => Auth::id(),
386        ]);
387
388        // Accept this pending change
389        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
390            $record = Registry::gedcomRecordFactory()->new($xref, $gedcom, null, $this);
391
392            $pending_changes_service = app(PendingChangesService::class);
393            assert($pending_changes_service instanceof PendingChangesService);
394
395            $pending_changes_service->acceptRecord($record);
396
397            return $record;
398        }
399
400        return Registry::gedcomRecordFactory()->new($xref, '', $gedcom, $this);
401    }
402
403    /**
404     * Create a new family from GEDCOM data.
405     *
406     * @param string $gedcom
407     *
408     * @return Family
409     * @throws InvalidArgumentException
410     */
411    public function createFamily(string $gedcom): GedcomRecord
412    {
413        if (!str_starts_with($gedcom, '0 @@ FAM')) {
414            throw new InvalidArgumentException('GedcomRecord::createFamily(' . $gedcom . ') does not begin 0 @@ FAM');
415        }
416
417        $xref   = Registry::xrefFactory()->make(Family::RECORD_TYPE);
418        $gedcom = substr_replace($gedcom, $xref, 3, 0);
419
420        // Create a change record
421        $today = strtoupper(date('d M Y'));
422        $now   = date('H:i:s');
423        $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
424
425        // Create a pending change
426        DB::table('change')->insert([
427            'gedcom_id'  => $this->id,
428            'xref'       => $xref,
429            'old_gedcom' => '',
430            'new_gedcom' => $gedcom,
431            'user_id'    => Auth::id(),
432        ]);
433
434        // Accept this pending change
435        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
436            $record = Registry::familyFactory()->new($xref, $gedcom, null, $this);
437
438            $pending_changes_service = app(PendingChangesService::class);
439            assert($pending_changes_service instanceof PendingChangesService);
440
441            $pending_changes_service->acceptRecord($record);
442
443            return $record;
444        }
445
446        return Registry::familyFactory()->new($xref, '', $gedcom, $this);
447    }
448
449    /**
450     * Create a new individual from GEDCOM data.
451     *
452     * @param string $gedcom
453     *
454     * @return Individual
455     * @throws InvalidArgumentException
456     */
457    public function createIndividual(string $gedcom): GedcomRecord
458    {
459        if (!str_starts_with($gedcom, '0 @@ INDI')) {
460            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ INDI');
461        }
462
463        $xref   = Registry::xrefFactory()->make(Individual::RECORD_TYPE);
464        $gedcom = substr_replace($gedcom, $xref, 3, 0);
465
466        // Create a change record
467        $today = strtoupper(date('d M Y'));
468        $now   = date('H:i:s');
469        $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
470
471        // Create a pending change
472        DB::table('change')->insert([
473            'gedcom_id'  => $this->id,
474            'xref'       => $xref,
475            'old_gedcom' => '',
476            'new_gedcom' => $gedcom,
477            'user_id'    => Auth::id(),
478        ]);
479
480        // Accept this pending change
481        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
482            $record = Registry::individualFactory()->new($xref, $gedcom, null, $this);
483
484            $pending_changes_service = app(PendingChangesService::class);
485            assert($pending_changes_service instanceof PendingChangesService);
486
487            $pending_changes_service->acceptRecord($record);
488
489            return $record;
490        }
491
492        return Registry::individualFactory()->new($xref, '', $gedcom, $this);
493    }
494
495    /**
496     * Create a new media object from GEDCOM data.
497     *
498     * @param string $gedcom
499     *
500     * @return Media
501     * @throws InvalidArgumentException
502     */
503    public function createMediaObject(string $gedcom): Media
504    {
505        if (!str_starts_with($gedcom, '0 @@ OBJE')) {
506            throw new InvalidArgumentException('GedcomRecord::createIndividual(' . $gedcom . ') does not begin 0 @@ OBJE');
507        }
508
509        $xref   = Registry::xrefFactory()->make(Media::RECORD_TYPE);
510        $gedcom = substr_replace($gedcom, $xref, 3, 0);
511
512        // Create a change record
513        $today = strtoupper(date('d M Y'));
514        $now   = date('H:i:s');
515        $gedcom .= "\n1 CHAN\n2 DATE " . $today . "\n3 TIME " . $now . "\n2 _WT_USER " . Auth::user()->userName();
516
517        // Create a pending change
518        DB::table('change')->insert([
519            'gedcom_id'  => $this->id,
520            'xref'       => $xref,
521            'old_gedcom' => '',
522            'new_gedcom' => $gedcom,
523            'user_id'    => Auth::id(),
524        ]);
525
526        // Accept this pending change
527        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
528            $record = Registry::mediaFactory()->new($xref, $gedcom, null, $this);
529
530            $pending_changes_service = app(PendingChangesService::class);
531            assert($pending_changes_service instanceof PendingChangesService);
532
533            $pending_changes_service->acceptRecord($record);
534
535            return $record;
536        }
537
538        return Registry::mediaFactory()->new($xref, '', $gedcom, $this);
539    }
540
541    /**
542     * What is the most significant individual in this tree.
543     *
544     * @param UserInterface $user
545     * @param string        $xref
546     *
547     * @return Individual
548     */
549    public function significantIndividual(UserInterface $user, string $xref = ''): Individual
550    {
551        if ($xref === '') {
552            $individual = null;
553        } else {
554            $individual = Registry::individualFactory()->make($xref, $this);
555
556            if ($individual === null) {
557                $family = Registry::familyFactory()->make($xref, $this);
558
559                if ($family instanceof Family) {
560                    $individual = $family->spouses()->first() ?? $family->children()->first();
561                }
562            }
563        }
564
565        if ($individual === null && $this->getUserPreference($user, UserInterface::PREF_TREE_DEFAULT_XREF) !== '') {
566            $individual = Registry::individualFactory()->make($this->getUserPreference($user, UserInterface::PREF_TREE_DEFAULT_XREF), $this);
567        }
568
569        if ($individual === null && $this->getUserPreference($user, UserInterface::PREF_TREE_ACCOUNT_XREF) !== '') {
570            $individual = Registry::individualFactory()->make($this->getUserPreference($user, UserInterface::PREF_TREE_ACCOUNT_XREF), $this);
571        }
572
573        if ($individual === null && $this->getPreference('PEDIGREE_ROOT_ID') !== '') {
574            $individual = Registry::individualFactory()->make($this->getPreference('PEDIGREE_ROOT_ID'), $this);
575        }
576        if ($individual === null) {
577            $xref = DB::table('individuals')
578                ->where('i_file', '=', $this->id())
579                ->min('i_id');
580
581            if (is_string($xref)) {
582                $individual = Registry::individualFactory()->make($xref, $this);
583            }
584        }
585        if ($individual === null) {
586            // always return a record
587            $individual = Registry::individualFactory()->new('I', '0 @I@ INDI', null, $this);
588        }
589
590        return $individual;
591    }
592
593    /**
594     * Where do we store our media files.
595     *
596     * @param FilesystemOperator $data_filesystem
597     *
598     * @return FilesystemOperator
599     */
600    public function mediaFilesystem(FilesystemOperator $data_filesystem): FilesystemOperator
601    {
602        $media_dir = $this->getPreference('MEDIA_DIRECTORY');
603        $adapter   = new ChrootAdapter($data_filesystem, $media_dir);
604
605        return new Filesystem($adapter);
606    }
607}
608