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