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