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