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