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