xref: /webtrees/app/Services/GedcomService.php (revision 06f42609e3f1764a2e55be21f0ce941f29f42167)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22/**
23 * Utilities for manipulating GEDCOM data.
24 */
25class GedcomService
26{
27    // Gedcom allows 255 characters (not bytes), including the EOL character.
28    private const EOL         = "\r\n";
29    private const EOL_REGEX   = '\r|\r\n|\n|\n\r';
30    private const LINE_LENGTH = 255 - 2;
31
32
33    // User defined tags begin with an underscore
34    private const USER_DEFINED_TAG_PREFIX = '_';
35
36    // Some applications, such as FTM, use GEDCOM tag names instead of the tags.
37    private const TAG_NAMES = [
38        'ABBREVIATION'      => 'ABBR',
39        'ADDRESS'           => 'ADDR',
40        'ADDRESS1'          => 'ADR1',
41        'ADDRESS2'          => 'ADR2',
42        'ADOPTION'          => 'ADOP',
43        'AFN'               => 'AFN',
44        'AGE'               => 'AGE',
45        'AGENCY'            => 'AGNC',
46        'ALIAS'             => 'ALIA',
47        'ANCESTORS'         => 'ANCE',
48        'ANCES_INTEREST'    => 'ANCI',
49        'ANULMENT'          => 'ANUL',
50        'ASSOCIATES'        => 'ASSO',
51        'AUTHOR'            => 'AUTH',
52        'BAPTISM-LDS'       => 'BAPL',
53        'BAPTISM'           => 'BAPM',
54        'BAR_MITZVAH'       => 'BARM',
55        'BAS_MITZVAH'       => 'BASM',
56        'BIRTH'             => 'BIRT',
57        'BLESSING'          => 'BLES',
58        'BURIAL'            => 'BURI',
59        'CALL_NUMBER'       => 'CALN',
60        'CASTE'             => 'CAST',
61        'CAUSE'             => 'CAUS',
62        'CENSUS'            => 'CENS',
63        'CHANGE'            => 'CHAN',
64        'CHARACTER'         => 'CHAR',
65        'CHILD'             => 'CHIL',
66        'CHRISTENING'       => 'CHR',
67        'ADULT_CHRISTENING' => 'CHRA',
68        'CITY'              => 'CITY',
69        'CONCATENATION'     => 'CONC',
70        'CONFIRMATION'      => 'CONF',
71        'CONFIRMATION-LDS'  => 'CONL',
72        'CONTINUED'         => 'CONT',
73        'COPYRIGHT'         => 'COPY',
74        'CORPORTATE'        => 'CORP',
75        'CREMATION'         => 'CREM',
76        'COUNTRY'           => 'CTRY',
77        'DATA'              => 'DATA',
78        'DATE'              => 'DATE',
79        'DEATH'             => 'DEAT',
80        'DESCENDANTS'       => 'DESC',
81        'DESCENDANTS_INT'   => 'DESI',
82        'DESTINATION'       => 'DEST',
83        'DIVORCE'           => 'DIV',
84        'DIVORCE_FILED'     => 'DIVF',
85        'PHY_DESCRIPTION'   => 'DSCR',
86        'EDUCATION'         => 'EDUC',
87        'EMAIL'             => 'EMAI',
88        'EMIGRATION'        => 'EMIG',
89        'ENDOWMENT'         => 'ENDL',
90        'ENGAGEMENT'        => 'ENGA',
91        'EVENT'             => 'EVEN',
92        'FACT'              => 'FACT',
93        'FAMILY'            => 'FAM',
94        'FAMILY_CHILD'      => 'FAMC',
95        'FAMILY_FILE'       => 'FAMF',
96        'FAMILY_SPOUSE'     => 'FAMS',
97        'FACIMILIE'         => 'FAX',
98        'FIRST_COMMUNION'   => 'FCOM',
99        'FILE'              => 'FILE',
100        'FORMAT'            => 'FORM',
101        'PHONETIC'          => 'FONE',
102        'GEDCOM'            => 'GEDC',
103        'GIVEN_NAME'        => 'GIVN',
104        'GRADUATION'        => 'GRAD',
105        'HEADER'            => 'HEAD',
106        'HUSBAND'           => 'HUSB',
107        'IDENT_NUMBER'      => 'IDNO',
108        'IMMIGRATION'       => 'IMMI',
109        'INDIVIDUAL'        => 'INDI',
110        'LANGUAGE'          => 'LANG',
111        'LATITUDE'          => 'LATI',
112        'LONGITUDE'         => 'LONG',
113        'MAP'               => 'MAP',
114        'MARRIAGE_BANN'     => 'MARB',
115        'MARR_CONTRACT'     => 'MARC',
116        'MARR_LICENSE'      => 'MARL',
117        'MARRIAGE'          => 'MARR',
118        'MEDIA'             => 'MEDI',
119        'NAME'              => 'NAME',
120        'NATIONALITY'       => 'NATI',
121        'NATURALIZATION'    => 'NATU',
122        'CHILDREN_COUNT'    => 'NCHI',
123        'NICKNAME'          => 'NICK',
124        'MARRIAGE_COUNT'    => 'NMR',
125        'NOTE'              => 'NOTE',
126        'NAME_PREFIX'       => 'NPFX',
127        'NAME_SUFFIX'       => 'NSFX',
128        'OBJECT'            => 'OBJE',
129        'OCCUPATION'        => 'OCCU',
130        'ORDINANCE'         => 'ORDI',
131        'ORDINATION'        => 'ORDN',
132        'PAGE'              => 'PAGE',
133        'PEDIGREE'          => 'PEDI',
134        'PHONE'             => 'PHON',
135        'PLACE'             => 'PLAC',
136        'POSTAL_CODE'       => 'POST',
137        'PROBATE'           => 'PROB',
138        'PROPERTY'          => 'PROP',
139        'PUBLICATION'       => 'PUBL',
140        'QUALITY_OF_DATA'   => 'QUAY',
141        'REFERENCE'         => 'REFN',
142        'RELATIONSHIP'      => 'RELA',
143        'RELIGION'          => 'RELI',
144        'REPOSITORY'        => 'REPO',
145        'RESIDENCE'         => 'RESI',
146        'RESTRICTION'       => 'RESN',
147        'RETIREMENT'        => 'RETI',
148        'REC_FILE_NUMBER'   => 'RFN',
149        'REC_ID_NUMBER'     => 'RIN',
150        'ROLE'              => 'ROLE',
151        'ROMANIZED'         => 'ROMN',
152        'SEALING_CHILD'     => 'SLGC',
153        'SEALING_SPOUSE'    => 'SLGS',
154        'SEX'               => 'SEX',
155        'SOURCE'            => 'SOUR',
156        'SURN_PREFIX'       => 'SPFX',
157        'SOC_SEC_NUMBER'    => 'SSN',
158        'STATE'             => 'STAE',
159        'STATUS'            => 'STAT',
160        'SUBMITTER'         => 'SUBM',
161        'SUBMISSION'        => 'SUBN',
162        'SURNAME'           => 'SURN',
163        'TEMPLE'            => 'TEMP',
164        'TEXT'              => 'TEXT',
165        'TIME'              => 'TIME',
166        'TITLE'             => 'TITL',
167        'TRAILER'           => 'TRLR',
168        'TYPE'              => 'TYPE',
169        'VERSION'           => 'VERS',
170        'WIFE'              => 'WIFE',
171        'WILL'              => 'WILL',
172        'WEB'               => 'WWW',
173        '_DEATH_OF_SPOUSE'  => 'DETS',
174        '_DEGREE'           => '_DEG',
175        '_FILE'             => 'FILE',
176        '_MEDICAL'          => '_MCL',
177        '_MILITARY_SERVICE' => '_MILT',
178    ];
179
180    // Custom tags used by other applications, with direct synonyms
181    private const TAG_SYNONYMS = [
182    ];
183
184    // LATI and LONG tags
185    private const DEGREE_FORMAT  = ' % .5f%s';
186    private const LATITUDE_NORTH = 'N';
187    private const LATITUDE_SOUTH = 'S';
188    private const LONGITUDE_EAST = 'E';
189    private const LONGITUDE_WEST = 'W';
190
191    // PLAC tags
192    private const PLACE_SEPARATOR       = ', ';
193    private const PLACE_SEPARATOR_REGEX = ' *, *';
194
195    // SEX tags
196    private const SEX_FEMALE  = 'F';
197    private const SEX_MALE    = 'M';
198    private const SEX_UNKNOWN = 'U';
199
200    /**
201     * Convert a GEDCOM tag to a canonical form.
202     *
203     * @param string $tag
204     *
205     * @return string
206     */
207    public function canonicalTag(string $tag): string
208    {
209        $tag = strtoupper($tag);
210
211        $tag = self::TAG_NAMES[$tag] ?? self::TAG_SYNONYMS[$tag] ?? $tag;
212
213        return $tag;
214    }
215
216    /**
217     * @param string $tag
218     *
219     * @return bool
220     */
221    public function isUserDefinedTag(string $tag): bool
222    {
223        return substr_compare($tag, self::USER_DEFINED_TAG_PREFIX, 0, 1) === 0;
224    }
225
226    /**
227     * @param string $text
228     *
229     * @return float
230     */
231    public function readLatitude(string $text): float
232    {
233        return $this->readDegrees($text, self::LATITUDE_NORTH, self::LATITUDE_SOUTH);
234    }
235
236    /**
237     * @param string $text
238     *
239     * @return float
240     */
241    public function readLongitude(string $text): float
242    {
243        return $this->readDegrees($text, self::LONGITUDE_EAST, self::LONGITUDE_WEST);
244    }
245
246    /**
247     * @param string $text
248     * @param string $positive
249     * @param string $negative
250     *
251     * @return float
252     */
253    private function readDegrees(string $text, string $positive, string $negative): float
254    {
255        $text       = trim($text);
256        $hemisphere = substr($text, 0, 1);
257        $degrees    = substr($text, 1);
258
259        // Match a valid GEDCOM format
260        if (is_numeric($degrees)) {
261            $hemisphere = strtoupper($hemisphere);
262            $degrees    = (float) $degrees;
263
264            if ($hemisphere === $positive) {
265                return $degrees;
266            }
267
268            if ($hemisphere === $negative) {
269                return -$degrees;
270            }
271        }
272
273        // Just a number?
274        if (is_numeric($text)) {
275            return (float) $text;
276        }
277
278        // Can't match anything.
279        return 0.0;
280    }
281
282    /**
283     * @param float $latitude
284     *
285     * @return string
286     */
287    public function writeLatitude(float $latitude): string
288    {
289        return $this->writeDegrees($latitude, self::LATITUDE_NORTH, self::LATITUDE_SOUTH);
290    }
291
292    /**
293     * @param float $longitude
294     *
295     * @return string
296     */
297    public function writeLongitude(float $longitude): string
298    {
299        return $this->writeDegrees($longitude, self::LONGITUDE_EAST, self::LONGITUDE_WEST);
300    }
301
302    /**
303     * @param float  $degrees
304     * @param string $positive
305     * @param string $negative
306     *
307     * @return string
308     */
309    private function writeDegrees(float $degrees, string $positive, string $negative): string
310    {
311        if ($degrees < 0.0) {
312            return sprintf(self::DEGREE_FORMAT, $degrees, $negative);
313        }
314
315        return sprintf(self::DEGREE_FORMAT, $degrees, $positive);
316    }
317
318    /**
319     * Although empty placenames are valid "Town, , Country", it is only meaningful
320     * when structured places are used (PLAC:FORM town, county, country), and
321     * structured places are discouraged.
322     *
323     * @param string $text
324     *
325     * @return string[]
326     */
327    public function readPlace(string $text): array
328    {
329        $text = trim($text);
330
331        return preg_split(self::PLACE_SEPARATOR_REGEX, $text, PREG_SPLIT_NO_EMPTY);
332    }
333
334    /**
335     * @param string[] $place
336     *
337     * @return string
338     */
339    public function writePlace(array $place): string
340    {
341        return implode(self::PLACE_SEPARATOR, $place);
342    }
343
344    /**
345     * Some applications use non-standard values for unknown.
346     *
347     * @param string $text
348     *
349     * @return string
350     */
351    public function readSex(string $text): string
352    {
353        $text = strtoupper($text);
354
355        if ($text !== self::SEX_MALE && $text !== self::SEX_FEMALE) {
356            $text = self::SEX_UNKNOWN;
357        }
358
359        return $text;
360    }
361}
362