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