xref: /webtrees/app/Http/RequestHandlers/CheckTree.php (revision 58c781b3c055e42036269e115fb5a3c4643b0df4)
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\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\Elements\AbstractXrefElement;
23use Fisharebest\Webtrees\Elements\MultimediaFileReference;
24use Fisharebest\Webtrees\Elements\MultimediaFormat;
25use Fisharebest\Webtrees\Elements\SubmitterText;
26use Fisharebest\Webtrees\Elements\UnknownElement;
27use Fisharebest\Webtrees\Elements\XrefFamily;
28use Fisharebest\Webtrees\Elements\XrefIndividual;
29use Fisharebest\Webtrees\Elements\XrefLocation;
30use Fisharebest\Webtrees\Elements\XrefMedia;
31use Fisharebest\Webtrees\Elements\XrefNote;
32use Fisharebest\Webtrees\Elements\XrefRepository;
33use Fisharebest\Webtrees\Elements\XrefSource;
34use Fisharebest\Webtrees\Elements\XrefSubmission;
35use Fisharebest\Webtrees\Elements\XrefSubmitter;
36use Fisharebest\Webtrees\Factories\ElementFactory;
37use Fisharebest\Webtrees\Factories\ImageFactory;
38use Fisharebest\Webtrees\Family;
39use Fisharebest\Webtrees\Gedcom;
40use Fisharebest\Webtrees\Header;
41use Fisharebest\Webtrees\Http\ViewResponseTrait;
42use Fisharebest\Webtrees\I18N;
43use Fisharebest\Webtrees\Individual;
44use Fisharebest\Webtrees\Location;
45use Fisharebest\Webtrees\Media;
46use Fisharebest\Webtrees\Mime;
47use Fisharebest\Webtrees\Note;
48use Fisharebest\Webtrees\Registry;
49use Fisharebest\Webtrees\Repository;
50use Fisharebest\Webtrees\Services\TimeoutService;
51use Fisharebest\Webtrees\Source;
52use Fisharebest\Webtrees\Submission;
53use Fisharebest\Webtrees\Submitter;
54use Fisharebest\Webtrees\Tree;
55use Fisharebest\Webtrees\Validator;
56use Illuminate\Database\Capsule\Manager as DB;
57use Illuminate\Database\Query\Expression;
58use Psr\Http\Message\ResponseInterface;
59use Psr\Http\Message\ServerRequestInterface;
60use Psr\Http\Server\RequestHandlerInterface;
61
62use function array_key_exists;
63use function array_slice;
64use function e;
65use function implode;
66use function in_array;
67use function preg_match;
68use function route;
69use function str_contains;
70use function str_starts_with;
71use function strtoupper;
72use function substr_count;
73use function var_dump;
74
75/**
76 * Check a tree for errors.
77 */
78class CheckTree implements RequestHandlerInterface
79{
80    use ViewResponseTrait;
81
82    private Gedcom $gedcom;
83
84    private TimeoutService $timeout_service;
85
86    /**
87     * @param Gedcom         $gedcom
88     * @param TimeoutService $timeout_service
89     */
90    public function __construct(Gedcom $gedcom, TimeoutService $timeout_service)
91    {
92        $this->gedcom          = $gedcom;
93        $this->timeout_service = $timeout_service;
94    }
95
96    /**
97     * @param ServerRequestInterface $request
98     *
99     * @return ResponseInterface
100     */
101    public function handle(ServerRequestInterface $request): ResponseInterface
102    {
103        $this->layout = 'layouts/administration';
104
105        $tree    = Validator::attributes($request)->tree();
106        $skip_to = Validator::queryParams($request)->string('skip_to', '');
107
108        // We need to work with raw GEDCOM data, as we are looking for errors
109        // which may prevent the GedcomRecord objects from working.
110
111        $q1 = DB::table('individuals')
112            ->where('i_file', '=', $tree->id())
113            ->select(['i_id AS xref', 'i_gedcom AS gedcom', new Expression("'INDI' AS type")]);
114        $q2 = DB::table('families')
115            ->where('f_file', '=', $tree->id())
116            ->select(['f_id AS xref', 'f_gedcom AS gedcom', new Expression("'FAM' AS type")]);
117        $q3 = DB::table('media')
118            ->where('m_file', '=', $tree->id())
119            ->select(['m_id AS xref', 'm_gedcom AS gedcom', new Expression("'OBJE' AS type")]);
120        $q4 = DB::table('sources')
121            ->where('s_file', '=', $tree->id())
122            ->select(['s_id AS xref', 's_gedcom AS gedcom', new Expression("'SOUR' AS type")]);
123        $q5 = DB::table('other')
124            ->where('o_file', '=', $tree->id())
125            ->select(['o_id AS xref', 'o_gedcom AS gedcom', 'o_type']);
126        $q6 = DB::table('change')
127            ->where('gedcom_id', '=', $tree->id())
128            ->where('status', '=', 'pending')
129            ->orderBy('change_id')
130            ->select(['xref', 'new_gedcom AS gedcom', new Expression("'' AS type")]);
131
132        $rows = $q1
133            ->unionAll($q2)
134            ->unionAll($q3)
135            ->unionAll($q4)
136            ->unionAll($q5)
137            ->unionAll($q6)
138            ->get()
139            ->map(static function (object $row): object {
140                // Extract type for pending record
141                if ($row->type === '' && str_starts_with($row->gedcom, '0 HEAD')) {
142                    $row->type = 'HEAD';
143                }
144
145                if ($row->type === '' && preg_match('/^0 @[^@]*@ ([_A-Z0-9]+)/', $row->gedcom, $match) === 1) {
146                    $row->type = $match[1];
147                }
148
149                return $row;
150            });
151
152        $records = [];
153        $xrefs   = [];
154
155        foreach ($rows as $row) {
156            if ($row->gedcom !== '') {
157                // existing or updated record
158                $records[$row->xref] = $row;
159            } else {
160                // deleted record
161                unset($records[$row->xref]);
162            }
163
164            $xrefs[strtoupper($row->xref)] = $row->xref;
165        }
166
167        unset($rows);
168
169        $errors   = [];
170        $warnings = [];
171        $infos    = [];
172
173        $element_factory = new ElementFactory();
174        $this->gedcom->registerTags($element_factory, false);
175
176        foreach ($records as $record) {
177            // If we are nearly out of time, then stop processing here
178            if ($skip_to === $record->xref) {
179                $skip_to = '';
180            } elseif ($skip_to !== '') {
181                continue;
182            } elseif ($this->timeout_service->isTimeNearlyUp()) {
183                $skip_to = $record->xref;
184                break;
185            }
186
187            $lines = explode("\n", $record->gedcom);
188            array_shift($lines);
189
190            $last_level = 0;
191            $hierarchy  = [$record->type];
192
193            foreach ($lines as $line_number => $line) {
194                if (preg_match('/^(\d+) (\w+) ?(.*)/', $line, $match) !== 1) {
195                    $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, I18N::translate('Invalid GEDCOM record.'));
196                    break;
197                }
198
199                $level = (int) $match[1];
200                if ($level > $last_level + 1) {
201                    $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, I18N::translate('Invalid GEDCOM level number.'));
202                    break;
203                }
204
205                $tag               = $match[2];
206                $value             = $match[3];
207                $hierarchy[$level] = $tag;
208                $full_tag          = implode(':', array_slice($hierarchy, 0, 1 + $level));
209                $element           = $element_factory->make($full_tag);
210                $last_level        = $level;
211
212                if ($tag === 'CONT') {
213                    $element = new SubmitterText('CONT');
214                }
215
216                if ($element instanceof UnknownElement) {
217                    if (str_starts_with($tag, '_') || str_starts_with($full_tag, '_') || str_contains($full_tag, ':_')) {
218                        $message    = I18N::translate('Custom GEDCOM tags are discouraged. Try to use only standard GEDCOM tags.');
219                        $warnings[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
220                    } else {
221                        $message  = I18N::translate('Invalid GEDCOM tag.') . ' ' . $full_tag;
222                        $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
223                    }
224                } elseif ($element instanceof AbstractXrefElement) {
225                    if (preg_match('/@(' . Gedcom::REGEX_XREF . ')@/', $value, $match) === 1) {
226                        $xref1  = $match[1];
227                        $xref2  = $xrefs[strtoupper($xref1)] ?? null;
228                        $linked = $records[$xref2] ?? null;
229
230                        if ($linked === null) {
231                            $message  = I18N::translate('%s does not exist.', e($xref1));
232                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
233                        } elseif ($element instanceof XrefFamily && $linked->type !== Family::RECORD_TYPE) {
234                            $message  = $this->linkErrorMessage($tree, $xref1, $linked->type, Family::RECORD_TYPE);
235                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
236                        } elseif ($element instanceof XrefIndividual && $linked->type !== Individual::RECORD_TYPE) {
237                            $message  = $this->linkErrorMessage($tree, $xref1, $linked->type, Individual::RECORD_TYPE);
238                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
239                        } elseif ($element instanceof XrefMedia && $linked->type !== Media::RECORD_TYPE) {
240                            $message  = $this->linkErrorMessage($tree, $xref1, $linked->type, Media::RECORD_TYPE);
241                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
242                        } elseif ($element instanceof XrefNote && $linked->type !== Note::RECORD_TYPE) {
243                            $message  = $this->linkErrorMessage($tree, $xref1, $linked->type, Note::RECORD_TYPE);
244                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
245                        } elseif ($element instanceof XrefSource && $linked->type !== Source::RECORD_TYPE) {
246                            $message  = $this->linkErrorMessage($tree, $xref1, $linked->type, Source::RECORD_TYPE);
247                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
248                        } elseif ($element instanceof XrefRepository && $linked->type !== Repository::RECORD_TYPE) {
249                            $message  = $this->linkErrorMessage($tree, $xref1, $linked->type, Repository::RECORD_TYPE);
250                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
251                        } elseif ($element instanceof XrefSubmitter && $linked->type !== Submitter::RECORD_TYPE) {
252                            $message  = $this->linkErrorMessage($tree, $xref1, $linked->type, Submitter::RECORD_TYPE);
253                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
254                        } elseif ($element instanceof XrefSubmission && $linked->type !== Submission::RECORD_TYPE) {
255                            $message  = $this->linkErrorMessage($tree, $xref1, $linked->type, Submission::RECORD_TYPE);
256                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
257                        } elseif ($element instanceof XrefLocation && $linked->type !== Location::RECORD_TYPE) {
258                            $message  = $this->linkErrorMessage($tree, $xref1, $linked->type, Location::RECORD_TYPE);
259                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
260                        } elseif (($full_tag === 'FAM:HUSB' || $full_tag === 'FAM:WIFE') && !str_contains($linked->gedcom, "\n1 FAMS @" . $record->xref . '@')) {
261                            $link1    = $this->recordLink($tree, $linked->xref);
262                            $link2    = $this->recordLink($tree, $record->xref);
263                            $message  = I18N::translate('%1$s does not have a link back to %2$s.', $link1, $link2);
264                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
265                        } elseif ($full_tag === 'FAM:CHIL' && !str_contains($linked->gedcom, "\n1 FAMC @" . $record->xref . '@')) {
266                            $link1    = $this->recordLink($tree, $linked->xref);
267                            $link2    = $this->recordLink($tree, $record->xref);
268                            $message  = I18N::translate('%1$s does not have a link back to %2$s.', $link1, $link2);
269                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
270                        } elseif ($full_tag === 'INDI:FAMC' && !str_contains($linked->gedcom, "\n1 CHIL @" . $record->xref . '@')) {
271                            $link1    = $this->recordLink($tree, $linked->xref);
272                            $link2    = $this->recordLink($tree, $record->xref);
273                            $message  = I18N::translate('%1$s does not have a link back to %2$s.', $link1, $link2);
274                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
275                        } elseif ($full_tag === 'INDI:FAMS' && !str_contains($linked->gedcom, "\n1 HUSB @" . $record->xref . '@') && !str_contains($linked->gedcom, "\n1 WIFE @" . $record->xref . '@')) {
276                            $link1    = $this->recordLink($tree, $linked->xref);
277                            $link2    = $this->recordLink($tree, $record->xref);
278                            $message  = I18N::translate('%1$s does not have a link back to %2$s.', $link1, $link2);
279                            $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
280                        } elseif ($xref1 !== $xref2) {
281                            $message    = I18N::translate('%1$s does not exist. Did you mean %2$s?', e($xref1), e($xref2));
282                            $warnings[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
283                        }
284                    } elseif ($tag === 'SOUR') {
285                        $message    = I18N::translate('Inline-source records are discouraged.');
286                        $warnings[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
287                    } else {
288                        $message  = I18N::translate('Invalid GEDCOM value.');
289                        $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
290                    }
291                } elseif ($element->canonical($value) !== $value) {
292                    $expected = e($element->canonical($value));
293                    $actual   = strtr(e($value), ["\t" => '&rarr;']);
294                    $message  = I18N::translate('“%1$s” should be “%2$s”.', $actual, $expected);
295                    if (strtoupper($element->canonical($value)) !== strtoupper($value)) {
296                        // This will be relevant for GEDCOM 7.0.  It's not relevant now, and causes confusion.
297                        $infos[]  = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
298                    }
299                } elseif ($element instanceof MultimediaFormat) {
300                    $mime = Mime::TYPES[$value] ?? Mime::DEFAULT_TYPE;
301
302                    if ($mime === Mime::DEFAULT_TYPE) {
303                        $message    = I18N::translate('webtrees does not recognise this file format.');
304                        $warnings[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
305                    } elseif (str_starts_with($mime, 'image/') && !array_key_exists($mime, ImageFactory::SUPPORTED_FORMATS)) {
306                        $message    = I18N::translate('webtrees cannot create thumbnails for this file format.');
307                        $warnings[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
308                    }
309                } elseif ($element instanceof MultimediaFileReference && $value === 'gedcom.ged') {
310                    $message  = I18N::translate('This filename is not compatible with the GEDZIP file format.');
311                    $errors[] = $this->lineError($tree, $record->type, $record->xref, $line_number, $line, $message);
312                }
313            }
314
315            if ($record->type === Family::RECORD_TYPE) {
316                if (substr_count($record->gedcom, "\n1 HUSB @") > 1) {
317                    $message  = I18N::translate('%s occurs too many times.', 'FAM:HUSB');
318                    $errors[] = $this->recordError($tree, $record->type, $record->xref, $message);
319                }
320                if (substr_count($record->gedcom, "\n1 WIFE @") > 1) {
321                    $message  = I18N::translate('%s occurs too many times.', 'FAM:WIFE');
322                    $errors[] = $this->recordError($tree, $record->type, $record->xref, $message);
323                }
324            }
325        }
326
327        $title = I18N::translate('Check for errors') . ' — ' . e($tree->title());
328
329        if ($skip_to === '') {
330            $more_url = '';
331        } else {
332            $more_url = route(self::class, ['tree' => $tree->name(), 'skip_to' => $skip_to]);
333        }
334
335        return $this->viewResponse('admin/trees-check', [
336            'errors'   => $errors,
337            'infos'    => $infos,
338            'more_url' => $more_url,
339            'title'    => $title,
340            'tree'     => $tree,
341            'warnings' => $warnings,
342        ]);
343    }
344
345    /**
346     * @param string $type
347     *
348     * @return string
349     */
350    private function recordType(string $type): string
351    {
352        $types = [
353            Family::RECORD_TYPE     => I18N::translate('Family'),
354            Header::RECORD_TYPE     => I18N::translate('Header'),
355            Individual::RECORD_TYPE => I18N::translate('Individual'),
356            Location::RECORD_TYPE   => I18N::translate('Location'),
357            Media::RECORD_TYPE      => I18N::translate('Media object'),
358            Note::RECORD_TYPE       => I18N::translate('Note'),
359            Repository::RECORD_TYPE => I18N::translate('Repository'),
360            Source::RECORD_TYPE     => I18N::translate('Source'),
361            Submission::RECORD_TYPE => I18N::translate('Submission'),
362            Submitter::RECORD_TYPE  => I18N::translate('Submitter'),
363        ];
364
365        return $types[$type] ?? e($type);
366    }
367
368    /**
369     * @param Tree   $tree
370     * @param string $xref
371     *
372     * @return string
373     */
374    private function recordLink(Tree $tree, string $xref): string
375    {
376        $url = route(GedcomRecordPage::class, ['xref' => $xref, 'tree' => $tree->name()]);
377
378        return '<a href="' . e($url) . '">' . e($xref) . '</a>';
379    }
380
381    /**
382     * Format a link to a record.
383     *
384     * @param Tree   $tree
385     * @param string $type
386     * @param string $xref
387     * @param int    $line_number
388     * @param string $line
389     * @param string $message
390     *
391     * @return string
392     */
393    private function lineError(Tree $tree, string $type, string $xref, int $line_number, string $line, string $message): string
394    {
395        return
396            I18N::translate('%1$s: %2$s', $this->recordType($type), $this->recordLink($tree, $xref)) .
397            ' — ' .
398            I18N::translate('%1$s: %2$s', I18N::translate('Line number'), I18N::number($line_number)) .
399            ' — ' .
400            '<code>' . e($line) . '</code>' .
401            '<br>' . $message;
402    }
403
404    /**
405     * Format a link to a record.
406     *
407     * @param Tree   $tree
408     * @param string $type
409     * @param string $xref
410     * @param string $message
411     *
412     * @return string
413     */
414    private function recordError(Tree $tree, string $type, string $xref, string $message): string
415    {
416        return I18N::translate('%1$s: %2$s', $this->recordType($type), $this->recordLink($tree, $xref)) . ' — ' . $message;
417    }
418
419    /**
420     * @param Tree   $tree
421     * @param string $xref
422     * @param string $type1
423     * @param string $type2
424     *
425     * @return string
426     */
427    private function linkErrorMessage(Tree $tree, string $xref, string $type1, string $type2): string
428    {
429        $link  = $this->recordLink($tree, $xref);
430        $type1 = $this->recordType($type1);
431        $type2 = $this->recordType($type2);
432
433        return I18N::translate('%1$s is a %2$s but a %3$s is expected.', $link, $type1, $type2);
434    }
435}
436