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