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