xref: /webtrees/app/Report/ReportParserGenerate.php (revision 1b3d473101dab7842c4b40a9b5108ea099b06b39)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16declare(strict_types=1);
17
18namespace Fisharebest\Webtrees\Report;
19
20use DomainException;
21use Fisharebest\Webtrees\Auth;
22use Fisharebest\Webtrees\Carbon;
23use Fisharebest\Webtrees\Date;
24use Fisharebest\Webtrees\Family;
25use Fisharebest\Webtrees\Filter;
26use Fisharebest\Webtrees\Functions\Functions;
27use Fisharebest\Webtrees\Gedcom;
28use Fisharebest\Webtrees\GedcomRecord;
29use Fisharebest\Webtrees\GedcomTag;
30use Fisharebest\Webtrees\I18N;
31use Fisharebest\Webtrees\Individual;
32use Fisharebest\Webtrees\Log;
33use Fisharebest\Webtrees\Media;
34use Fisharebest\Webtrees\Note;
35use Fisharebest\Webtrees\Place;
36use Fisharebest\Webtrees\Tree;
37use Illuminate\Database\Capsule\Manager as DB;
38use Illuminate\Database\Query\Builder;
39use Illuminate\Database\Query\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): void
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): void
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): void
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): void
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): void
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(): void
369    {
370        $this->wt_report->run();
371    }
372
373    /**
374     * XML <Header>
375     *
376     * @return void
377     */
378    private function headerStartHandler(): void
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(): void
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(): void
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(): void
417    {
418        $this->wt_report->setProcessing('B');
419    }
420
421    /**
422     * XML <footerStartHandler>
423     *
424     * @return void
425     */
426    private function footerStartHandler(): void
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): void
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(): void
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(): void
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(): void
617    {
618        $this->current_element->addText('#PAGENUM#');
619    }
620
621    /**
622     * XML <TotalPages /> element handler
623     *
624     * @return void
625     */
626    private function totalPagesStartHandler(): void
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): void
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     = 1 + (int) $temp[0];
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(): void
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): void
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(): void
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): void
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(): void
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): void
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): void
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, 4) === '<br>') {
1034                        $value = substr($value, 4);
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
1045                if (!empty($attrs['truncate'])) {
1046                    $value = strip_tags($value);
1047                    $value = Str::limit($value, $attrs['truncate'], I18N::translate('…'));
1048                }
1049                $this->current_element->addText($value);
1050            }
1051        }
1052    }
1053
1054    /**
1055     * XML <RepeatTag>
1056     *
1057     * @param string[] $attrs an array of key value pairs for the attributes
1058     *
1059     * @return void
1060     */
1061    private function repeatTagStartHandler(array $attrs): void
1062    {
1063        $this->process_repeats++;
1064        if ($this->process_repeats > 1) {
1065            return;
1066        }
1067
1068        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1069        $this->repeats         = [];
1070        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1071
1072        $tag = $attrs['tag'] ?? '';
1073        if (!empty($tag)) {
1074            if ($tag === '@desc') {
1075                $value = $this->desc;
1076                $value = trim($value);
1077                $this->current_element->addText($value);
1078            } else {
1079                $tag   = str_replace('@fact', $this->fact, $tag);
1080                $tags  = explode(':', $tag);
1081                $temp  = explode(' ', trim($this->gedrec));
1082                $level = $temp[0];
1083                if ($level == 0) {
1084                    $level++;
1085                }
1086                $subrec = $this->gedrec;
1087                $t      = $tag;
1088                $count  = count($tags);
1089                $i      = 0;
1090                while ($i < $count) {
1091                    $t = $tags[$i];
1092                    if (!empty($t)) {
1093                        if ($i < ($count - 1)) {
1094                            $subrec = Functions::getSubRecord($level, "$level $t", $subrec);
1095                            if (empty($subrec)) {
1096                                $level--;
1097                                $subrec = Functions::getSubRecord($level, "@ $t", $this->gedrec);
1098                                if (empty($subrec)) {
1099                                    return;
1100                                }
1101                            }
1102                        }
1103                        $level++;
1104                    }
1105                    $i++;
1106                }
1107                $level--;
1108                $count = preg_match_all("/$level $t(.*)/", $subrec, $match, PREG_SET_ORDER);
1109                $i     = 0;
1110                while ($i < $count) {
1111                    $i++;
1112                    // Privacy check - is this a link, and are we allowed to view the linked object?
1113                    $subrecord = Functions::getSubRecord($level, "$level $t", $subrec, $i);
1114                    if (preg_match('/^\d ' . Gedcom::REGEX_TAG . ' @(' . Gedcom::REGEX_XREF . ')@/', $subrecord, $xref_match)) {
1115                        $linked_object = GedcomRecord::getInstance($xref_match[1], $this->tree);
1116                        if ($linked_object && !$linked_object->canShow()) {
1117                            continue;
1118                        }
1119                    }
1120                    $this->repeats[] = $subrecord;
1121                }
1122            }
1123        }
1124    }
1125
1126    /**
1127     * XML </ RepeatTag>
1128     *
1129     * @return void
1130     */
1131    private function repeatTagEndHandler(): void
1132    {
1133        $this->process_repeats--;
1134        if ($this->process_repeats > 0) {
1135            return;
1136        }
1137
1138        // Check if there is anything to repeat
1139        if (count($this->repeats) > 0) {
1140            // No need to load them if not used...
1141
1142            $lineoffset = 0;
1143            foreach ($this->repeats_stack as $rep) {
1144                $lineoffset += $rep[1];
1145            }
1146            //-- read the xml from the file
1147            $lines = file($this->report);
1148            while (strpos($lines[$lineoffset + $this->repeat_bytes], '<RepeatTag') === false) {
1149                $lineoffset--;
1150            }
1151            $lineoffset++;
1152            $reportxml = "<tempdoc>\n";
1153            $line_nr   = $lineoffset + $this->repeat_bytes;
1154            // RepeatTag Level counter
1155            $count = 1;
1156            while (0 < $count) {
1157                if (strstr($lines[$line_nr], '<RepeatTag') !== false) {
1158                    $count++;
1159                } elseif (strstr($lines[$line_nr], '</RepeatTag') !== false) {
1160                    $count--;
1161                }
1162                if (0 < $count) {
1163                    $reportxml .= $lines[$line_nr];
1164                }
1165                $line_nr++;
1166            }
1167            // No need to drag this
1168            unset($lines);
1169            $reportxml .= "</tempdoc>\n";
1170            // Save original values
1171            $this->parser_stack[] = $this->parser;
1172            $oldgedrec            = $this->gedrec;
1173            foreach ($this->repeats as $gedrec) {
1174                $this->gedrec  = $gedrec;
1175                $repeat_parser = xml_parser_create();
1176                $this->parser  = $repeat_parser;
1177                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
1178
1179                xml_set_element_handler(
1180                    $repeat_parser,
1181                    function ($parser, string $name, array $attrs) {
1182                        $this->startElement($parser, $name, $attrs);
1183                    },
1184                    function ($parser, string $name) {
1185                        $this->endElement($parser, $name);
1186                    }
1187                );
1188
1189                xml_set_character_data_handler(
1190                    $repeat_parser,
1191                    function ($parser, $data) {
1192                        $this->characterData($parser, $data);
1193                    }
1194                );
1195
1196                if (!xml_parse($repeat_parser, $reportxml, true)) {
1197                    throw new DomainException(sprintf(
1198                        'RepeatTagEHandler XML error: %s at line %d',
1199                        xml_error_string(xml_get_error_code($repeat_parser)),
1200                        xml_get_current_line_number($repeat_parser)
1201                    ));
1202                }
1203                xml_parser_free($repeat_parser);
1204            }
1205            // Restore original values
1206            $this->gedrec = $oldgedrec;
1207            $this->parser = array_pop($this->parser_stack);
1208        }
1209        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1210    }
1211
1212    /**
1213     * Variable lookup
1214     * Retrieve predefined variables :
1215     * @ desc GEDCOM fact description, example:
1216     *        1 EVEN This is a description
1217     * @ fact GEDCOM fact tag, such as BIRT, DEAT etc.
1218     * $ I18N::translate('....')
1219     * $ language_settings[]
1220     *
1221     * @param string[] $attrs an array of key value pairs for the attributes
1222     *
1223     * @return void
1224     */
1225    private function varStartHandler(array $attrs): void
1226    {
1227        if (empty($attrs['var'])) {
1228            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));
1229        }
1230
1231        $var = $attrs['var'];
1232        // SetVar element preset variables
1233        if (!empty($this->vars[$var]['id'])) {
1234            $var = $this->vars[$var]['id'];
1235        } else {
1236            $tfact = $this->fact;
1237            if (($this->fact === 'EVEN' || $this->fact === 'FACT') && $this->type !== ' ') {
1238                // Use :
1239                // n TYPE This text if string
1240                $tfact = $this->type;
1241            }
1242            $var = str_replace([
1243                '@fact',
1244                '@desc',
1245            ], [
1246                GedcomTag::getLabel($tfact),
1247                $this->desc,
1248            ], $var);
1249            if (preg_match('/^I18N::number\((.+)\)$/', $var, $match)) {
1250                $var = I18N::number((int) $match[1]);
1251            } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $var, $match)) {
1252                $var = I18N::translate($match[1]);
1253            } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $var, $match)) {
1254                $var = I18N::translateContext($match[1], $match[2]);
1255            }
1256        }
1257        // Check if variable is set as a date and reformat the date
1258        if (isset($attrs['date'])) {
1259            if ($attrs['date'] === '1') {
1260                $g   = new Date($var);
1261                $var = $g->display();
1262            }
1263        }
1264        $this->current_element->addText($var);
1265        $this->text = $var; // Used for title/descriptio
1266    }
1267
1268    /**
1269     * XML <Facts>
1270     *
1271     * @param string[] $attrs an array of key value pairs for the attributes
1272     *
1273     * @return void
1274     */
1275    private function factsStartHandler(array $attrs): void
1276    {
1277        $this->process_repeats++;
1278        if ($this->process_repeats > 1) {
1279            return;
1280        }
1281
1282        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1283        $this->repeats         = [];
1284        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1285
1286        $id    = '';
1287        $match = [];
1288        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1289            $id = $match[1];
1290        }
1291        $tag = '';
1292        if (isset($attrs['ignore'])) {
1293            $tag .= $attrs['ignore'];
1294        }
1295        if (preg_match('/\$(.+)/', $tag, $match)) {
1296            $tag = $this->vars[$match[1]]['id'];
1297        }
1298
1299        $record = GedcomRecord::getInstance($id, $this->tree);
1300        if (empty($attrs['diff']) && !empty($id)) {
1301            $facts = $record->facts([], true);
1302            $this->repeats = [];
1303            $nonfacts      = explode(',', $tag);
1304            foreach ($facts as $fact) {
1305                if (!in_array($fact->getTag(), $nonfacts, true)) {
1306                    $this->repeats[] = $fact->gedcom();
1307                }
1308            }
1309        } else {
1310            foreach ($record->facts() as $fact) {
1311                if (($fact->isPendingAddition() || $fact->isPendingDeletion()) && $fact->getTag() !== 'CHAN') {
1312                    $this->repeats[] = $fact->gedcom();
1313                }
1314            }
1315        }
1316    }
1317
1318    /**
1319     * XML </Facts>
1320     *
1321     * @return void
1322     */
1323    private function factsEndHandler(): void
1324    {
1325        $this->process_repeats--;
1326        if ($this->process_repeats > 0) {
1327            return;
1328        }
1329
1330        // Check if there is anything to repeat
1331        if (count($this->repeats) > 0) {
1332            $line       = xml_get_current_line_number($this->parser) - 1;
1333            $lineoffset = 0;
1334            foreach ($this->repeats_stack as $rep) {
1335                $lineoffset += $rep[1];
1336            }
1337
1338            //-- read the xml from the file
1339            $lines = file($this->report);
1340            while ($lineoffset + $this->repeat_bytes > 0 && strpos($lines[$lineoffset + $this->repeat_bytes], '<Facts ') === false) {
1341                $lineoffset--;
1342            }
1343            $lineoffset++;
1344            $reportxml = "<tempdoc>\n";
1345            $i         = $line + $lineoffset;
1346            $line_nr   = $this->repeat_bytes + $lineoffset;
1347            while ($line_nr < $i) {
1348                $reportxml .= $lines[$line_nr];
1349                $line_nr++;
1350            }
1351            // No need to drag this
1352            unset($lines);
1353            $reportxml .= "</tempdoc>\n";
1354            // Save original values
1355            $this->parser_stack[] = $this->parser;
1356            $oldgedrec            = $this->gedrec;
1357            $count                = count($this->repeats);
1358            $i                    = 0;
1359            while ($i < $count) {
1360                $this->gedrec = $this->repeats[$i];
1361                $this->fact   = '';
1362                $this->desc   = '';
1363                if (preg_match('/1 (\w+)(.*)/', $this->gedrec, $match)) {
1364                    $this->fact = $match[1];
1365                    if ($this->fact === 'EVEN' || $this->fact === 'FACT') {
1366                        $tmatch = [];
1367                        if (preg_match('/2 TYPE (.+)/', $this->gedrec, $tmatch)) {
1368                            $this->type = trim($tmatch[1]);
1369                        } else {
1370                            $this->type = ' ';
1371                        }
1372                    }
1373                    $this->desc = trim($match[2]);
1374                    $this->desc .= Functions::getCont(2, $this->gedrec);
1375                }
1376                $repeat_parser = xml_parser_create();
1377                $this->parser  = $repeat_parser;
1378                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
1379
1380                xml_set_element_handler(
1381                    $repeat_parser,
1382                    function ($parser, string $name, array $attrs) {
1383                        $this->startElement($parser, $name, $attrs);
1384                    },
1385                    function ($parser, string $name) {
1386                        $this->endElement($parser, $name);
1387                    }
1388                );
1389
1390                xml_set_character_data_handler(
1391                    $repeat_parser,
1392                    function ($parser, $data) {
1393                        $this->characterData($parser, $data);
1394                    }
1395                );
1396
1397                if (!xml_parse($repeat_parser, $reportxml, true)) {
1398                    throw new DomainException(sprintf(
1399                        'FactsEHandler XML error: %s at line %d',
1400                        xml_error_string(xml_get_error_code($repeat_parser)),
1401                        xml_get_current_line_number($repeat_parser)
1402                    ));
1403                }
1404                xml_parser_free($repeat_parser);
1405                $i++;
1406            }
1407            // Restore original values
1408            $this->parser = array_pop($this->parser_stack);
1409            $this->gedrec = $oldgedrec;
1410        }
1411        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1412    }
1413
1414    /**
1415     * Setting upp or changing variables in the XML
1416     * The XML variable name and value is stored in $this->vars
1417     *
1418     * @param string[] $attrs an array of key value pairs for the attributes
1419     *
1420     * @return void
1421     */
1422    private function setVarStartHandler(array $attrs): void
1423    {
1424        if (empty($attrs['name'])) {
1425            throw new DomainException('REPORT ERROR var: The attribute "name" is missing or not set in the XML file');
1426        }
1427
1428        $name  = $attrs['name'];
1429        $value = $attrs['value'];
1430        $match = [];
1431        // Current GEDCOM record strings
1432        if ($value === '@ID') {
1433            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1434                $value = $match[1];
1435            }
1436        } elseif ($value === '@fact') {
1437            $value = $this->fact;
1438        } elseif ($value === '@desc') {
1439            $value = $this->desc;
1440        } elseif ($value === '@generation') {
1441            $value = (string) $this->generation;
1442        } elseif (preg_match("/@(\w+)/", $value, $match)) {
1443            $gmatch = [];
1444            if (preg_match("/\d $match[1] (.+)/", $this->gedrec, $gmatch)) {
1445                $value = str_replace('@', '', trim($gmatch[1]));
1446            }
1447        }
1448        if (preg_match("/\\$(\w+)/", $name, $match)) {
1449            $name = $this->vars["'" . $match[1] . "'"]['id'];
1450        }
1451        $count = preg_match_all("/\\$(\w+)/", $value, $match, PREG_SET_ORDER);
1452        $i     = 0;
1453        while ($i < $count) {
1454            $t     = $this->vars[$match[$i][1]]['id'];
1455            $value = preg_replace('/\$' . $match[$i][1] . '/', $t, $value, 1);
1456            $i++;
1457        }
1458        if (preg_match('/^I18N::number\((.+)\)$/', $value, $match)) {
1459            $value = I18N::number((int) $match[1]);
1460        } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $value, $match)) {
1461            $value = I18N::translate($match[1]);
1462        } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $value, $match)) {
1463            $value = I18N::translateContext($match[1], $match[2]);
1464        }
1465
1466        // Arithmetic functions
1467        if (preg_match("/(\d+)\s*([\-\+\*\/])\s*(\d+)/", $value, $match)) {
1468            // Create an expression language with the functions used by our reports.
1469            $expression_provider  = new ReportExpressionLanguageProvider();
1470            $expression_cache     = new NullAdapter();
1471            $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1472
1473            $value = (string) $expression_language->evaluate($value);
1474        }
1475
1476        if (strpos($value, '@') !== false) {
1477            $value = '';
1478        }
1479        $this->vars[$name]['id'] = $value;
1480    }
1481
1482    /**
1483     * XML <if > start element
1484     *
1485     * @param string[] $attrs an array of key value pairs for the attributes
1486     *
1487     * @return void
1488     */
1489    private function ifStartHandler(array $attrs): void
1490    {
1491        if ($this->process_ifs > 0) {
1492            $this->process_ifs++;
1493
1494            return;
1495        }
1496
1497        $condition = $attrs['condition'];
1498        $condition = $this->substituteVars($condition, true);
1499        $condition = str_replace([
1500            ' LT ',
1501            ' GT ',
1502        ], [
1503            '<',
1504            '>',
1505        ], $condition);
1506        // Replace the first accurance only once of @fact:DATE or in any other combinations to the current fact, such as BIRT
1507        $condition = str_replace('@fact:', $this->fact . ':', $condition);
1508        $match     = [];
1509        $count     = preg_match_all("/@([\w:\.]+)/", $condition, $match, PREG_SET_ORDER);
1510        $i         = 0;
1511        while ($i < $count) {
1512            $id    = $match[$i][1];
1513            $value = '""';
1514            if ($id === 'ID') {
1515                if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1516                    $value = "'" . $match[1] . "'";
1517                }
1518            } elseif ($id === 'fact') {
1519                $value = '"' . $this->fact . '"';
1520            } elseif ($id === 'desc') {
1521                $value = '"' . addslashes($this->desc) . '"';
1522            } elseif ($id === 'generation') {
1523                $value = '"' . $this->generation . '"';
1524            } else {
1525                $temp  = explode(' ', trim($this->gedrec));
1526                $level = $temp[0];
1527                if ($level == 0) {
1528                    $level++;
1529                }
1530                $value = $this->getGedcomValue($id, $level, $this->gedrec);
1531                if (empty($value)) {
1532                    $level++;
1533                    $value = $this->getGedcomValue($id, $level, $this->gedrec);
1534                }
1535                $value = preg_replace('/^@(' . Gedcom::REGEX_XREF . ')@$/', '$1', $value);
1536                $value = '"' . addslashes($value) . '"';
1537            }
1538            $condition = str_replace("@$id", $value, $condition);
1539            $i++;
1540        }
1541
1542        // Create an expression language with the functions used by our reports.
1543        $expression_provider  = new ReportExpressionLanguageProvider();
1544        $expression_cache     = new NullAdapter();
1545        $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1546
1547        $ret = $expression_language->evaluate($condition);
1548
1549        if (!$ret) {
1550            $this->process_ifs++;
1551        }
1552    }
1553
1554    /**
1555     * XML <if /> end element
1556     *
1557     * @return void
1558     */
1559    private function ifEndHandler(): void
1560    {
1561        if ($this->process_ifs > 0) {
1562            $this->process_ifs--;
1563        }
1564    }
1565
1566    /**
1567     * XML <Footnote > start element
1568     * Collect the Footnote links
1569     * GEDCOM Records that are protected by Privacy setting will be ignore
1570     *
1571     * @param string[] $attrs an array of key value pairs for the attributes
1572     *
1573     * @return void
1574     */
1575    private function footnoteStartHandler(array $attrs): void
1576    {
1577        $id = '';
1578        if (preg_match('/[0-9] (.+) @(.+)@/', $this->gedrec, $match)) {
1579            $id = $match[2];
1580        }
1581        $record = GedcomRecord::getInstance($id, $this->tree);
1582        if ($record && $record->canShow()) {
1583            $this->print_data_stack[] = $this->print_data;
1584            $this->print_data         = true;
1585            $style                    = '';
1586            if (!empty($attrs['style'])) {
1587                $style = $attrs['style'];
1588            }
1589            $this->footnote_element = $this->current_element;
1590            $this->current_element  = $this->report_root->createFootnote($style);
1591        } else {
1592            $this->print_data       = false;
1593            $this->process_footnote = false;
1594        }
1595    }
1596
1597    /**
1598     * XML <Footnote /> end element
1599     * Print the collected Footnote data
1600     *
1601     * @return void
1602     */
1603    private function footnoteEndHandler(): void
1604    {
1605        if ($this->process_footnote) {
1606            $this->print_data = array_pop($this->print_data_stack);
1607            $temp             = trim($this->current_element->getValue());
1608            if (strlen($temp) > 3) {
1609                $this->wt_report->addElement($this->current_element);
1610            }
1611            $this->current_element = $this->footnote_element;
1612        } else {
1613            $this->process_footnote = true;
1614        }
1615    }
1616
1617    /**
1618     * XML <FootnoteTexts /> element
1619     *
1620     * @return void
1621     */
1622    private function footnoteTextsStartHandler(): void
1623    {
1624        $temp = 'footnotetexts';
1625        $this->wt_report->addElement($temp);
1626    }
1627
1628    /**
1629     * XML element Forced line break handler - HTML code
1630     *
1631     * @return void
1632     */
1633    private function brStartHandler(): void
1634    {
1635        if ($this->print_data && $this->process_gedcoms === 0) {
1636            $this->current_element->addText('<br>');
1637        }
1638    }
1639
1640    /**
1641     * XML <sp />element Forced space handler
1642     *
1643     * @return void
1644     */
1645    private function spStartHandler(): void
1646    {
1647        if ($this->print_data && $this->process_gedcoms === 0) {
1648            $this->current_element->addText(' ');
1649        }
1650    }
1651
1652    /**
1653     * XML <HighlightedImage/>
1654     *
1655     * @param string[] $attrs an array of key value pairs for the attributes
1656     *
1657     * @return void
1658     */
1659    private function highlightedImageStartHandler(array $attrs): void
1660    {
1661        $id = '';
1662        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1663            $id = $match[1];
1664        }
1665
1666        // Position the top corner of this box on the page
1667        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
1668
1669        // Position the left corner of this box on the page
1670        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
1671
1672        // string Align the image in left, center, right (or empty to use x/y position).
1673        $align = $attrs['align'] ?? '';
1674
1675        // string Next Line should be T:next to the image, N:next line
1676        $ln = $attrs['ln'] ?? 'T';
1677
1678        // Width, height (or both).
1679        $width  = (float) ($attrs['width'] ?? 0.0);
1680        $height = (float) ($attrs['height'] ?? 0.0);
1681
1682        $person     = Individual::getInstance($id, $this->tree);
1683        $media_file = $person->findHighlightedMediaFile();
1684
1685        if ($media_file !== null && $media_file->fileExists()) {
1686            $attributes = getimagesize($media_file->getServerFilename()) ?: [
1687                0,
1688                0,
1689            ];
1690            if ($width > 0 && $height == 0) {
1691                $perc   = $width / $attributes[0];
1692                $height = round($attributes[1] * $perc);
1693            } elseif ($height > 0 && $width == 0) {
1694                $perc  = $height / $attributes[1];
1695                $width = round($attributes[0] * $perc);
1696            } else {
1697                $width  = $attributes[0];
1698                $height = $attributes[1];
1699            }
1700            $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
1701            $this->wt_report->addElement($image);
1702        }
1703    }
1704
1705    /**
1706     * XML <Image/>
1707     *
1708     * @param string[] $attrs an array of key value pairs for the attributes
1709     *
1710     * @return void
1711     */
1712    private function imageStartHandler(array $attrs): void
1713    {
1714        // Position the top corner of this box on the page. the default is the current position
1715        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
1716
1717        // mixed Position the left corner of this box on the page. the default is the current position
1718        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
1719
1720        // string Align the image in left, center, right (or empty to use x/y position).
1721        $align = $attrs['align'] ?? '';
1722
1723        // string Next Line should be T:next to the image, N:next line
1724        $ln = $attrs['ln'] ?? 'T';
1725
1726        // Width, height (or both).
1727        $width  = (float) ($attrs['width'] ?? 0.0);
1728        $height = (float) ($attrs['height'] ?? 0.0);
1729
1730        $file = $attrs['file'] ?? '';
1731
1732        if ($file === '@FILE') {
1733            $match = [];
1734            if (preg_match("/\d OBJE @(.+)@/", $this->gedrec, $match)) {
1735                $mediaobject = Media::getInstance($match[1], $this->tree);
1736                $media_file  = $mediaobject->firstImageFile();
1737
1738                if ($media_file !== null && $media_file->fileExists()) {
1739                    $attributes = getimagesize($media_file->getServerFilename()) ?: [
1740                        0,
1741                        0,
1742                    ];
1743                    if ($width > 0 && $height == 0) {
1744                        $perc   = $width / $attributes[0];
1745                        $height = round($attributes[1] * $perc);
1746                    } elseif ($height > 0 && $width == 0) {
1747                        $perc  = $height / $attributes[1];
1748                        $width = round($attributes[0] * $perc);
1749                    } else {
1750                        $width  = $attributes[0];
1751                        $height = $attributes[1];
1752                    }
1753                    $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
1754                    $this->wt_report->addElement($image);
1755                }
1756            }
1757        } else {
1758            if (file_exists($file) && preg_match('/(jpg|jpeg|png|gif)$/i', $file)) {
1759                $size = getimagesize($file);
1760                if ($width > 0 && $height == 0) {
1761                    $perc   = $width / $size[0];
1762                    $height = round($size[1] * $perc);
1763                } elseif ($height > 0 && $width == 0) {
1764                    $perc  = $height / $size[1];
1765                    $width = round($size[0] * $perc);
1766                } else {
1767                    $width  = $size[0];
1768                    $height = $size[1];
1769                }
1770                $image = $this->report_root->createImage($file, $left, $top, $width, $height, $align, $ln);
1771                $this->wt_report->addElement($image);
1772            }
1773        }
1774    }
1775
1776    /**
1777     * XML <Line> element handler
1778     *
1779     * @param string[] $attrs an array of key value pairs for the attributes
1780     *
1781     * @return void
1782     */
1783    private function lineStartHandler(array $attrs): void
1784    {
1785        // Start horizontal position, current position (default)
1786        $x1 = ReportBaseElement::CURRENT_POSITION;
1787        if (isset($attrs['x1'])) {
1788            if ($attrs['x1'] === '0') {
1789                $x1 = 0;
1790            } elseif ($attrs['x1'] === '.') {
1791                $x1 = ReportBaseElement::CURRENT_POSITION;
1792            } elseif (!empty($attrs['x1'])) {
1793                $x1 = (float) $attrs['x1'];
1794            }
1795        }
1796        // Start vertical position, current position (default)
1797        $y1 = ReportBaseElement::CURRENT_POSITION;
1798        if (isset($attrs['y1'])) {
1799            if ($attrs['y1'] === '0') {
1800                $y1 = 0;
1801            } elseif ($attrs['y1'] === '.') {
1802                $y1 = ReportBaseElement::CURRENT_POSITION;
1803            } elseif (!empty($attrs['y1'])) {
1804                $y1 = (float) $attrs['y1'];
1805            }
1806        }
1807        // End horizontal position, maximum width (default)
1808        $x2 = ReportBaseElement::CURRENT_POSITION;
1809        if (isset($attrs['x2'])) {
1810            if ($attrs['x2'] === '0') {
1811                $x2 = 0;
1812            } elseif ($attrs['x2'] === '.') {
1813                $x2 = ReportBaseElement::CURRENT_POSITION;
1814            } elseif (!empty($attrs['x2'])) {
1815                $x2 = (float) $attrs['x2'];
1816            }
1817        }
1818        // End vertical position
1819        $y2 = ReportBaseElement::CURRENT_POSITION;
1820        if (isset($attrs['y2'])) {
1821            if ($attrs['y2'] === '0') {
1822                $y2 = 0;
1823            } elseif ($attrs['y2'] === '.') {
1824                $y2 = ReportBaseElement::CURRENT_POSITION;
1825            } elseif (!empty($attrs['y2'])) {
1826                $y2 = (float) $attrs['y2'];
1827            }
1828        }
1829
1830        $line = $this->report_root->createLine($x1, $y1, $x2, $y2);
1831        $this->wt_report->addElement($line);
1832    }
1833
1834    /**
1835     * XML <List>
1836     *
1837     * @param string[] $attrs an array of key value pairs for the attributes
1838     *
1839     * @return void
1840     */
1841    private function listStartHandler(array $attrs): void
1842    {
1843        $this->process_repeats++;
1844        if ($this->process_repeats > 1) {
1845            return;
1846        }
1847
1848        $match = [];
1849        if (isset($attrs['sortby'])) {
1850            $sortby = $attrs['sortby'];
1851            if (preg_match("/\\$(\w+)/", $sortby, $match)) {
1852                $sortby = $this->vars[$match[1]]['id'];
1853                $sortby = trim($sortby);
1854            }
1855        } else {
1856            $sortby = 'NAME';
1857        }
1858
1859        $listname = $attrs['list'] ?? 'individual';
1860
1861        // Some filters/sorts can be applied using SQL, while others require PHP
1862        switch ($listname) {
1863            case 'pending':
1864                $xrefs = DB::table('change')
1865                    ->whereIn('change_id', function (Builder $query): void {
1866                        $query->select(DB::raw('MAX(change_id)'))
1867                            ->from('change')
1868                            ->where('gedcom_id', '=', $this->tree->id())
1869                            ->where('status', '=', 'pending')
1870                            ->groupBy('xref');
1871                    })
1872                    ->pluck('xref');
1873
1874                $this->list = [];
1875                foreach ($xrefs as $xref) {
1876                    $this->list[] = GedcomRecord::getInstance($xref, $this->tree);
1877                }
1878                break;
1879            case 'individual':
1880                $query = DB::table('individuals')
1881                    ->where('i_file', '=', $this->tree->id())
1882                    ->select(['i_id AS xref', 'i_gedcom AS gedcom'])
1883                    ->distinct();
1884
1885                foreach ($attrs as $attr => $value) {
1886                    if (strpos($attr, 'filter') === 0 && $value) {
1887                        $value = $this->substituteVars($value, false);
1888                        // Convert the various filters into SQL
1889                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
1890                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
1891                                $join
1892                                    ->on($attr . '.d_gid', '=', 'i_id')
1893                                    ->on($attr . '.d_file', '=', 'i_file');
1894                            });
1895
1896                            $query->where($attr . '.d_fact', '=', $match[1]);
1897
1898                            $date = new Date($match[3]);
1899
1900                            if ($match[2] === 'LTE') {
1901                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
1902                            } else {
1903                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
1904                            }
1905
1906                            // This filter has been fully processed
1907                            unset($attrs[$attr]);
1908                        } elseif (preg_match('/^NAME CONTAINS (.+)$/', $value, $match)) {
1909                            $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
1910                                $join
1911                                    ->on($attr . '.n_id', '=', 'i_id')
1912                                    ->on($attr . '.n_file', '=', 'i_file');
1913                            });
1914                            // Search the DB only if there is any name supplied
1915                            $names = explode(' ', $match[1]);
1916                            foreach ($names as $n => $name) {
1917                                $query->whereContains($attr . '.n_full', $name);
1918                            }
1919
1920                            // This filter has been fully processed
1921                            unset($attrs[$attr]);
1922                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
1923                            // Convert newline escape sequences to actual new lines
1924                            $match[1] = str_replace('\n', "\n", $match[1]);
1925
1926                            $query->where('i_gedcom', 'LIKE', $match[1]);
1927
1928                            // This filter has been fully processed
1929                            unset($attrs[$attr]);
1930                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
1931                            // Don't unset this filter. This is just initial filtering for performance
1932                            $query
1933                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
1934                                    $join
1935                                        ->on($attr . 'a.pl_file', '=', 'i_file')
1936                                        ->on($attr . 'a.pl_gid', '=', 'i_id');
1937                                })
1938                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
1939                                    $join
1940                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
1941                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
1942                                })
1943                                ->whereContains($attr . 'b.p_place', $match[1]);
1944                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
1945                            // Don't unset this filter. This is just initial filtering for performance
1946                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
1947                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
1948                            $query->where('i_gedcom', 'LIKE', $like);
1949                        } elseif (preg_match('/^(\w+) CONTAINS (.+)$/', $value, $match)) {
1950                            // Don't unset this filter. This is just initial filtering for performance
1951                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
1952                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
1953                            $query->where('i_gedcom', 'LIKE', $like);
1954                        }
1955                    }
1956                }
1957
1958                $this->list = [];
1959
1960                foreach ($query->get() as $row) {
1961                    $this->list[$row->xref] = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
1962                }
1963                break;
1964
1965            case 'family':
1966                $query = DB::table('families')
1967                    ->where('f_file', '=', $this->tree->id())
1968                    ->select(['f_id AS xref', 'f_gedcom AS gedcom'])
1969                    ->distinct();
1970
1971                foreach ($attrs as $attr => $value) {
1972                    if (strpos($attr, 'filter') === 0 && $value) {
1973                        $value = $this->substituteVars($value, false);
1974                        // Convert the various filters into SQL
1975                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
1976                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
1977                                $join
1978                                    ->on($attr . '.d_gid', '=', 'f_id')
1979                                    ->on($attr . '.d_file', '=', 'f_file');
1980                            });
1981
1982                            $query->where($attr . '.d_fact', '=', $match[1]);
1983
1984                            $date = new Date($match[3]);
1985
1986                            if ($match[2] === 'LTE') {
1987                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
1988                            } else {
1989                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
1990                            }
1991
1992                            // This filter has been fully processed
1993                            unset($attrs[$attr]);
1994                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
1995                            // Convert newline escape sequences to actual new lines
1996                            $match[1] = str_replace('\n', "\n", $match[1]);
1997
1998                            $query->where('f_gedcom', 'LIKE', $match[1]);
1999
2000                            // This filter has been fully processed
2001                            unset($attrs[$attr]);
2002                        } elseif (preg_match('/^NAME CONTAINS (.*)$/', $value, $match)) {
2003                            if ($sortby === 'NAME' || $match[1] !== '') {
2004                                $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2005                                    $join
2006                                        ->on($attr . '.n_file', '=', 'f_file')
2007                                        ->where(static function (Builder $query): void {
2008                                            $query
2009                                                ->whereColumn('n_id', '=', 'f_husb')
2010                                                ->orWhereColumn('n_id', '=', 'f_wife');
2011                                        });
2012                                });
2013                                // Search the DB only if there is any name supplied
2014                                if ($match[1] != '') {
2015                                    $names = explode(' ', $match[1]);
2016                                    foreach ($names as $n => $name) {
2017                                        $query->whereContains($attr . '.n_full', $name);
2018                                    }
2019                                }
2020                            }
2021
2022                            // This filter has been fully processed
2023                            unset($attrs[$attr]);
2024                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
2025                            // Don't unset this filter. This is just initial filtering for performance
2026                            $query
2027                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
2028                                    $join
2029                                        ->on($attr . 'a.pl_file', '=', 'f_file')
2030                                        ->on($attr . 'a.pl_gid', '=', 'f_id');
2031                                })
2032                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
2033                                    $join
2034                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
2035                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
2036                                })
2037                                ->whereContains($attr . 'b.p_place', $match[1]);
2038                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
2039                            // Don't unset this filter. This is just initial filtering for performance
2040                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2041                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
2042                            $query->where('f_gedcom', 'LIKE', $like);
2043                        } elseif (preg_match('/^(\w+) CONTAINS (.+)$/', $value, $match)) {
2044                            // Don't unset this filter. This is just initial filtering for performance
2045                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2046                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
2047                            $query->where('f_gedcom', 'LIKE', $like);
2048                        }
2049                    }
2050                }
2051
2052                $this->list = [];
2053
2054                foreach ($query->get() as $row) {
2055                    $this->list[$row->xref] = Family::getInstance($row->xref, $this->tree, $row->gedcom);
2056                }
2057                break;
2058
2059            default:
2060                throw new DomainException('Invalid list name: ' . $listname);
2061        }
2062
2063        $filters  = [];
2064        $filters2 = [];
2065        if (isset($attrs['filter1']) && count($this->list) > 0) {
2066            foreach ($attrs as $key => $value) {
2067                if (preg_match("/filter(\d)/", $key)) {
2068                    $condition = $value;
2069                    if (preg_match("/@(\w+)/", $condition, $match)) {
2070                        $id    = $match[1];
2071                        $value = "''";
2072                        if ($id === 'ID') {
2073                            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
2074                                $value = "'" . $match[1] . "'";
2075                            }
2076                        } elseif ($id === 'fact') {
2077                            $value = "'" . $this->fact . "'";
2078                        } elseif ($id === 'desc') {
2079                            $value = "'" . $this->desc . "'";
2080                        } else {
2081                            if (preg_match("/\d $id (.+)/", $this->gedrec, $match)) {
2082                                $value = "'" . str_replace('@', '', trim($match[1])) . "'";
2083                            }
2084                        }
2085                        $condition = preg_replace("/@$id/", $value, $condition);
2086                    }
2087                    //-- handle regular expressions
2088                    if (preg_match("/([A-Z:]+)\s*([^\s]+)\s*(.+)/", $condition, $match)) {
2089                        $tag  = trim($match[1]);
2090                        $expr = trim($match[2]);
2091                        $val  = trim($match[3]);
2092                        if (preg_match("/\\$(\w+)/", $val, $match)) {
2093                            $val = $this->vars[$match[1]]['id'];
2094                            $val = trim($val);
2095                        }
2096                        if ($val) {
2097                            $searchstr = '';
2098                            $tags      = explode(':', $tag);
2099                            //-- only limit to a level number if we are specifically looking at a level
2100                            if (count($tags) > 1) {
2101                                $level = 1;
2102                                foreach ($tags as $t) {
2103                                    if (!empty($searchstr)) {
2104                                        $searchstr .= "[^\n]*(\n[2-9][^\n]*)*\n";
2105                                    }
2106                                    //-- search for both EMAIL and _EMAIL... silly double gedcom standard
2107                                    if ($t === 'EMAIL' || $t === '_EMAIL') {
2108                                        $t = '_?EMAIL';
2109                                    }
2110                                    $searchstr .= $level . ' ' . $t;
2111                                    $level++;
2112                                }
2113                            } else {
2114                                if ($tag === 'EMAIL' || $tag === '_EMAIL') {
2115                                    $tag = '_?EMAIL';
2116                                }
2117                                $t         = $tag;
2118                                $searchstr = '1 ' . $tag;
2119                            }
2120                            switch ($expr) {
2121                                case 'CONTAINS':
2122                                    if ($t === 'PLAC') {
2123                                        $searchstr .= "[^\n]*[, ]*" . $val;
2124                                    } else {
2125                                        $searchstr .= "[^\n]*" . $val;
2126                                    }
2127                                    $filters[] = $searchstr;
2128                                    break;
2129                                default:
2130                                    $filters2[] = [
2131                                        'tag'  => $tag,
2132                                        'expr' => $expr,
2133                                        'val'  => $val,
2134                                    ];
2135                                    break;
2136                            }
2137                        }
2138                    }
2139                }
2140            }
2141        }
2142        //-- apply other filters to the list that could not be added to the search string
2143        if ($filters) {
2144            foreach ($this->list as $key => $record) {
2145                foreach ($filters as $filter) {
2146                    if (!preg_match('/' . $filter . '/i', $record->privatizeGedcom(Auth::accessLevel($this->tree)))) {
2147                        unset($this->list[$key]);
2148                        break;
2149                    }
2150                }
2151            }
2152        }
2153        if ($filters2) {
2154            $mylist = [];
2155            foreach ($this->list as $indi) {
2156                $key  = $indi->xref();
2157                $grec = $indi->privatizeGedcom(Auth::accessLevel($this->tree));
2158                $keep = true;
2159                foreach ($filters2 as $filter) {
2160                    if ($keep) {
2161                        $tag  = $filter['tag'];
2162                        $expr = $filter['expr'];
2163                        $val  = $filter['val'];
2164                        if ($val == "''") {
2165                            $val = '';
2166                        }
2167                        $tags = explode(':', $tag);
2168                        $t    = end($tags);
2169                        $v    = $this->getGedcomValue($tag, 1, $grec);
2170                        //-- check for EMAIL and _EMAIL (silly double gedcom standard :P)
2171                        if ($t === 'EMAIL' && empty($v)) {
2172                            $tag  = str_replace('EMAIL', '_EMAIL', $tag);
2173                            $tags = explode(':', $tag);
2174                            $t    = end($tags);
2175                            $v    = Functions::getSubRecord(1, $tag, $grec);
2176                        }
2177
2178                        switch ($expr) {
2179                            case 'GTE':
2180                                if ($t === 'DATE') {
2181                                    $date1 = new Date($v);
2182                                    $date2 = new Date($val);
2183                                    $keep  = (Date::compare($date1, $date2) >= 0);
2184                                } elseif ($val >= $v) {
2185                                    $keep = true;
2186                                }
2187                                break;
2188                            case 'LTE':
2189                                if ($t === 'DATE') {
2190                                    $date1 = new Date($v);
2191                                    $date2 = new Date($val);
2192                                    $keep  = (Date::compare($date1, $date2) <= 0);
2193                                } elseif ($val >= $v) {
2194                                    $keep = true;
2195                                }
2196                                break;
2197                            default:
2198                                if ($v == $val) {
2199                                    $keep = true;
2200                                } else {
2201                                    $keep = false;
2202                                }
2203                                break;
2204                        }
2205                    }
2206                }
2207                if ($keep) {
2208                    $mylist[$key] = $indi;
2209                }
2210            }
2211            $this->list = $mylist;
2212        }
2213
2214        switch ($sortby) {
2215            case 'NAME':
2216                uasort($this->list, GedcomRecord::nameComparator());
2217                break;
2218            case 'CHAN':
2219                uasort($this->list, GedcomRecord::lastChangeComparator());
2220                break;
2221            case 'BIRT:DATE':
2222                uasort($this->list, Individual::birthDateComparator());
2223                break;
2224            case 'DEAT:DATE':
2225                uasort($this->list, Individual::deathDateComparator());
2226                break;
2227            case 'MARR:DATE':
2228                uasort($this->list, Family::marriageDateComparator());
2229                break;
2230            default:
2231                // unsorted or already sorted by SQL
2232                break;
2233        }
2234
2235        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2236        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2237    }
2238
2239    /**
2240     * XML <List>
2241     *
2242     * @return void
2243     */
2244    private function listEndHandler(): void
2245    {
2246        $this->process_repeats--;
2247        if ($this->process_repeats > 0) {
2248            return;
2249        }
2250
2251        // Check if there is any list
2252        if (count($this->list) > 0) {
2253            $lineoffset = 0;
2254            foreach ($this->repeats_stack as $rep) {
2255                $lineoffset += $rep[1];
2256            }
2257            //-- read the xml from the file
2258            $lines = file($this->report);
2259            while ((strpos($lines[$lineoffset + $this->repeat_bytes], '<List') === false) && (($lineoffset + $this->repeat_bytes) > 0)) {
2260                $lineoffset--;
2261            }
2262            $lineoffset++;
2263            $reportxml = "<tempdoc>\n";
2264            $line_nr   = $lineoffset + $this->repeat_bytes;
2265            // List Level counter
2266            $count = 1;
2267            while (0 < $count) {
2268                if (strpos($lines[$line_nr], '<List') !== false) {
2269                    $count++;
2270                } elseif (strpos($lines[$line_nr], '</List') !== false) {
2271                    $count--;
2272                }
2273                if (0 < $count) {
2274                    $reportxml .= $lines[$line_nr];
2275                }
2276                $line_nr++;
2277            }
2278            // No need to drag this
2279            unset($lines);
2280            $reportxml .= '</tempdoc>';
2281            // Save original values
2282            $this->parser_stack[] = $this->parser;
2283            $oldgedrec            = $this->gedrec;
2284
2285            $this->list_total   = count($this->list);
2286            $this->list_private = 0;
2287            foreach ($this->list as $record) {
2288                if ($record->canShow()) {
2289                    $this->gedrec = $record->privatizeGedcom(Auth::accessLevel($record->tree()));
2290                    //-- start the sax parser
2291                    $repeat_parser = xml_parser_create();
2292                    $this->parser  = $repeat_parser;
2293                    xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
2294
2295                    xml_set_element_handler(
2296                        $repeat_parser,
2297                        function ($parser, string $name, array $attrs) {
2298                            $this->startElement($parser, $name, $attrs);
2299                        },
2300                        function ($parser, string $name) {
2301                            $this->endElement($parser, $name);
2302                        }
2303                    );
2304
2305                    xml_set_character_data_handler(
2306                        $repeat_parser,
2307                        function ($parser, $data) {
2308                            $this->characterData($parser, $data);
2309                        }
2310                    );
2311
2312                    if (!xml_parse($repeat_parser, $reportxml, true)) {
2313                        throw new DomainException(sprintf(
2314                            'ListEHandler XML error: %s at line %d',
2315                            xml_error_string(xml_get_error_code($repeat_parser)),
2316                            xml_get_current_line_number($repeat_parser)
2317                        ));
2318                    }
2319                    xml_parser_free($repeat_parser);
2320                } else {
2321                    $this->list_private++;
2322                }
2323            }
2324            $this->list   = [];
2325            $this->parser = array_pop($this->parser_stack);
2326            $this->gedrec = $oldgedrec;
2327        }
2328        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2329    }
2330
2331    /**
2332     * XML <ListTotal> element handler
2333     * Prints the total number of records in a list
2334     * The total number is collected from
2335     * List and Relatives
2336     *
2337     * @return void
2338     */
2339    private function listTotalStartHandler(): void
2340    {
2341        if ($this->list_private == 0) {
2342            $this->current_element->addText((string) $this->list_total);
2343        } else {
2344            $this->current_element->addText(($this->list_total - $this->list_private) . ' / ' . $this->list_total);
2345        }
2346    }
2347
2348    /**
2349     * XML <Relatives>
2350     *
2351     * @param string[] $attrs an array of key value pairs for the attributes
2352     *
2353     * @return void
2354     */
2355    private function relativesStartHandler(array $attrs): void
2356    {
2357        $this->process_repeats++;
2358        if ($this->process_repeats > 1) {
2359            return;
2360        }
2361
2362        $sortby = $attrs['sortby'] ?? 'NAME';
2363
2364        $match = [];
2365        if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2366            $sortby = $this->vars[$match[1]]['id'];
2367            $sortby = trim($sortby);
2368        }
2369
2370        $maxgen = -1;
2371        if (isset($attrs['maxgen'])) {
2372            $maxgen = (int) $attrs['maxgen'];
2373        }
2374        if ($maxgen === '*') {
2375            $maxgen = -1;
2376        }
2377
2378        $group = $attrs['group'] ?? 'child-family';
2379
2380        if (preg_match("/\\$(\w+)/", $group, $match)) {
2381            $group = $this->vars[$match[1]]['id'];
2382            $group = trim($group);
2383        }
2384
2385        $id = $attrs['id'] ?? '';
2386
2387        if (preg_match("/\\$(\w+)/", $id, $match)) {
2388            $id = $this->vars[$match[1]]['id'];
2389            $id = trim($id);
2390        }
2391
2392        $this->list = [];
2393        $person     = Individual::getInstance($id, $this->tree);
2394        if ($person instanceof Individual) {
2395            $this->list[$id] = $person;
2396            switch ($group) {
2397                case 'child-family':
2398                    foreach ($person->childFamilies() as $family) {
2399                        foreach ($family->spouses() as $spouse) {
2400                            $this->list[$spouse->xref()] = $spouse;
2401                        }
2402
2403                        foreach ($family->children() as $child) {
2404                            $this->list[$child->xref()] = $child;
2405                        }
2406                    }
2407                    break;
2408                case 'spouse-family':
2409                    foreach ($person->spouseFamilies() as $family) {
2410                        foreach ($family->spouses() as $spouse) {
2411                            $this->list[$spouse->xref()] = $spouse;
2412                        }
2413
2414                        foreach ($family->children() as $child) {
2415                            $this->list[$child->xref()] = $child;
2416                        }
2417                    }
2418                    break;
2419                case 'direct-ancestors':
2420                    $this->addAncestors($this->list, $id, false, $maxgen);
2421                    break;
2422                case 'ancestors':
2423                    $this->addAncestors($this->list, $id, true, $maxgen);
2424                    break;
2425                case 'descendants':
2426                    $this->list[$id]->generation = 1;
2427                    $this->addDescendancy($this->list, $id, false, $maxgen);
2428                    break;
2429                case 'all':
2430                    $this->addAncestors($this->list, $id, true, $maxgen);
2431                    $this->addDescendancy($this->list, $id, true, $maxgen);
2432                    break;
2433            }
2434        }
2435
2436        switch ($sortby) {
2437            case 'NAME':
2438                uasort($this->list, GedcomRecord::nameComparator());
2439                break;
2440            case 'BIRT:DATE':
2441                uasort($this->list, Individual::birthDateComparator());
2442                break;
2443            case 'DEAT:DATE':
2444                uasort($this->list, Individual::deathDateComparator());
2445                break;
2446            case 'generation':
2447                $newarray = [];
2448                reset($this->list);
2449                $genCounter = 1;
2450                while (count($newarray) < count($this->list)) {
2451                    foreach ($this->list as $key => $value) {
2452                        $this->generation = $value->generation;
2453                        if ($this->generation == $genCounter) {
2454                            $newarray[$key]             = new stdClass();
2455                            $newarray[$key]->generation = $this->generation;
2456                        }
2457                    }
2458                    $genCounter++;
2459                }
2460                $this->list = $newarray;
2461                break;
2462            default:
2463                // unsorted
2464                break;
2465        }
2466        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2467        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2468    }
2469
2470    /**
2471     * XML </ Relatives>
2472     *
2473     * @return void
2474     */
2475    private function relativesEndHandler(): void
2476    {
2477        $this->process_repeats--;
2478        if ($this->process_repeats > 0) {
2479            return;
2480        }
2481
2482        // Check if there is any relatives
2483        if (count($this->list) > 0) {
2484            $lineoffset = 0;
2485            foreach ($this->repeats_stack as $rep) {
2486                $lineoffset += $rep[1];
2487            }
2488            //-- read the xml from the file
2489            $lines = file($this->report);
2490            while ((strpos($lines[$lineoffset + $this->repeat_bytes], '<Relatives') === false) && (($lineoffset + $this->repeat_bytes) > 0)) {
2491                $lineoffset--;
2492            }
2493            $lineoffset++;
2494            $reportxml = "<tempdoc>\n";
2495            $line_nr   = $lineoffset + $this->repeat_bytes;
2496            // Relatives Level counter
2497            $count = 1;
2498            while (0 < $count) {
2499                if (strpos($lines[$line_nr], '<Relatives') !== false) {
2500                    $count++;
2501                } elseif (strpos($lines[$line_nr], '</Relatives') !== false) {
2502                    $count--;
2503                }
2504                if (0 < $count) {
2505                    $reportxml .= $lines[$line_nr];
2506                }
2507                $line_nr++;
2508            }
2509            // No need to drag this
2510            unset($lines);
2511            $reportxml .= "</tempdoc>\n";
2512            // Save original values
2513            $this->parser_stack[] = $this->parser;
2514            $oldgedrec            = $this->gedrec;
2515
2516            $this->list_total   = count($this->list);
2517            $this->list_private = 0;
2518            foreach ($this->list as $key => $value) {
2519                if (isset($value->generation)) {
2520                    $this->generation = $value->generation;
2521                }
2522                $tmp          = GedcomRecord::getInstance($key, $this->tree);
2523                $this->gedrec = $tmp->privatizeGedcom(Auth::accessLevel($this->tree));
2524
2525                $repeat_parser = xml_parser_create();
2526                $this->parser  = $repeat_parser;
2527                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
2528
2529                xml_set_element_handler(
2530                    $repeat_parser,
2531                    function ($parser, string $name, array $attrs) {
2532                        $this->startElement($parser, $name, $attrs);
2533                    },
2534                    function ($parser, string $name) {
2535                        $this->endElement($parser, $name);
2536                    }
2537                );
2538
2539                xml_set_character_data_handler(
2540                    $repeat_parser,
2541                    function ($parser, $data) {
2542                        $this->characterData($parser, $data);
2543                    }
2544                );
2545
2546                if (!xml_parse($repeat_parser, $reportxml, true)) {
2547                    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)));
2548                }
2549                xml_parser_free($repeat_parser);
2550            }
2551            // Clean up the list array
2552            $this->list   = [];
2553            $this->parser = array_pop($this->parser_stack);
2554            $this->gedrec = $oldgedrec;
2555        }
2556        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2557    }
2558
2559    /**
2560     * XML <Generation /> element handler
2561     * Prints the number of generations
2562     *
2563     * @return void
2564     */
2565    private function generationStartHandler(): void
2566    {
2567        $this->current_element->addText((string) $this->generation);
2568    }
2569
2570    /**
2571     * XML <NewPage /> element handler
2572     * Has to be placed in an element (header, pageheader, body or footer)
2573     *
2574     * @return void
2575     */
2576    private function newPageStartHandler(): void
2577    {
2578        $temp = 'addpage';
2579        $this->wt_report->addElement($temp);
2580    }
2581
2582    /**
2583     * XML <html>
2584     *
2585     * @param string   $tag   HTML tag name
2586     * @param string[] $attrs an array of key value pairs for the attributes
2587     *
2588     * @return void
2589     */
2590    private function htmlStartHandler(string $tag, array $attrs): void
2591    {
2592        if ($tag === 'tempdoc') {
2593            return;
2594        }
2595        $this->wt_report_stack[] = $this->wt_report;
2596        $this->wt_report         = $this->report_root->createHTML($tag, $attrs);
2597        $this->current_element   = $this->wt_report;
2598
2599        $this->print_data_stack[] = $this->print_data;
2600        $this->print_data         = true;
2601    }
2602
2603    /**
2604     * XML </html>
2605     *
2606     * @param string $tag
2607     *
2608     * @return void
2609     */
2610    private function htmlEndHandler($tag): void
2611    {
2612        if ($tag === 'tempdoc') {
2613            return;
2614        }
2615
2616        $this->print_data      = array_pop($this->print_data_stack);
2617        $this->current_element = $this->wt_report;
2618        $this->wt_report       = array_pop($this->wt_report_stack);
2619        if ($this->wt_report !== null) {
2620            $this->wt_report->addElement($this->current_element);
2621        } else {
2622            $this->wt_report = $this->current_element;
2623        }
2624    }
2625
2626    /**
2627     * Handle <Input>
2628     *
2629     * @return void
2630     */
2631    private function inputStartHandler(): void
2632    {
2633        // Dummy function, to prevent the default HtmlStartHandler() being called
2634    }
2635
2636    /**
2637     * Handle </Input>
2638     *
2639     * @return void
2640     */
2641    private function inputEndHandler(): void
2642    {
2643        // Dummy function, to prevent the default HtmlEndHandler() being called
2644    }
2645
2646    /**
2647     * Handle <Report>
2648     *
2649     * @return void
2650     */
2651    private function reportStartHandler(): void
2652    {
2653        // Dummy function, to prevent the default HtmlStartHandler() being called
2654    }
2655
2656    /**
2657     * Handle </Report>
2658     *
2659     * @return void
2660     */
2661    private function reportEndHandler(): void
2662    {
2663        // Dummy function, to prevent the default HtmlEndHandler() being called
2664    }
2665
2666    /**
2667     * XML </titleEndHandler>
2668     *
2669     * @return void
2670     */
2671    private function titleEndHandler(): void
2672    {
2673        $this->report_root->addTitle($this->text);
2674    }
2675
2676    /**
2677     * XML </descriptionEndHandler>
2678     *
2679     * @return void
2680     */
2681    private function descriptionEndHandler(): void
2682    {
2683        $this->report_root->addDescription($this->text);
2684    }
2685
2686    /**
2687     * Create a list of all descendants.
2688     *
2689     * @param string[] $list
2690     * @param string   $pid
2691     * @param bool     $parents
2692     * @param int      $generations
2693     *
2694     * @return void
2695     */
2696    private function addDescendancy(&$list, $pid, $parents = false, $generations = -1): void
2697    {
2698        $person = Individual::getInstance($pid, $this->tree);
2699        if ($person === null) {
2700            return;
2701        }
2702        if (!isset($list[$pid])) {
2703            $list[$pid] = $person;
2704        }
2705        if (!isset($list[$pid]->generation)) {
2706            $list[$pid]->generation = 0;
2707        }
2708        foreach ($person->spouseFamilies() as $family) {
2709            if ($parents) {
2710                $husband = $family->husband();
2711                $wife    = $family->wife();
2712                if ($husband) {
2713                    $list[$husband->xref()] = $husband;
2714                    if (isset($list[$pid]->generation)) {
2715                        $list[$husband->xref()]->generation = $list[$pid]->generation - 1;
2716                    } else {
2717                        $list[$husband->xref()]->generation = 1;
2718                    }
2719                }
2720                if ($wife) {
2721                    $list[$wife->xref()] = $wife;
2722                    if (isset($list[$pid]->generation)) {
2723                        $list[$wife->xref()]->generation = $list[$pid]->generation - 1;
2724                    } else {
2725                        $list[$wife->xref()]->generation = 1;
2726                    }
2727                }
2728            }
2729
2730            $children = $family->children();
2731
2732            foreach ($children as $child) {
2733                if ($child) {
2734                    $list[$child->xref()] = $child;
2735
2736                    if (isset($list[$pid]->generation)) {
2737                        $list[$child->xref()]->generation = $list[$pid]->generation + 1;
2738                    } else {
2739                        $list[$child->xref()]->generation = 2;
2740                    }
2741                }
2742            }
2743            if ($generations == -1 || $list[$pid]->generation + 1 < $generations) {
2744                foreach ($children as $child) {
2745                    $this->addDescendancy($list, $child->xref(), $parents, $generations); // recurse on the childs family
2746                }
2747            }
2748        }
2749    }
2750
2751    /**
2752     * Create a list of all ancestors.
2753     *
2754     * @param string[] $list
2755     * @param string   $pid
2756     * @param bool     $children
2757     * @param int      $generations
2758     *
2759     * @return void
2760     */
2761    private function addAncestors(array &$list, string $pid, bool $children = false, int $generations = -1): void
2762    {
2763        $genlist                = [$pid];
2764        $list[$pid]->generation = 1;
2765        while (count($genlist) > 0) {
2766            $id = array_shift($genlist);
2767            if (strpos($id, 'empty') === 0) {
2768                continue; // id can be something like “empty7”
2769            }
2770            $person = Individual::getInstance($id, $this->tree);
2771            foreach ($person->childFamilies() as $family) {
2772                $husband = $family->husband();
2773                $wife    = $family->wife();
2774                if ($husband) {
2775                    $list[$husband->xref()]             = $husband;
2776                    $list[$husband->xref()]->generation = $list[$id]->generation + 1;
2777                }
2778                if ($wife) {
2779                    $list[$wife->xref()]             = $wife;
2780                    $list[$wife->xref()]->generation = $list[$id]->generation + 1;
2781                }
2782                if ($generations == -1 || $list[$id]->generation + 1 < $generations) {
2783                    if ($husband) {
2784                        $genlist[] = $husband->xref();
2785                    }
2786                    if ($wife) {
2787                        $genlist[] = $wife->xref();
2788                    }
2789                }
2790                if ($children) {
2791                    foreach ($family->children() as $child) {
2792                        $list[$child->xref()] = $child;
2793                        $list[$child->xref()]->generation = $list[$id]->generation ?? 1;
2794                    }
2795                }
2796            }
2797        }
2798    }
2799
2800    /**
2801     * get gedcom tag value
2802     *
2803     * @param string $tag    The tag to find, use : to delineate subtags
2804     * @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
2805     * @param string $gedrec The gedcom record to get the value from
2806     *
2807     * @return string the value of a gedcom tag from the given gedcom record
2808     */
2809    private function getGedcomValue($tag, $level, $gedrec): string
2810    {
2811        if (empty($gedrec)) {
2812            return '';
2813        }
2814        $tags      = explode(':', $tag);
2815        $origlevel = $level;
2816        if ($level == 0) {
2817            $level = $gedrec[0] + 1;
2818        }
2819
2820        $subrec = $gedrec;
2821        foreach ($tags as $t) {
2822            $lastsubrec = $subrec;
2823            $subrec     = Functions::getSubRecord($level, "$level $t", $subrec);
2824            if (empty($subrec) && $origlevel == 0) {
2825                $level--;
2826                $subrec = Functions::getSubRecord($level, "$level $t", $lastsubrec);
2827            }
2828            if (empty($subrec)) {
2829                if ($t === 'TITL') {
2830                    $subrec = Functions::getSubRecord($level, "$level ABBR", $lastsubrec);
2831                    if (!empty($subrec)) {
2832                        $t = 'ABBR';
2833                    }
2834                }
2835                if (empty($subrec)) {
2836                    if ($level > 0) {
2837                        $level--;
2838                    }
2839                    $subrec = Functions::getSubRecord($level, "@ $t", $gedrec);
2840                    if (empty($subrec)) {
2841                        return '';
2842                    }
2843                }
2844            }
2845            $level++;
2846        }
2847        $level--;
2848        $ct = preg_match("/$level $t(.*)/", $subrec, $match);
2849        if ($ct == 0) {
2850            $ct = preg_match("/$level @.+@ (.+)/", $subrec, $match);
2851        }
2852        if ($ct == 0) {
2853            $ct = preg_match("/@ $t (.+)/", $subrec, $match);
2854        }
2855        if ($ct > 0) {
2856            $value = trim($match[1]);
2857            if ($t === 'NOTE' && preg_match('/^@(.+)@$/', $value, $match)) {
2858                $note = Note::getInstance($match[1], $this->tree);
2859                if ($note instanceof Note) {
2860                    $value = $note->getNote();
2861                } else {
2862                    //-- set the value to the id without the @
2863                    $value = $match[1];
2864                }
2865            }
2866            if ($level != 0 || $t != 'NOTE') {
2867                $value .= Functions::getCont($level + 1, $subrec);
2868            }
2869
2870            return $value;
2871        }
2872
2873        return '';
2874    }
2875
2876    /**
2877     * Replace variable identifiers with their values.
2878     *
2879     * @param string $expression An expression such as "$foo == 123"
2880     * @param bool   $quote      Whether to add quotation marks
2881     *
2882     * @return string
2883     */
2884    private function substituteVars($expression, $quote): string
2885    {
2886        return preg_replace_callback(
2887            '/\$(\w+)/',
2888            function (array $matches) use ($quote): string {
2889                if (isset($this->vars[$matches[1]]['id'])) {
2890                    if ($quote) {
2891                        return "'" . addcslashes($this->vars[$matches[1]]['id'], "'") . "'";
2892                    }
2893
2894                    return $this->vars[$matches[1]]['id'];
2895                }
2896
2897                Log::addErrorLog(sprintf('Undefined variable $%s in report', $matches[1]));
2898
2899                return '$' . $matches[1];
2900            },
2901            $expression
2902        );
2903    }
2904}
2905