xref: /webtrees/app/Http/RequestHandlers/GedcomLoad.php (revision 94db7d2d27c3ad6a04fceebbdcb98e28e97649b3)
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 Exception;
23use Fisharebest\Webtrees\Encodings\UTF8;
24use Fisharebest\Webtrees\Exceptions\GedcomErrorException;
25use Fisharebest\Webtrees\Http\ViewResponseTrait;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Services\GedcomImportService;
28use Fisharebest\Webtrees\Services\TimeoutService;
29use Fisharebest\Webtrees\Services\TreeService;
30use Fisharebest\Webtrees\Validator;
31use Illuminate\Database\Capsule\Manager as DB;
32use Illuminate\Database\DetectsConcurrencyErrors;
33use Psr\Http\Message\ResponseInterface;
34use Psr\Http\Message\ServerRequestInterface;
35use Psr\Http\Server\RequestHandlerInterface;
36
37use function preg_split;
38use function response;
39use function str_replace;
40use function str_starts_with;
41use function strlen;
42use function substr;
43use function view;
44
45/**
46 * Load a chunk of GEDCOM data.
47 */
48class GedcomLoad implements RequestHandlerInterface
49{
50    use ViewResponseTrait;
51    use DetectsConcurrencyErrors;
52
53    private GedcomImportService $gedcom_import_service;
54
55    private TimeoutService $timeout_service;
56
57    private TreeService $tree_service;
58
59    /**
60     * GedcomLoad constructor.
61     *
62     * @param GedcomImportService $gedcom_import_service
63     * @param TimeoutService      $timeout_service
64     * @param TreeService         $tree_service
65     */
66    public function __construct(
67        GedcomImportService $gedcom_import_service,
68        TimeoutService $timeout_service,
69        TreeService $tree_service
70    ) {
71        $this->gedcom_import_service = $gedcom_import_service;
72        $this->timeout_service       = $timeout_service;
73        $this->tree_service          = $tree_service;
74    }
75
76    /**
77     * @param ServerRequestInterface $request
78     *
79     * @return ResponseInterface
80     */
81    public function handle(ServerRequestInterface $request): ResponseInterface
82    {
83        $this->layout = 'layouts/ajax';
84
85        $tree = Validator::attributes($request)->tree();
86
87        try {
88            // What is the current import status?
89            $import_offset = DB::table('gedcom_chunk')
90                ->where('gedcom_id', '=', $tree->id())
91                ->where('imported', '=', '1')
92                ->count();
93
94            $import_total = DB::table('gedcom_chunk')
95                ->where('gedcom_id', '=', $tree->id())
96                ->count();
97
98            // Finished?
99            if ($import_offset === $import_total) {
100                $tree->setPreference('imported', '1');
101
102                $html = view('admin/import-complete', ['tree' => $tree]);
103
104                return response($html);
105            }
106
107            // Calculate progress so far
108            $progress = $import_offset / $import_total;
109
110            $first_time = $import_offset === 0;
111
112            // Collect up any errors, and show them later.
113            $errors = '';
114
115            // Run for a short period of time. This keeps the resource requirements low.
116            do {
117                $data = DB::table('gedcom_chunk')
118                    ->where('gedcom_id', '=', $tree->id())
119                    ->where('imported', '=', '0')
120                    ->orderBy('gedcom_chunk_id')
121                    ->select(['gedcom_chunk_id', 'chunk_data'])
122                    ->first();
123
124                if ($data === null) {
125                    break;
126                }
127
128                // Mark the chunk as imported.  This will create a row-lock, to prevent other
129                // processes from reading it until we have finished.
130                $n = DB::table('gedcom_chunk')
131                    ->where('gedcom_chunk_id', '=', $data->gedcom_chunk_id)
132                    ->where('imported', '=', '0')
133                    ->update(['imported' => 1]);
134
135                // Another process has already imported this data?
136                if ($n === 0) {
137                    break;
138                }
139
140                // If we are loading the first (header) record, then delete old data.
141                if ($first_time) {
142                    $this->tree_service->deleteGenealogyData($tree, (bool) $tree->getPreference('keep_media'));
143
144                    // Remove any byte-order-mark
145                    if (str_starts_with($data->chunk_data, UTF8::BYTE_ORDER_MARK)) {
146                        $data->chunk_data = substr($data->chunk_data, strlen(UTF8::BYTE_ORDER_MARK));
147                        DB::table('gedcom_chunk')
148                            ->where('gedcom_chunk_id', '=', $data->gedcom_chunk_id)
149                            ->update(['chunk_data' => $data->chunk_data]);
150                    }
151
152                    if (!str_starts_with($data->chunk_data, '0 HEAD')) {
153                        return $this->viewResponse('admin/import-fail', [
154                            'error' => I18N::translate('Invalid GEDCOM file - no header record found.'),
155                            'tree'  => $tree,
156                        ]);
157                    }
158
159                    $first_time = false;
160                }
161
162                $data->chunk_data = str_replace("\r", "\n", $data->chunk_data);
163
164                // Import all the records in this chunk of data
165                foreach (preg_split('/\n+(?=0)/', $data->chunk_data) as $rec) {
166                    try {
167                        $this->gedcom_import_service->importRecord($rec, $tree, false);
168                    } catch (GedcomErrorException $exception) {
169                        $errors .= $exception->getMessage();
170                    }
171                }
172
173                // Do not need the data any more.
174                DB::table('gedcom_chunk')
175                    ->where('gedcom_chunk_id', '=', $data->gedcom_chunk_id)
176                    ->update(['chunk_data' => '']);
177            } while (!$this->timeout_service->isTimeLimitUp());
178
179            return $this->viewResponse('admin/import-progress', [
180                'errors'   => $errors,
181                'progress' => $progress,
182                'tree'     => $tree,
183            ]);
184        } catch (Exception $ex) {
185            DB::connection()->rollBack();
186
187            // Deadlock? Try again.
188            if ($this->causedByConcurrencyError($ex)) {
189                return $this->viewResponse('admin/import-progress', [
190                    'errors'   => '',
191                    'progress' => $progress ?? 0.0,
192                    'tree'     => $tree,
193                ]);
194            }
195
196            return $this->viewResponse('admin/import-fail', [
197                'error' => $ex->getMessage(),
198                'tree'  => $tree,
199            ]);
200        }
201    }
202}
203