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\Exceptions\GedcomErrorException; 24use Fisharebest\Webtrees\Functions\FunctionsImport; 25use Fisharebest\Webtrees\Gedcom; 26use Fisharebest\Webtrees\Http\ViewResponseTrait; 27use Fisharebest\Webtrees\I18N; 28use Fisharebest\Webtrees\Services\TimeoutService; 29use Fisharebest\Webtrees\Services\TreeService; 30use Fisharebest\Webtrees\Tree; 31use Illuminate\Database\Capsule\Manager as DB; 32use Illuminate\Database\DetectsConcurrencyErrors; 33use Illuminate\Database\Query\Expression; 34use Psr\Http\Message\ResponseInterface; 35use Psr\Http\Message\ServerRequestInterface; 36use Psr\Http\Server\RequestHandlerInterface; 37 38use function assert; 39use function preg_match; 40use function preg_split; 41use function response; 42use function str_replace; 43use function str_starts_with; 44use function strlen; 45use function strtoupper; 46use function substr; 47use function trim; 48use function view; 49 50/** 51 * Load a chunk of GEDCOM data. 52 */ 53class GedcomLoad implements RequestHandlerInterface 54{ 55 use ViewResponseTrait; 56 use DetectsConcurrencyErrors; 57 58 private TimeoutService $timeout_service; 59 60 private TreeService $tree_service; 61 62 /** 63 * GedcomLoad constructor. 64 * 65 * @param TimeoutService $timeout_service 66 * @param TreeService $tree_service 67 */ 68 public function __construct(TimeoutService $timeout_service, TreeService $tree_service) 69 { 70 $this->timeout_service = $timeout_service; 71 $this->tree_service = $tree_service; 72 } 73 74 /** 75 * @param ServerRequestInterface $request 76 * 77 * @return ResponseInterface 78 */ 79 public function handle(ServerRequestInterface $request): ResponseInterface 80 { 81 $this->layout = 'layouts/ajax'; 82 83 $tree = $request->getAttribute('tree'); 84 assert($tree instanceof Tree); 85 86 try { 87 // What is the current import status? 88 $import_offset = DB::table('gedcom_chunk') 89 ->where('gedcom_id', '=', $tree->id()) 90 ->where('imported', '=', '1') 91 ->count(); 92 93 $import_total = DB::table('gedcom_chunk') 94 ->where('gedcom_id', '=', $tree->id()) 95 ->count(); 96 97 // Finished? 98 if ($import_offset === $import_total) { 99 $tree->setPreference('imported', '1'); 100 101 $html = view('admin/import-complete', ['tree' => $tree]); 102 103 return response($html); 104 } 105 106 // Calculate progress so far 107 $progress = $import_offset / $import_total; 108 109 $first_time = $import_offset === 0; 110 111 // Collect up any errors, and show them later. 112 $errors = ''; 113 114 // Run for a short period of time. This keeps the resource requirements low. 115 do { 116 $data = DB::table('gedcom_chunk') 117 ->where('gedcom_id', '=', $tree->id()) 118 ->where('imported', '=', '0') 119 ->orderBy('gedcom_chunk_id') 120 ->select(['gedcom_chunk_id', 'chunk_data']) 121 ->first(); 122 123 if ($data === null) { 124 break; 125 } 126 127 // Mark the chunk as imported. This will create a row-lock, to prevent other 128 // processes from reading it until we have finished. 129 $n = DB::table('gedcom_chunk') 130 ->where('gedcom_chunk_id', '=', $data->gedcom_chunk_id) 131 ->where('imported', '=', '0') 132 ->update(['imported' => 1]); 133 134 // Another process has already imported this data? 135 if ($n === 0) { 136 break; 137 } 138 139 // If we are loading the first (header) record, then delete old data and convert to UTF-8. 140 if ($first_time) { 141 $this->tree_service->deleteGenealogyData($tree, (bool) $tree->getPreference('keep_media')); 142 143 // Remove any byte-order-mark 144 if (str_starts_with($data->chunk_data, Gedcom::UTF8_BOM)) { 145 $data->chunk_data = substr($data->chunk_data, strlen(Gedcom::UTF8_BOM)); 146 // Put it back in the database, so we can do character conversion 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 // What character set is this? Need to convert it to UTF8 160 if (preg_match('/[\r\n][ \t]*1 CHAR(?:ACTER)? ([^\r\n]+)/', $data->chunk_data, $match)) { 161 $charset = strtoupper(trim($match[1])); 162 } else { 163 $charset = 'ASCII'; 164 } 165 166 // MySQL supports a wide range of collation conversions. These are ones that 167 // have been encountered "in the wild". 168 switch ($charset) { 169 case 'ASCII': 170 DB::table('gedcom_chunk') 171 ->where('gedcom_id', '=', $tree->id()) 172 ->update(['chunk_data' => new Expression('CONVERT(CONVERT(chunk_data USING ascii) USING utf8)')]); 173 break; 174 case 'IBMPC': // IBMPC, IBM WINDOWS and MS-DOS could be anything. Mostly it means CP850. 175 case 'IBM WINDOWS': 176 case 'MS-DOS': 177 case 'CP437': 178 case 'CP850': 179 // CP850 has extra letters with diacritics to replace box-drawing chars in CP437. 180 DB::table('gedcom_chunk') 181 ->where('gedcom_id', '=', $tree->id()) 182 ->update(['chunk_data' => new Expression('CONVERT(CONVERT(chunk_data USING cp850) USING utf8)')]); 183 break; 184 case 'ANSI': // ANSI could be anything. Most applications seem to treat it as latin1. 185 case 'WINDOWS': 186 case 'CP1252': 187 case 'ISO8859-1': 188 case 'ISO-8859-1': 189 case 'LATIN1': 190 case 'LATIN-1': 191 // Convert from ISO-8859-1 (western european) to UTF8. 192 DB::table('gedcom_chunk') 193 ->where('gedcom_id', '=', $tree->id()) 194 ->update(['chunk_data' => new Expression('CONVERT(CONVERT(chunk_data USING latin1) USING utf8)')]); 195 break; 196 case 'CP1250': 197 case 'ISO8859-2': 198 case 'ISO-8859-2': 199 case 'LATIN2': 200 case 'LATIN-2': 201 // Convert from ISO-8859-2 (eastern european) to UTF8. 202 DB::table('gedcom_chunk') 203 ->where('gedcom_id', '=', $tree->id()) 204 ->update(['chunk_data' => new Expression('CONVERT(CONVERT(chunk_data USING latin2) USING utf8)')]); 205 break; 206 case 'MACINTOSH': 207 // Convert from MAC Roman to UTF8. 208 DB::table('gedcom_chunk') 209 ->where('gedcom_id', '=', $tree->id()) 210 ->update(['chunk_data' => new Expression('CONVERT(CONVERT(chunk_data USING macroman) USING utf8)')]); 211 break; 212 case 'UTF8': 213 case 'UTF-8': 214 // Already UTF-8 so nothing to do! 215 break; 216 case 'ANSEL': 217 default: 218 return $this->viewResponse('admin/import-fail', [ 219 'error' => I18N::translate('Error: converting GEDCOM files from %s encoding to UTF-8 encoding not currently supported.', $charset), 220 'tree' => $tree, 221 ]); 222 } 223 $first_time = false; 224 225 // Re-fetch the data, now that we have performed character set conversion. 226 $data = DB::table('gedcom_chunk') 227 ->where('gedcom_chunk_id', '=', $data->gedcom_chunk_id) 228 ->select(['gedcom_chunk_id', 'chunk_data']) 229 ->first(); 230 } 231 232 $data->chunk_data = str_replace("\r", "\n", $data->chunk_data); 233 234 // Import all the records in this chunk of data 235 foreach (preg_split('/\n+(?=0)/', $data->chunk_data) as $rec) { 236 try { 237 FunctionsImport::importRecord($rec, $tree, false); 238 } catch (GedcomErrorException $exception) { 239 $errors .= $exception->getMessage(); 240 } 241 } 242 243 // Do not need the data any more. 244 DB::table('gedcom_chunk') 245 ->where('gedcom_chunk_id', '=', $data->gedcom_chunk_id) 246 ->update(['chunk_data' => '']); 247 } while (!$this->timeout_service->isTimeLimitUp()); 248 249 return $this->viewResponse('admin/import-progress', [ 250 'errors' => $errors, 251 'progress' => $progress, 252 'tree' => $tree, 253 ]); 254 } catch (Exception $ex) { 255 DB::connection()->rollBack(); 256 257 // Deadlock? Try again. 258 if ($this->causedByConcurrencyError($ex)) { 259 return $this->viewResponse('admin/import-progress', [ 260 'errors' => '', 261 'progress' => $progress ?? 0.0, 262 'tree' => $tree, 263 ]); 264 } 265 266 return $this->viewResponse('admin/import-fail', [ 267 'error' => $ex->getMessage(), 268 'tree' => $tree, 269 ]); 270 } 271 } 272} 273