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