xref: /webtrees/app/Report/ReportParserGenerate.php (revision b112142ef0330ffced39153e5d475e1ea4f936ae)
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\Report;
21
22use DomainException;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Date;
25use Fisharebest\Webtrees\Elements\UnknownElement;
26use Fisharebest\Webtrees\Factories\MarkdownFactory;
27use Fisharebest\Webtrees\Family;
28use Fisharebest\Webtrees\Gedcom;
29use Fisharebest\Webtrees\GedcomRecord;
30use Fisharebest\Webtrees\I18N;
31use Fisharebest\Webtrees\Individual;
32use Fisharebest\Webtrees\Log;
33use Fisharebest\Webtrees\MediaFile;
34use Fisharebest\Webtrees\Note;
35use Fisharebest\Webtrees\Place;
36use Fisharebest\Webtrees\Registry;
37use Fisharebest\Webtrees\Tree;
38use Illuminate\Database\Capsule\Manager as DB;
39use Illuminate\Database\Query\Builder;
40use Illuminate\Database\Query\Expression;
41use Illuminate\Database\Query\JoinClause;
42use Illuminate\Support\Str;
43use League\Flysystem\FilesystemOperator;
44use LogicException;
45use Symfony\Component\Cache\Adapter\NullAdapter;
46use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
47use XMLParser;
48
49use function addcslashes;
50use function addslashes;
51use function array_pop;
52use function array_shift;
53use function assert;
54use function call_user_func;
55use function count;
56use function end;
57use function explode;
58use function file;
59use function file_exists;
60use function getimagesize;
61use function imagecreatefromstring;
62use function imagesx;
63use function imagesy;
64use function in_array;
65use function method_exists;
66use function preg_match;
67use function preg_match_all;
68use function preg_replace;
69use function preg_replace_callback;
70use function preg_split;
71use function reset;
72use function round;
73use function sprintf;
74use function str_contains;
75use function str_replace;
76use function str_starts_with;
77use function strip_tags;
78use function strlen;
79use function strtoupper;
80use function substr;
81use function trim;
82use function uasort;
83use function xml_error_string;
84use function xml_get_current_line_number;
85use function xml_get_error_code;
86use function xml_parse;
87use function xml_parser_create;
88use function xml_parser_free;
89use function xml_parser_set_option;
90use function xml_set_character_data_handler;
91use function xml_set_element_handler;
92
93use const PREG_SET_ORDER;
94use const XML_OPTION_CASE_FOLDING;
95
96/**
97 * Class ReportParserGenerate - parse a report.xml file and generate the report.
98 */
99class ReportParserGenerate extends ReportParserBase
100{
101    /** @var bool Are we collecting data from <Footnote> elements */
102    private $process_footnote = true;
103
104    /** @var bool Are we currently outputing data? */
105    private $print_data = false;
106
107    /** @var bool[] Push-down stack of $print_data */
108    private $print_data_stack = [];
109
110    /** @var int Are we processing GEDCOM data */
111    private $process_gedcoms = 0;
112
113    /** @var int Are we processing conditionals */
114    private $process_ifs = 0;
115
116    /** @var int Are we processing repeats */
117    private $process_repeats = 0;
118
119    /** @var int Quantity of data to repeat during loops */
120    private $repeat_bytes = 0;
121
122    /** @var array<string> Repeated data when iterating over loops */
123    private array $repeats = [];
124
125    /** @var array<int,array<int,array<string>|int>> Nested repeating data */
126    private array $repeats_stack = [];
127
128    /** @var array<AbstractRenderer> Nested repeating data */
129    private array $wt_report_stack = [];
130
131    // Nested repeating data
132    private XMLParser $parser;
133
134    /** @var XMLParser[] (resource[] before PHP 8.0) Nested repeating data */
135    private array $parser_stack = [];
136
137    /** @var string The current GEDCOM record */
138    private $gedrec = '';
139
140    /** @var array<string> Nested GEDCOM records */
141    private array $gedrec_stack = [];
142
143    /** @var ReportBaseElement The currently processed element */
144    private $current_element;
145
146    /** @var ReportBaseElement The currently processed element */
147    private $footnote_element;
148
149    /** @var string The GEDCOM fact currently being processed */
150    private $fact = '';
151
152    /** @var string The GEDCOM value currently being processed */
153    private $desc = '';
154
155    /** @var string The GEDCOM type currently being processed */
156    private $type = '';
157
158    /** @var int The current generational level */
159    private $generation = 1;
160
161    /** @var array<static|GedcomRecord> Source data for processing lists */
162    private array $list = [];
163
164    /** @var int Number of items in lists */
165    private $list_total = 0;
166
167    /** @var int Number of items filtered from lists */
168    private $list_private = 0;
169
170    /** @var string The filename of the XML report */
171    protected $report;
172
173    /** @var AbstractRenderer A factory for creating report elements */
174    private $report_root;
175
176    /** @var AbstractRenderer Nested report elements */
177    private $wt_report;
178
179    /** @var array<array<string>> Variables defined in the report at run-time */
180    private array $vars;
181
182    private Tree $tree;
183
184    /**
185     * Create a parser for a report
186     *
187     * @param string               $report The XML filename
188     * @param AbstractRenderer     $report_root
189     * @param array<array<string>> $vars
190     * @param Tree                 $tree
191     */
192    public function __construct(string $report, AbstractRenderer $report_root, array $vars, Tree $tree)
193    {
194        $this->report          = $report;
195        $this->report_root     = $report_root;
196        $this->wt_report       = $report_root;
197        $this->current_element = new ReportBaseElement();
198        $this->vars            = $vars;
199        $this->tree            = $tree;
200
201        parent::__construct($report);
202    }
203
204    /**
205     * get a gedcom subrecord
206     *
207     * searches a gedcom record and returns a subrecord of it. A subrecord is defined starting at a
208     * line with level N and all subsequent lines greater than N until the next N level is reached.
209     * For example, the following is a BIRT subrecord:
210     * <code>1 BIRT
211     * 2 DATE 1 JAN 1900
212     * 2 PLAC Phoenix, Maricopa, Arizona</code>
213     * The following example is the DATE subrecord of the above BIRT subrecord:
214     * <code>2 DATE 1 JAN 1900</code>
215     *
216     * @param int    $level   the N level of the subrecord to get
217     * @param string $tag     a gedcom tag or string to search for in the record (ie 1 BIRT or 2 DATE)
218     * @param string $gedrec  the parent gedcom record to search in
219     * @param int    $num     this allows you to specify which matching <var>$tag</var> to get. Oftentimes a
220     *                        gedcom record will have more that 1 of the same type of subrecord. An individual may have
221     *                        multiple events for example. Passing $num=1 would get the first 1. Passing $num=2 would get the
222     *                        second one, etc.
223     *
224     * @return string the subrecord that was found or an empty string "" if not found.
225     */
226    public static function getSubRecord(int $level, string $tag, string $gedrec, int $num = 1): string
227    {
228        if ($gedrec === '') {
229            return '';
230        }
231        // -- adding \n before and after gedrec
232        $gedrec       = "\n" . $gedrec . "\n";
233        $tag          = trim($tag);
234        $searchTarget = "~[\n]" . $tag . "[\s]~";
235        $ct           = preg_match_all($searchTarget, $gedrec, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
236        if ($ct === 0) {
237            return '';
238        }
239        if ($ct < $num) {
240            return '';
241        }
242        $pos1 = $match[$num - 1][0][1];
243        $pos2 = strpos($gedrec, "\n$level", $pos1 + 1);
244        if (!$pos2) {
245            $pos2 = strpos($gedrec, "\n1", $pos1 + 1);
246        }
247        if (!$pos2) {
248            $pos2 = strpos($gedrec, "\nWT_", $pos1 + 1); // WT_SPOUSE, WT_FAMILY_ID ...
249        }
250        if (!$pos2) {
251            return ltrim(substr($gedrec, $pos1));
252        }
253        $subrec = substr($gedrec, $pos1, $pos2 - $pos1);
254
255        return ltrim($subrec);
256    }
257
258    /**
259     * get CONT lines
260     *
261     * get the N+1 CONT or CONC lines of a gedcom subrecord
262     *
263     * @param int    $nlevel the level of the CONT lines to get
264     * @param string $nrec   the gedcom subrecord to search in
265     *
266     * @return string a string with all CONT lines merged
267     */
268    public static function getCont(int $nlevel, string $nrec): string
269    {
270        $text = '';
271
272        $subrecords = explode("\n", $nrec);
273        foreach ($subrecords as $thisSubrecord) {
274            if (substr($thisSubrecord, 0, 2) !== $nlevel . ' ') {
275                continue;
276            }
277            $subrecordType = substr($thisSubrecord, 2, 4);
278            if ($subrecordType === 'CONT') {
279                $text .= "\n" . substr($thisSubrecord, 7);
280            }
281        }
282
283        return $text;
284    }
285
286    /**
287     * XML start element handler
288     * This function is called whenever a starting element is reached
289     * The element handler will be called if found, otherwise it must be HTML
290     *
291     * @param resource      $parser the resource handler for the XML parser
292     * @param string        $name   the name of the XML element parsed
293     * @param array<string> $attrs  an array of key value pairs for the attributes
294     *
295     * @return void
296     */
297    protected function startElement($parser, string $name, array $attrs): void
298    {
299        $newattrs = [];
300
301        foreach ($attrs as $key => $value) {
302            if (preg_match("/^\\$(\w+)$/", $value, $match)) {
303                if (isset($this->vars[$match[1]]['id']) && !isset($this->vars[$match[1]]['gedcom'])) {
304                    $value = $this->vars[$match[1]]['id'];
305                }
306            }
307            $newattrs[$key] = $value;
308        }
309        $attrs = $newattrs;
310        if ($this->process_footnote && ($this->process_ifs === 0 || $name === 'if') && ($this->process_gedcoms === 0 || $name === 'Gedcom') && ($this->process_repeats === 0 || $name === 'Facts' || $name === 'RepeatTag')) {
311            $method = $name . 'StartHandler';
312
313            if (method_exists($this, $method)) {
314                call_user_func([$this, $method], $attrs);
315            }
316        }
317    }
318
319    /**
320     * XML end element handler
321     * This function is called whenever an ending element is reached
322     * The element handler will be called if found, otherwise it must be HTML
323     *
324     * @param resource $parser the resource handler for the XML parser
325     * @param string   $name   the name of the XML element parsed
326     *
327     * @return void
328     */
329    protected function endElement($parser, string $name): void
330    {
331        if (($this->process_footnote || $name === 'Footnote') && ($this->process_ifs === 0 || $name === 'if') && ($this->process_gedcoms === 0 || $name === 'Gedcom') && ($this->process_repeats === 0 || $name === 'Facts' || $name === 'RepeatTag' || $name === 'List' || $name === 'Relatives')) {
332            $method = $name . 'EndHandler';
333
334            if (method_exists($this, $method)) {
335                call_user_func([$this, $method]);
336            }
337        }
338    }
339
340    /**
341     * XML character data handler
342     *
343     * @param resource $parser the resource handler for the XML parser
344     * @param string   $data   the name of the XML element parsed
345     *
346     * @return void
347     */
348    protected function characterData($parser, string $data): void
349    {
350        if ($this->print_data && $this->process_gedcoms === 0 && $this->process_ifs === 0 && $this->process_repeats === 0) {
351            $this->current_element->addText($data);
352        }
353    }
354
355    /**
356     * Handle <style>
357     *
358     * @param array<string> $attrs
359     *
360     * @return void
361     */
362    protected function styleStartHandler(array $attrs): void
363    {
364        if (empty($attrs['name'])) {
365            throw new DomainException('REPORT ERROR Style: The "name" of the style is missing or not set in the XML file.');
366        }
367
368        // array Style that will be passed on
369        $s = [];
370
371        // string Name af the style
372        $s['name'] = $attrs['name'];
373
374        // string Name of the DEFAULT font
375        $s['font'] = $this->wt_report->default_font;
376        if (!empty($attrs['font'])) {
377            $s['font'] = $attrs['font'];
378        }
379
380        // int The size of the font in points
381        $s['size'] = $this->wt_report->default_font_size;
382        if (!empty($attrs['size'])) {
383            // Get it as int to ignore all decimal points or text (if no text then 0)
384            $s['size'] = (string) (int) $attrs['size'];
385        }
386
387        // string B: bold, I: italic, U: underline, D: line trough, The default value is regular.
388        $s['style'] = '';
389        if (!empty($attrs['style'])) {
390            $s['style'] = $attrs['style'];
391        }
392
393        $this->wt_report->addStyle($s);
394    }
395
396    /**
397     * Handle <doc>
398     * Sets up the basics of the document proparties
399     *
400     * @param array<string> $attrs
401     *
402     * @return void
403     */
404    protected function docStartHandler(array $attrs): void
405    {
406        $this->parser = $this->xml_parser;
407
408        // Custom page width
409        if (!empty($attrs['customwidth'])) {
410            $this->wt_report->page_width = (int) $attrs['customwidth'];
411        } // Get it as int to ignore all decimal points or text (if any text then int(0))
412        // Custom Page height
413        if (!empty($attrs['customheight'])) {
414            $this->wt_report->page_height = (int) $attrs['customheight'];
415        } // Get it as int to ignore all decimal points or text (if any text then int(0))
416
417        // Left Margin
418        if (isset($attrs['leftmargin'])) {
419            if ($attrs['leftmargin'] === '0') {
420                $this->wt_report->left_margin = 0;
421            } elseif (!empty($attrs['leftmargin'])) {
422                $this->wt_report->left_margin = (int) $attrs['leftmargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
423            }
424        }
425        // Right Margin
426        if (isset($attrs['rightmargin'])) {
427            if ($attrs['rightmargin'] === '0') {
428                $this->wt_report->right_margin = 0;
429            } elseif (!empty($attrs['rightmargin'])) {
430                $this->wt_report->right_margin = (int) $attrs['rightmargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
431            }
432        }
433        // Top Margin
434        if (isset($attrs['topmargin'])) {
435            if ($attrs['topmargin'] === '0') {
436                $this->wt_report->top_margin = 0;
437            } elseif (!empty($attrs['topmargin'])) {
438                $this->wt_report->top_margin = (int) $attrs['topmargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
439            }
440        }
441        // Bottom Margin
442        if (isset($attrs['bottommargin'])) {
443            if ($attrs['bottommargin'] === '0') {
444                $this->wt_report->bottom_margin = 0;
445            } elseif (!empty($attrs['bottommargin'])) {
446                $this->wt_report->bottom_margin = (int) $attrs['bottommargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
447            }
448        }
449        // Header Margin
450        if (isset($attrs['headermargin'])) {
451            if ($attrs['headermargin'] === '0') {
452                $this->wt_report->header_margin = 0;
453            } elseif (!empty($attrs['headermargin'])) {
454                $this->wt_report->header_margin = (int) $attrs['headermargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
455            }
456        }
457        // Footer Margin
458        if (isset($attrs['footermargin'])) {
459            if ($attrs['footermargin'] === '0') {
460                $this->wt_report->footer_margin = 0;
461            } elseif (!empty($attrs['footermargin'])) {
462                $this->wt_report->footer_margin = (int) $attrs['footermargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
463            }
464        }
465
466        // Page Orientation
467        if (!empty($attrs['orientation'])) {
468            if ($attrs['orientation'] === 'landscape') {
469                $this->wt_report->orientation = 'landscape';
470            } elseif ($attrs['orientation'] === 'portrait') {
471                $this->wt_report->orientation = 'portrait';
472            }
473        }
474        // Page Size
475        if (!empty($attrs['pageSize'])) {
476            $this->wt_report->page_format = strtoupper($attrs['pageSize']);
477        }
478
479        // Show Generated By...
480        if (isset($attrs['showGeneratedBy'])) {
481            if ($attrs['showGeneratedBy'] === '0') {
482                $this->wt_report->show_generated_by = false;
483            } elseif ($attrs['showGeneratedBy'] === '1') {
484                $this->wt_report->show_generated_by = true;
485            }
486        }
487
488        $this->wt_report->setup();
489    }
490
491    /**
492     * Handle </doc>
493     *
494     * @return void
495     */
496    protected function docEndHandler(): void
497    {
498        $this->wt_report->run();
499    }
500
501    /**
502     * Handle <header>
503     *
504     * @return void
505     */
506    protected function headerStartHandler(): void
507    {
508        // Clear the Header before any new elements are added
509        $this->wt_report->clearHeader();
510        $this->wt_report->setProcessing('H');
511    }
512
513    /**
514     * Handle <body>
515     *
516     * @return void
517     */
518    protected function bodyStartHandler(): void
519    {
520        $this->wt_report->setProcessing('B');
521    }
522
523    /**
524     * Handle <footer>
525     *
526     * @return void
527     */
528    protected function footerStartHandler(): void
529    {
530        $this->wt_report->setProcessing('F');
531    }
532
533    /**
534     * Handle <cell>
535     *
536     * @param array<string,string> $attrs
537     *
538     * @return void
539     */
540    protected function cellStartHandler(array $attrs): void
541    {
542        // string The text alignment of the text in this box.
543        $align = $attrs['align'] ?? '';
544        // RTL supported left/right alignment
545        if ($align === 'rightrtl') {
546            if ($this->wt_report->rtl) {
547                $align = 'left';
548            } else {
549                $align = 'right';
550            }
551        } elseif ($align === 'leftrtl') {
552            if ($this->wt_report->rtl) {
553                $align = 'right';
554            } else {
555                $align = 'left';
556            }
557        }
558
559        // The color to fill the background of this cell
560        $bgcolor = $attrs['bgcolor'] ?? '';
561
562        // Whether the background should be painted
563        $fill = (int) ($attrs['fill'] ?? '0');
564
565        // If true reset the last cell height
566        $reseth = (bool) ($attrs['reseth'] ?? '1');
567
568        // Whether a border should be printed around this box
569        $border = $attrs['border'] ?? '';
570
571        // string Border color in HTML code
572        $bocolor = $attrs['bocolor'] ?? '';
573
574        // Cell height (expressed in points) The starting height of this cell. If the text wraps the height will automatically be adjusted.
575        $height = (int) ($attrs['height'] ?? '0');
576
577        // int Cell width (expressed in points) Setting the width to 0 will make it the width from the current location to the right margin.
578        $width = (int) ($attrs['width'] ?? '0');
579
580        // Stretch character mode
581        $stretch = (int) ($attrs['stretch'] ?? '0');
582
583        // mixed Position the left corner of this box on the page. The default is the current position.
584        $left = ReportBaseElement::CURRENT_POSITION;
585        if (isset($attrs['left'])) {
586            if ($attrs['left'] === '.') {
587                $left = ReportBaseElement::CURRENT_POSITION;
588            } elseif (!empty($attrs['left'])) {
589                $left = (int) $attrs['left'];
590            } elseif ($attrs['left'] === '0') {
591                $left = 0;
592            }
593        }
594        // mixed Position the top corner of this box on the page. the default is the current position
595        $top = ReportBaseElement::CURRENT_POSITION;
596        if (isset($attrs['top'])) {
597            if ($attrs['top'] === '.') {
598                $top = ReportBaseElement::CURRENT_POSITION;
599            } elseif (!empty($attrs['top'])) {
600                $top = (int) $attrs['top'];
601            } elseif ($attrs['top'] === '0') {
602                $top = 0;
603            }
604        }
605
606        // The name of the Style that should be used to render the text.
607        $style = $attrs['style'] ?? '';
608
609        // string Text color in html code
610        $tcolor = $attrs['tcolor'] ?? '';
611
612        // int Indicates where the current position should go after the call.
613        $ln = 0;
614        if (isset($attrs['newline'])) {
615            if (!empty($attrs['newline'])) {
616                $ln = (int) $attrs['newline'];
617            } elseif ($attrs['newline'] === '0') {
618                $ln = 0;
619            }
620        }
621
622        if ($align === 'left') {
623            $align = 'L';
624        } elseif ($align === 'right') {
625            $align = 'R';
626        } elseif ($align === 'center') {
627            $align = 'C';
628        } elseif ($align === 'justify') {
629            $align = 'J';
630        }
631
632        $this->print_data_stack[] = $this->print_data;
633        $this->print_data         = true;
634
635        $this->current_element = $this->report_root->createCell(
636            (int) $width,
637            (int) $height,
638            $border,
639            $align,
640            $bgcolor,
641            $style,
642            $ln,
643            $top,
644            $left,
645            $fill,
646            $stretch,
647            $bocolor,
648            $tcolor,
649            $reseth
650        );
651    }
652
653    /**
654     * Handle </cell>
655     *
656     * @return void
657     */
658    protected function cellEndHandler(): void
659    {
660        $this->print_data = array_pop($this->print_data_stack);
661        $this->wt_report->addElement($this->current_element);
662    }
663
664    /**
665     * Handle <now />
666     *
667     * @return void
668     */
669    protected function nowStartHandler(): void
670    {
671        $this->current_element->addText(Registry::timestampFactory()->now()->isoFormat('LLLL'));
672    }
673
674    /**
675     * Handle <pageNum />
676     *
677     * @return void
678     */
679    protected function pageNumStartHandler(): void
680    {
681        $this->current_element->addText('#PAGENUM#');
682    }
683
684    /**
685     * Handle <totalPages />
686     *
687     * @return void
688     */
689    protected function totalPagesStartHandler(): void
690    {
691        $this->current_element->addText('{{:ptp:}}');
692    }
693
694    /**
695     * Called at the start of an element.
696     *
697     * @param array<string> $attrs an array of key value pairs for the attributes
698     *
699     * @return void
700     */
701    protected function gedcomStartHandler(array $attrs): void
702    {
703        if ($this->process_gedcoms > 0) {
704            $this->process_gedcoms++;
705
706            return;
707        }
708
709        $tag       = $attrs['id'];
710        $tag       = str_replace('@fact', $this->fact, $tag);
711        $tags      = explode(':', $tag);
712        $newgedrec = '';
713        if (count($tags) < 2) {
714            $tmp       = Registry::gedcomRecordFactory()->make($attrs['id'], $this->tree);
715            $newgedrec = $tmp ? $tmp->privatizeGedcom(Auth::accessLevel($this->tree)) : '';
716        }
717        if (empty($newgedrec)) {
718            $tgedrec   = $this->gedrec;
719            $newgedrec = '';
720            foreach ($tags as $tag) {
721                if (preg_match('/\$(.+)/', $tag, $match)) {
722                    if (isset($this->vars[$match[1]]['gedcom'])) {
723                        $newgedrec = $this->vars[$match[1]]['gedcom'];
724                    } else {
725                        $tmp       = Registry::gedcomRecordFactory()->make($match[1], $this->tree);
726                        $newgedrec = $tmp ? $tmp->privatizeGedcom(Auth::accessLevel($this->tree)) : '';
727                    }
728                } else {
729                    if (preg_match('/@(.+)/', $tag, $match)) {
730                        $gmatch = [];
731                        if (preg_match("/\d $match[1] @([^@]+)@/", $tgedrec, $gmatch)) {
732                            $tmp       = Registry::gedcomRecordFactory()->make($gmatch[1], $this->tree);
733                            $newgedrec = $tmp ? $tmp->privatizeGedcom(Auth::accessLevel($this->tree)) : '';
734                            $tgedrec   = $newgedrec;
735                        } else {
736                            $newgedrec = '';
737                            break;
738                        }
739                    } else {
740                        $level     = 1 + (int) explode(' ', trim($tgedrec))[0];
741                        $newgedrec = self::getSubRecord($level, "$level $tag", $tgedrec);
742                        $tgedrec   = $newgedrec;
743                    }
744                }
745            }
746        }
747        if (!empty($newgedrec)) {
748            $this->gedrec_stack[] = [$this->gedrec, $this->fact, $this->desc];
749            $this->gedrec         = $newgedrec;
750            if (preg_match("/(\d+) (_?[A-Z0-9]+) (.*)/", $this->gedrec, $match)) {
751                $this->fact = $match[2];
752                $this->desc = trim($match[3]);
753            }
754        } else {
755            $this->process_gedcoms++;
756        }
757    }
758
759    /**
760     * Called at the end of an element.
761     *
762     * @return void
763     */
764    protected function gedcomEndHandler(): void
765    {
766        if ($this->process_gedcoms > 0) {
767            $this->process_gedcoms--;
768        } else {
769            [$this->gedrec, $this->fact, $this->desc] = array_pop($this->gedrec_stack);
770        }
771    }
772
773    /**
774     * Handle <textBox>
775     *
776     * @param array<string> $attrs
777     *
778     * @return void
779     */
780    protected function textBoxStartHandler(array $attrs): void
781    {
782        // string Background color code
783        $bgcolor = '';
784        if (!empty($attrs['bgcolor'])) {
785            $bgcolor = $attrs['bgcolor'];
786        }
787
788        // boolean Wether or not fill the background color
789        $fill = true;
790        if (isset($attrs['fill'])) {
791            if ($attrs['fill'] === '0') {
792                $fill = false;
793            } elseif ($attrs['fill'] === '1') {
794                $fill = true;
795            }
796        }
797
798        // var boolean Whether or not a border should be printed around this box. 0 = no border, 1 = border. Default is 0
799        $border = false;
800        if (isset($attrs['border'])) {
801            if ($attrs['border'] === '1') {
802                $border = true;
803            } elseif ($attrs['border'] === '0') {
804                $border = false;
805            }
806        }
807
808        // int The starting height of this cell. If the text wraps the height will automatically be adjusted
809        $height = 0;
810        if (!empty($attrs['height'])) {
811            $height = (int) $attrs['height'];
812        }
813        // int Setting the width to 0 will make it the width from the current location to the margin
814        $width = 0;
815        if (!empty($attrs['width'])) {
816            $width = (int) $attrs['width'];
817        }
818
819        // mixed Position the left corner of this box on the page. The default is the current position.
820        $left = ReportBaseElement::CURRENT_POSITION;
821        if (isset($attrs['left'])) {
822            if ($attrs['left'] === '.') {
823                $left = ReportBaseElement::CURRENT_POSITION;
824            } elseif (!empty($attrs['left'])) {
825                $left = (int) $attrs['left'];
826            } elseif ($attrs['left'] === '0') {
827                $left = 0;
828            }
829        }
830        // mixed Position the top corner of this box on the page. the default is the current position
831        $top = ReportBaseElement::CURRENT_POSITION;
832        if (isset($attrs['top'])) {
833            if ($attrs['top'] === '.') {
834                $top = ReportBaseElement::CURRENT_POSITION;
835            } elseif (!empty($attrs['top'])) {
836                $top = (int) $attrs['top'];
837            } elseif ($attrs['top'] === '0') {
838                $top = 0;
839            }
840        }
841        // boolean After this box is finished rendering, should the next section of text start immediately after the this box or should it start on a new line under this box. 0 = no new line, 1 = force new line. Default is 0
842        $newline = false;
843        if (isset($attrs['newline'])) {
844            if ($attrs['newline'] === '1') {
845                $newline = true;
846            } elseif ($attrs['newline'] === '0') {
847                $newline = false;
848            }
849        }
850        // boolean
851        $pagecheck = true;
852        if (isset($attrs['pagecheck'])) {
853            if ($attrs['pagecheck'] === '0') {
854                $pagecheck = false;
855            } elseif ($attrs['pagecheck'] === '1') {
856                $pagecheck = true;
857            }
858        }
859        // boolean Cell padding
860        $padding = true;
861        if (isset($attrs['padding'])) {
862            if ($attrs['padding'] === '0') {
863                $padding = false;
864            } elseif ($attrs['padding'] === '1') {
865                $padding = true;
866            }
867        }
868        // boolean Reset this box Height
869        $reseth = false;
870        if (isset($attrs['reseth'])) {
871            if ($attrs['reseth'] === '1') {
872                $reseth = true;
873            } elseif ($attrs['reseth'] === '0') {
874                $reseth = false;
875            }
876        }
877
878        // string Style of rendering
879        $style = '';
880
881        $this->print_data_stack[] = $this->print_data;
882        $this->print_data         = false;
883
884        $this->wt_report_stack[] = $this->wt_report;
885        $this->wt_report         = $this->report_root->createTextBox(
886            $width,
887            $height,
888            $border,
889            $bgcolor,
890            $newline,
891            $left,
892            $top,
893            $pagecheck,
894            $style,
895            $fill,
896            $padding,
897            $reseth
898        );
899    }
900
901    /**
902     * Handle <textBox>
903     *
904     * @return void
905     */
906    protected function textBoxEndHandler(): void
907    {
908        $this->print_data      = array_pop($this->print_data_stack);
909        $this->current_element = $this->wt_report;
910
911        // The TextBox handler is mis-using the wt_report attribute to store an element.
912        // Until this can be re-designed, we need this assertion to help static analysis tools.
913        assert($this->current_element instanceof ReportBaseElement, new LogicException());
914
915        $this->wt_report = array_pop($this->wt_report_stack);
916        $this->wt_report->addElement($this->current_element);
917    }
918
919    /**
920     * XLM <Text>.
921     *
922     * @param array<string> $attrs an array of key value pairs for the attributes
923     *
924     * @return void
925     */
926    protected function textStartHandler(array $attrs): void
927    {
928        $this->print_data_stack[] = $this->print_data;
929        $this->print_data         = true;
930
931        // string The name of the Style that should be used to render the text.
932        $style = '';
933        if (!empty($attrs['style'])) {
934            $style = $attrs['style'];
935        }
936
937        // string  The color of the text - Keep the black color as default
938        $color = '';
939        if (!empty($attrs['color'])) {
940            $color = $attrs['color'];
941        }
942
943        $this->current_element = $this->report_root->createText($style, $color);
944    }
945
946    /**
947     * Handle </text>
948     *
949     * @return void
950     */
951    protected function textEndHandler(): void
952    {
953        $this->print_data = array_pop($this->print_data_stack);
954        $this->wt_report->addElement($this->current_element);
955    }
956
957    /**
958     * Handle <getPersonName />
959     * Get the name
960     * 1. id is empty - current GEDCOM record
961     * 2. id is set with a record id
962     *
963     * @param array<string> $attrs an array of key value pairs for the attributes
964     *
965     * @return void
966     */
967    protected function getPersonNameStartHandler(array $attrs): void
968    {
969        $id    = '';
970        $match = [];
971        if (empty($attrs['id'])) {
972            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
973                $id = $match[1];
974            }
975        } else {
976            if (preg_match('/\$(.+)/', $attrs['id'], $match)) {
977                if (isset($this->vars[$match[1]]['id'])) {
978                    $id = $this->vars[$match[1]]['id'];
979                }
980            } else {
981                if (preg_match('/@(.+)/', $attrs['id'], $match)) {
982                    $gmatch = [];
983                    if (preg_match("/\d $match[1] @([^@]+)@/", $this->gedrec, $gmatch)) {
984                        $id = $gmatch[1];
985                    }
986                } else {
987                    $id = $attrs['id'];
988                }
989            }
990        }
991        if (!empty($id)) {
992            $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
993            if ($record === null) {
994                return;
995            }
996            if (!$record->canShowName()) {
997                $this->current_element->addText(I18N::translate('Private'));
998            } else {
999                $name = $record->fullName();
1000                $name = strip_tags($name);
1001                if (!empty($attrs['truncate'])) {
1002                    $name = Str::limit($name, (int) $attrs['truncate'], I18N::translate('…'));
1003                } else {
1004                    $addname = (string) $record->alternateName();
1005                    $addname = strip_tags($addname);
1006                    if (!empty($addname)) {
1007                        $name .= ' ' . $addname;
1008                    }
1009                }
1010                $this->current_element->addText(trim($name));
1011            }
1012        }
1013    }
1014
1015    /**
1016     * Handle <gedcomValue />
1017     *
1018     * @param array<string> $attrs
1019     *
1020     * @return void
1021     */
1022    protected function gedcomValueStartHandler(array $attrs): void
1023    {
1024        $id    = '';
1025        $match = [];
1026        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1027            $id = $match[1];
1028        }
1029
1030        if (isset($attrs['newline']) && $attrs['newline'] === '1') {
1031            $useBreak = '1';
1032        } else {
1033            $useBreak = '0';
1034        }
1035
1036        $tag = $attrs['tag'];
1037        if (!empty($tag)) {
1038            if ($tag === '@desc') {
1039                $value = $this->desc;
1040                $value = trim($value);
1041                $this->current_element->addText($value);
1042            }
1043            if ($tag === '@id') {
1044                $this->current_element->addText($id);
1045            } else {
1046                $tag = str_replace('@fact', $this->fact, $tag);
1047                if (empty($attrs['level'])) {
1048                    $level = (int) explode(' ', trim($this->gedrec))[0];
1049                    if ($level === 0) {
1050                        $level++;
1051                    }
1052                } else {
1053                    $level = (int) $attrs['level'];
1054                }
1055                $tags  = preg_split('/[: ]/', $tag);
1056                $value = $this->getGedcomValue($tag, $level, $this->gedrec);
1057                switch (end($tags)) {
1058                    case 'DATE':
1059                        $tmp   = new Date($value);
1060                        $value = strip_tags($tmp->display());
1061                        break;
1062                    case 'PLAC':
1063                        $tmp   = new Place($value, $this->tree);
1064                        $value = $tmp->shortName();
1065                        break;
1066                }
1067                if ($useBreak === '1') {
1068                    // Insert <br> when multiple dates exist.
1069                    // This works around a TCPDF bug that incorrectly wraps RTL dates on LTR pages
1070                    $value = str_replace('(', '<br>(', $value);
1071                    $value = str_replace('<span dir="ltr"><br>', '<br><span dir="ltr">', $value);
1072                    $value = str_replace('<span dir="rtl"><br>', '<br><span dir="rtl">', $value);
1073                    if (substr($value, 0, 4) === '<br>') {
1074                        $value = substr($value, 4);
1075                    }
1076                }
1077                $tmp = explode(':', $tag);
1078                if (in_array(end($tmp), ['NOTE', 'TEXT'], true)) {
1079                    if ($this->tree->getPreference('FORMAT_TEXT') === 'markdown') {
1080                        $value = strip_tags(Registry::markdownFactory()->markdown($value, $this->tree), ['br']);
1081                    } else {
1082                        $value = strip_tags(Registry::markdownFactory()->autolink($value, $this->tree), ['br']);
1083                    }
1084                    $value = strtr($value, [MarkdownFactory::BREAK => ' ']);
1085                }
1086
1087                if (!empty($attrs['truncate'])) {
1088                    $value = Str::limit($value, (int) $attrs['truncate'], I18N::translate('…'));
1089                }
1090                $this->current_element->addText($value);
1091            }
1092        }
1093    }
1094
1095    /**
1096     * Handle <repeatTag>
1097     *
1098     * @param array<string> $attrs
1099     *
1100     * @return void
1101     */
1102    protected function repeatTagStartHandler(array $attrs): void
1103    {
1104        $this->process_repeats++;
1105        if ($this->process_repeats > 1) {
1106            return;
1107        }
1108
1109        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1110        $this->repeats         = [];
1111        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1112
1113        $tag = $attrs['tag'] ?? '';
1114        if (!empty($tag)) {
1115            if ($tag === '@desc') {
1116                $value = $this->desc;
1117                $value = trim($value);
1118                $this->current_element->addText($value);
1119            } else {
1120                $tag   = str_replace('@fact', $this->fact, $tag);
1121                $tags  = explode(':', $tag);
1122                $level = (int) explode(' ', trim($this->gedrec))[0];
1123                if ($level === 0) {
1124                    $level++;
1125                }
1126                $subrec = $this->gedrec;
1127                $t      = $tag;
1128                $count  = count($tags);
1129                $i      = 0;
1130                while ($i < $count) {
1131                    $t = $tags[$i];
1132                    if (!empty($t)) {
1133                        if ($i < ($count - 1)) {
1134                            $subrec = self::getSubRecord($level, "$level $t", $subrec);
1135                            if (empty($subrec)) {
1136                                $level--;
1137                                $subrec = self::getSubRecord($level, "@ $t", $this->gedrec);
1138                                if (empty($subrec)) {
1139                                    return;
1140                                }
1141                            }
1142                        }
1143                        $level++;
1144                    }
1145                    $i++;
1146                }
1147                $level--;
1148                $count = preg_match_all("/$level $t(.*)/", $subrec, $match, PREG_SET_ORDER);
1149                $i     = 0;
1150                while ($i < $count) {
1151                    $i++;
1152                    // Privacy check - is this a link, and are we allowed to view the linked object?
1153                    $subrecord = self::getSubRecord($level, "$level $t", $subrec, $i);
1154                    if (preg_match('/^\d ' . Gedcom::REGEX_TAG . ' @(' . Gedcom::REGEX_XREF . ')@/', $subrecord, $xref_match)) {
1155                        $linked_object = Registry::gedcomRecordFactory()->make($xref_match[1], $this->tree);
1156                        if ($linked_object && !$linked_object->canShow()) {
1157                            continue;
1158                        }
1159                    }
1160                    $this->repeats[] = $subrecord;
1161                }
1162            }
1163        }
1164    }
1165
1166    /**
1167     * Handle </repeatTag>
1168     *
1169     * @return void
1170     */
1171    protected function repeatTagEndHandler(): void
1172    {
1173        $this->process_repeats--;
1174        if ($this->process_repeats > 0) {
1175            return;
1176        }
1177
1178        // Check if there is anything to repeat
1179        if (count($this->repeats) > 0) {
1180            // No need to load them if not used...
1181
1182            $lineoffset = 0;
1183            foreach ($this->repeats_stack as $rep) {
1184                $lineoffset += $rep[1];
1185            }
1186            //-- read the xml from the file
1187            $lines = file($this->report);
1188            while (!str_contains($lines[$lineoffset + $this->repeat_bytes], '<RepeatTag')) {
1189                $lineoffset--;
1190            }
1191            $lineoffset++;
1192            $reportxml = "<tempdoc>\n";
1193            $line_nr   = $lineoffset + $this->repeat_bytes;
1194            // RepeatTag Level counter
1195            $count = 1;
1196            while (0 < $count) {
1197                if (str_contains($lines[$line_nr], '<RepeatTag')) {
1198                    $count++;
1199                } elseif (str_contains($lines[$line_nr], '</RepeatTag')) {
1200                    $count--;
1201                }
1202                if (0 < $count) {
1203                    $reportxml .= $lines[$line_nr];
1204                }
1205                $line_nr++;
1206            }
1207            // No need to drag this
1208            unset($lines);
1209            $reportxml .= "</tempdoc>\n";
1210            // Save original values
1211            $this->parser_stack[] = $this->parser;
1212            $oldgedrec            = $this->gedrec;
1213            foreach ($this->repeats as $gedrec) {
1214                $this->gedrec  = $gedrec;
1215                $repeat_parser = xml_parser_create();
1216                $this->parser  = $repeat_parser;
1217                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
1218
1219                xml_set_element_handler(
1220                    $repeat_parser,
1221                    function ($parser, string $name, array $attrs): void {
1222                        $this->startElement($parser, $name, $attrs);
1223                    },
1224                    function ($parser, string $name): void {
1225                        $this->endElement($parser, $name);
1226                    }
1227                );
1228
1229                xml_set_character_data_handler(
1230                    $repeat_parser,
1231                    function ($parser, string $data): void {
1232                        $this->characterData($parser, $data);
1233                    }
1234                );
1235
1236                if (!xml_parse($repeat_parser, $reportxml, true)) {
1237                    throw new DomainException(sprintf(
1238                        'RepeatTagEHandler XML error: %s at line %d',
1239                        xml_error_string(xml_get_error_code($repeat_parser)),
1240                        xml_get_current_line_number($repeat_parser)
1241                    ));
1242                }
1243                xml_parser_free($repeat_parser);
1244            }
1245            // Restore original values
1246            $this->gedrec = $oldgedrec;
1247            $this->parser = array_pop($this->parser_stack);
1248        }
1249        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1250    }
1251
1252    /**
1253     * Variable lookup
1254     * Retrieve predefined variables :
1255     * @ desc GEDCOM fact description, example:
1256     *        1 EVEN This is a description
1257     * @ fact GEDCOM fact tag, such as BIRT, DEAT etc.
1258     * $ I18N::translate('....')
1259     * $ language_settings[]
1260     *
1261     * @param array<string> $attrs an array of key value pairs for the attributes
1262     *
1263     * @return void
1264     */
1265    protected function varStartHandler(array $attrs): void
1266    {
1267        if (empty($attrs['var'])) {
1268            throw new DomainException('REPORT ERROR var: The attribute "var=" is missing or not set in the XML file on line: ' . xml_get_current_line_number($this->parser));
1269        }
1270
1271        $var = $attrs['var'];
1272        // SetVar element preset variables
1273        if (!empty($this->vars[$var]['id'])) {
1274            $var = $this->vars[$var]['id'];
1275        } else {
1276            $tfact = $this->fact;
1277            if (($this->fact === 'EVEN' || $this->fact === 'FACT') && $this->type !== '') {
1278                // Use :
1279                // n TYPE This text if string
1280                $tfact = $this->type;
1281            } else {
1282                foreach ([Individual::RECORD_TYPE, Family::RECORD_TYPE] as $record_type) {
1283                    $element = Registry::elementFactory()->make($record_type . ':' . $this->fact);
1284
1285                    if (!$element instanceof UnknownElement) {
1286                        $tfact = $element->label();
1287                        break;
1288                    }
1289                }
1290            }
1291
1292            $var = strtr($var, ['@desc' => $this->desc, '@fact' => $tfact]);
1293
1294            if (preg_match('/^I18N::number\((.+)\)$/', $var, $match)) {
1295                $var = I18N::number((int) $match[1]);
1296            } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $var, $match)) {
1297                $var = I18N::translate($match[1]);
1298            } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $var, $match)) {
1299                $var = I18N::translateContext($match[1], $match[2]);
1300            }
1301        }
1302        // Check if variable is set as a date and reformat the date
1303        if (isset($attrs['date'])) {
1304            if ($attrs['date'] === '1') {
1305                $g   = new Date($var);
1306                $var = $g->display();
1307            }
1308        }
1309        $this->current_element->addText($var);
1310        $this->text = $var; // Used for title/descriptio
1311    }
1312
1313    /**
1314     * Handle <facts>
1315     *
1316     * @param array<string> $attrs
1317     *
1318     * @return void
1319     */
1320    protected function factsStartHandler(array $attrs): void
1321    {
1322        $this->process_repeats++;
1323        if ($this->process_repeats > 1) {
1324            return;
1325        }
1326
1327        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1328        $this->repeats         = [];
1329        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1330
1331        $id    = '';
1332        $match = [];
1333        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1334            $id = $match[1];
1335        }
1336        $tag = '';
1337        if (isset($attrs['ignore'])) {
1338            $tag .= $attrs['ignore'];
1339        }
1340        if (preg_match('/\$(.+)/', $tag, $match)) {
1341            $tag = $this->vars[$match[1]]['id'];
1342        }
1343
1344        $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1345        if (empty($attrs['diff']) && !empty($id)) {
1346            $facts = $record->facts([], true);
1347            $this->repeats = [];
1348            $nonfacts      = explode(',', $tag);
1349            foreach ($facts as $fact) {
1350                $tag = explode(':', $fact->tag())[1];
1351
1352                if (!in_array($tag, $nonfacts, true)) {
1353                    $this->repeats[] = $fact->gedcom();
1354                }
1355            }
1356        } else {
1357            foreach ($record->facts() as $fact) {
1358                if (($fact->isPendingAddition() || $fact->isPendingDeletion()) && !str_ends_with($fact->tag(), ':CHAN')) {
1359                    $this->repeats[] = $fact->gedcom();
1360                }
1361            }
1362        }
1363    }
1364
1365    /**
1366     * Handle </facts>
1367     *
1368     * @return void
1369     */
1370    protected function factsEndHandler(): void
1371    {
1372        $this->process_repeats--;
1373        if ($this->process_repeats > 0) {
1374            return;
1375        }
1376
1377        // Check if there is anything to repeat
1378        if (count($this->repeats) > 0) {
1379            $line       = xml_get_current_line_number($this->parser) - 1;
1380            $lineoffset = 0;
1381            foreach ($this->repeats_stack as $rep) {
1382                $lineoffset += $rep[1];
1383            }
1384
1385            //-- read the xml from the file
1386            $lines = file($this->report);
1387            while ($lineoffset + $this->repeat_bytes > 0 && !str_contains($lines[$lineoffset + $this->repeat_bytes], '<Facts ')) {
1388                $lineoffset--;
1389            }
1390            $lineoffset++;
1391            $reportxml = "<tempdoc>\n";
1392            $i         = $line + $lineoffset;
1393            $line_nr   = $this->repeat_bytes + $lineoffset;
1394            while ($line_nr < $i) {
1395                $reportxml .= $lines[$line_nr];
1396                $line_nr++;
1397            }
1398            // No need to drag this
1399            unset($lines);
1400            $reportxml .= "</tempdoc>\n";
1401            // Save original values
1402            $this->parser_stack[] = $this->parser;
1403            $oldgedrec            = $this->gedrec;
1404            $count                = count($this->repeats);
1405            $i                    = 0;
1406            while ($i < $count) {
1407                $this->gedrec = $this->repeats[$i];
1408                $this->fact   = '';
1409                $this->desc   = '';
1410                if (preg_match('/1 (\w+)(.*)/', $this->gedrec, $match)) {
1411                    $this->fact = $match[1];
1412                    if ($this->fact === 'EVEN' || $this->fact === 'FACT') {
1413                        $tmatch = [];
1414                        if (preg_match('/2 TYPE (.+)/', $this->gedrec, $tmatch)) {
1415                            $this->type = trim($tmatch[1]);
1416                        } else {
1417                            $this->type = ' ';
1418                        }
1419                    }
1420                    $this->desc = trim($match[2]);
1421                    $this->desc .= self::getCont(2, $this->gedrec);
1422                }
1423                $repeat_parser = xml_parser_create();
1424                $this->parser  = $repeat_parser;
1425                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
1426
1427                xml_set_element_handler(
1428                    $repeat_parser,
1429                    function ($parser, string $name, array $attrs): void {
1430                        $this->startElement($parser, $name, $attrs);
1431                    },
1432                    function ($parser, string $name): void {
1433                        $this->endElement($parser, $name);
1434                    }
1435                );
1436
1437                xml_set_character_data_handler(
1438                    $repeat_parser,
1439                    function ($parser, string $data): void {
1440                        $this->characterData($parser, $data);
1441                    }
1442                );
1443
1444                if (!xml_parse($repeat_parser, $reportxml, true)) {
1445                    throw new DomainException(sprintf(
1446                        'FactsEHandler XML error: %s at line %d',
1447                        xml_error_string(xml_get_error_code($repeat_parser)),
1448                        xml_get_current_line_number($repeat_parser)
1449                    ));
1450                }
1451                xml_parser_free($repeat_parser);
1452                $i++;
1453            }
1454            // Restore original values
1455            $this->parser = array_pop($this->parser_stack);
1456            $this->gedrec = $oldgedrec;
1457        }
1458        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1459    }
1460
1461    /**
1462     * Setting upp or changing variables in the XML
1463     * The XML variable name and value is stored in $this->vars
1464     *
1465     * @param array<string> $attrs an array of key value pairs for the attributes
1466     *
1467     * @return void
1468     */
1469    protected function setVarStartHandler(array $attrs): void
1470    {
1471        if (empty($attrs['name'])) {
1472            throw new DomainException('REPORT ERROR var: The attribute "name" is missing or not set in the XML file');
1473        }
1474
1475        $name  = $attrs['name'];
1476        $value = $attrs['value'];
1477        $match = [];
1478        // Current GEDCOM record strings
1479        if ($value === '@ID') {
1480            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1481                $value = $match[1];
1482            }
1483        } elseif ($value === '@fact') {
1484            $value = $this->fact;
1485        } elseif ($value === '@desc') {
1486            $value = $this->desc;
1487        } elseif ($value === '@generation') {
1488            $value = (string) $this->generation;
1489        } elseif (preg_match("/@(\w+)/", $value, $match)) {
1490            $gmatch = [];
1491            if (preg_match("/\d $match[1] (.+)/", $this->gedrec, $gmatch)) {
1492                $value = str_replace('@', '', trim($gmatch[1]));
1493            }
1494        }
1495        if (preg_match("/\\$(\w+)/", $name, $match)) {
1496            $name = $this->vars["'" . $match[1] . "'"]['id'];
1497        }
1498        $count = preg_match_all("/\\$(\w+)/", $value, $match, PREG_SET_ORDER);
1499        $i     = 0;
1500        while ($i < $count) {
1501            $t     = $this->vars[$match[$i][1]]['id'];
1502            $value = preg_replace('/\$' . $match[$i][1] . '/', $t, $value, 1);
1503            $i++;
1504        }
1505        if (preg_match('/^I18N::number\((.+)\)$/', $value, $match)) {
1506            $value = I18N::number((int) $match[1]);
1507        } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $value, $match)) {
1508            $value = I18N::translate($match[1]);
1509        } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $value, $match)) {
1510            $value = I18N::translateContext($match[1], $match[2]);
1511        }
1512
1513        // Arithmetic functions
1514        if (preg_match("/(\d+)\s*([-+*\/])\s*(\d+)/", $value, $match)) {
1515            // Create an expression language with the functions used by our reports.
1516            $expression_provider  = new ReportExpressionLanguageProvider();
1517            $expression_cache     = new NullAdapter();
1518            $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1519
1520            $value = (string) $expression_language->evaluate($value);
1521        }
1522
1523        if (str_contains($value, '@')) {
1524            $value = '';
1525        }
1526        $this->vars[$name]['id'] = $value;
1527    }
1528
1529    /**
1530     * Handle <if>
1531     *
1532     * @param array<string> $attrs
1533     *
1534     * @return void
1535     */
1536    protected function ifStartHandler(array $attrs): void
1537    {
1538        if ($this->process_ifs > 0) {
1539            $this->process_ifs++;
1540
1541            return;
1542        }
1543
1544        $condition = $attrs['condition'];
1545        $condition = $this->substituteVars($condition, true);
1546        $condition = str_replace([
1547            ' LT ',
1548            ' GT ',
1549        ], [
1550            '<',
1551            '>',
1552        ], $condition);
1553        // Replace the first occurrence only once of @fact:DATE or in any other combinations to the current fact, such as BIRT
1554        $condition = str_replace('@fact:', $this->fact . ':', $condition);
1555        $match     = [];
1556        $count     = preg_match_all("/@([\w:.]+)/", $condition, $match, PREG_SET_ORDER);
1557        $i         = 0;
1558        while ($i < $count) {
1559            $id    = $match[$i][1];
1560            $value = '""';
1561            if ($id === 'ID') {
1562                if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1563                    $value = "'" . $match[1] . "'";
1564                }
1565            } elseif ($id === 'fact') {
1566                $value = '"' . $this->fact . '"';
1567            } elseif ($id === 'desc') {
1568                $value = '"' . addslashes($this->desc) . '"';
1569            } elseif ($id === 'generation') {
1570                $value = '"' . $this->generation . '"';
1571            } else {
1572                $level = (int) explode(' ', trim($this->gedrec))[0];
1573                if ($level === 0) {
1574                    $level++;
1575                }
1576                $value = $this->getGedcomValue($id, $level, $this->gedrec);
1577                if (empty($value)) {
1578                    $level++;
1579                    $value = $this->getGedcomValue($id, $level, $this->gedrec);
1580                }
1581                $value = preg_replace('/^@(' . Gedcom::REGEX_XREF . ')@$/', '$1', $value);
1582                $value = '"' . addslashes($value) . '"';
1583            }
1584            $condition = str_replace("@$id", $value, $condition);
1585            $i++;
1586        }
1587
1588        // Create an expression language with the functions used by our reports.
1589        $expression_provider  = new ReportExpressionLanguageProvider();
1590        $expression_cache     = new NullAdapter();
1591        $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1592
1593        $ret = $expression_language->evaluate($condition);
1594
1595        if (!$ret) {
1596            $this->process_ifs++;
1597        }
1598    }
1599
1600    /**
1601     * Handle </if>
1602     *
1603     * @return void
1604     */
1605    protected function ifEndHandler(): void
1606    {
1607        if ($this->process_ifs > 0) {
1608            $this->process_ifs--;
1609        }
1610    }
1611
1612    /**
1613     * Handle <footnote>
1614     * Collect the Footnote links
1615     * GEDCOM Records that are protected by Privacy setting will be ignored
1616     *
1617     * @param array<string> $attrs
1618     *
1619     * @return void
1620     */
1621    protected function footnoteStartHandler(array $attrs): void
1622    {
1623        $id = '';
1624        if (preg_match('/[0-9] (.+) @(.+)@/', $this->gedrec, $match)) {
1625            $id = $match[2];
1626        }
1627        $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1628        if ($record && $record->canShow()) {
1629            $this->print_data_stack[] = $this->print_data;
1630            $this->print_data         = true;
1631            $style                    = '';
1632            if (!empty($attrs['style'])) {
1633                $style = $attrs['style'];
1634            }
1635            $this->footnote_element = $this->current_element;
1636            $this->current_element  = $this->report_root->createFootnote($style);
1637        } else {
1638            $this->print_data       = false;
1639            $this->process_footnote = false;
1640        }
1641    }
1642
1643    /**
1644     * Handle </footnote>
1645     * Print the collected Footnote data
1646     *
1647     * @return void
1648     */
1649    protected function footnoteEndHandler(): void
1650    {
1651        if ($this->process_footnote) {
1652            $this->print_data = array_pop($this->print_data_stack);
1653            $temp             = trim($this->current_element->getValue());
1654            if (strlen($temp) > 3) {
1655                $this->wt_report->addElement($this->current_element);
1656            }
1657            $this->current_element = $this->footnote_element;
1658        } else {
1659            $this->process_footnote = true;
1660        }
1661    }
1662
1663    /**
1664     * Handle <footnoteTexts />
1665     *
1666     * @return void
1667     */
1668    protected function footnoteTextsStartHandler(): void
1669    {
1670        $temp = 'footnotetexts';
1671        $this->wt_report->addElement($temp);
1672    }
1673
1674    /**
1675     * XML element Forced line break handler - HTML code
1676     *
1677     * @return void
1678     */
1679    protected function brStartHandler(): void
1680    {
1681        if ($this->print_data && $this->process_gedcoms === 0) {
1682            $this->current_element->addText('<br>');
1683        }
1684    }
1685
1686    /**
1687     * Handle <sp />
1688     * Forced space
1689     *
1690     * @return void
1691     */
1692    protected function spStartHandler(): void
1693    {
1694        if ($this->print_data && $this->process_gedcoms === 0) {
1695            $this->current_element->addText(' ');
1696        }
1697    }
1698
1699    /**
1700     * Handle <highlightedImage />
1701     *
1702     * @param array<string> $attrs
1703     *
1704     * @return void
1705     */
1706    protected function highlightedImageStartHandler(array $attrs): void
1707    {
1708        $id = '';
1709        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1710            $id = $match[1];
1711        }
1712
1713        // Position the top corner of this box on the page
1714        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
1715
1716        // Position the left corner of this box on the page
1717        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
1718
1719        // string Align the image in left, center, right (or empty to use x/y position).
1720        $align = $attrs['align'] ?? '';
1721
1722        // string Next Line should be T:next to the image, N:next line
1723        $ln = $attrs['ln'] ?? 'T';
1724
1725        // Width, height (or both).
1726        $width  = (float) ($attrs['width'] ?? 0.0);
1727        $height = (float) ($attrs['height'] ?? 0.0);
1728
1729        $person     = Registry::individualFactory()->make($id, $this->tree);
1730        $media_file = $person->findHighlightedMediaFile();
1731
1732        if ($media_file instanceof MediaFile && $media_file->fileExists()) {
1733            $image      = imagecreatefromstring($media_file->fileContents());
1734            $attributes = [imagesx($image), imagesy($image)];
1735
1736            if ($width > 0 && $height == 0) {
1737                $perc   = $width / $attributes[0];
1738                $height = round($attributes[1] * $perc);
1739            } elseif ($height > 0 && $width == 0) {
1740                $perc  = $height / $attributes[1];
1741                $width = round($attributes[0] * $perc);
1742            } else {
1743                $width  = (float) $attributes[0];
1744                $height = (float) $attributes[1];
1745            }
1746            $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
1747            $this->wt_report->addElement($image);
1748        }
1749    }
1750
1751    /**
1752     * Handle <image/>
1753     *
1754     * @param array<string> $attrs
1755     *
1756     * @return void
1757     */
1758    protected function imageStartHandler(array $attrs): void
1759    {
1760        // Position the top corner of this box on the page. the default is the current position
1761        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
1762
1763        // mixed Position the left corner of this box on the page. the default is the current position
1764        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
1765
1766        // string Align the image in left, center, right (or empty to use x/y position).
1767        $align = $attrs['align'] ?? '';
1768
1769        // string Next Line should be T:next to the image, N:next line
1770        $ln = $attrs['ln'] ?? 'T';
1771
1772        // Width, height (or both).
1773        $width  = (float) ($attrs['width'] ?? 0.0);
1774        $height = (float) ($attrs['height'] ?? 0.0);
1775
1776        $file = $attrs['file'] ?? '';
1777
1778        if ($file === '@FILE') {
1779            $match = [];
1780            if (preg_match("/\d OBJE @(.+)@/", $this->gedrec, $match)) {
1781                $mediaobject = Registry::mediaFactory()->make($match[1], $this->tree);
1782                $media_file  = $mediaobject->firstImageFile();
1783
1784                if ($media_file instanceof MediaFile && $media_file->fileExists()) {
1785                    $image      = imagecreatefromstring($media_file->fileContents());
1786                    $attributes = [imagesx($image), imagesy($image)];
1787
1788                    if ($width > 0 && $height == 0) {
1789                        $perc   = $width / $attributes[0];
1790                        $height = round($attributes[1] * $perc);
1791                    } elseif ($height > 0 && $width == 0) {
1792                        $perc  = $height / $attributes[1];
1793                        $width = round($attributes[0] * $perc);
1794                    } else {
1795                        $width  = (float) $attributes[0];
1796                        $height = (float) $attributes[1];
1797                    }
1798                    $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
1799                    $this->wt_report->addElement($image);
1800                }
1801            }
1802        } else {
1803            if (file_exists($file) && preg_match('/(jpg|jpeg|png|gif)$/i', $file)) {
1804                $size = getimagesize($file);
1805                if ($width > 0 && $height == 0) {
1806                    $perc   = $width / $size[0];
1807                    $height = round($size[1] * $perc);
1808                } elseif ($height > 0 && $width == 0) {
1809                    $perc  = $height / $size[1];
1810                    $width = round($size[0] * $perc);
1811                } else {
1812                    $width  = $size[0];
1813                    $height = $size[1];
1814                }
1815                $image = $this->report_root->createImage($file, $left, $top, $width, $height, $align, $ln);
1816                $this->wt_report->addElement($image);
1817            }
1818        }
1819    }
1820
1821    /**
1822     * Handle <line>
1823     *
1824     * @param array<string> $attrs
1825     *
1826     * @return void
1827     */
1828    protected function lineStartHandler(array $attrs): void
1829    {
1830        // Start horizontal position, current position (default)
1831        $x1 = ReportBaseElement::CURRENT_POSITION;
1832        if (isset($attrs['x1'])) {
1833            if ($attrs['x1'] === '0') {
1834                $x1 = 0;
1835            } elseif ($attrs['x1'] === '.') {
1836                $x1 = ReportBaseElement::CURRENT_POSITION;
1837            } elseif (!empty($attrs['x1'])) {
1838                $x1 = (float) $attrs['x1'];
1839            }
1840        }
1841        // Start vertical position, current position (default)
1842        $y1 = ReportBaseElement::CURRENT_POSITION;
1843        if (isset($attrs['y1'])) {
1844            if ($attrs['y1'] === '0') {
1845                $y1 = 0;
1846            } elseif ($attrs['y1'] === '.') {
1847                $y1 = ReportBaseElement::CURRENT_POSITION;
1848            } elseif (!empty($attrs['y1'])) {
1849                $y1 = (float) $attrs['y1'];
1850            }
1851        }
1852        // End horizontal position, maximum width (default)
1853        $x2 = ReportBaseElement::CURRENT_POSITION;
1854        if (isset($attrs['x2'])) {
1855            if ($attrs['x2'] === '0') {
1856                $x2 = 0;
1857            } elseif ($attrs['x2'] === '.') {
1858                $x2 = ReportBaseElement::CURRENT_POSITION;
1859            } elseif (!empty($attrs['x2'])) {
1860                $x2 = (float) $attrs['x2'];
1861            }
1862        }
1863        // End vertical position
1864        $y2 = ReportBaseElement::CURRENT_POSITION;
1865        if (isset($attrs['y2'])) {
1866            if ($attrs['y2'] === '0') {
1867                $y2 = 0;
1868            } elseif ($attrs['y2'] === '.') {
1869                $y2 = ReportBaseElement::CURRENT_POSITION;
1870            } elseif (!empty($attrs['y2'])) {
1871                $y2 = (float) $attrs['y2'];
1872            }
1873        }
1874
1875        $line = $this->report_root->createLine($x1, $y1, $x2, $y2);
1876        $this->wt_report->addElement($line);
1877    }
1878
1879    /**
1880     * Handle <list>
1881     *
1882     * @param array<string> $attrs
1883     *
1884     * @return void
1885     */
1886    protected function listStartHandler(array $attrs): void
1887    {
1888        $this->process_repeats++;
1889        if ($this->process_repeats > 1) {
1890            return;
1891        }
1892
1893        $match = [];
1894        if (isset($attrs['sortby'])) {
1895            $sortby = $attrs['sortby'];
1896            if (preg_match("/\\$(\w+)/", $sortby, $match)) {
1897                $sortby = $this->vars[$match[1]]['id'];
1898                $sortby = trim($sortby);
1899            }
1900        } else {
1901            $sortby = 'NAME';
1902        }
1903
1904        $listname = $attrs['list'] ?? 'individual';
1905
1906        // Some filters/sorts can be applied using SQL, while others require PHP
1907        switch ($listname) {
1908            case 'pending':
1909                $this->list = DB::table('change')
1910                    ->whereIn('change_id', function (Builder $query): void {
1911                        $query->select(new Expression('MAX(change_id)'))
1912                            ->from('change')
1913                            ->where('gedcom_id', '=', $this->tree->id())
1914                            ->where('status', '=', 'pending')
1915                            ->groupBy(['xref']);
1916                    })
1917                    ->get()
1918                    ->map(fn (object $row): ?GedcomRecord => Registry::gedcomRecordFactory()->make($row->xref, $this->tree, $row->new_gedcom ?: $row->old_gedcom))
1919                    ->filter()
1920                    ->all();
1921                break;
1922
1923            case 'individual':
1924                $query = DB::table('individuals')
1925                    ->where('i_file', '=', $this->tree->id())
1926                    ->select(['i_id AS xref', 'i_gedcom AS gedcom'])
1927                    ->distinct();
1928
1929                foreach ($attrs as $attr => $value) {
1930                    if (str_starts_with($attr, 'filter') && $value !== '') {
1931                        $value = $this->substituteVars($value, false);
1932                        // Convert the various filters into SQL
1933                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
1934                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
1935                                $join
1936                                    ->on($attr . '.d_gid', '=', 'i_id')
1937                                    ->on($attr . '.d_file', '=', 'i_file');
1938                            });
1939
1940                            $query->where($attr . '.d_fact', '=', $match[1]);
1941
1942                            $date = new Date($match[3]);
1943
1944                            if ($match[2] === 'LTE') {
1945                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
1946                            } else {
1947                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
1948                            }
1949
1950                            // This filter has been fully processed
1951                            unset($attrs[$attr]);
1952                        } elseif (preg_match('/^NAME CONTAINS (.+)$/', $value, $match)) {
1953                            $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
1954                                $join
1955                                    ->on($attr . '.n_id', '=', 'i_id')
1956                                    ->on($attr . '.n_file', '=', 'i_file');
1957                            });
1958                            // Search the DB only if there is any name supplied
1959                            $names = explode(' ', $match[1]);
1960                            foreach ($names as $n => $name) {
1961                                $query->where($attr . '.n_full', 'LIKE', '%' . addcslashes($name, '\\%_') . '%');
1962                            }
1963
1964                            // This filter has been fully processed
1965                            unset($attrs[$attr]);
1966                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
1967                            // Convert newline escape sequences to actual new lines
1968                            $match[1] = str_replace('\n', "\n", $match[1]);
1969
1970                            $query->where('i_gedcom', 'LIKE', $match[1]);
1971
1972                            // This filter has been fully processed
1973                            unset($attrs[$attr]);
1974                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
1975                            // Don't unset this filter. This is just initial filtering for performance
1976                            $query
1977                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
1978                                    $join
1979                                        ->on($attr . 'a.pl_file', '=', 'i_file')
1980                                        ->on($attr . 'a.pl_gid', '=', 'i_id');
1981                                })
1982                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
1983                                    $join
1984                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
1985                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
1986                                })
1987                                ->where($attr . 'b.p_place', 'LIKE', '%' . addcslashes($match[1], '\\%_') . '%');
1988                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
1989                            // Don't unset this filter. This is just initial filtering for performance
1990                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
1991                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
1992                            $query->where('i_gedcom', 'LIKE', $like);
1993                        } elseif (preg_match('/^(\w+) CONTAINS (.*)$/', $value, $match)) {
1994                            // Don't unset this filter. This is just initial filtering for performance
1995                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
1996                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
1997                            $query->where('i_gedcom', 'LIKE', $like);
1998                        }
1999                    }
2000                }
2001
2002                $this->list = [];
2003
2004                foreach ($query->get() as $row) {
2005                    $this->list[$row->xref] = Registry::individualFactory()->make($row->xref, $this->tree, $row->gedcom);
2006                }
2007                break;
2008
2009            case 'family':
2010                $query = DB::table('families')
2011                    ->where('f_file', '=', $this->tree->id())
2012                    ->select(['f_id AS xref', 'f_gedcom AS gedcom'])
2013                    ->distinct();
2014
2015                foreach ($attrs as $attr => $value) {
2016                    if (str_starts_with($attr, 'filter') && $value !== '') {
2017                        $value = $this->substituteVars($value, false);
2018                        // Convert the various filters into SQL
2019                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
2020                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2021                                $join
2022                                    ->on($attr . '.d_gid', '=', 'f_id')
2023                                    ->on($attr . '.d_file', '=', 'f_file');
2024                            });
2025
2026                            $query->where($attr . '.d_fact', '=', $match[1]);
2027
2028                            $date = new Date($match[3]);
2029
2030                            if ($match[2] === 'LTE') {
2031                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
2032                            } else {
2033                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
2034                            }
2035
2036                            // This filter has been fully processed
2037                            unset($attrs[$attr]);
2038                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
2039                            // Convert newline escape sequences to actual new lines
2040                            $match[1] = str_replace('\n', "\n", $match[1]);
2041
2042                            $query->where('f_gedcom', 'LIKE', $match[1]);
2043
2044                            // This filter has been fully processed
2045                            unset($attrs[$attr]);
2046                        } elseif (preg_match('/^NAME CONTAINS (.*)$/', $value, $match)) {
2047                            if ($sortby === 'NAME' || $match[1] !== '') {
2048                                $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2049                                    $join
2050                                        ->on($attr . '.n_file', '=', 'f_file')
2051                                        ->where(static function (Builder $query): void {
2052                                            $query
2053                                                ->whereColumn('n_id', '=', 'f_husb')
2054                                                ->orWhereColumn('n_id', '=', 'f_wife');
2055                                        });
2056                                });
2057                                // Search the DB only if there is any name supplied
2058                                if ($match[1] != '') {
2059                                    $names = explode(' ', $match[1]);
2060                                    foreach ($names as $n => $name) {
2061                                        $query->where($attr . '.n_full', 'LIKE', '%' . addcslashes($name, '\\%_') . '%');
2062                                    }
2063                                }
2064                            }
2065
2066                            // This filter has been fully processed
2067                            unset($attrs[$attr]);
2068                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
2069                            // Don't unset this filter. This is just initial filtering for performance
2070                            $query
2071                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
2072                                    $join
2073                                        ->on($attr . 'a.pl_file', '=', 'f_file')
2074                                        ->on($attr . 'a.pl_gid', '=', 'f_id');
2075                                })
2076                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
2077                                    $join
2078                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
2079                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
2080                                })
2081                                ->where($attr . 'b.p_place', 'LIKE', '%' . addcslashes($match[1], '\\%_') . '%');
2082                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
2083                            // Don't unset this filter. This is just initial filtering for performance
2084                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2085                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
2086                            $query->where('f_gedcom', 'LIKE', $like);
2087                        } elseif (preg_match('/^(\w+) CONTAINS (.+)$/', $value, $match)) {
2088                            // Don't unset this filter. This is just initial filtering for performance
2089                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2090                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
2091                            $query->where('f_gedcom', 'LIKE', $like);
2092                        }
2093                    }
2094                }
2095
2096                $this->list = [];
2097
2098                foreach ($query->get() as $row) {
2099                    $this->list[$row->xref] = Registry::familyFactory()->make($row->xref, $this->tree, $row->gedcom);
2100                }
2101                break;
2102
2103            default:
2104                throw new DomainException('Invalid list name: ' . $listname);
2105        }
2106
2107        $filters  = [];
2108        $filters2 = [];
2109        if (isset($attrs['filter1']) && count($this->list) > 0) {
2110            foreach ($attrs as $key => $value) {
2111                if (preg_match("/filter(\d)/", $key)) {
2112                    $condition = $value;
2113                    if (preg_match("/@(\w+)/", $condition, $match)) {
2114                        $id    = $match[1];
2115                        $value = "''";
2116                        if ($id === 'ID') {
2117                            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
2118                                $value = "'" . $match[1] . "'";
2119                            }
2120                        } elseif ($id === 'fact') {
2121                            $value = "'" . $this->fact . "'";
2122                        } elseif ($id === 'desc') {
2123                            $value = "'" . $this->desc . "'";
2124                        } else {
2125                            if (preg_match("/\d $id (.+)/", $this->gedrec, $match)) {
2126                                $value = "'" . str_replace('@', '', trim($match[1])) . "'";
2127                            }
2128                        }
2129                        $condition = preg_replace("/@$id/", $value, $condition);
2130                    }
2131                    //-- handle regular expressions
2132                    if (preg_match("/([A-Z:]+)\s*([^\s]+)\s*(.+)/", $condition, $match)) {
2133                        $tag  = trim($match[1]);
2134                        $expr = trim($match[2]);
2135                        $val  = trim($match[3]);
2136                        if (preg_match("/\\$(\w+)/", $val, $match)) {
2137                            $val = $this->vars[$match[1]]['id'];
2138                            $val = trim($val);
2139                        }
2140                        if ($val) {
2141                            $searchstr = '';
2142                            $tags      = explode(':', $tag);
2143                            //-- only limit to a level number if we are specifically looking at a level
2144                            if (count($tags) > 1) {
2145                                $level = 1;
2146                                $t = 'XXXX';
2147                                foreach ($tags as $t) {
2148                                    if (!empty($searchstr)) {
2149                                        $searchstr .= "[^\n]*(\n[2-9][^\n]*)*\n";
2150                                    }
2151                                    //-- search for both EMAIL and _EMAIL... silly double gedcom standard
2152                                    if ($t === 'EMAIL' || $t === '_EMAIL') {
2153                                        $t = '_?EMAIL';
2154                                    }
2155                                    $searchstr .= $level . ' ' . $t;
2156                                    $level++;
2157                                }
2158                            } else {
2159                                if ($tag === 'EMAIL' || $tag === '_EMAIL') {
2160                                    $tag = '_?EMAIL';
2161                                }
2162                                $t         = $tag;
2163                                $searchstr = '1 ' . $tag;
2164                            }
2165                            switch ($expr) {
2166                                case 'CONTAINS':
2167                                    if ($t === 'PLAC') {
2168                                        $searchstr .= "[^\n]*[, ]*" . $val;
2169                                    } else {
2170                                        $searchstr .= "[^\n]*" . $val;
2171                                    }
2172                                    $filters[] = $searchstr;
2173                                    break;
2174                                default:
2175                                    $filters2[] = [
2176                                        'tag'  => $tag,
2177                                        'expr' => $expr,
2178                                        'val'  => $val,
2179                                    ];
2180                                    break;
2181                            }
2182                        }
2183                    }
2184                }
2185            }
2186        }
2187        //-- apply other filters to the list that could not be added to the search string
2188        if ($filters) {
2189            foreach ($this->list as $key => $record) {
2190                foreach ($filters as $filter) {
2191                    if (!preg_match('/' . $filter . '/i', $record->privatizeGedcom(Auth::accessLevel($this->tree)))) {
2192                        unset($this->list[$key]);
2193                        break;
2194                    }
2195                }
2196            }
2197        }
2198        if ($filters2) {
2199            $mylist = [];
2200            foreach ($this->list as $indi) {
2201                $key  = $indi->xref();
2202                $grec = $indi->privatizeGedcom(Auth::accessLevel($this->tree));
2203                $keep = true;
2204                foreach ($filters2 as $filter) {
2205                    if ($keep) {
2206                        $tag  = $filter['tag'];
2207                        $expr = $filter['expr'];
2208                        $val  = $filter['val'];
2209                        if ($val === "''") {
2210                            $val = '';
2211                        }
2212                        $tags = explode(':', $tag);
2213                        $t    = end($tags);
2214                        $v    = $this->getGedcomValue($tag, 1, $grec);
2215                        //-- check for EMAIL and _EMAIL (silly double gedcom standard :P)
2216                        if ($t === 'EMAIL' && empty($v)) {
2217                            $tag  = str_replace('EMAIL', '_EMAIL', $tag);
2218                            $tags = explode(':', $tag);
2219                            $t    = end($tags);
2220                            $v    = self::getSubRecord(1, $tag, $grec);
2221                        }
2222
2223                        switch ($expr) {
2224                            case 'GTE':
2225                                if ($t === 'DATE') {
2226                                    $date1 = new Date($v);
2227                                    $date2 = new Date($val);
2228                                    $keep  = (Date::compare($date1, $date2) >= 0);
2229                                } elseif ($val >= $v) {
2230                                    $keep = true;
2231                                }
2232                                break;
2233                            case 'LTE':
2234                                if ($t === 'DATE') {
2235                                    $date1 = new Date($v);
2236                                    $date2 = new Date($val);
2237                                    $keep  = (Date::compare($date1, $date2) <= 0);
2238                                } elseif ($val >= $v) {
2239                                    $keep = true;
2240                                }
2241                                break;
2242                            default:
2243                                if ($v == $val) {
2244                                    $keep = true;
2245                                } else {
2246                                    $keep = false;
2247                                }
2248                                break;
2249                        }
2250                    }
2251                }
2252                if ($keep) {
2253                    $mylist[$key] = $indi;
2254                }
2255            }
2256            $this->list = $mylist;
2257        }
2258
2259        switch ($sortby) {
2260            case 'NAME':
2261                uasort($this->list, GedcomRecord::nameComparator());
2262                break;
2263            case 'CHAN':
2264                uasort($this->list, GedcomRecord::lastChangeComparator());
2265                break;
2266            case 'BIRT:DATE':
2267                uasort($this->list, Individual::birthDateComparator());
2268                break;
2269            case 'DEAT:DATE':
2270                uasort($this->list, Individual::deathDateComparator());
2271                break;
2272            case 'MARR:DATE':
2273                uasort($this->list, Family::marriageDateComparator());
2274                break;
2275            default:
2276                // unsorted or already sorted by SQL
2277                break;
2278        }
2279
2280        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2281        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2282    }
2283
2284    /**
2285     * Handle </list>
2286     *
2287     * @return void
2288     */
2289    protected function listEndHandler(): void
2290    {
2291        $this->process_repeats--;
2292        if ($this->process_repeats > 0) {
2293            return;
2294        }
2295
2296        // Check if there is any list
2297        if (count($this->list) > 0) {
2298            $lineoffset = 0;
2299            foreach ($this->repeats_stack as $rep) {
2300                $lineoffset += $rep[1];
2301            }
2302            //-- read the xml from the file
2303            $lines = file($this->report);
2304            while ((!str_contains($lines[$lineoffset + $this->repeat_bytes], '<List')) && (($lineoffset + $this->repeat_bytes) > 0)) {
2305                $lineoffset--;
2306            }
2307            $lineoffset++;
2308            $reportxml = "<tempdoc>\n";
2309            $line_nr   = $lineoffset + $this->repeat_bytes;
2310            // List Level counter
2311            $count = 1;
2312            while (0 < $count) {
2313                if (str_contains($lines[$line_nr], '<List')) {
2314                    $count++;
2315                } elseif (str_contains($lines[$line_nr], '</List')) {
2316                    $count--;
2317                }
2318                if (0 < $count) {
2319                    $reportxml .= $lines[$line_nr];
2320                }
2321                $line_nr++;
2322            }
2323            // No need to drag this
2324            unset($lines);
2325            $reportxml .= '</tempdoc>';
2326            // Save original values
2327            $this->parser_stack[] = $this->parser;
2328            $oldgedrec            = $this->gedrec;
2329
2330            $this->list_total   = count($this->list);
2331            $this->list_private = 0;
2332            foreach ($this->list as $record) {
2333                if ($record->canShow()) {
2334                    $this->gedrec = $record->privatizeGedcom(Auth::accessLevel($record->tree()));
2335                    //-- start the sax parser
2336                    $repeat_parser = xml_parser_create();
2337                    $this->parser  = $repeat_parser;
2338                    xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
2339
2340                    xml_set_element_handler(
2341                        $repeat_parser,
2342                        function ($parser, string $name, array $attrs): void {
2343                            $this->startElement($parser, $name, $attrs);
2344                        },
2345                        function ($parser, string $name): void {
2346                            $this->endElement($parser, $name);
2347                        }
2348                    );
2349
2350                    xml_set_character_data_handler(
2351                        $repeat_parser,
2352                        function ($parser, string $data): void {
2353                            $this->characterData($parser, $data);
2354                        }
2355                    );
2356
2357                    if (!xml_parse($repeat_parser, $reportxml, true)) {
2358                        throw new DomainException(sprintf(
2359                            'ListEHandler XML error: %s at line %d',
2360                            xml_error_string(xml_get_error_code($repeat_parser)),
2361                            xml_get_current_line_number($repeat_parser)
2362                        ));
2363                    }
2364                    xml_parser_free($repeat_parser);
2365                } else {
2366                    $this->list_private++;
2367                }
2368            }
2369            $this->list   = [];
2370            $this->parser = array_pop($this->parser_stack);
2371            $this->gedrec = $oldgedrec;
2372        }
2373        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2374    }
2375
2376    /**
2377     * Handle <listTotal>
2378     * Prints the total number of records in a list
2379     * The total number is collected from <list> and <relatives>
2380     *
2381     * @return void
2382     */
2383    protected function listTotalStartHandler(): void
2384    {
2385        if ($this->list_private == 0) {
2386            $this->current_element->addText((string) $this->list_total);
2387        } else {
2388            $this->current_element->addText(($this->list_total - $this->list_private) . ' / ' . $this->list_total);
2389        }
2390    }
2391
2392    /**
2393     * Handle <relatives>
2394     *
2395     * @param array<string> $attrs
2396     *
2397     * @return void
2398     */
2399    protected function relativesStartHandler(array $attrs): void
2400    {
2401        $this->process_repeats++;
2402        if ($this->process_repeats > 1) {
2403            return;
2404        }
2405
2406        $sortby = $attrs['sortby'] ?? 'NAME';
2407
2408        $match = [];
2409        if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2410            $sortby = $this->vars[$match[1]]['id'];
2411            $sortby = trim($sortby);
2412        }
2413
2414        $maxgen = -1;
2415        if (isset($attrs['maxgen'])) {
2416            $maxgen = (int) $attrs['maxgen'];
2417        }
2418
2419        $group = $attrs['group'] ?? 'child-family';
2420
2421        if (preg_match("/\\$(\w+)/", $group, $match)) {
2422            $group = $this->vars[$match[1]]['id'];
2423            $group = trim($group);
2424        }
2425
2426        $id = $attrs['id'] ?? '';
2427
2428        if (preg_match("/\\$(\w+)/", $id, $match)) {
2429            $id = $this->vars[$match[1]]['id'];
2430            $id = trim($id);
2431        }
2432
2433        $this->list = [];
2434        $person     = Registry::individualFactory()->make($id, $this->tree);
2435        if ($person instanceof Individual) {
2436            $this->list[$id] = $person;
2437            switch ($group) {
2438                case 'child-family':
2439                    foreach ($person->childFamilies() as $family) {
2440                        foreach ($family->spouses() as $spouse) {
2441                            $this->list[$spouse->xref()] = $spouse;
2442                        }
2443
2444                        foreach ($family->children() as $child) {
2445                            $this->list[$child->xref()] = $child;
2446                        }
2447                    }
2448                    break;
2449                case 'spouse-family':
2450                    foreach ($person->spouseFamilies() as $family) {
2451                        foreach ($family->spouses() as $spouse) {
2452                            $this->list[$spouse->xref()] = $spouse;
2453                        }
2454
2455                        foreach ($family->children() as $child) {
2456                            $this->list[$child->xref()] = $child;
2457                        }
2458                    }
2459                    break;
2460                case 'direct-ancestors':
2461                    $this->addAncestors($this->list, $id, false, $maxgen);
2462                    break;
2463                case 'ancestors':
2464                    $this->addAncestors($this->list, $id, true, $maxgen);
2465                    break;
2466                case 'descendants':
2467                    $this->list[$id]->generation = 1;
2468                    $this->addDescendancy($this->list, $id, false, $maxgen);
2469                    break;
2470                case 'all':
2471                    $this->addAncestors($this->list, $id, true, $maxgen);
2472                    $this->addDescendancy($this->list, $id, true, $maxgen);
2473                    break;
2474            }
2475        }
2476
2477        switch ($sortby) {
2478            case 'NAME':
2479                uasort($this->list, GedcomRecord::nameComparator());
2480                break;
2481            case 'BIRT:DATE':
2482                uasort($this->list, Individual::birthDateComparator());
2483                break;
2484            case 'DEAT:DATE':
2485                uasort($this->list, Individual::deathDateComparator());
2486                break;
2487            case 'generation':
2488                $newarray = [];
2489                reset($this->list);
2490                $genCounter = 1;
2491                while (count($newarray) < count($this->list)) {
2492                    foreach ($this->list as $key => $value) {
2493                        $this->generation = $value->generation;
2494                        if ($this->generation == $genCounter) {
2495                            $newarray[$key] = (object) ['generation' => $this->generation];
2496                        }
2497                    }
2498                    $genCounter++;
2499                }
2500                $this->list = $newarray;
2501                break;
2502            default:
2503                // unsorted
2504                break;
2505        }
2506        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2507        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2508    }
2509
2510    /**
2511     * Handle </relatives>
2512     *
2513     * @return void
2514     */
2515    protected function relativesEndHandler(): void
2516    {
2517        $this->process_repeats--;
2518        if ($this->process_repeats > 0) {
2519            return;
2520        }
2521
2522        // Check if there is any relatives
2523        if (count($this->list) > 0) {
2524            $lineoffset = 0;
2525            foreach ($this->repeats_stack as $rep) {
2526                $lineoffset += $rep[1];
2527            }
2528            //-- read the xml from the file
2529            $lines = file($this->report);
2530            while (!str_contains($lines[$lineoffset + $this->repeat_bytes], '<Relatives') && $lineoffset + $this->repeat_bytes > 0) {
2531                $lineoffset--;
2532            }
2533            $lineoffset++;
2534            $reportxml = "<tempdoc>\n";
2535            $line_nr   = $lineoffset + $this->repeat_bytes;
2536            // Relatives Level counter
2537            $count = 1;
2538            while (0 < $count) {
2539                if (str_contains($lines[$line_nr], '<Relatives')) {
2540                    $count++;
2541                } elseif (str_contains($lines[$line_nr], '</Relatives')) {
2542                    $count--;
2543                }
2544                if (0 < $count) {
2545                    $reportxml .= $lines[$line_nr];
2546                }
2547                $line_nr++;
2548            }
2549            // No need to drag this
2550            unset($lines);
2551            $reportxml .= "</tempdoc>\n";
2552            // Save original values
2553            $this->parser_stack[] = $this->parser;
2554            $oldgedrec            = $this->gedrec;
2555
2556            $this->list_total   = count($this->list);
2557            $this->list_private = 0;
2558            foreach ($this->list as $xref => $value) {
2559                if (isset($value->generation)) {
2560                    $this->generation = $value->generation;
2561                }
2562                $tmp          = Registry::gedcomRecordFactory()->make((string) $xref, $this->tree);
2563                $this->gedrec = $tmp->privatizeGedcom(Auth::accessLevel($this->tree));
2564
2565                $repeat_parser = xml_parser_create();
2566                $this->parser  = $repeat_parser;
2567                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
2568
2569                xml_set_element_handler(
2570                    $repeat_parser,
2571                    function ($parser, string $name, array $attrs): void {
2572                        $this->startElement($parser, $name, $attrs);
2573                    },
2574                    function ($parser, string $name): void {
2575                        $this->endElement($parser, $name);
2576                    }
2577                );
2578
2579                xml_set_character_data_handler(
2580                    $repeat_parser,
2581                    function ($parser, string $data): void {
2582                        $this->characterData($parser, $data);
2583                    }
2584                );
2585
2586                if (!xml_parse($repeat_parser, $reportxml, true)) {
2587                    throw new DomainException(sprintf('RelativesEHandler XML error: %s at line %d', xml_error_string(xml_get_error_code($repeat_parser)), xml_get_current_line_number($repeat_parser)));
2588                }
2589                xml_parser_free($repeat_parser);
2590            }
2591            // Clean up the list array
2592            $this->list   = [];
2593            $this->parser = array_pop($this->parser_stack);
2594            $this->gedrec = $oldgedrec;
2595        }
2596        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2597    }
2598
2599    /**
2600     * Handle <generation />
2601     * Prints the number of generations
2602     *
2603     * @return void
2604     */
2605    protected function generationStartHandler(): void
2606    {
2607        $this->current_element->addText((string) $this->generation);
2608    }
2609
2610    /**
2611     * Handle <newPage />
2612     * Has to be placed in an element (header, body or footer)
2613     *
2614     * @return void
2615     */
2616    protected function newPageStartHandler(): void
2617    {
2618        $temp = 'addpage';
2619        $this->wt_report->addElement($temp);
2620    }
2621
2622    /**
2623     * Handle </title>
2624     *
2625     * @return void
2626     */
2627    protected function titleEndHandler(): void
2628    {
2629        $this->report_root->addTitle($this->text);
2630    }
2631
2632    /**
2633     * Handle </description>
2634     *
2635     * @return void
2636     */
2637    protected function descriptionEndHandler(): void
2638    {
2639        $this->report_root->addDescription($this->text);
2640    }
2641
2642    /**
2643     * Create a list of all descendants.
2644     *
2645     * @param array<Individual> $list
2646     * @param string            $pid
2647     * @param bool              $parents
2648     * @param int               $generations
2649     *
2650     * @return void
2651     */
2652    private function addDescendancy(&$list, $pid, $parents = false, $generations = -1): void
2653    {
2654        $person = Registry::individualFactory()->make($pid, $this->tree);
2655        if ($person === null) {
2656            return;
2657        }
2658        if (!isset($list[$pid])) {
2659            $list[$pid] = $person;
2660        }
2661        if (!isset($list[$pid]->generation)) {
2662            $list[$pid]->generation = 0;
2663        }
2664        foreach ($person->spouseFamilies() as $family) {
2665            if ($parents) {
2666                $husband = $family->husband();
2667                $wife    = $family->wife();
2668                if ($husband) {
2669                    $list[$husband->xref()] = $husband;
2670                    if (isset($list[$pid]->generation)) {
2671                        $list[$husband->xref()]->generation = $list[$pid]->generation - 1;
2672                    } else {
2673                        $list[$husband->xref()]->generation = 1;
2674                    }
2675                }
2676                if ($wife) {
2677                    $list[$wife->xref()] = $wife;
2678                    if (isset($list[$pid]->generation)) {
2679                        $list[$wife->xref()]->generation = $list[$pid]->generation - 1;
2680                    } else {
2681                        $list[$wife->xref()]->generation = 1;
2682                    }
2683                }
2684            }
2685
2686            $children = $family->children();
2687
2688            foreach ($children as $child) {
2689                if ($child) {
2690                    $list[$child->xref()] = $child;
2691
2692                    if (isset($list[$pid]->generation)) {
2693                        $list[$child->xref()]->generation = $list[$pid]->generation + 1;
2694                    } else {
2695                        $list[$child->xref()]->generation = 2;
2696                    }
2697                }
2698            }
2699            if ($generations == -1 || $list[$pid]->generation + 1 < $generations) {
2700                foreach ($children as $child) {
2701                    $this->addDescendancy($list, $child->xref(), $parents, $generations); // recurse on the childs family
2702                }
2703            }
2704        }
2705    }
2706
2707    /**
2708     * Create a list of all ancestors.
2709     *
2710     * @param array<Individual> $list
2711     * @param string            $pid
2712     * @param bool              $children
2713     * @param int               $generations
2714     *
2715     * @return void
2716     */
2717    private function addAncestors(array &$list, string $pid, bool $children = false, int $generations = -1): void
2718    {
2719        $genlist                = [$pid];
2720        $list[$pid]->generation = 1;
2721        while (count($genlist) > 0) {
2722            $id = array_shift($genlist);
2723            if (str_starts_with($id, 'empty')) {
2724                continue; // id can be something like “empty7”
2725            }
2726            $person = Registry::individualFactory()->make($id, $this->tree);
2727            foreach ($person->childFamilies() as $family) {
2728                $husband = $family->husband();
2729                $wife    = $family->wife();
2730                if ($husband) {
2731                    $list[$husband->xref()]             = $husband;
2732                    $list[$husband->xref()]->generation = $list[$id]->generation + 1;
2733                }
2734                if ($wife) {
2735                    $list[$wife->xref()]             = $wife;
2736                    $list[$wife->xref()]->generation = $list[$id]->generation + 1;
2737                }
2738                if ($generations == -1 || $list[$id]->generation + 1 < $generations) {
2739                    if ($husband) {
2740                        $genlist[] = $husband->xref();
2741                    }
2742                    if ($wife) {
2743                        $genlist[] = $wife->xref();
2744                    }
2745                }
2746                if ($children) {
2747                    foreach ($family->children() as $child) {
2748                        $list[$child->xref()] = $child;
2749                        $list[$child->xref()]->generation = $list[$id]->generation ?? 1;
2750                    }
2751                }
2752            }
2753        }
2754    }
2755
2756    /**
2757     * get gedcom tag value
2758     *
2759     * @param string $tag    The tag to find, use : to delineate subtags
2760     * @param int    $level  The gedcom line level of the first tag to find, setting level to 0 will cause it to use 1+ the level of the incoming record
2761     * @param string $gedrec The gedcom record to get the value from
2762     *
2763     * @return string the value of a gedcom tag from the given gedcom record
2764     */
2765    private function getGedcomValue(string $tag, int $level, string $gedrec): string
2766    {
2767        if ($gedrec === '') {
2768            return '';
2769        }
2770        $tags      = explode(':', $tag);
2771        $origlevel = $level;
2772        if ($level === 0) {
2773            $level = $gedrec[0] + 1;
2774        }
2775
2776        $subrec = $gedrec;
2777        $t = 'XXXX';
2778        foreach ($tags as $t) {
2779            $lastsubrec = $subrec;
2780            $subrec     = self::getSubRecord($level, "$level $t", $subrec);
2781            if (empty($subrec) && $origlevel == 0) {
2782                $level--;
2783                $subrec = self::getSubRecord($level, "$level $t", $lastsubrec);
2784            }
2785            if (empty($subrec)) {
2786                if ($t === 'TITL') {
2787                    $subrec = self::getSubRecord($level, "$level ABBR", $lastsubrec);
2788                    if (!empty($subrec)) {
2789                        $t = 'ABBR';
2790                    }
2791                }
2792                if ($subrec === '') {
2793                    if ($level > 0) {
2794                        $level--;
2795                    }
2796                    $subrec = self::getSubRecord($level, "@ $t", $gedrec);
2797                    if ($subrec === '') {
2798                        return '';
2799                    }
2800                }
2801            }
2802            $level++;
2803        }
2804        $level--;
2805        $ct = preg_match("/$level $t(.*)/", $subrec, $match);
2806        if ($ct === 0) {
2807            $ct = preg_match("/$level @.+@ (.+)/", $subrec, $match);
2808        }
2809        if ($ct === 0) {
2810            $ct = preg_match("/@ $t (.+)/", $subrec, $match);
2811        }
2812        if ($ct > 0) {
2813            $value = trim($match[1]);
2814            if ($t === 'NOTE' && preg_match('/^@(.+)@$/', $value, $match)) {
2815                $note = Registry::noteFactory()->make($match[1], $this->tree);
2816                if ($note instanceof Note) {
2817                    $value = $note->getNote();
2818                } else {
2819                    //-- set the value to the id without the @
2820                    $value = $match[1];
2821                }
2822            }
2823            if ($level !== 0 || $t !== 'NOTE') {
2824                $value .= self::getCont($level + 1, $subrec);
2825            }
2826
2827            return $value;
2828        }
2829
2830        return '';
2831    }
2832
2833    /**
2834     * Replace variable identifiers with their values.
2835     *
2836     * @param string $expression An expression such as "$foo == 123"
2837     * @param bool   $quote      Whether to add quotation marks
2838     *
2839     * @return string
2840     */
2841    private function substituteVars($expression, $quote): string
2842    {
2843        return preg_replace_callback(
2844            '/\$(\w+)/',
2845            function (array $matches) use ($quote): string {
2846                if (isset($this->vars[$matches[1]]['id'])) {
2847                    if ($quote) {
2848                        return "'" . addcslashes($this->vars[$matches[1]]['id'], "'") . "'";
2849                    }
2850
2851                    return $this->vars[$matches[1]]['id'];
2852                }
2853
2854                Log::addErrorLog(sprintf('Undefined variable $%s in report', $matches[1]));
2855
2856                return '$' . $matches[1];
2857            },
2858            $expression
2859        );
2860    }
2861}
2862