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