1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2022 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\Date; 23use Fisharebest\Webtrees\Elements\UnknownElement; 24use Fisharebest\Webtrees\Exceptions\GedcomErrorException; 25use Fisharebest\Webtrees\Family; 26use Fisharebest\Webtrees\Gedcom; 27use Fisharebest\Webtrees\Header; 28use Fisharebest\Webtrees\Individual; 29use Fisharebest\Webtrees\Location; 30use Fisharebest\Webtrees\Media; 31use Fisharebest\Webtrees\Note; 32use Fisharebest\Webtrees\Place; 33use Fisharebest\Webtrees\PlaceLocation; 34use Fisharebest\Webtrees\Registry; 35use Fisharebest\Webtrees\Repository; 36use Fisharebest\Webtrees\Soundex; 37use Fisharebest\Webtrees\Source; 38use Fisharebest\Webtrees\Submission; 39use Fisharebest\Webtrees\Submitter; 40use Fisharebest\Webtrees\Tree; 41use Illuminate\Database\Capsule\Manager as DB; 42use Illuminate\Database\Query\JoinClause; 43 44use function app; 45use function array_chunk; 46use function array_intersect_key; 47use function array_map; 48use function array_unique; 49use function assert; 50use function date; 51use function explode; 52use function max; 53use function mb_substr; 54use function preg_match; 55use function preg_match_all; 56use function preg_replace; 57use function round; 58use function str_contains; 59use function str_replace; 60use function str_starts_with; 61use function strlen; 62use function strtoupper; 63use function strtr; 64use function substr; 65use function trim; 66 67use const PREG_SET_ORDER; 68 69/** 70 * Class GedcomImportService - import GEDCOM data 71 */ 72class GedcomImportService 73{ 74 /** 75 * Tidy up a gedcom record on import, so that we can access it consistently/efficiently. 76 * 77 * @param string $rec 78 * @param Tree $tree 79 * 80 * @return string 81 */ 82 private function reformatRecord(string $rec, Tree $tree): string 83 { 84 $gedcom_service = app(GedcomService::class); 85 assert($gedcom_service instanceof GedcomService); 86 87 // Strip out mac/msdos line endings 88 $rec = preg_replace("/[\r\n]+/", "\n", $rec); 89 90 // Extract lines from the record; lines consist of: level + optional xref + tag + optional data 91 $num_matches = preg_match_all('/^[ \t]*(\d+)[ \t]*(@[^@]*@)?[ \t]*(\w+)[ \t]?(.*)$/m', $rec, $matches, PREG_SET_ORDER); 92 93 // Process the record line-by-line 94 $newrec = ''; 95 foreach ($matches as $n => $match) { 96 [, $level, $xref, $tag, $data] = $match; 97 98 $tag = $gedcom_service->canonicalTag($tag); 99 100 switch ($tag) { 101 case 'DATE': 102 // Preserve text from INT dates 103 if (str_contains($data, '(')) { 104 [$date, $text] = explode('(', $data, 2); 105 $text = ' (' . $text; 106 } else { 107 $date = $data; 108 $text = ''; 109 } 110 // Capitals 111 $date = strtoupper($date); 112 // Temporarily add leading/trailing spaces, to allow efficient matching below 113 $date = ' ' . $date . ' '; 114 // Ensure space digits and letters 115 $date = preg_replace('/([A-Z])(\d)/', '$1 $2', $date); 116 $date = preg_replace('/(\d)([A-Z])/', '$1 $2', $date); 117 // Ensure space before/after calendar escapes 118 $date = preg_replace('/@#[^@]+@/', ' $0 ', $date); 119 // "BET." => "BET" 120 $date = preg_replace('/(\w\w)\./', '$1', $date); 121 // "CIR" => "ABT" 122 $date = str_replace(' CIR ', ' ABT ', $date); 123 $date = str_replace(' APX ', ' ABT ', $date); 124 // B.C. => BC (temporarily, to allow easier handling of ".") 125 $date = str_replace(' B.C. ', ' BC ', $date); 126 // TMG uses "EITHER X OR Y" 127 $date = preg_replace('/^ EITHER (.+) OR (.+)/', ' BET $1 AND $2', $date); 128 // "BET X - Y " => "BET X AND Y" 129 $date = preg_replace('/^(.* BET .+) - (.+)/', '$1 AND $2', $date); 130 $date = preg_replace('/^(.* FROM .+) - (.+)/', '$1 TO $2', $date); 131 // "@#ESC@ FROM X TO Y" => "FROM @#ESC@ X TO @#ESC@ Y" 132 $date = preg_replace('/^ +(@#[^@]+@) +FROM +(.+) +TO +(.+)/', ' FROM $1 $2 TO $1 $3', $date); 133 $date = preg_replace('/^ +(@#[^@]+@) +BET +(.+) +AND +(.+)/', ' BET $1 $2 AND $1 $3', $date); 134 // "@#ESC@ AFT X" => "AFT @#ESC@ X" 135 $date = preg_replace('/^ +(@#[^@]+@) +(FROM|BET|TO|AND|BEF|AFT|CAL|EST|INT|ABT) +(.+)/', ' $2 $1 $3', $date); 136 // Ignore any remaining punctuation, e.g. "14-MAY, 1900" => "14 MAY 1900" 137 // (don't change "/" - it is used in NS/OS dates) 138 $date = preg_replace('/[.,:;-]/', ' ', $date); 139 // BC => B.C. 140 $date = str_replace(' BC ', ' B.C. ', $date); 141 // Append the "INT" text 142 $data = $date . $text; 143 break; 144 case 'HEAD': 145 case 'TRLR': 146 // HEAD and TRLR records do not have an XREF or DATA 147 if ($level === '0') { 148 $xref = ''; 149 $data = ''; 150 } 151 break; 152 case 'NAME': 153 // Tidy up non-printing characters 154 $data = preg_replace('/ +/', ' ', trim($data)); 155 break; 156 case 'PLAC': 157 // Consistent commas 158 $data = preg_replace('/ *[,,،] */u', ', ', $data); 159 // The Master Genealogist stores LAT/LONG data in the PLAC field, e.g. Pennsylvania, USA, 395945N0751013W 160 if (preg_match('/(.*), (\d\d)(\d\d)(\d\d)([NS])(\d\d\d)(\d\d)(\d\d)([EW])$/', $data, $match)) { 161 $data = 162 $match[1] . "\n" . 163 ($level + 1) . " MAP\n" . 164 ($level + 2) . ' LATI ' . ($match[5] . round($match[2] + ($match[3] / 60) + ($match[4] / 3600), 4)) . "\n" . 165 ($level + 2) . ' LONG ' . ($match[9] . round($match[6] + ($match[7] / 60) + ($match[8] / 3600), 4)); 166 } 167 break; 168 case 'SEX': 169 $data = strtoupper($data); 170 break; 171 } 172 // Suppress "Y", for facts/events with a DATE or PLAC 173 if ($data === 'y') { 174 $data = 'Y'; 175 } 176 if ($level === '1' && $data === 'Y') { 177 for ($i = $n + 1; $i < $num_matches - 1 && $matches[$i][1] !== '1'; ++$i) { 178 if ($matches[$i][3] === 'DATE' || $matches[$i][3] === 'PLAC') { 179 $data = ''; 180 break; 181 } 182 } 183 } 184 // Reassemble components back into a single line 185 switch ($tag) { 186 default: 187 // Remove tabs and multiple/leading/trailing spaces 188 $data = strtr($data, ["\t" => ' ']); 189 $data = trim($data, ' '); 190 while (str_contains($data, ' ')) { 191 $data = strtr($data, [' ' => ' ']); 192 } 193 $newrec .= ($newrec ? "\n" : '') . $level . ' ' . ($level === '0' && $xref ? $xref . ' ' : '') . $tag . ($data === '' && $tag !== 'NOTE' ? '' : ' ' . $data); 194 break; 195 case 'NOTE': 196 case 'TEXT': 197 case 'DATA': 198 case 'CONT': 199 $newrec .= ($newrec ? "\n" : '') . $level . ' ' . ($level === '0' && $xref ? $xref . ' ' : '') . $tag . ($data === '' && $tag !== 'NOTE' ? '' : ' ' . $data); 200 break; 201 case 'FILE': 202 // Strip off the user-defined path prefix 203 $GEDCOM_MEDIA_PATH = $tree->getPreference('GEDCOM_MEDIA_PATH'); 204 if ($GEDCOM_MEDIA_PATH !== '' && str_starts_with($data, $GEDCOM_MEDIA_PATH)) { 205 $data = substr($data, strlen($GEDCOM_MEDIA_PATH)); 206 } 207 // convert backslashes in filenames to forward slashes 208 $data = preg_replace("/\\\\/", '/', $data); 209 210 $newrec .= ($newrec ? "\n" : '') . $level . ' ' . ($level === '0' && $xref ? $xref . ' ' : '') . $tag . ($data === '' && $tag !== 'NOTE' ? '' : ' ' . $data); 211 break; 212 case 'CONC': 213 // Merge CONC lines, to simplify access later on. 214 $newrec .= ($tree->getPreference('WORD_WRAPPED_NOTES') ? ' ' : '') . $data; 215 break; 216 } 217 } 218 219 return $newrec; 220 } 221 222 /** 223 * import record into database 224 * this function will parse the given gedcom record and add it to the database 225 * 226 * @param string $gedrec the raw gedcom record to parse 227 * @param Tree $tree import the record into this tree 228 * @param bool $update whether this is an updated record that has been accepted 229 * 230 * @return void 231 * @throws GedcomErrorException 232 */ 233 public function importRecord(string $gedrec, Tree $tree, bool $update): void 234 { 235 $tree_id = $tree->id(); 236 237 // Escaped @ signs (only if importing from file) 238 if (!$update) { 239 $gedrec = str_replace('@@', '@', $gedrec); 240 } 241 242 // Standardise gedcom format 243 $gedrec = $this->reformatRecord($gedrec, $tree); 244 245 // import different types of records 246 if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedrec, $match)) { 247 [, $xref, $type] = $match; 248 } elseif (str_starts_with($gedrec, '0 HEAD')) { 249 $type = 'HEAD'; 250 $xref = 'HEAD'; // For records without an XREF, use the type as a pseudo XREF. 251 } elseif (str_starts_with($gedrec, '0 TRLR')) { 252 $tree->setPreference('imported', '1'); 253 $type = 'TRLR'; 254 $xref = 'TRLR'; // For records without an XREF, use the type as a pseudo XREF. 255 } elseif (str_starts_with($gedrec, '0 _PLAC_DEFN')) { 256 $this->importLegacyPlacDefn($gedrec); 257 258 return; 259 } elseif (str_starts_with($gedrec, '0 _PLAC ')) { 260 $this->importTNGPlac($gedrec); 261 262 return; 263 } else { 264 foreach (Gedcom::CUSTOM_RECORDS_WITHOUT_XREFS as $record_type) { 265 if (preg_match('/^0 ' . $record_type . '\b/', $gedrec) === 1) { 266 return; 267 } 268 } 269 270 throw new GedcomErrorException($gedrec); 271 } 272 273 // Add a _UID 274 if ($tree->getPreference('GENERATE_UIDS') === '1' && !str_contains($gedrec, "\n1 _UID ")) { 275 $element = Registry::elementFactory()->make($type . ':_UID'); 276 if (!$element instanceof UnknownElement) { 277 $gedrec .= "\n1 _UID " . $element->default($tree); 278 } 279 } 280 281 // If the user has downloaded their GEDCOM data (containing media objects) and edited it 282 // using an application which does not support (and deletes) media objects, then add them 283 // back in. 284 if ($tree->getPreference('keep_media')) { 285 $old_linked_media = DB::table('link') 286 ->where('l_from', '=', $xref) 287 ->where('l_file', '=', $tree_id) 288 ->where('l_type', '=', 'OBJE') 289 ->pluck('l_to'); 290 291 // Delete these links - so that we do not insert them again in updateLinks() 292 DB::table('link') 293 ->where('l_from', '=', $xref) 294 ->where('l_file', '=', $tree_id) 295 ->where('l_type', '=', 'OBJE') 296 ->delete(); 297 298 foreach ($old_linked_media as $media_id) { 299 $gedrec .= "\n1 OBJE @" . $media_id . '@'; 300 } 301 } 302 303 // Convert inline media into media objects 304 $gedrec = $this->convertInlineMedia($tree, $gedrec); 305 306 switch ($type) { 307 case Individual::RECORD_TYPE: 308 $record = Registry::individualFactory()->new($xref, $gedrec, null, $tree); 309 310 if (preg_match('/\n1 RIN (.+)/', $gedrec, $match)) { 311 $rin = $match[1]; 312 } else { 313 $rin = $xref; 314 } 315 316 // The database can only store MFU, and many of the stats queries assume this. 317 $sex = $record->sex(); 318 $sex = $sex === 'M' || $sex === 'F' ? $sex : 'U'; 319 320 DB::table('individuals')->insert([ 321 'i_id' => $xref, 322 'i_file' => $tree_id, 323 'i_rin' => $rin, 324 'i_sex' => $sex, 325 'i_gedcom' => $gedrec, 326 ]); 327 328 // Update the cross-reference/index tables. 329 $this->updatePlaces($xref, $tree, $gedrec); 330 $this->updateDates($xref, $tree_id, $gedrec); 331 $this->updateNames($xref, $tree_id, $record); 332 break; 333 334 case Family::RECORD_TYPE: 335 if (preg_match('/\n1 HUSB @(' . Gedcom::REGEX_XREF . ')@/', $gedrec, $match)) { 336 $husb = $match[1]; 337 } else { 338 $husb = ''; 339 } 340 if (preg_match('/\n1 WIFE @(' . Gedcom::REGEX_XREF . ')@/', $gedrec, $match)) { 341 $wife = $match[1]; 342 } else { 343 $wife = ''; 344 } 345 $nchi = preg_match_all('/\n1 CHIL @(' . Gedcom::REGEX_XREF . ')@/', $gedrec, $match); 346 if (preg_match('/\n1 NCHI (\d+)/', $gedrec, $match)) { 347 $nchi = max($nchi, $match[1]); 348 } 349 350 DB::table('families')->insert([ 351 'f_id' => $xref, 352 'f_file' => $tree_id, 353 'f_husb' => $husb, 354 'f_wife' => $wife, 355 'f_gedcom' => $gedrec, 356 'f_numchil' => $nchi, 357 ]); 358 359 // Update the cross-reference/index tables. 360 $this->updatePlaces($xref, $tree, $gedrec); 361 $this->updateDates($xref, $tree_id, $gedrec); 362 break; 363 364 case Source::RECORD_TYPE: 365 if (preg_match('/\n1 TITL (.+)/', $gedrec, $match)) { 366 $name = $match[1]; 367 } elseif (preg_match('/\n1 ABBR (.+)/', $gedrec, $match)) { 368 $name = $match[1]; 369 } else { 370 $name = $xref; 371 } 372 373 DB::table('sources')->insert([ 374 's_id' => $xref, 375 's_file' => $tree_id, 376 's_name' => mb_substr($name, 0, 255), 377 's_gedcom' => $gedrec, 378 ]); 379 break; 380 381 case Repository::RECORD_TYPE: 382 case Note::RECORD_TYPE: 383 case Submission::RECORD_TYPE: 384 case Submitter::RECORD_TYPE: 385 case Location::RECORD_TYPE: 386 DB::table('other')->insert([ 387 'o_id' => $xref, 388 'o_file' => $tree_id, 389 'o_type' => $type, 390 'o_gedcom' => $gedrec, 391 ]); 392 break; 393 394 case Header::RECORD_TYPE: 395 // Force HEAD records to have a creation date. 396 if (!str_contains($gedrec, "\n1 DATE ")) { 397 $today = strtoupper(date('d M Y')); 398 $gedrec .= "\n1 DATE " . $today; 399 } 400 401 DB::table('other')->insert([ 402 'o_id' => $xref, 403 'o_file' => $tree_id, 404 'o_type' => Header::RECORD_TYPE, 405 'o_gedcom' => $gedrec, 406 ]); 407 break; 408 409 410 case Media::RECORD_TYPE: 411 $record = Registry::mediaFactory()->new($xref, $gedrec, null, $tree); 412 413 DB::table('media')->insert([ 414 'm_id' => $xref, 415 'm_file' => $tree_id, 416 'm_gedcom' => $gedrec, 417 ]); 418 419 foreach ($record->mediaFiles() as $media_file) { 420 DB::table('media_file')->insert([ 421 'm_id' => $xref, 422 'm_file' => $tree_id, 423 'multimedia_file_refn' => mb_substr($media_file->filename(), 0, 248), 424 'multimedia_format' => mb_substr($media_file->format(), 0, 4), 425 'source_media_type' => mb_substr($media_file->type(), 0, 15), 426 'descriptive_title' => mb_substr($media_file->title(), 0, 248), 427 ]); 428 } 429 break; 430 431 default: // Custom record types. 432 DB::table('other')->insert([ 433 'o_id' => $xref, 434 'o_file' => $tree_id, 435 'o_type' => mb_substr($type, 0, 15), 436 'o_gedcom' => $gedrec, 437 ]); 438 break; 439 } 440 441 // Update the cross-reference/index tables. 442 $this->updateLinks($xref, $tree_id, $gedrec); 443 } 444 445 /** 446 * Legacy Family Tree software generates _PLAC_DEFN records containing LAT/LONG values 447 * 448 * @param string $gedcom 449 */ 450 private function importLegacyPlacDefn(string $gedcom): void 451 { 452 $gedcom_service = new GedcomService(); 453 454 if (preg_match('/\n1 PLAC (.+)/', $gedcom, $match)) { 455 $place_name = $match[1]; 456 } else { 457 return; 458 } 459 460 if (preg_match('/\n3 LATI ([NS].+)/', $gedcom, $match)) { 461 $latitude = $gedcom_service->readLatitude($match[1]); 462 } else { 463 return; 464 } 465 466 if (preg_match('/\n3 LONG ([EW].+)/', $gedcom, $match)) { 467 $longitude = $gedcom_service->readLongitude($match[1]); 468 } else { 469 return; 470 } 471 472 $location = new PlaceLocation($place_name); 473 474 if ($location->latitude() === null && $location->longitude() === null) { 475 DB::table('place_location') 476 ->where('id', '=', $location->id()) 477 ->update([ 478 'latitude' => $latitude, 479 'longitude' => $longitude, 480 ]); 481 } 482 } 483 484 /** 485 * Legacy Family Tree software generates _PLAC records containing LAT/LONG values 486 * 487 * @param string $gedcom 488 */ 489 private function importTNGPlac(string $gedcom): void 490 { 491 if (preg_match('/^0 _PLAC (.+)/', $gedcom, $match)) { 492 $place_name = $match[1]; 493 } else { 494 return; 495 } 496 497 if (preg_match('/\n2 LATI (.+)/', $gedcom, $match)) { 498 $latitude = (float) $match[1]; 499 } else { 500 return; 501 } 502 503 if (preg_match('/\n2 LONG (.+)/', $gedcom, $match)) { 504 $longitude = (float) $match[1]; 505 } else { 506 return; 507 } 508 509 $location = new PlaceLocation($place_name); 510 511 if ($location->latitude() === null && $location->longitude() === null) { 512 DB::table('place_location') 513 ->where('id', '=', $location->id()) 514 ->update([ 515 'latitude' => $latitude, 516 'longitude' => $longitude, 517 ]); 518 } 519 } 520 521 /** 522 * Extract all level 2 places from the given record and insert them into the places table 523 * 524 * @param string $xref 525 * @param Tree $tree 526 * @param string $gedrec 527 * 528 * @return void 529 */ 530 public function updatePlaces(string $xref, Tree $tree, string $gedrec): void 531 { 532 // Insert all new rows together 533 $rows = []; 534 535 preg_match_all('/\n2 PLAC (.+)/', $gedrec, $matches); 536 537 $places = array_unique($matches[1]); 538 539 foreach ($places as $place_name) { 540 $place = new Place($place_name, $tree); 541 542 // Calling Place::id() will create the entry in the database, if it doesn't already exist. 543 while ($place->id() !== 0) { 544 $rows[] = [ 545 'pl_p_id' => $place->id(), 546 'pl_gid' => $xref, 547 'pl_file' => $tree->id(), 548 ]; 549 550 $place = $place->parent(); 551 } 552 } 553 554 // array_unique doesn't work with arrays of arrays 555 $rows = array_intersect_key($rows, array_unique(array_map('serialize', $rows))); 556 557 // PDO has a limit of 65535 placeholders, and each row requires 3 placeholders. 558 foreach (array_chunk($rows, 20000) as $chunk) { 559 DB::table('placelinks')->insert($chunk); 560 } 561 } 562 563 /** 564 * Extract all the dates from the given record and insert them into the database. 565 * 566 * @param string $xref 567 * @param int $ged_id 568 * @param string $gedrec 569 * 570 * @return void 571 */ 572 private function updateDates(string $xref, int $ged_id, string $gedrec): void 573 { 574 // Insert all new rows together 575 $rows = []; 576 577 preg_match_all("/\n1 (\w+).*(?:\n[2-9].*)*\n2 DATE (.+)(?:\n[2-9].*)*/", $gedrec, $matches, PREG_SET_ORDER); 578 579 foreach ($matches as $match) { 580 $fact = $match[1]; 581 $date = new Date($match[2]); 582 $rows[] = [ 583 'd_day' => $date->minimumDate()->day, 584 'd_month' => $date->minimumDate()->format('%O'), 585 'd_mon' => $date->minimumDate()->month, 586 'd_year' => $date->minimumDate()->year, 587 'd_julianday1' => $date->minimumDate()->minimumJulianDay(), 588 'd_julianday2' => $date->minimumDate()->maximumJulianDay(), 589 'd_fact' => $fact, 590 'd_gid' => $xref, 591 'd_file' => $ged_id, 592 'd_type' => $date->minimumDate()->format('%@'), 593 ]; 594 595 $rows[] = [ 596 'd_day' => $date->maximumDate()->day, 597 'd_month' => $date->maximumDate()->format('%O'), 598 'd_mon' => $date->maximumDate()->month, 599 'd_year' => $date->maximumDate()->year, 600 'd_julianday1' => $date->maximumDate()->minimumJulianDay(), 601 'd_julianday2' => $date->maximumDate()->maximumJulianDay(), 602 'd_fact' => $fact, 603 'd_gid' => $xref, 604 'd_file' => $ged_id, 605 'd_type' => $date->minimumDate()->format('%@'), 606 ]; 607 } 608 609 // array_unique doesn't work with arrays of arrays 610 $rows = array_intersect_key($rows, array_unique(array_map('serialize', $rows))); 611 612 DB::table('dates')->insert($rows); 613 } 614 615 /** 616 * Extract all the links from the given record and insert them into the database 617 * 618 * @param string $xref 619 * @param int $ged_id 620 * @param string $gedrec 621 * 622 * @return void 623 */ 624 private function updateLinks(string $xref, int $ged_id, string $gedrec): void 625 { 626 // Insert all new rows together 627 $rows = []; 628 629 preg_match_all('/\n\d+ (' . Gedcom::REGEX_TAG . ') @(' . Gedcom::REGEX_XREF . ')@/', $gedrec, $matches, PREG_SET_ORDER); 630 631 foreach ($matches as $match) { 632 // Some applications (e.g. GenoPro) create links longer than 15 characters. 633 $link = mb_substr($match[1], 0, 15); 634 635 // Take care of "duplicates" that differ on case/collation, e.g. "SOUR @S1@" and "SOUR @s1@" 636 $rows[$link . strtoupper($match[2])] = [ 637 'l_from' => $xref, 638 'l_to' => $match[2], 639 'l_type' => $link, 640 'l_file' => $ged_id, 641 ]; 642 } 643 644 DB::table('link')->insert($rows); 645 } 646 647 /** 648 * Extract all the names from the given record and insert them into the database. 649 * 650 * @param string $xref 651 * @param int $ged_id 652 * @param Individual $record 653 * 654 * @return void 655 */ 656 private function updateNames(string $xref, int $ged_id, Individual $record): void 657 { 658 // Insert all new rows together 659 $rows = []; 660 661 foreach ($record->getAllNames() as $n => $name) { 662 if ($name['givn'] === Individual::PRAENOMEN_NESCIO) { 663 $soundex_givn_std = null; 664 $soundex_givn_dm = null; 665 } else { 666 $soundex_givn_std = Soundex::russell($name['givn']); 667 $soundex_givn_dm = Soundex::daitchMokotoff($name['givn']); 668 } 669 670 if ($name['surn'] === Individual::NOMEN_NESCIO) { 671 $soundex_surn_std = null; 672 $soundex_surn_dm = null; 673 } else { 674 $soundex_surn_std = Soundex::russell($name['surname']); 675 $soundex_surn_dm = Soundex::daitchMokotoff($name['surname']); 676 } 677 678 $rows[] = [ 679 'n_file' => $ged_id, 680 'n_id' => $xref, 681 'n_num' => $n, 682 'n_type' => $name['type'], 683 'n_sort' => mb_substr($name['sort'], 0, 255), 684 'n_full' => mb_substr($name['fullNN'], 0, 255), 685 'n_surname' => mb_substr($name['surname'], 0, 255), 686 'n_surn' => mb_substr($name['surn'], 0, 255), 687 'n_givn' => mb_substr($name['givn'], 0, 255), 688 'n_soundex_givn_std' => $soundex_givn_std, 689 'n_soundex_surn_std' => $soundex_surn_std, 690 'n_soundex_givn_dm' => $soundex_givn_dm, 691 'n_soundex_surn_dm' => $soundex_surn_dm, 692 ]; 693 } 694 695 DB::table('name')->insert($rows); 696 } 697 698 /** 699 * Extract inline media data, and convert to media objects. 700 * 701 * @param Tree $tree 702 * @param string $gedcom 703 * 704 * @return string 705 */ 706 private function convertInlineMedia(Tree $tree, string $gedcom): string 707 { 708 while (preg_match('/\n1 OBJE(?:\n[2-9].+)+/', $gedcom, $match)) { 709 $xref = $this->createMediaObject($match[0], $tree); 710 $gedcom = strtr($gedcom, [$match[0] => "\n1 OBJE @" . $xref . '@']); 711 } 712 while (preg_match('/\n2 OBJE(?:\n[3-9].+)+/', $gedcom, $match)) { 713 $xref = $this->createMediaObject($match[0], $tree); 714 $gedcom = strtr($gedcom, [$match[0] => "\n2 OBJE @" . $xref . '@']); 715 } 716 while (preg_match('/\n3 OBJE(?:\n[4-9].+)+/', $gedcom, $match)) { 717 $xref = $this->createMediaObject($match[0], $tree); 718 $gedcom = strtr($gedcom, [$match[0] => "\n3 OBJE @" . $xref . '@']); 719 } 720 721 return $gedcom; 722 } 723 724 /** 725 * Create a new media object, from inline media data. 726 * 727 * GEDCOM 5.5.1 specifies: +1 FILE / +2 FORM / +3 MEDI / +1 TITL 728 * GEDCOM 5.5 specifies: +1 FILE / +1 FORM / +1 TITL 729 * GEDCOM 5.5.1 says that GEDCOM 5.5 specifies: +1 FILE / +1 FORM / +2 MEDI 730 * 731 * Legacy generates: +1 FORM / +1 FILE / +1 TITL / +1 _SCBK / +1 _PRIM / +1 _TYPE / +1 NOTE 732 * RootsMagic generates: +1 FILE / +1 FORM / +1 TITL 733 * 734 * @param string $gedcom 735 * @param Tree $tree 736 * 737 * @return string 738 */ 739 private function createMediaObject(string $gedcom, Tree $tree): string 740 { 741 preg_match('/\n\d FILE (.+)/', $gedcom, $match); 742 $file = $match[1] ?? ''; 743 744 preg_match('/\n\d TITL (.+)/', $gedcom, $match); 745 $title = $match[1] ?? ''; 746 747 preg_match('/\n\d FORM (.+)/', $gedcom, $match); 748 $format = $match[1] ?? ''; 749 750 preg_match('/\n\d MEDI (.+)/', $gedcom, $match); 751 $media = $match[1] ?? ''; 752 753 preg_match('/\n\d _SCBK (.+)/', $gedcom, $match); 754 $scrapbook = $match[1] ?? ''; 755 756 preg_match('/\n\d _PRIM (.+)/', $gedcom, $match); 757 $primary = $match[1] ?? ''; 758 759 preg_match('/\n\d _TYPE (.+)/', $gedcom, $match); 760 if ($media === '') { 761 // Legacy uses _TYPE instead of MEDI 762 $media = $match[1] ?? ''; 763 $type = ''; 764 } else { 765 $type = $match[1] ?? ''; 766 } 767 768 preg_match_all('/\n\d NOTE (.+(?:\n\d CONT.*)*)/', $gedcom, $matches); 769 $notes = $matches[1] ?? []; 770 771 // Have we already created a media object with the same title/filename? 772 $xref = DB::table('media_file') 773 ->where('m_file', '=', $tree->id()) 774 ->where('descriptive_title', '=', mb_substr($title, 0, 248)) 775 ->where('multimedia_file_refn', '=', mb_substr($file, 0, 248)) 776 ->value('m_id'); 777 778 if ($xref === null) { 779 $xref = Registry::xrefFactory()->make(Media::RECORD_TYPE); 780 781 // convert to a media-object 782 $gedcom = '0 @' . $xref . "@ OBJE\n1 FILE " . $file; 783 784 if ($format !== '') { 785 $gedcom .= "\n2 FORM " . $format; 786 787 if ($media !== '') { 788 $gedcom .= "\n3 TYPE " . $media; 789 } 790 } 791 792 if ($title !== '') { 793 $gedcom .= "\n2 TITL " . $title; 794 } 795 796 if ($scrapbook !== '') { 797 $gedcom .= "\n1 _SCBK " . $scrapbook; 798 } 799 800 if ($primary !== '') { 801 $gedcom .= "\n1 _PRIM " . $primary; 802 } 803 804 if ($type !== '') { 805 $gedcom .= "\n1 _TYPE " . $type; 806 } 807 808 foreach ($notes as $note) { 809 $gedcom .= "\n1 NOTE " . strtr($note, ["\n3" => "\n2", "\n4" => "\n2", "\n5" => "\n2"]); 810 } 811 812 DB::table('media')->insert([ 813 'm_id' => $xref, 814 'm_file' => $tree->id(), 815 'm_gedcom' => $gedcom, 816 ]); 817 818 DB::table('media_file')->insert([ 819 'm_id' => $xref, 820 'm_file' => $tree->id(), 821 'multimedia_file_refn' => mb_substr($file, 0, 248), 822 'multimedia_format' => mb_substr($format, 0, 4), 823 'source_media_type' => mb_substr($media, 0, 15), 824 'descriptive_title' => mb_substr($title, 0, 248), 825 ]); 826 } 827 828 return $xref; 829 } 830 831 /** 832 * update a record in the database 833 * 834 * @param string $gedrec 835 * @param Tree $tree 836 * @param bool $delete 837 * 838 * @return void 839 * @throws GedcomErrorException 840 */ 841 public function updateRecord(string $gedrec, Tree $tree, bool $delete): void 842 { 843 if (preg_match('/^0 @(' . Gedcom::REGEX_XREF . ')@ (' . Gedcom::REGEX_TAG . ')/', $gedrec, $match)) { 844 [, $gid, $type] = $match; 845 } elseif (preg_match('/^0 (HEAD)(?:\n|$)/', $gedrec, $match)) { 846 // The HEAD record has no XREF. Any others? 847 $gid = $match[1]; 848 $type = $match[1]; 849 } else { 850 throw new GedcomErrorException($gedrec); 851 } 852 853 // Place links 854 DB::table('placelinks') 855 ->where('pl_gid', '=', $gid) 856 ->where('pl_file', '=', $tree->id()) 857 ->delete(); 858 859 // Orphaned places. If we're deleting "Westminster, London, England", 860 // then we may also need to delete "London, England" and "England". 861 do { 862 $affected = DB::table('places') 863 ->leftJoin('placelinks', function (JoinClause $join): void { 864 $join 865 ->on('p_id', '=', 'pl_p_id') 866 ->on('p_file', '=', 'pl_file'); 867 }) 868 ->whereNull('pl_p_id') 869 ->delete(); 870 } while ($affected > 0); 871 872 DB::table('dates') 873 ->where('d_gid', '=', $gid) 874 ->where('d_file', '=', $tree->id()) 875 ->delete(); 876 877 DB::table('name') 878 ->where('n_id', '=', $gid) 879 ->where('n_file', '=', $tree->id()) 880 ->delete(); 881 882 DB::table('link') 883 ->where('l_from', '=', $gid) 884 ->where('l_file', '=', $tree->id()) 885 ->delete(); 886 887 switch ($type) { 888 case Individual::RECORD_TYPE: 889 DB::table('individuals') 890 ->where('i_id', '=', $gid) 891 ->where('i_file', '=', $tree->id()) 892 ->delete(); 893 break; 894 895 case Family::RECORD_TYPE: 896 DB::table('families') 897 ->where('f_id', '=', $gid) 898 ->where('f_file', '=', $tree->id()) 899 ->delete(); 900 break; 901 902 case Source::RECORD_TYPE: 903 DB::table('sources') 904 ->where('s_id', '=', $gid) 905 ->where('s_file', '=', $tree->id()) 906 ->delete(); 907 break; 908 909 case Media::RECORD_TYPE: 910 DB::table('media_file') 911 ->where('m_id', '=', $gid) 912 ->where('m_file', '=', $tree->id()) 913 ->delete(); 914 915 DB::table('media') 916 ->where('m_id', '=', $gid) 917 ->where('m_file', '=', $tree->id()) 918 ->delete(); 919 break; 920 921 default: 922 DB::table('other') 923 ->where('o_id', '=', $gid) 924 ->where('o_file', '=', $tree->id()) 925 ->delete(); 926 break; 927 } 928 929 if (!$delete) { 930 $this->importRecord($gedrec, $tree, true); 931 } 932 } 933} 934