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