xref: /webtrees/app/Services/TreeService.php (revision 3340ecd27b8901a894bff51b7c40bfa2896a552b)
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\Services;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Contracts\UserInterface;
24use Fisharebest\Webtrees\Functions\FunctionsImport;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Site;
28use Fisharebest\Webtrees\Tree;
29use Illuminate\Database\Capsule\Manager as DB;
30use Illuminate\Database\Query\Builder;
31use Illuminate\Database\Query\Expression;
32use Illuminate\Database\Query\JoinClause;
33use Illuminate\Support\Collection;
34use Psr\Http\Message\StreamInterface;
35use RuntimeException;
36
37use function assert;
38use function strlen;
39use function substr;
40
41/**
42 * Tree management and queries.
43 */
44class TreeService
45{
46    // The most likely surname tradition for a given language.
47    private const DEFAULT_SURNAME_TRADITIONS = [
48        'es'    => 'spanish',
49        'is'    => 'icelandic',
50        'lt'    => 'lithuanian',
51        'pl'    => 'polish',
52        'pt'    => 'portuguese',
53        'pt-BR' => 'portuguese',
54    ];
55
56    /**
57     * All the trees that the current user has permission to access.
58     *
59     * @return Collection<Tree>
60     */
61    public function all(): Collection
62    {
63        return Registry::cache()->array()->remember('all-trees', static function (): Collection {
64            // All trees
65            $query = DB::table('gedcom')
66                ->leftJoin('gedcom_setting', static function (JoinClause $join): void {
67                    $join->on('gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
68                        ->where('gedcom_setting.setting_name', '=', 'title');
69                })
70                ->where('gedcom.gedcom_id', '>', 0)
71                ->select([
72                    'gedcom.gedcom_id AS tree_id',
73                    'gedcom.gedcom_name AS tree_name',
74                    'gedcom_setting.setting_value AS tree_title',
75                ])
76                ->orderBy('gedcom.sort_order')
77                ->orderBy('gedcom_setting.setting_value');
78
79            // Non-admins may not see all trees
80            if (!Auth::isAdmin()) {
81                $query
82                    ->join('gedcom_setting AS gs2', static function (JoinClause $join): void {
83                        $join
84                            ->on('gs2.gedcom_id', '=', 'gedcom.gedcom_id')
85                            ->where('gs2.setting_name', '=', 'imported');
86                    })
87                    ->join('gedcom_setting AS gs3', static function (JoinClause $join): void {
88                        $join
89                            ->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
90                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
91                    })
92                    ->leftJoin('user_gedcom_setting', static function (JoinClause $join): void {
93                        $join
94                            ->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
95                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
96                            ->where('user_gedcom_setting.setting_name', '=', UserInterface::PREF_TREE_ROLE);
97                    })
98                    ->where(static function (Builder $query): void {
99                        $query
100                            // Managers
101                            ->where('user_gedcom_setting.setting_value', '=', UserInterface::ROLE_MANAGER)
102                            // Members
103                            ->orWhere(static function (Builder $query): void {
104                                $query
105                                    ->where('gs2.setting_value', '=', '1')
106                                    ->where('gs3.setting_value', '=', '1')
107                                    ->where('user_gedcom_setting.setting_value', '<>', UserInterface::ROLE_VISITOR);
108                            })
109                            // Public trees
110                            ->orWhere(static function (Builder $query): void {
111                                $query
112                                    ->where('gs2.setting_value', '=', '1')
113                                    ->where('gs3.setting_value', '<>', '1');
114                            });
115                    });
116            }
117
118            return $query
119                ->get()
120                ->mapWithKeys(static function (object $row): array {
121                    return [$row->tree_name => Tree::rowMapper()($row)];
122                });
123        });
124    }
125
126    /**
127     * Find a tree by its ID.
128     *
129     * @param int $id
130     *
131     * @return Tree
132     */
133    public function find(int $id): Tree
134    {
135        $tree = $this->all()->first(static function (Tree $tree) use ($id): bool {
136            return $tree->id() === $id;
137        });
138
139        assert($tree instanceof Tree, new RuntimeException());
140
141        return $tree;
142    }
143
144    /**
145     * All trees, name => title
146     *
147     * @return array<string>
148     */
149    public function titles(): array
150    {
151        return $this->all()->map(static function (Tree $tree): string {
152            return $tree->title();
153        })->all();
154    }
155
156    /**
157     * @param string $name
158     * @param string $title
159     *
160     * @return Tree
161     */
162    public function create(string $name, string $title): Tree
163    {
164        DB::table('gedcom')->insert([
165            'gedcom_name' => $name,
166        ]);
167
168        $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
169
170        $tree = new Tree($tree_id, $name, $title);
171
172        $tree->setPreference('imported', '1');
173        $tree->setPreference('title', $title);
174
175        // Set preferences from default tree
176        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
177            ['gedcom_id', 'setting_name', 'setting_value'],
178            static function (Builder $query) use ($tree_id): void {
179                $query
180                    ->select([new Expression($tree_id), 'setting_name', 'setting_value'])
181                    ->from('gedcom_setting')
182                    ->where('gedcom_id', '=', -1);
183            }
184        );
185
186        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
187            ['gedcom_id', 'tag_type', 'resn'],
188            static function (Builder $query) use ($tree_id): void {
189                $query
190                    ->select([new Expression($tree_id), 'tag_type', 'resn'])
191                    ->from('default_resn')
192                    ->where('gedcom_id', '=', -1);
193            }
194        );
195
196        // Gedcom and privacy settings
197        $tree->setPreference('REQUIRE_AUTHENTICATION', '');
198        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
199        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
200        $tree->setPreference('LANGUAGE', I18N::languageTag()); // Default to the current admin’s language
201        $tree->setPreference('SURNAME_TRADITION', self::DEFAULT_SURNAME_TRADITIONS[I18N::languageTag()] ?? 'paternal');
202
203        // A tree needs at least one record.
204        $head = "0 HEAD\n1 SOUR webtrees\n2 DEST webtrees\n1 GEDC\n2 VERS 5.5.1\n2 FORM LINEAGE-LINKED\n1 CHAR UTF-8";
205        FunctionsImport::importRecord($head, $tree, true);
206
207        // I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname.
208        $name = I18N::translate('John /DOE/');
209        $note = I18N::translate('Edit this individual and replace their details with your own.');
210        $indi = "0 @X1@ INDI\n1 NAME " . $name . "\n1 SEX M\n1 BIRT\n2 DATE 01 JAN 1850\n2 NOTE " . $note;
211        FunctionsImport::importRecord($indi, $tree, true);
212
213        return $tree;
214    }
215
216    /**
217     * Import data from a gedcom file into this tree.
218     *
219     * @param Tree            $tree
220     * @param StreamInterface $stream   The GEDCOM file.
221     * @param string          $filename The preferred filename, for export/download.
222     *
223     * @return void
224     */
225    public function importGedcomFile(Tree $tree, StreamInterface $stream, string $filename): void
226    {
227        // Read the file in blocks of roughly 64K. Ensure that each block
228        // contains complete gedcom records. This will ensure we don’t split
229        // multi-byte characters, as well as simplifying the code to import
230        // each block.
231
232        $file_data = '';
233
234        $tree->setPreference('gedcom_filename', $filename);
235        $tree->setPreference('imported', '0');
236
237        DB::table('gedcom_chunk')->where('gedcom_id', '=', $tree->id())->delete();
238
239        while (!$stream->eof()) {
240            $file_data .= $stream->read(65536);
241            // There is no strrpos() function that searches for substrings :-(
242            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
243                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
244                    // We’ve found the last record boundary in this chunk of data
245                    break;
246                }
247            }
248            if ($pos) {
249                DB::table('gedcom_chunk')->insert([
250                    'gedcom_id'  => $tree->id(),
251                    'chunk_data' => substr($file_data, 0, $pos),
252                ]);
253
254                $file_data = substr($file_data, $pos);
255            }
256        }
257        DB::table('gedcom_chunk')->insert([
258            'gedcom_id'  => $tree->id(),
259            'chunk_data' => $file_data,
260        ]);
261
262        $stream->close();
263    }
264
265    /**
266     * @param Tree $tree
267     */
268    public function delete(Tree $tree): void
269    {
270        // If this is the default tree, then unset it
271        if (Site::getPreference('DEFAULT_GEDCOM') === $tree->name()) {
272            Site::setPreference('DEFAULT_GEDCOM', '');
273        }
274
275        DB::table('gedcom_chunk')->where('gedcom_id', '=', $tree->id())->delete();
276
277        $this->deleteGenealogyData($tree, false);
278
279        DB::table('block_setting')
280            ->join('block', 'block.block_id', '=', 'block_setting.block_id')
281            ->where('gedcom_id', '=', $tree->id())
282            ->delete();
283        DB::table('block')->where('gedcom_id', '=', $tree->id())->delete();
284        DB::table('user_gedcom_setting')->where('gedcom_id', '=', $tree->id())->delete();
285        DB::table('gedcom_setting')->where('gedcom_id', '=', $tree->id())->delete();
286        DB::table('module_privacy')->where('gedcom_id', '=', $tree->id())->delete();
287        DB::table('hit_counter')->where('gedcom_id', '=', $tree->id())->delete();
288        DB::table('default_resn')->where('gedcom_id', '=', $tree->id())->delete();
289        DB::table('gedcom_chunk')->where('gedcom_id', '=', $tree->id())->delete();
290        DB::table('log')->where('gedcom_id', '=', $tree->id())->delete();
291        DB::table('gedcom')->where('gedcom_id', '=', $tree->id())->delete();
292    }
293
294    /**
295     * Delete all the genealogy data from a tree - in preparation for importing
296     * new data. Optionally retain the media data, for when the user has been
297     * editing their data offline using an application which deletes (or does not
298     * support) media data.
299     *
300     * @param Tree $tree
301     * @param bool $keep_media
302     *
303     * @return void
304     */
305    public function deleteGenealogyData(Tree $tree, bool $keep_media): void
306    {
307        DB::table('individuals')->where('i_file', '=', $tree->id())->delete();
308        DB::table('families')->where('f_file', '=', $tree->id())->delete();
309        DB::table('sources')->where('s_file', '=', $tree->id())->delete();
310        DB::table('other')->where('o_file', '=', $tree->id())->delete();
311        DB::table('places')->where('p_file', '=', $tree->id())->delete();
312        DB::table('placelinks')->where('pl_file', '=', $tree->id())->delete();
313        DB::table('name')->where('n_file', '=', $tree->id())->delete();
314        DB::table('dates')->where('d_file', '=', $tree->id())->delete();
315        DB::table('change')->where('gedcom_id', '=', $tree->id())->delete();
316
317        if ($keep_media) {
318            DB::table('link')->where('l_file', '=', $tree->id())
319                ->where('l_type', '<>', 'OBJE')
320                ->delete();
321        } else {
322            DB::table('link')->where('l_file', '=', $tree->id())->delete();
323            DB::table('media_file')->where('m_file', '=', $tree->id())->delete();
324            DB::table('media')->where('m_file', '=', $tree->id())->delete();
325        }
326    }
327
328    /**
329     * Generate a unique name for a new tree.
330     *
331     * @return string
332     */
333    public function uniqueTreeName(): string
334    {
335        $name   = 'tree';
336        $number = 1;
337
338        while ($this->all()->get($name . $number) instanceof Tree) {
339            $number++;
340        }
341
342        return $name . $number;
343    }
344}
345