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