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