xref: /webtrees/app/Http/RequestHandlers/MergeFactsAction.php (revision afc2d1902ecd3bf5ad093d4f0c848f540e3f1cc8)
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\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\Auth;
23use Fisharebest\Webtrees\Contracts\UserInterface;
24use Fisharebest\Webtrees\FlashMessages;
25use Fisharebest\Webtrees\I18N;
26use Fisharebest\Webtrees\Registry;
27use Fisharebest\Webtrees\Tree;
28use Illuminate\Database\Capsule\Manager as DB;
29use Illuminate\Database\Query\Expression;
30use Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32use Psr\Http\Server\RequestHandlerInterface;
33
34use function assert;
35use function e;
36use function in_array;
37use function preg_replace;
38use function redirect;
39use function route;
40use function str_replace;
41
42/**
43 * Merge records
44 */
45class MergeFactsAction implements RequestHandlerInterface
46{
47    /**
48     * @param ServerRequestInterface $request
49     *
50     * @return ResponseInterface
51     */
52    public function handle(ServerRequestInterface $request): ResponseInterface
53    {
54        $tree = $request->getAttribute('tree');
55        assert($tree instanceof Tree);
56
57        $params = (array) $request->getParsedBody();
58
59        $xref1 = $params['xref1'] ?? '';
60        $xref2 = $params['xref2'] ?? '';
61
62        $keep1 = $params['keep1'] ?? [];
63        $keep2 = $params['keep2'] ?? [];
64
65        // Merge record2 into record1
66        $record1 = Registry::gedcomRecordFactory()->make($xref1, $tree);
67        $record2 = Registry::gedcomRecordFactory()->make($xref2, $tree);
68
69        if (
70            $record1 === null ||
71            $record2 === null ||
72            $record1 === $record2 ||
73            $record1->tag() !== $record2->tag() ||
74            $record1->isPendingDeletion() ||
75            $record2->isPendingDeletion()
76        ) {
77            return redirect(route(MergeRecordsPage::class, [
78                'tree'  => $tree->name(),
79                'xref1' => $xref1,
80                'xref2' => $xref2,
81            ]));
82        }
83
84        // If we are not auto-accepting, then we can show a link to the pending deletion
85        if (Auth::user()->getPreference(UserInterface::PREF_AUTO_ACCEPT_EDITS) === '1') {
86            $record2_name = $record2->fullName();
87        } else {
88            $record2_name = '<a class="alert-link" href="' . e($record2->url()) . '">' . $record2->fullName() . '</a>';
89        }
90
91        // Update records that link to the one we will be removing.
92        $linking_records = $record2->linkingRecords();
93
94        foreach ($linking_records as $record) {
95            if (!$record->isPendingDeletion()) {
96                /* I18N: The placeholders are the names of individuals, sources, etc. */
97                FlashMessages::addMessage(I18N::translate(
98                    'The link from “%1$s” to “%2$s” has been updated.',
99                    '<a class="alert-link" href="' . e($record->url()) . '">' . $record->fullName() . '</a>',
100                    $record2_name
101                ), 'info');
102                $gedcom = str_replace('@' . $xref2 . '@', '@' . $xref1 . '@', $record->gedcom());
103                $gedcom = preg_replace(
104                    '/(\n1.*@.+@.*(?:\n[2-9].*)*)((?:\n1.*(?:\n[2-9].*)*)*\1)/',
105                    '$2',
106                    $gedcom
107                );
108                $record->updateRecord($gedcom, true);
109            }
110        }
111
112        // Update any linked user-accounts
113        DB::table('user_gedcom_setting')
114            ->where('gedcom_id', '=', $tree->id())
115            ->whereIn('setting_name', [UserInterface::PREF_TREE_ACCOUNT_XREF, UserInterface::PREF_TREE_DEFAULT_XREF])
116            ->where('setting_value', '=', $xref2)
117            ->update(['setting_value' => $xref1]);
118
119        // Merge stories, etc.
120        DB::table('block')
121            ->where('gedcom_id', '=', $tree->id())
122            ->where('xref', '=', $xref2)
123            ->update(['xref' => $xref1]);
124
125        // Merge hit counters
126        $hits = DB::table('hit_counter')
127            ->where('gedcom_id', '=', $tree->id())
128            ->whereIn('page_parameter', [$xref1, $xref2])
129            ->groupBy(['page_name'])
130            ->pluck(new Expression('SUM(page_count)'), 'page_name');
131
132        foreach ($hits as $page_name => $page_count) {
133            DB::table('hit_counter')
134                ->where('gedcom_id', '=', $tree->id())
135                ->where('page_name', '=', $page_name)
136                ->where('page_parameter', '=', $xref1)
137                ->update(['page_count' => $page_count]);
138        }
139
140        DB::table('hit_counter')
141            ->where('gedcom_id', '=', $tree->id())
142            ->where('page_parameter', '=', $xref2)
143            ->delete();
144
145        $gedcom = '0 @' . $record1->xref() . '@ ' . $record1->tag();
146
147        foreach ($record1->facts() as $fact) {
148            if (in_array($fact->id(), $keep1, true)) {
149                $gedcom .= "\n" . $fact->gedcom();
150            }
151        }
152
153        foreach ($record2->facts() as $fact) {
154            if (in_array($fact->id(), $keep2, true)) {
155                $gedcom .= "\n" . $fact->gedcom();
156            }
157        }
158
159        DB::table('favorite')
160            ->where('gedcom_id', '=', $tree->id())
161            ->where('xref', '=', $xref2)
162            ->update(['xref' => $xref1]);
163
164        $record1->updateRecord($gedcom, true);
165        $record2->deleteRecord();
166
167        /* I18N: Records are individuals, sources, etc. */
168        FlashMessages::addMessage(I18N::translate(
169            'The records “%1$s” and “%2$s” have been merged.',
170            '<a class="alert-link" href="' . e($record1->url()) . '">' . $record1->fullName() . '</a>',
171            $record2_name
172        ), 'success');
173
174        return redirect(route(ManageTrees::class, ['tree' => $tree->name()]));
175    }
176}
177