xref: /webtrees/app/Services/TreeService.php (revision f70bcff589628705e50ed72a6fc6cbad68558677)
15afbc57aSGreg Roach<?php
25afbc57aSGreg Roach
35afbc57aSGreg Roach/**
45afbc57aSGreg Roach * webtrees: online genealogy
51fe542e9SGreg Roach * Copyright (C) 2021 webtrees development team
65afbc57aSGreg Roach * This program is free software: you can redistribute it and/or modify
75afbc57aSGreg Roach * it under the terms of the GNU General Public License as published by
85afbc57aSGreg Roach * the Free Software Foundation, either version 3 of the License, or
95afbc57aSGreg Roach * (at your option) any later version.
105afbc57aSGreg Roach * This program is distributed in the hope that it will be useful,
115afbc57aSGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
125afbc57aSGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
135afbc57aSGreg Roach * GNU General Public License for more details.
145afbc57aSGreg Roach * You should have received a copy of the GNU General Public License
1589f7189bSGreg Roach * along with this program. If not, see <https://www.gnu.org/licenses/>.
165afbc57aSGreg Roach */
17fcfa147eSGreg Roach
185afbc57aSGreg Roachdeclare(strict_types=1);
195afbc57aSGreg Roach
205afbc57aSGreg Roachnamespace Fisharebest\Webtrees\Services;
215afbc57aSGreg Roach
225afbc57aSGreg Roachuse Fisharebest\Webtrees\Auth;
231fe542e9SGreg Roachuse Fisharebest\Webtrees\Contracts\UserInterface;
245afbc57aSGreg Roachuse Fisharebest\Webtrees\Functions\FunctionsImport;
255afbc57aSGreg Roachuse Fisharebest\Webtrees\I18N;
269d173e09SGreg Roachuse Fisharebest\Webtrees\Registry;
275afbc57aSGreg Roachuse Fisharebest\Webtrees\Site;
285afbc57aSGreg Roachuse Fisharebest\Webtrees\Tree;
295afbc57aSGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
305afbc57aSGreg Roachuse Illuminate\Database\Query\Builder;
315afbc57aSGreg Roachuse Illuminate\Database\Query\Expression;
325afbc57aSGreg Roachuse Illuminate\Database\Query\JoinClause;
335afbc57aSGreg Roachuse Illuminate\Support\Collection;
345cd281f4SGreg Roachuse Psr\Http\Message\StreamInterface;
351e653452SGreg Roachuse RuntimeException;
365afbc57aSGreg Roach
3790a2f718SGreg Roachuse function assert;
385cd281f4SGreg Roachuse function strlen;
395cd281f4SGreg Roachuse function substr;
405afbc57aSGreg Roach
415afbc57aSGreg Roach/**
425afbc57aSGreg Roach * Tree management and queries.
435afbc57aSGreg Roach */
445afbc57aSGreg Roachclass TreeService
455afbc57aSGreg Roach{
465afbc57aSGreg Roach    // The most likely surname tradition for a given language.
475afbc57aSGreg Roach    private const DEFAULT_SURNAME_TRADITIONS = [
485afbc57aSGreg Roach        'es'    => 'spanish',
495afbc57aSGreg Roach        'is'    => 'icelandic',
505afbc57aSGreg Roach        'lt'    => 'lithuanian',
515afbc57aSGreg Roach        'pl'    => 'polish',
525afbc57aSGreg Roach        'pt'    => 'portuguese',
535afbc57aSGreg Roach        'pt-BR' => 'portuguese',
545afbc57aSGreg Roach    ];
555afbc57aSGreg Roach
565afbc57aSGreg Roach    /**
575afbc57aSGreg Roach     * All the trees that the current user has permission to access.
585afbc57aSGreg Roach     *
59b5c8fd7eSGreg Roach     * @return Collection<Tree>
605afbc57aSGreg Roach     */
615afbc57aSGreg Roach    public function all(): Collection
625afbc57aSGreg Roach    {
636b9cb339SGreg Roach        return Registry::cache()->array()->remember('all-trees', static function (): Collection {
645afbc57aSGreg Roach            // All trees
655afbc57aSGreg Roach            $query = DB::table('gedcom')
665afbc57aSGreg Roach                ->leftJoin('gedcom_setting', static function (JoinClause $join): void {
675afbc57aSGreg Roach                    $join->on('gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
685afbc57aSGreg Roach                        ->where('gedcom_setting.setting_name', '=', 'title');
695afbc57aSGreg Roach                })
705afbc57aSGreg Roach                ->where('gedcom.gedcom_id', '>', 0)
715afbc57aSGreg Roach                ->select([
725afbc57aSGreg Roach                    'gedcom.gedcom_id AS tree_id',
735afbc57aSGreg Roach                    'gedcom.gedcom_name AS tree_name',
745afbc57aSGreg Roach                    'gedcom_setting.setting_value AS tree_title',
755afbc57aSGreg Roach                ])
765afbc57aSGreg Roach                ->orderBy('gedcom.sort_order')
775afbc57aSGreg Roach                ->orderBy('gedcom_setting.setting_value');
785afbc57aSGreg Roach
795afbc57aSGreg Roach            // Non-admins may not see all trees
805afbc57aSGreg Roach            if (!Auth::isAdmin()) {
815afbc57aSGreg Roach                $query
825afbc57aSGreg Roach                    ->join('gedcom_setting AS gs2', static function (JoinClause $join): void {
836b736a8bSGreg Roach                        $join
846b736a8bSGreg Roach                            ->on('gs2.gedcom_id', '=', 'gedcom.gedcom_id')
85cc194e3fSGreg Roach                            ->where('gs2.setting_name', '=', 'imported');
865afbc57aSGreg Roach                    })
875afbc57aSGreg Roach                    ->join('gedcom_setting AS gs3', static function (JoinClause $join): void {
886b736a8bSGreg Roach                        $join
896b736a8bSGreg Roach                            ->on('gs3.gedcom_id', '=', 'gedcom.gedcom_id')
90cc194e3fSGreg Roach                            ->where('gs3.setting_name', '=', 'REQUIRE_AUTHENTICATION');
915afbc57aSGreg Roach                    })
925afbc57aSGreg Roach                    ->leftJoin('user_gedcom_setting', static function (JoinClause $join): void {
936b736a8bSGreg Roach                        $join
946b736a8bSGreg Roach                            ->on('user_gedcom_setting.gedcom_id', '=', 'gedcom.gedcom_id')
95cc194e3fSGreg Roach                            ->where('user_gedcom_setting.user_id', '=', Auth::id())
96cc194e3fSGreg Roach                            ->where('user_gedcom_setting.setting_name', '=', UserInterface::PREF_TREE_ROLE);
975afbc57aSGreg Roach                    })
985afbc57aSGreg Roach                    ->where(static function (Builder $query): void {
995afbc57aSGreg Roach                        $query
1005afbc57aSGreg Roach                            // Managers
1011fe542e9SGreg Roach                            ->where('user_gedcom_setting.setting_value', '=', UserInterface::ROLE_MANAGER)
1025afbc57aSGreg Roach                            // Members
1035afbc57aSGreg Roach                            ->orWhere(static function (Builder $query): void {
1045afbc57aSGreg Roach                                $query
1055afbc57aSGreg Roach                                    ->where('gs2.setting_value', '=', '1')
1065afbc57aSGreg Roach                                    ->where('gs3.setting_value', '=', '1')
1071fe542e9SGreg Roach                                    ->where('user_gedcom_setting.setting_value', '<>', UserInterface::ROLE_VISITOR);
1085afbc57aSGreg Roach                            })
1095afbc57aSGreg Roach                            // Public trees
1105afbc57aSGreg Roach                            ->orWhere(static function (Builder $query): void {
1115afbc57aSGreg Roach                                $query
1125afbc57aSGreg Roach                                    ->where('gs2.setting_value', '=', '1')
1135afbc57aSGreg Roach                                    ->where('gs3.setting_value', '<>', '1');
1145afbc57aSGreg Roach                            });
1155afbc57aSGreg Roach                    });
1165afbc57aSGreg Roach            }
1175afbc57aSGreg Roach
1185afbc57aSGreg Roach            return $query
1195afbc57aSGreg Roach                ->get()
120*f70bcff5SGreg Roach                ->mapWithKeys(static function (object $row): array {
1211e653452SGreg Roach                    return [$row->tree_name => Tree::rowMapper()($row)];
1225afbc57aSGreg Roach                });
1235afbc57aSGreg Roach        });
1245afbc57aSGreg Roach    }
1255afbc57aSGreg Roach
1265afbc57aSGreg Roach    /**
1271e653452SGreg Roach     * Find a tree by its ID.
1285afbc57aSGreg Roach     *
1291e653452SGreg Roach     * @param int $id
1305afbc57aSGreg Roach     *
1311e653452SGreg Roach     * @return Tree
1325afbc57aSGreg Roach     */
1331e653452SGreg Roach    public function find(int $id): Tree
1345afbc57aSGreg Roach    {
1351e653452SGreg Roach        $tree = $this->all()->first(static function (Tree $tree) use ($id): bool {
1361e653452SGreg Roach            return $tree->id() === $id;
1375afbc57aSGreg Roach        });
1381e653452SGreg Roach
1391e653452SGreg Roach        assert($tree instanceof Tree, new RuntimeException());
1401e653452SGreg Roach
1411e653452SGreg Roach        return $tree;
1421e653452SGreg Roach    }
1431e653452SGreg Roach
1441e653452SGreg Roach    /**
1451e653452SGreg Roach     * All trees, name => title
1461e653452SGreg Roach     *
14724f2a3afSGreg Roach     * @return array<string>
1481e653452SGreg Roach     */
1491e653452SGreg Roach    public function titles(): array
1501e653452SGreg Roach    {
1511e653452SGreg Roach        return $this->all()->map(static function (Tree $tree): string {
1521e653452SGreg Roach            return $tree->title();
1531e653452SGreg Roach        })->all();
1545afbc57aSGreg Roach    }
1555afbc57aSGreg Roach
1565afbc57aSGreg Roach    /**
1575afbc57aSGreg Roach     * @param string $name
1585afbc57aSGreg Roach     * @param string $title
1595afbc57aSGreg Roach     *
1605afbc57aSGreg Roach     * @return Tree
1615afbc57aSGreg Roach     */
1625afbc57aSGreg Roach    public function create(string $name, string $title): Tree
1635afbc57aSGreg Roach    {
1645afbc57aSGreg Roach        DB::table('gedcom')->insert([
1655afbc57aSGreg Roach            'gedcom_name' => $name,
1665afbc57aSGreg Roach        ]);
1675afbc57aSGreg Roach
1685afbc57aSGreg Roach        $tree_id = (int) DB::connection()->getPdo()->lastInsertId();
1695afbc57aSGreg Roach
1705afbc57aSGreg Roach        $tree = new Tree($tree_id, $name, $title);
1715afbc57aSGreg Roach
1725afbc57aSGreg Roach        $tree->setPreference('imported', '1');
1735afbc57aSGreg Roach        $tree->setPreference('title', $title);
1745afbc57aSGreg Roach
1755afbc57aSGreg Roach        // Set preferences from default tree
1765afbc57aSGreg Roach        (new Builder(DB::connection()))->from('gedcom_setting')->insertUsing(
1775afbc57aSGreg Roach            ['gedcom_id', 'setting_name', 'setting_value'],
1785afbc57aSGreg Roach            static function (Builder $query) use ($tree_id): void {
1795afbc57aSGreg Roach                $query
1805afbc57aSGreg Roach                    ->select([new Expression($tree_id), 'setting_name', 'setting_value'])
1815afbc57aSGreg Roach                    ->from('gedcom_setting')
1825afbc57aSGreg Roach                    ->where('gedcom_id', '=', -1);
1835afbc57aSGreg Roach            }
1845afbc57aSGreg Roach        );
1855afbc57aSGreg Roach
1865afbc57aSGreg Roach        (new Builder(DB::connection()))->from('default_resn')->insertUsing(
1875afbc57aSGreg Roach            ['gedcom_id', 'tag_type', 'resn'],
1885afbc57aSGreg Roach            static function (Builder $query) use ($tree_id): void {
1895afbc57aSGreg Roach                $query
1905afbc57aSGreg Roach                    ->select([new Expression($tree_id), 'tag_type', 'resn'])
1915afbc57aSGreg Roach                    ->from('default_resn')
1925afbc57aSGreg Roach                    ->where('gedcom_id', '=', -1);
1935afbc57aSGreg Roach            }
1945afbc57aSGreg Roach        );
1955afbc57aSGreg Roach
1965afbc57aSGreg Roach        // Gedcom and privacy settings
1976b736a8bSGreg Roach        $tree->setPreference('REQUIRE_AUTHENTICATION', '');
1985afbc57aSGreg Roach        $tree->setPreference('CONTACT_USER_ID', (string) Auth::id());
1995afbc57aSGreg Roach        $tree->setPreference('WEBMASTER_USER_ID', (string) Auth::id());
20065cf5706SGreg Roach        $tree->setPreference('LANGUAGE', I18N::languageTag()); // Default to the current admin’s language
20165cf5706SGreg Roach        $tree->setPreference('SURNAME_TRADITION', self::DEFAULT_SURNAME_TRADITIONS[I18N::languageTag()] ?? 'paternal');
2025afbc57aSGreg Roach
2035afbc57aSGreg Roach        // A tree needs at least one record.
2049b5c9597SGreg Roach        $head = "0 HEAD\n1 SOUR webtrees\n2 DEST webtrees\n1 GEDC\n2 VERS 5.5.1\n2 FORM LINEAGE-LINKED\n1 CHAR UTF-8";
2059b5c9597SGreg Roach        FunctionsImport::importRecord($head, $tree, true);
2065afbc57aSGreg Roach
2075afbc57aSGreg Roach        // I18N: This should be a common/default/placeholder name of an individual. Put slashes around the surname.
2085afbc57aSGreg Roach        $name = I18N::translate('John /DOE/');
2095afbc57aSGreg Roach        $note = I18N::translate('Edit this individual and replace their details with your own.');
2109b5c9597SGreg Roach        $indi = "0 @X1@ INDI\n1 NAME " . $name . "\n1 SEX M\n1 BIRT\n2 DATE 01 JAN 1850\n2 NOTE " . $note;
2119b5c9597SGreg Roach        FunctionsImport::importRecord($indi, $tree, true);
2125afbc57aSGreg Roach
2135afbc57aSGreg Roach        return $tree;
2145afbc57aSGreg Roach    }
2155afbc57aSGreg Roach
2165afbc57aSGreg Roach    /**
2175cd281f4SGreg Roach     * Import data from a gedcom file into this tree.
2185cd281f4SGreg Roach     *
2195cd281f4SGreg Roach     * @param Tree            $tree
2205cd281f4SGreg Roach     * @param StreamInterface $stream   The GEDCOM file.
2215cd281f4SGreg Roach     * @param string          $filename The preferred filename, for export/download.
2225cd281f4SGreg Roach     *
2235cd281f4SGreg Roach     * @return void
2245cd281f4SGreg Roach     */
2255cd281f4SGreg Roach    public function importGedcomFile(Tree $tree, StreamInterface $stream, string $filename): void
2265cd281f4SGreg Roach    {
2275cd281f4SGreg Roach        // Read the file in blocks of roughly 64K. Ensure that each block
2285cd281f4SGreg Roach        // contains complete gedcom records. This will ensure we don’t split
2295cd281f4SGreg Roach        // multi-byte characters, as well as simplifying the code to import
2305cd281f4SGreg Roach        // each block.
2315cd281f4SGreg Roach
2325cd281f4SGreg Roach        $file_data = '';
2335cd281f4SGreg Roach
2345cd281f4SGreg Roach        $tree->setPreference('gedcom_filename', $filename);
2355cd281f4SGreg Roach        $tree->setPreference('imported', '0');
2365cd281f4SGreg Roach
2375cd281f4SGreg Roach        DB::table('gedcom_chunk')->where('gedcom_id', '=', $tree->id())->delete();
2385cd281f4SGreg Roach
2395cd281f4SGreg Roach        while (!$stream->eof()) {
2405cd281f4SGreg Roach            $file_data .= $stream->read(65536);
2415cd281f4SGreg Roach            // There is no strrpos() function that searches for substrings :-(
2425cd281f4SGreg Roach            for ($pos = strlen($file_data) - 1; $pos > 0; --$pos) {
2435cd281f4SGreg Roach                if ($file_data[$pos] === '0' && ($file_data[$pos - 1] === "\n" || $file_data[$pos - 1] === "\r")) {
2445cd281f4SGreg Roach                    // We’ve found the last record boundary in this chunk of data
2455cd281f4SGreg Roach                    break;
2465cd281f4SGreg Roach                }
2475cd281f4SGreg Roach            }
2485cd281f4SGreg Roach            if ($pos) {
2495cd281f4SGreg Roach                DB::table('gedcom_chunk')->insert([
2505cd281f4SGreg Roach                    'gedcom_id'  => $tree->id(),
2515cd281f4SGreg Roach                    'chunk_data' => substr($file_data, 0, $pos),
2525cd281f4SGreg Roach                ]);
2535cd281f4SGreg Roach
2545cd281f4SGreg Roach                $file_data = substr($file_data, $pos);
2555cd281f4SGreg Roach            }
2565cd281f4SGreg Roach        }
2575cd281f4SGreg Roach        DB::table('gedcom_chunk')->insert([
2585cd281f4SGreg Roach            'gedcom_id'  => $tree->id(),
2595cd281f4SGreg Roach            'chunk_data' => $file_data,
2605cd281f4SGreg Roach        ]);
2615cd281f4SGreg Roach
2625cd281f4SGreg Roach        $stream->close();
2635cd281f4SGreg Roach    }
2645cd281f4SGreg Roach
2655cd281f4SGreg Roach    /**
2665afbc57aSGreg Roach     * @param Tree $tree
2675afbc57aSGreg Roach     */
2685afbc57aSGreg Roach    public function delete(Tree $tree): void
2695afbc57aSGreg Roach    {
2705afbc57aSGreg Roach        // If this is the default tree, then unset it
2715afbc57aSGreg Roach        if (Site::getPreference('DEFAULT_GEDCOM') === $tree->name()) {
2725afbc57aSGreg Roach            Site::setPreference('DEFAULT_GEDCOM', '');
2735afbc57aSGreg Roach        }
2745afbc57aSGreg Roach
2755cd281f4SGreg Roach        DB::table('gedcom_chunk')->where('gedcom_id', '=', $tree->id())->delete();
2765cd281f4SGreg Roach
2775cd281f4SGreg Roach        $this->deleteGenealogyData($tree, false);
2785afbc57aSGreg Roach
2795afbc57aSGreg Roach        DB::table('block_setting')
2805afbc57aSGreg Roach            ->join('block', 'block.block_id', '=', 'block_setting.block_id')
2815afbc57aSGreg Roach            ->where('gedcom_id', '=', $tree->id())
2825afbc57aSGreg Roach            ->delete();
2835afbc57aSGreg Roach        DB::table('block')->where('gedcom_id', '=', $tree->id())->delete();
2845afbc57aSGreg Roach        DB::table('user_gedcom_setting')->where('gedcom_id', '=', $tree->id())->delete();
2855afbc57aSGreg Roach        DB::table('gedcom_setting')->where('gedcom_id', '=', $tree->id())->delete();
2865afbc57aSGreg Roach        DB::table('module_privacy')->where('gedcom_id', '=', $tree->id())->delete();
2875afbc57aSGreg Roach        DB::table('hit_counter')->where('gedcom_id', '=', $tree->id())->delete();
2885afbc57aSGreg Roach        DB::table('default_resn')->where('gedcom_id', '=', $tree->id())->delete();
2895afbc57aSGreg Roach        DB::table('gedcom_chunk')->where('gedcom_id', '=', $tree->id())->delete();
2905afbc57aSGreg Roach        DB::table('log')->where('gedcom_id', '=', $tree->id())->delete();
2915afbc57aSGreg Roach        DB::table('gedcom')->where('gedcom_id', '=', $tree->id())->delete();
2925afbc57aSGreg Roach    }
2935afbc57aSGreg Roach
2945afbc57aSGreg Roach    /**
2955cd281f4SGreg Roach     * Delete all the genealogy data from a tree - in preparation for importing
2965cd281f4SGreg Roach     * new data. Optionally retain the media data, for when the user has been
2975cd281f4SGreg Roach     * editing their data offline using an application which deletes (or does not
2985cd281f4SGreg Roach     * support) media data.
2995cd281f4SGreg Roach     *
3005cd281f4SGreg Roach     * @param Tree $tree
3015cd281f4SGreg Roach     * @param bool $keep_media
3025cd281f4SGreg Roach     *
3035cd281f4SGreg Roach     * @return void
3045cd281f4SGreg Roach     */
3055cd281f4SGreg Roach    public function deleteGenealogyData(Tree $tree, bool $keep_media): void
3065cd281f4SGreg Roach    {
3075cd281f4SGreg Roach        DB::table('individuals')->where('i_file', '=', $tree->id())->delete();
3085cd281f4SGreg Roach        DB::table('families')->where('f_file', '=', $tree->id())->delete();
3095cd281f4SGreg Roach        DB::table('sources')->where('s_file', '=', $tree->id())->delete();
3105cd281f4SGreg Roach        DB::table('other')->where('o_file', '=', $tree->id())->delete();
3115cd281f4SGreg Roach        DB::table('places')->where('p_file', '=', $tree->id())->delete();
3125cd281f4SGreg Roach        DB::table('placelinks')->where('pl_file', '=', $tree->id())->delete();
3135cd281f4SGreg Roach        DB::table('name')->where('n_file', '=', $tree->id())->delete();
3145cd281f4SGreg Roach        DB::table('dates')->where('d_file', '=', $tree->id())->delete();
3155cd281f4SGreg Roach        DB::table('change')->where('gedcom_id', '=', $tree->id())->delete();
3165cd281f4SGreg Roach
3175cd281f4SGreg Roach        if ($keep_media) {
3185cd281f4SGreg Roach            DB::table('link')->where('l_file', '=', $tree->id())
3195cd281f4SGreg Roach                ->where('l_type', '<>', 'OBJE')
3205cd281f4SGreg Roach                ->delete();
3215cd281f4SGreg Roach        } else {
3225cd281f4SGreg Roach            DB::table('link')->where('l_file', '=', $tree->id())->delete();
3235cd281f4SGreg Roach            DB::table('media_file')->where('m_file', '=', $tree->id())->delete();
3245cd281f4SGreg Roach            DB::table('media')->where('m_file', '=', $tree->id())->delete();
3255cd281f4SGreg Roach        }
3265cd281f4SGreg Roach    }
3275cd281f4SGreg Roach
3285cd281f4SGreg Roach    /**
3295afbc57aSGreg Roach     * Generate a unique name for a new tree.
3305afbc57aSGreg Roach     *
3315afbc57aSGreg Roach     * @return string
3325afbc57aSGreg Roach     */
3335afbc57aSGreg Roach    public function uniqueTreeName(): string
3345afbc57aSGreg Roach    {
3355afbc57aSGreg Roach        $name   = 'tree';
3365afbc57aSGreg Roach        $number = 1;
3375afbc57aSGreg Roach
3381e653452SGreg Roach        while ($this->all()->get($name . $number) instanceof Tree) {
3395afbc57aSGreg Roach            $number++;
3405afbc57aSGreg Roach        }
3415afbc57aSGreg Roach
3425afbc57aSGreg Roach        return $name . $number;
3435afbc57aSGreg Roach    }
3445afbc57aSGreg Roach}
345