xref: /webtrees/app/Services/TreeService.php (revision a67cd39f5bed0a01c3af3490de0599bfc69d5f12)
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 */
17declare(strict_types=1);
18
19namespace Fisharebest\Webtrees\Services;
20
21use Fisharebest\Webtrees\Auth;
22use Fisharebest\Webtrees\Functions\FunctionsImport;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Site;
25use Fisharebest\Webtrees\Tree;
26use Illuminate\Database\Capsule\Manager as DB;
27use Illuminate\Database\Query\Builder;
28use Illuminate\Database\Query\Expression;
29use Illuminate\Database\Query\JoinClause;
30use Illuminate\Support\Collection;
31use stdClass;
32
33use function app;
34
35/**
36 * Tree management and queries.
37 */
38class TreeService
39{
40    // The most likely surname tradition for a given language.
41    private const DEFAULT_SURNAME_TRADITIONS = [
42        'es'    => 'spanish',
43        'is'    => 'icelandic',
44        'lt'    => 'lithuanian',
45        'pl'    => 'polish',
46        'pt'    => 'portuguese',
47        'pt-BR' => 'portuguese',
48    ];
49
50    /**
51     * All the trees that the current user has permission to access.
52     *
53     * @return Collection
54     */
55    public function all(): Collection
56    {
57        return app('cache.array')->rememberForever(__CLASS__ . __METHOD__, static function (): Collection {
58            // All trees
59            $query = DB::table('gedcom')
60                ->leftJoin('gedcom_setting', static function (JoinClause $join): void {
61                    $join->on('gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
62                        ->where('gedcom_setting.setting_name', '=', 'title');
63                })
64                ->where('gedcom.gedcom_id', '>', 0)
65                ->select([
66                    'gedcom.gedcom_id AS tree_id',
67                    'gedcom.gedcom_name AS tree_name',
68                    'gedcom_setting.setting_value AS tree_title',
69                ])
70                ->orderBy('gedcom.sort_order')
71                ->orderBy('gedcom_setting.setting_value');
72
73            // Non-admins may not see all trees
74            if (!Auth::isAdmin()) {
75                $query
76                    ->join('gedcom_setting AS gs2', static function (JoinClause $join): void {
77                        $join->on('gs2.gedcom_id', '=', 'gedcom.gedcom_id')
78                            ->where('gs2.setting_name', '=', 'imported');
79                    })
80                    ->join('gedcom_setting AS gs3', static function (JoinClause $join): void {
81                        $join->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
82                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
83                    })
84                    ->leftJoin('user_gedcom_setting', static function (JoinClause $join): void {
85                        $join->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
86                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
87                            ->where('user_gedcom_setting.setting_name', '=', 'canedit');
88                    })
89                    ->where(static function (Builder $query): void {
90                        $query
91                            // Managers
92                            ->where('user_gedcom_setting.setting_value', '=', 'admin')
93                            // Members
94                            ->orWhere(static function (Builder $query): void {
95                                $query
96                                    ->where('gs2.setting_value', '=', '1')
97                                    ->where('gs3.setting_value', '=', '1')
98                                    ->where('user_gedcom_setting.setting_value', '<>', 'none');
99                            })
100                            // Public trees
101                            ->orWhere(static function (Builder $query): void {
102                                $query
103                                    ->where('gs2.setting_value', '=', '1')
104                                    ->where('gs3.setting_value', '<>', '1');
105                            });
106                    });
107            }
108
109            return $query
110                ->get()
111                ->mapWithKeys(static function (stdClass $row): array {
112                    return [$row->tree_id => Tree::rowMapper()($row)];
113                });
114        });
115    }
116
117    /**
118     * Find the tree with a specific name.
119     *
120     * @param string $name
121     *
122     * @return Tree|null
123     */
124    public function findByName($name): ?Tree
125    {
126        return $this->all()->first(static function (Tree $tree) use ($name): bool {
127            return $tree->name() === $name;
128        });
129    }
130
131    /**
132     * @param string $name
133     * @param string $title
134     *
135     * @return Tree
136     */
137    public function create(string $name, string $title): Tree
138    {
139        DB::table('gedcom')->insert([
140            'gedcom_name' => $name,
141        ]);
142
143        $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
144
145        $tree = new Tree($tree_id, $name, $title);
146
147        $tree->setPreference('imported', '1');
148        $tree->setPreference('title', $title);
149
150        // Set preferences from default tree
151        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
152            ['gedcom_id', 'setting_name', 'setting_value'],
153            static function (Builder $query) use ($tree_id): void {
154                $query
155                    ->select([new Expression($tree_id), 'setting_name', 'setting_value'])
156                    ->from('gedcom_setting')
157                    ->where('gedcom_id', '=', -1);
158            }
159        );
160
161        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
162            ['gedcom_id', 'tag_type', 'resn'],
163            static function (Builder $query) use ($tree_id): void {
164                $query
165                    ->select([new Expression($tree_id), 'tag_type', 'resn'])
166                    ->from('default_resn')
167                    ->where('gedcom_id', '=', -1);
168            }
169        );
170
171        // Gedcom and privacy settings
172        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
173        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
174        $tree->setPreference('LANGUAGE', WT_LOCALE); // Default to the current admin’s language
175        $tree->setPreference('SURNAME_TRADITION', self::DEFAULT_SURNAME_TRADITIONS[WT_LOCALE] ?? 'paternal');
176
177        // A tree needs at least one record.
178        $head = "0 HEAD\n1 SOUR webtrees\n2 DEST webtrees\n1 GEDC\n2 VERS 5.5.1\n2 FORM LINEAGE-LINKED\n1 CHAR UTF-8";
179        FunctionsImport::importRecord($head, $tree, true);
180
181        // I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname.
182        $name = I18N::translate('John /DOE/');
183        $note = I18N::translate('Edit this individual and replace their details with your own.');
184        $indi = "0 @X1@ INDI\n1 NAME " . $name . "\n1 SEX M\n1 BIRT\n2 DATE 01 JAN 1850\n2 NOTE " . $note;
185        FunctionsImport::importRecord($indi, $tree, true);
186
187        return $tree;
188    }
189
190    /**
191     * @param Tree $tree
192     */
193    public function delete(Tree $tree): void
194    {
195        // If this is the default tree, then unset it
196        if (Site::getPreference('DEFAULT_GEDCOM') === $tree->name()) {
197            Site::setPreference('DEFAULT_GEDCOM', '');
198        }
199
200        $tree->deleteGenealogyData(false);
201
202        DB::table('block_setting')
203            ->join('block', 'block.block_id', '=', 'block_setting.block_id')
204            ->where('gedcom_id', '=', $tree->id())
205            ->delete();
206        DB::table('block')->where('gedcom_id', '=', $tree->id())->delete();
207        DB::table('user_gedcom_setting')->where('gedcom_id', '=', $tree->id())->delete();
208        DB::table('gedcom_setting')->where('gedcom_id', '=', $tree->id())->delete();
209        DB::table('module_privacy')->where('gedcom_id', '=', $tree->id())->delete();
210        DB::table('hit_counter')->where('gedcom_id', '=', $tree->id())->delete();
211        DB::table('default_resn')->where('gedcom_id', '=', $tree->id())->delete();
212        DB::table('gedcom_chunk')->where('gedcom_id', '=', $tree->id())->delete();
213        DB::table('log')->where('gedcom_id', '=', $tree->id())->delete();
214        DB::table('gedcom')->where('gedcom_id', '=', $tree->id())->delete();
215    }
216
217    /**
218     * Generate a unique name for a new tree.
219     *
220     * @return string
221     */
222    public function uniqueTreeName(): string
223    {
224        $name   = 'tree';
225        $number = 1;
226
227        while ($this->findByName($name . $number) instanceof Tree) {
228            $number++;
229        }
230
231        return $name . $number;
232    }
233}
234