xref: /webtrees/app/Services/GedcomEditService.php (revision 6de87b62c2f9ee5ee446e7c23a7efdb096c917fc)
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\Elements\AbstractXrefElement;
23use Fisharebest\Webtrees\Fact;
24use Fisharebest\Webtrees\Family;
25use Fisharebest\Webtrees\Gedcom;
26use Fisharebest\Webtrees\GedcomRecord;
27use Fisharebest\Webtrees\Individual;
28use Fisharebest\Webtrees\Note;
29use Fisharebest\Webtrees\Registry;
30use Fisharebest\Webtrees\Site;
31use Fisharebest\Webtrees\Tree;
32use Illuminate\Support\Collection;
33
34use function array_diff;
35use function array_filter;
36use function array_keys;
37use function array_merge;
38use function array_shift;
39use function array_slice;
40use function array_values;
41use function assert;
42use function count;
43use function explode;
44use function implode;
45use function max;
46use function preg_replace;
47use function preg_split;
48use function str_ends_with;
49use function str_repeat;
50use function str_replace;
51use function str_starts_with;
52use function substr_count;
53use function trim;
54
55use const ARRAY_FILTER_USE_BOTH;
56use const ARRAY_FILTER_USE_KEY;
57use const PHP_INT_MAX;
58
59/**
60 * Utilities to edit/save GEDCOM data.
61 */
62class GedcomEditService
63{
64    /**
65     * @param Tree $tree
66     *
67     * @return Collection<int,Fact>
68     */
69    public function newFamilyFacts(Tree $tree): Collection
70    {
71        $dummy = Registry::familyFactory()->new('', '0 @@ FAM', null, $tree);
72        $tags  = new Collection(explode(',', $tree->getPreference('QUICK_REQUIRED_FAMFACTS')));
73        $facts = $tags->map(fn (string $tag): Fact => $this->createNewFact($dummy, $tag));
74
75        return Fact::sortFacts($facts);
76    }
77
78    /**
79     * @param Tree          $tree
80     * @param string        $sex
81     * @param array<string> $names
82     *
83     * @return Collection<int,Fact>
84     */
85    public function newIndividualFacts(Tree $tree, string $sex, array $names): Collection
86    {
87        $dummy      = Registry::individualFactory()->new('', '0 @@ INDI', null, $tree);
88        $tags       = new Collection(explode(',', $tree->getPreference('QUICK_REQUIRED_FACTS')));
89        $facts      = $tags->map(fn (string $tag): Fact => $this->createNewFact($dummy, $tag));
90        $sex_fact   = new Collection([new Fact('1 SEX ' . $sex, $dummy, '')]);
91        $name_facts = Collection::make($names)->map(static fn (string $gedcom): Fact => new Fact($gedcom, $dummy, ''));
92
93        return $sex_fact->concat($name_facts)->concat(Fact::sortFacts($facts));
94    }
95
96    /**
97     * @param GedcomRecord $record
98     * @param string       $tag
99     *
100     * @return Fact
101     */
102    private function createNewFact(GedcomRecord $record, string $tag): Fact
103    {
104        $element = Registry::elementFactory()->make($record->tag() . ':' . $tag);
105        $default = $element->default($record->tree());
106        $gedcom  = trim('1 ' . $tag . ' ' . $default);
107
108        return new Fact($gedcom, $record, '');
109    }
110
111    /**
112     * Reassemble edited GEDCOM fields into a GEDCOM fact/event string.
113     *
114     * @param string        $record_type
115     * @param array<string> $levels
116     * @param array<string> $tags
117     * @param array<string> $values
118     *
119     * @return string
120     */
121    public function editLinesToGedcom(string $record_type, array $levels, array $tags, array $values): string
122    {
123        // Assert all arrays are the same size.
124        $count = count($levels);
125        assert($count > 0);
126        assert(count($tags) === $count);
127        assert(count($values) === $count);
128
129        $gedcom_lines = [];
130        $hierarchy    = [$record_type];
131
132        for ($i = 0; $i < $count; $i++) {
133            $hierarchy[$levels[$i]] = $tags[$i];
134
135            $full_tag   = implode(':', array_slice($hierarchy, 0, 1 + (int) $levels[$i]));
136            $element    = Registry::elementFactory()->make($full_tag);
137            $values[$i] = $element->canonical($values[$i]);
138
139            // If "1 FACT Y" has a DATE or PLAC, then delete the value of Y
140            if ($levels[$i] === '1' && $values[$i] === 'Y') {
141                for ($j = $i + 1; $j < $count && $levels[$j] > $levels[$i]; ++$j) {
142                    if ($levels[$j] === '2' && ($tags[$j] === 'DATE' || $tags[$j] === 'PLAC') && $values[$j] !== '') {
143                        $values[$i] = '';
144                        break;
145                    }
146                }
147            }
148
149            // Find the next tag at the same level.  Check if any child tags have values.
150            $children_with_values = false;
151            for ($j = $i + 1; $j < $count && $levels[$j] > $levels[$i]; $j++) {
152                if ($values[$j] !== '') {
153                    $children_with_values = true;
154                }
155            }
156
157            if ($values[$i] !== '' || $children_with_values  && !$element instanceof AbstractXrefElement) {
158                if ($values[$i] === '') {
159                    $gedcom_lines[] = $levels[$i] . ' ' . $tags[$i];
160                } else {
161                    // We use CONC for editing NOTE records.
162                    if ($tags[$i] === 'CONC') {
163                        $next_level = (int) $levels[$i];
164                    } else {
165                        $next_level = 1 + (int) $levels[$i];
166                    }
167
168                    $gedcom_lines[] = $levels[$i] . ' ' . $tags[$i] . ' ' . str_replace("\n", "\n" . $next_level . ' CONT ', $values[$i]);
169                }
170            } else {
171                $i = $j - 1;
172            }
173        }
174
175        return implode("\n", $gedcom_lines);
176    }
177
178    /**
179     * Add blank lines, to allow a user to add/edit new values.
180     *
181     * @param Fact $fact
182     * @param bool $include_hidden
183     *
184     * @return string
185     */
186    public function insertMissingFactSubtags(Fact $fact, bool $include_hidden): string
187    {
188        // Merge CONT records onto their parent line.
189        $gedcom = preg_replace('/\n\d CONT ?/', "\r", $fact->gedcom());
190
191        return $this->insertMissingLevels($fact->record()->tree(), $fact->tag(), $gedcom, $include_hidden);
192    }
193
194    /**
195     * Add blank lines, to allow a user to add/edit new values.
196     *
197     * @param GedcomRecord $record
198     * @param bool         $include_hidden
199     *
200     * @return string
201     */
202    public function insertMissingRecordSubtags(GedcomRecord $record, bool $include_hidden): string
203    {
204        // Merge CONT records onto their parent line.
205        $gedcom = preg_replace('/\n\d CONT ?/', "\r", $record->gedcom());
206
207        $gedcom = $this->insertMissingLevels($record->tree(), $record->tag(), $gedcom, $include_hidden);
208
209        // NOTE records have data at level 0.  Move it to 1 CONC.
210        if ($record instanceof Note) {
211            return preg_replace('/^0 @[^@]+@ NOTE/', '1 CONC', $gedcom);
212        }
213
214        return preg_replace('/^0.*\n/', '', $gedcom);
215    }
216
217    /**
218     * List of facts/events to add to families and individuals.
219     *
220     * @param Family|Individual $record
221     * @param bool              $include_hidden
222     *
223     * @return array<string>
224     */
225    public function factsToAdd(GedcomRecord $record, bool $include_hidden): array
226    {
227        $subtags = Registry::elementFactory()->make($record->tag())->subtags();
228
229        $subtags = array_filter($subtags, static fn (string $v, string $k) => !str_ends_with($v, ':1') || $record->facts([$k])->isEmpty(), ARRAY_FILTER_USE_BOTH);
230
231        $subtags = array_keys($subtags);
232
233        // Don't include facts/events that we have hidden in the control panel.
234        $subtags = array_filter($subtags, fn (string $subtag): bool => !$this->isHiddenTag($record->tag() . ':' . $subtag));
235
236        if (!$include_hidden) {
237            $fn_hidden = fn (string $t): bool => !$this->isHiddenTag($record->tag() . ':' . $t);
238            $subtags   = array_filter($subtags, $fn_hidden);
239        }
240
241        return array_diff($subtags, ['HUSB', 'WIFE', 'CHIL', 'FAMC', 'FAMS', 'CHAN']);
242    }
243
244    /**
245     * @param Tree   $tree
246     * @param string $tag
247     * @param string $gedcom
248     * @param bool   $include_hidden
249     *
250     * @return string
251     */
252    protected function insertMissingLevels(Tree $tree, string $tag, string $gedcom, bool $include_hidden): string
253    {
254        $next_level = substr_count($tag, ':') + 1;
255        $factory    = Registry::elementFactory();
256        $subtags    = $factory->make($tag)->subtags();
257
258        // The first part is level N.  The remainder are level N+1.
259        $parts  = preg_split('/\n(?=' . $next_level . ')/', $gedcom);
260        $return = array_shift($parts) ?? '';
261
262        foreach ($subtags as $subtag => $occurrences) {
263            $hidden = str_ends_with($occurrences, ':?') || $this->isHiddenTag($tag . ':' . $subtag);
264
265            if (!$include_hidden && $hidden) {
266                continue;
267            }
268
269            [$min, $max] = explode(':', $occurrences);
270
271            $min = (int) $min;
272
273            if ($max === 'M') {
274                $max = PHP_INT_MAX;
275            } else {
276                $max = (int) $max;
277            }
278
279            $count = 0;
280
281            // Add expected subtags in our preferred order.
282            foreach ($parts as $n => $part) {
283                if (str_starts_with($part, $next_level . ' ' . $subtag)) {
284                    $return .= "\n" . $this->insertMissingLevels($tree, $tag . ':' . $subtag, $part, $include_hidden);
285                    $count++;
286                    unset($parts[$n]);
287                }
288            }
289
290            // Allowed to have more of this subtag?
291            if ($count < $max) {
292                // Create a new one.
293                $gedcom  = $next_level . ' ' . $subtag;
294                $default = $factory->make($tag . ':' . $subtag)->default($tree);
295                if ($default !== '') {
296                    $gedcom .= ' ' . $default;
297                }
298
299                $number_to_add = max(1, $min - $count);
300                $gedcom_to_add = "\n" . $this->insertMissingLevels($tree, $tag . ':' . $subtag, $gedcom, $include_hidden);
301
302                $return .= str_repeat($gedcom_to_add, $number_to_add);
303            }
304        }
305
306        // Now add any unexpected/existing data.
307        if ($parts !== []) {
308            $return .= "\n" . implode("\n", $parts);
309        }
310
311        return $return;
312    }
313
314    /**
315     * List of tags to exclude when creating new data.
316     *
317     * @param string $tag
318     *
319     * @return bool
320     */
321    private function isHiddenTag(string $tag): bool
322    {
323        // Function to filter hidden tags.
324        $fn_hide = static fn (string $x): bool => (bool) Site::getPreference('HIDE_' . $x);
325
326        $preferences = array_filter(Gedcom::HIDDEN_TAGS, $fn_hide, ARRAY_FILTER_USE_KEY);
327        $preferences = array_values($preferences);
328        $hidden_tags = array_merge(...$preferences);
329
330        foreach ($hidden_tags as $hidden_tag) {
331            if (str_contains($tag, $hidden_tag)) {
332                return true;
333            }
334        }
335
336        return false;
337    }
338}
339