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