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