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