xref: /webtrees/app/Services/AdminService.php (revision efd4768b0eab1f325771cdbc6181ff84f85f2149)
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\Registry;
23use Fisharebest\Webtrees\Family;
24use Fisharebest\Webtrees\Gedcom;
25use Fisharebest\Webtrees\GedcomRecord;
26use Fisharebest\Webtrees\Header;
27use Fisharebest\Webtrees\I18N;
28use Fisharebest\Webtrees\Individual;
29use Fisharebest\Webtrees\Media;
30use Fisharebest\Webtrees\Site;
31use Fisharebest\Webtrees\Source;
32use Fisharebest\Webtrees\Tree;
33use Illuminate\Database\Capsule\Manager as DB;
34use Illuminate\Database\Query\Expression;
35use Illuminate\Database\Query\JoinClause;
36use Illuminate\Support\Collection;
37use League\Flysystem\FilesystemException;
38use League\Flysystem\FilesystemOperator;
39use League\Flysystem\StorageAttributes;
40
41use function array_map;
42use function explode;
43use function fclose;
44use function fread;
45use function preg_match;
46
47/**
48 * Utilities for the control panel.
49 */
50class AdminService
51{
52    // Show a reduced page when there are more than a certain number of trees
53    private const MULTIPLE_TREE_THRESHOLD = '500';
54
55    /**
56     * Count of XREFs used by two trees at the same time.
57     *
58     * @param Tree $tree1
59     * @param Tree $tree2
60     *
61     * @return int
62     */
63    public function countCommonXrefs(Tree $tree1, Tree $tree2): int
64    {
65        $subquery1 = DB::table('individuals')
66            ->where('i_file', '=', $tree1->id())
67            ->select(['i_id AS xref'])
68            ->union(DB::table('families')
69                ->where('f_file', '=', $tree1->id())
70                ->select(['f_id AS xref']))
71            ->union(DB::table('sources')
72                ->where('s_file', '=', $tree1->id())
73                ->select(['s_id AS xref']))
74            ->union(DB::table('media')
75                ->where('m_file', '=', $tree1->id())
76                ->select(['m_id AS xref']))
77            ->union(DB::table('other')
78                ->where('o_file', '=', $tree1->id())
79                ->whereNotIn('o_type', [Header::RECORD_TYPE, 'TRLR'])
80                ->select(['o_id AS xref']));
81
82        $subquery2 = DB::table('change')
83            ->where('gedcom_id', '=', $tree2->id())
84            ->select(['xref AS other_xref'])
85            ->union(DB::table('individuals')
86                ->where('i_file', '=', $tree2->id())
87                ->select(['i_id AS xref']))
88            ->union(DB::table('families')
89                ->where('f_file', '=', $tree2->id())
90                ->select(['f_id AS xref']))
91            ->union(DB::table('sources')
92                ->where('s_file', '=', $tree2->id())
93                ->select(['s_id AS xref']))
94            ->union(DB::table('media')
95                ->where('m_file', '=', $tree2->id())
96                ->select(['m_id AS xref']))
97            ->union(DB::table('other')
98                ->where('o_file', '=', $tree2->id())
99                ->whereNotIn('o_type', [Header::RECORD_TYPE, 'TRLR'])
100                ->select(['o_id AS xref']));
101
102        return DB::table(new Expression('(' . $subquery1->toSql() . ') AS sub1'))
103            ->mergeBindings($subquery1)
104            ->joinSub($subquery2, 'sub2', 'other_xref', '=', 'xref')
105            ->count();
106    }
107
108    /**
109     * @param Tree $tree
110     *
111     * @return array<string,array<int,array<int,GedcomRecord>>>
112     */
113    public function duplicateRecords(Tree $tree): array
114    {
115        // We can't do any reasonable checks using MySQL.
116        // Will need to wait for a "repositories" table.
117        $repositories = [];
118
119        $sources = DB::table('sources')
120            ->where('s_file', '=', $tree->id())
121            ->groupBy(['s_name'])
122            ->having(new Expression('COUNT(s_id)'), '>', '1')
123            ->select([new Expression('GROUP_CONCAT(s_id) AS xrefs')])
124            ->orderBy('xrefs')
125            ->pluck('xrefs')
126            ->map(static function (string $xrefs) use ($tree): array {
127                return array_map(static function (string $xref) use ($tree): Source {
128                    return Registry::sourceFactory()->make($xref, $tree);
129                }, explode(',', $xrefs));
130            })
131            ->all();
132
133        $individuals = DB::table('dates')
134            ->join('name', static function (JoinClause $join): void {
135                $join
136                    ->on('d_file', '=', 'n_file')
137                    ->on('d_gid', '=', 'n_id');
138            })
139            ->where('d_file', '=', $tree->id())
140            ->whereIn('d_fact', ['BIRT', 'CHR', 'BAPM', 'DEAT', 'BURI'])
141            ->groupBy(['d_year', 'd_month', 'd_day', 'd_type', 'd_fact', 'n_type', 'n_full'])
142            ->having(new Expression('COUNT(DISTINCT d_gid)'), '>', '1')
143            ->select([new Expression('GROUP_CONCAT(DISTINCT d_gid ORDER BY d_gid) AS xrefs')])
144            ->distinct()
145            ->orderBy('xrefs')
146            ->pluck('xrefs')
147            ->map(static function (string $xrefs) use ($tree): array {
148                return array_map(static function (string $xref) use ($tree): Individual {
149                    return Registry::individualFactory()->make($xref, $tree);
150                }, explode(',', $xrefs));
151            })
152            ->all();
153
154        $families = DB::table('families')
155            ->where('f_file', '=', $tree->id())
156            ->groupBy([new Expression('LEAST(f_husb, f_wife)')])
157            ->groupBy([new Expression('GREATEST(f_husb, f_wife)')])
158            ->having(new Expression('COUNT(f_id)'), '>', '1')
159            ->select([new Expression('GROUP_CONCAT(f_id) AS xrefs')])
160            ->orderBy('xrefs')
161            ->pluck('xrefs')
162            ->map(static function (string $xrefs) use ($tree): array {
163                return array_map(static function (string $xref) use ($tree): Family {
164                    return Registry::familyFactory()->make($xref, $tree);
165                }, explode(',', $xrefs));
166            })
167            ->all();
168
169        $media = DB::table('media_file')
170            ->where('m_file', '=', $tree->id())
171            ->where('descriptive_title', '<>', '')
172            ->groupBy(['descriptive_title'])
173            ->having(new Expression('COUNT(m_id)'), '>', '1')
174            ->select([new Expression('GROUP_CONCAT(m_id) AS xrefs')])
175            ->orderBy('xrefs')
176            ->pluck('xrefs')
177            ->map(static function (string $xrefs) use ($tree): array {
178                return array_map(static function (string $xref) use ($tree): Media {
179                    return Registry::mediaFactory()->make($xref, $tree);
180                }, explode(',', $xrefs));
181            })
182            ->all();
183
184        return [
185            I18N::translate('Repositories')  => $repositories,
186            I18N::translate('Sources')       => $sources,
187            I18N::translate('Individuals')   => $individuals,
188            I18N::translate('Families')      => $families,
189            I18N::translate('Media objects') => $media,
190        ];
191    }
192
193    /**
194     * Every XREF used by this tree and also used by some other tree
195     *
196     * @param Tree $tree
197     *
198     * @return array<string>
199     */
200    public function duplicateXrefs(Tree $tree): array
201    {
202        $subquery1 = DB::table('individuals')
203            ->where('i_file', '=', $tree->id())
204            ->select(['i_id AS xref', new Expression("'INDI' AS type")])
205            ->union(DB::table('families')
206                ->where('f_file', '=', $tree->id())
207                ->select(['f_id AS xref', new Expression("'FAM' AS type")]))
208            ->union(DB::table('sources')
209                ->where('s_file', '=', $tree->id())
210                ->select(['s_id AS xref', new Expression("'SOUR' AS type")]))
211            ->union(DB::table('media')
212                ->where('m_file', '=', $tree->id())
213                ->select(['m_id AS xref', new Expression("'OBJE' AS type")]))
214            ->union(DB::table('other')
215                ->where('o_file', '=', $tree->id())
216                ->whereNotIn('o_type', [Header::RECORD_TYPE, 'TRLR'])
217                ->select(['o_id AS xref', 'o_type AS type']));
218
219        $subquery2 = DB::table('change')
220            ->where('gedcom_id', '<>', $tree->id())
221            ->select(['xref AS other_xref'])
222            ->union(DB::table('individuals')
223                ->where('i_file', '<>', $tree->id())
224                ->select(['i_id AS xref']))
225            ->union(DB::table('families')
226                ->where('f_file', '<>', $tree->id())
227                ->select(['f_id AS xref']))
228            ->union(DB::table('sources')
229                ->where('s_file', '<>', $tree->id())
230                ->select(['s_id AS xref']))
231            ->union(DB::table('media')
232                ->where('m_file', '<>', $tree->id())
233                ->select(['m_id AS xref']))
234            ->union(DB::table('other')
235                ->where('o_file', '<>', $tree->id())
236                ->whereNotIn('o_type', [Header::RECORD_TYPE, 'TRLR'])
237                ->select(['o_id AS xref']));
238
239        return DB::query()
240            ->fromSub($subquery1, 'sub1')
241            ->joinSub($subquery2, 'sub2', 'other_xref', '=', 'xref')
242            ->pluck('type', 'xref')
243            ->all();
244    }
245
246    /**
247     * A list of GEDCOM files in the data folder.
248     *
249     * @param FilesystemOperator $filesystem
250     *
251     * @return Collection<string>
252     */
253    public function gedcomFiles(FilesystemOperator $filesystem): Collection
254    {
255        try {
256            $files = $filesystem->listContents('')
257                ->filter(static function (StorageAttributes $attributes) use ($filesystem) {
258                    if (!$attributes->isFile()) {
259                        return false;
260                    }
261
262                    $stream = $filesystem->readStream($attributes->path());
263
264                    $header = fread($stream, 10);
265                    fclose($stream);
266
267                    return preg_match('/^(' . Gedcom::UTF8_BOM . ')?0 HEAD/', $header) > 0;
268                })
269                ->map(function (StorageAttributes $attributes) {
270                    return $attributes->path();
271                })
272                ->toArray();
273        } catch (FilesystemException $ex) {
274            $files = [];
275        }
276
277        return Collection::make($files)->sort();
278    }
279
280    /**
281     * Change the behaviour a little, when there are a lot of trees.
282     *
283     * @return int
284     */
285    public function multipleTreeThreshold(): int
286    {
287        return (int) Site::getPreference('MULTIPLE_TREE_THRESHOLD', self::MULTIPLE_TREE_THRESHOLD);
288    }
289}
290