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