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