xref: /webtrees/app/Report/ReportParserGenerate.php (revision 17907095d917ef2b56d7bdf08f08ea42db03cb32)
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, '\Fisharebest\Webtrees\GedcomRecord::compare');
2202                break;
2203            case 'CHAN':
2204                uasort($this->list, function (GedcomRecord $x, GedcomRecord $y): int {
2205                    return $y->lastChangeTimestamp(true) - $x->lastChangeTimestamp(true);
2206                });
2207                break;
2208            case 'BIRT:DATE':
2209                uasort($this->list, '\Fisharebest\Webtrees\Individual::compareBirthDate');
2210                break;
2211            case 'DEAT:DATE':
2212                uasort($this->list, '\Fisharebest\Webtrees\Individual::compareDeathDate');
2213                break;
2214            case 'MARR:DATE':
2215                uasort($this->list, '\Fisharebest\Webtrees\Family::compareMarrDate');
2216                break;
2217            default:
2218                // unsorted or already sorted by SQL
2219                break;
2220        }
2221
2222        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2223        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2224    }
2225
2226    /**
2227     * XML <List>
2228     *
2229     * @return void
2230     */
2231    private function listEndHandler()
2232    {
2233        $this->process_repeats--;
2234        if ($this->process_repeats > 0) {
2235            return;
2236        }
2237
2238        // Check if there is any list
2239        if (count($this->list) > 0) {
2240            $lineoffset = 0;
2241            foreach ($this->repeats_stack as $rep) {
2242                $lineoffset += $rep[1];
2243            }
2244            //-- read the xml from the file
2245            $lines = file($this->report);
2246            while ((strpos($lines[$lineoffset + $this->repeat_bytes], '<List') === false) && (($lineoffset + $this->repeat_bytes) > 0)) {
2247                $lineoffset--;
2248            }
2249            $lineoffset++;
2250            $reportxml = "<tempdoc>\n";
2251            $line_nr   = $lineoffset + $this->repeat_bytes;
2252            // List Level counter
2253            $count = 1;
2254            while (0 < $count) {
2255                if (strpos($lines[$line_nr], '<List') !== false) {
2256                    $count++;
2257                } elseif (strpos($lines[$line_nr], '</List') !== false) {
2258                    $count--;
2259                }
2260                if (0 < $count) {
2261                    $reportxml .= $lines[$line_nr];
2262                }
2263                $line_nr++;
2264            }
2265            // No need to drag this
2266            unset($lines);
2267            $reportxml .= '</tempdoc>';
2268            // Save original values
2269            $this->parser_stack[] = $this->parser;
2270            $oldgedrec            = $this->gedrec;
2271
2272            $this->list_total   = count($this->list);
2273            $this->list_private = 0;
2274            foreach ($this->list as $record) {
2275                if ($record->canShow()) {
2276                    $this->gedrec = $record->privatizeGedcom(Auth::accessLevel($record->tree()));
2277                    //-- start the sax parser
2278                    $repeat_parser = xml_parser_create();
2279                    $this->parser  = $repeat_parser;
2280                    xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
2281
2282                    xml_set_element_handler(
2283                        $repeat_parser,
2284                        function ($parser, string $name, array $attrs) {
2285                            $this->startElement($parser, $name, $attrs);
2286                        },
2287                        function ($parser, string $name) {
2288                            $this->endElement($parser, $name);
2289                        }
2290                    );
2291
2292                    xml_set_character_data_handler(
2293                        $repeat_parser,
2294                        function ($parser, $data) {
2295                            $this->characterData($parser, $data);
2296                        }
2297                    );
2298
2299                    if (!xml_parse($repeat_parser, $reportxml, true)) {
2300                        throw new \DomainException(sprintf(
2301                            'ListEHandler XML error: %s at line %d',
2302                            xml_error_string(xml_get_error_code($repeat_parser)),
2303                            xml_get_current_line_number($repeat_parser)
2304                        ));
2305                    }
2306                    xml_parser_free($repeat_parser);
2307                } else {
2308                    $this->list_private++;
2309                }
2310            }
2311            $this->list   = [];
2312            $this->parser = array_pop($this->parser_stack);
2313            $this->gedrec = $oldgedrec;
2314        }
2315        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2316    }
2317
2318    /**
2319     * XML <ListTotal> element handler
2320     * Prints the total number of records in a list
2321     * The total number is collected from
2322     * List and Relatives
2323     *
2324     * @return void
2325     */
2326    private function listTotalStartHandler()
2327    {
2328        if ($this->list_private == 0) {
2329            $this->current_element->addText((string) $this->list_total);
2330        } else {
2331            $this->current_element->addText(($this->list_total - $this->list_private) . ' / ' . $this->list_total);
2332        }
2333    }
2334
2335    /**
2336     * XML <Relatives>
2337     *
2338     * @param string[] $attrs an array of key value pairs for the attributes
2339     *
2340     * @return void
2341     */
2342    private function relativesStartHandler(array $attrs)
2343    {
2344        $this->process_repeats++;
2345        if ($this->process_repeats > 1) {
2346            return;
2347        }
2348
2349        $sortby = 'NAME';
2350        if (isset($attrs['sortby'])) {
2351            $sortby = $attrs['sortby'];
2352        }
2353        $match = [];
2354        if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2355            $sortby = $this->vars[$match[1]]['id'];
2356            $sortby = trim($sortby);
2357        }
2358
2359        $maxgen = -1;
2360        if (isset($attrs['maxgen'])) {
2361            $maxgen = $attrs['maxgen'];
2362        }
2363        if ($maxgen === '*') {
2364            $maxgen = -1;
2365        }
2366
2367        $group = 'child-family';
2368        if (isset($attrs['group'])) {
2369            $group = $attrs['group'];
2370        }
2371        if (preg_match("/\\$(\w+)/", $group, $match)) {
2372            $group = $this->vars[$match[1]]['id'];
2373            $group = trim($group);
2374        }
2375
2376        $id = '';
2377        if (isset($attrs['id'])) {
2378            $id = $attrs['id'];
2379        }
2380        if (preg_match("/\\$(\w+)/", $id, $match)) {
2381            $id = $this->vars[$match[1]]['id'];
2382            $id = trim($id);
2383        }
2384
2385        $this->list = [];
2386        $person     = Individual::getInstance($id, $this->tree);
2387        if (!empty($person)) {
2388            $this->list[$id] = $person;
2389            switch ($group) {
2390                case 'child-family':
2391                    foreach ($person->getChildFamilies() as $family) {
2392                        $husband = $family->getHusband();
2393                        $wife    = $family->getWife();
2394                        if (!empty($husband)) {
2395                            $this->list[$husband->xref()] = $husband;
2396                        }
2397                        if (!empty($wife)) {
2398                            $this->list[$wife->xref()] = $wife;
2399                        }
2400                        $children = $family->getChildren();
2401                        foreach ($children as $child) {
2402                            if (!empty($child)) {
2403                                $this->list[$child->xref()] = $child;
2404                            }
2405                        }
2406                    }
2407                    break;
2408                case 'spouse-family':
2409                    foreach ($person->getSpouseFamilies() as $family) {
2410                        $husband = $family->getHusband();
2411                        $wife    = $family->getWife();
2412                        if (!empty($husband)) {
2413                            $this->list[$husband->xref()] = $husband;
2414                        }
2415                        if (!empty($wife)) {
2416                            $this->list[$wife->xref()] = $wife;
2417                        }
2418                        $children = $family->getChildren();
2419                        foreach ($children as $child) {
2420                            if (!empty($child)) {
2421                                $this->list[$child->xref()] = $child;
2422                            }
2423                        }
2424                    }
2425                    break;
2426                case 'direct-ancestors':
2427                    $this->addAncestors($this->list, $id, false, $maxgen);
2428                    break;
2429                case 'ancestors':
2430                    $this->addAncestors($this->list, $id, true, $maxgen);
2431                    break;
2432                case 'descendants':
2433                    $this->list[$id]->generation = 1;
2434                    $this->addDescendancy($this->list, $id, false, $maxgen);
2435                    break;
2436                case 'all':
2437                    $this->addAncestors($this->list, $id, true, $maxgen);
2438                    $this->addDescendancy($this->list, $id, true, $maxgen);
2439                    break;
2440            }
2441        }
2442
2443        switch ($sortby) {
2444            case 'NAME':
2445                uasort($this->list, '\Fisharebest\Webtrees\GedcomRecord::compare');
2446                break;
2447            case 'BIRT:DATE':
2448                uasort($this->list, '\Fisharebest\Webtrees\Individual::compareBirthDate');
2449                break;
2450            case 'DEAT:DATE':
2451                uasort($this->list, '\Fisharebest\Webtrees\Individual::compareDeathDate');
2452                break;
2453            case 'generation':
2454                $newarray = [];
2455                reset($this->list);
2456                $genCounter = 1;
2457                while (count($newarray) < count($this->list)) {
2458                    foreach ($this->list as $key => $value) {
2459                        $this->generation = $value->generation;
2460                        if ($this->generation == $genCounter) {
2461                            $newarray[$key]             = new stdClass();
2462                            $newarray[$key]->generation = $this->generation;
2463                        }
2464                    }
2465                    $genCounter++;
2466                }
2467                $this->list = $newarray;
2468                break;
2469            default:
2470                // unsorted
2471                break;
2472        }
2473        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2474        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2475    }
2476
2477    /**
2478     * XML </ Relatives>
2479     *
2480     * @return void
2481     */
2482    private function relativesEndHandler()
2483    {
2484        $this->process_repeats--;
2485        if ($this->process_repeats > 0) {
2486            return;
2487        }
2488
2489        // Check if there is any relatives
2490        if (count($this->list) > 0) {
2491            $lineoffset = 0;
2492            foreach ($this->repeats_stack as $rep) {
2493                $lineoffset += $rep[1];
2494            }
2495            //-- read the xml from the file
2496            $lines = file($this->report);
2497            while ((strpos($lines[$lineoffset + $this->repeat_bytes], '<Relatives') === false) && (($lineoffset + $this->repeat_bytes) > 0)) {
2498                $lineoffset--;
2499            }
2500            $lineoffset++;
2501            $reportxml = "<tempdoc>\n";
2502            $line_nr   = $lineoffset + $this->repeat_bytes;
2503            // Relatives Level counter
2504            $count = 1;
2505            while (0 < $count) {
2506                if (strpos($lines[$line_nr], '<Relatives') !== false) {
2507                    $count++;
2508                } elseif (strpos($lines[$line_nr], '</Relatives') !== false) {
2509                    $count--;
2510                }
2511                if (0 < $count) {
2512                    $reportxml .= $lines[$line_nr];
2513                }
2514                $line_nr++;
2515            }
2516            // No need to drag this
2517            unset($lines);
2518            $reportxml .= "</tempdoc>\n";
2519            // Save original values
2520            $this->parser_stack[] = $this->parser;
2521            $oldgedrec            = $this->gedrec;
2522
2523            $this->list_total   = count($this->list);
2524            $this->list_private = 0;
2525            foreach ($this->list as $key => $value) {
2526                if (isset($value->generation)) {
2527                    $this->generation = $value->generation;
2528                }
2529                $tmp          = GedcomRecord::getInstance($key, $this->tree);
2530                $this->gedrec = $tmp->privatizeGedcom(Auth::accessLevel($this->tree));
2531
2532                $repeat_parser = xml_parser_create();
2533                $this->parser  = $repeat_parser;
2534                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
2535
2536                xml_set_element_handler(
2537                    $repeat_parser,
2538                    function ($parser, string $name, array $attrs) {
2539                        $this->startElement($parser, $name, $attrs);
2540                    },
2541                    function ($parser, string $name) {
2542                        $this->endElement($parser, $name);
2543                    }
2544                );
2545
2546                xml_set_character_data_handler(
2547                    $repeat_parser,
2548                    function ($parser, $data) {
2549                        $this->characterData($parser, $data);
2550                    }
2551                );
2552
2553                if (!xml_parse($repeat_parser, $reportxml, true)) {
2554                    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)));
2555                }
2556                xml_parser_free($repeat_parser);
2557            }
2558            // Clean up the list array
2559            $this->list   = [];
2560            $this->parser = array_pop($this->parser_stack);
2561            $this->gedrec = $oldgedrec;
2562        }
2563        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2564    }
2565
2566    /**
2567     * XML <Generation /> element handler
2568     * Prints the number of generations
2569     *
2570     * @return void
2571     */
2572    private function generationStartHandler()
2573    {
2574        $this->current_element->addText((string) $this->generation);
2575    }
2576
2577    /**
2578     * XML <NewPage /> element handler
2579     * Has to be placed in an element (header, pageheader, body or footer)
2580     *
2581     * @return void
2582     */
2583    private function newPageStartHandler()
2584    {
2585        $temp = 'addpage';
2586        $this->wt_report->addElement($temp);
2587    }
2588
2589    /**
2590     * XML <html>
2591     *
2592     * @param string   $tag   HTML tag name
2593     * @param string[] $attrs an array of key value pairs for the attributes
2594     *
2595     * @return void
2596     */
2597    private function htmlStartHandler(string $tag, array $attrs)
2598    {
2599        if ($tag === 'tempdoc') {
2600            return;
2601        }
2602        $this->wt_report_stack[] = $this->wt_report;
2603        $this->wt_report         = $this->report_root->createHTML($tag, $attrs);
2604        $this->current_element   = $this->wt_report;
2605
2606        $this->print_data_stack[] = $this->print_data;
2607        $this->print_data         = true;
2608    }
2609
2610    /**
2611     * XML </html>
2612     *
2613     * @param string $tag
2614     *
2615     * @return void
2616     */
2617    private function htmlEndHandler($tag)
2618    {
2619        if ($tag === 'tempdoc') {
2620            return;
2621        }
2622
2623        $this->print_data      = array_pop($this->print_data_stack);
2624        $this->current_element = $this->wt_report;
2625        $this->wt_report       = array_pop($this->wt_report_stack);
2626        if ($this->wt_report !== null) {
2627            $this->wt_report->addElement($this->current_element);
2628        } else {
2629            $this->wt_report = $this->current_element;
2630        }
2631    }
2632
2633    /**
2634     * Handle <Input>
2635     *
2636     * @return void
2637     */
2638    private function inputStartHandler()
2639    {
2640        // Dummy function, to prevent the default HtmlStartHandler() being called
2641    }
2642
2643    /**
2644     * Handle </Input>
2645     *
2646     * @return void
2647     */
2648    private function inputEndHandler()
2649    {
2650        // Dummy function, to prevent the default HtmlEndHandler() being called
2651    }
2652
2653    /**
2654     * Handle <Report>
2655     *
2656     * @return void
2657     */
2658    private function reportStartHandler()
2659    {
2660        // Dummy function, to prevent the default HtmlStartHandler() being called
2661    }
2662
2663    /**
2664     * Handle </Report>
2665     *
2666     * @return void
2667     */
2668    private function reportEndHandler()
2669    {
2670        // Dummy function, to prevent the default HtmlEndHandler() being called
2671    }
2672
2673    /**
2674     * XML </titleEndHandler>
2675     *
2676     * @return void
2677     */
2678    private function titleEndHandler()
2679    {
2680        $this->report_root->addTitle($this->text);
2681    }
2682
2683    /**
2684     * XML </descriptionEndHandler>
2685     *
2686     * @return void
2687     */
2688    private function descriptionEndHandler()
2689    {
2690        $this->report_root->addDescription($this->text);
2691    }
2692
2693    /**
2694     * Create a list of all descendants.
2695     *
2696     * @param string[] $list
2697     * @param string   $pid
2698     * @param bool     $parents
2699     * @param int      $generations
2700     *
2701     * @return void
2702     */
2703    private function addDescendancy(&$list, $pid, $parents = false, $generations = -1)
2704    {
2705        $person = Individual::getInstance($pid, $this->tree);
2706        if ($person === null) {
2707            return;
2708        }
2709        if (!isset($list[$pid])) {
2710            $list[$pid] = $person;
2711        }
2712        if (!isset($list[$pid]->generation)) {
2713            $list[$pid]->generation = 0;
2714        }
2715        foreach ($person->getSpouseFamilies() as $family) {
2716            if ($parents) {
2717                $husband = $family->getHusband();
2718                $wife    = $family->getWife();
2719                if ($husband) {
2720                    $list[$husband->xref()] = $husband;
2721                    if (isset($list[$pid]->generation)) {
2722                        $list[$husband->xref()]->generation = $list[$pid]->generation - 1;
2723                    } else {
2724                        $list[$husband->xref()]->generation = 1;
2725                    }
2726                }
2727                if ($wife) {
2728                    $list[$wife->xref()] = $wife;
2729                    if (isset($list[$pid]->generation)) {
2730                        $list[$wife->xref()]->generation = $list[$pid]->generation - 1;
2731                    } else {
2732                        $list[$wife->xref()]->generation = 1;
2733                    }
2734                }
2735            }
2736            $children = $family->getChildren();
2737            foreach ($children as $child) {
2738                if ($child) {
2739                    $list[$child->xref()] = $child;
2740                    if (isset($list[$pid]->generation)) {
2741                        $list[$child->xref()]->generation = $list[$pid]->generation + 1;
2742                    } else {
2743                        $list[$child->xref()]->generation = 2;
2744                    }
2745                }
2746            }
2747            if ($generations == -1 || $list[$pid]->generation + 1 < $generations) {
2748                foreach ($children as $child) {
2749                    $this->addDescendancy($list, $child->xref(), $parents, $generations); // recurse on the childs family
2750                }
2751            }
2752        }
2753    }
2754
2755    /**
2756     * Create a list of all ancestors.
2757     *
2758     * @param string[] $list
2759     * @param string   $pid
2760     * @param bool     $children
2761     * @param int      $generations
2762     *
2763     * @return void
2764     */
2765    private function addAncestors(&$list, $pid, $children = false, $generations = -1)
2766    {
2767        $genlist                = [$pid];
2768        $list[$pid]->generation = 1;
2769        while (count($genlist) > 0) {
2770            $id = array_shift($genlist);
2771            if (strpos($id, 'empty') === 0) {
2772                continue; // id can be something like “empty7”
2773            }
2774            $person = Individual::getInstance($id, $this->tree);
2775            foreach ($person->getChildFamilies() as $family) {
2776                $husband = $family->getHusband();
2777                $wife    = $family->getWife();
2778                if ($husband) {
2779                    $list[$husband->xref()]             = $husband;
2780                    $list[$husband->xref()]->generation = $list[$id]->generation + 1;
2781                }
2782                if ($wife) {
2783                    $list[$wife->xref()]             = $wife;
2784                    $list[$wife->xref()]->generation = $list[$id]->generation + 1;
2785                }
2786                if ($generations == -1 || $list[$id]->generation + 1 < $generations) {
2787                    if ($husband) {
2788                        $genlist[] = $husband->xref();
2789                    }
2790                    if ($wife) {
2791                        $genlist[] = $wife->xref();
2792                    }
2793                }
2794                if ($children) {
2795                    foreach ($family->getChildren() as $child) {
2796                        $list[$child->xref()] = $child;
2797                        if (isset($list[$id]->generation)) {
2798                            $list[$child->xref()]->generation = $list[$id]->generation;
2799                        } else {
2800                            $list[$child->xref()]->generation = 1;
2801                        }
2802                    }
2803                }
2804            }
2805        }
2806    }
2807
2808    /**
2809     * get gedcom tag value
2810     *
2811     * @param string $tag    The tag to find, use : to delineate subtags
2812     * @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
2813     * @param string $gedrec The gedcom record to get the value from
2814     *
2815     * @return string the value of a gedcom tag from the given gedcom record
2816     */
2817    private function getGedcomValue($tag, $level, $gedrec): string
2818    {
2819        if (empty($gedrec)) {
2820            return '';
2821        }
2822        $tags      = explode(':', $tag);
2823        $origlevel = $level;
2824        if ($level == 0) {
2825            $level = $gedrec[0] + 1;
2826        }
2827
2828        $subrec = $gedrec;
2829        foreach ($tags as $t) {
2830            $lastsubrec = $subrec;
2831            $subrec     = Functions::getSubRecord($level, "$level $t", $subrec);
2832            if (empty($subrec) && $origlevel == 0) {
2833                $level--;
2834                $subrec = Functions::getSubRecord($level, "$level $t", $lastsubrec);
2835            }
2836            if (empty($subrec)) {
2837                if ($t === 'TITL') {
2838                    $subrec = Functions::getSubRecord($level, "$level ABBR", $lastsubrec);
2839                    if (!empty($subrec)) {
2840                        $t = 'ABBR';
2841                    }
2842                }
2843                if (empty($subrec)) {
2844                    if ($level > 0) {
2845                        $level--;
2846                    }
2847                    $subrec = Functions::getSubRecord($level, "@ $t", $gedrec);
2848                    if (empty($subrec)) {
2849                        return '';
2850                    }
2851                }
2852            }
2853            $level++;
2854        }
2855        $level--;
2856        $ct = preg_match("/$level $t(.*)/", $subrec, $match);
2857        if ($ct == 0) {
2858            $ct = preg_match("/$level @.+@ (.+)/", $subrec, $match);
2859        }
2860        if ($ct == 0) {
2861            $ct = preg_match("/@ $t (.+)/", $subrec, $match);
2862        }
2863        if ($ct > 0) {
2864            $value = trim($match[1]);
2865            if ($t === 'NOTE' && preg_match('/^@(.+)@$/', $value, $match)) {
2866                $note = Note::getInstance($match[1], $this->tree);
2867                if ($note instanceof Note) {
2868                    $value = $note->getNote();
2869                } else {
2870                    //-- set the value to the id without the @
2871                    $value = $match[1];
2872                }
2873            }
2874            if ($level != 0 || $t != 'NOTE') {
2875                $value .= Functions::getCont($level + 1, $subrec);
2876            }
2877
2878            return $value;
2879        }
2880
2881        return '';
2882    }
2883
2884    /**
2885     * Replace variable identifiers with their values.
2886     *
2887     * @param string $expression An expression such as "$foo == 123"
2888     * @param bool   $quote      Whether to add quotation marks
2889     *
2890     * @return string
2891     */
2892    private function substituteVars($expression, $quote): string
2893    {
2894        return preg_replace_callback(
2895            '/\$(\w+)/',
2896            function (array $matches) use ($quote): string {
2897                if (isset($this->vars[$matches[1]]['id'])) {
2898                    if ($quote) {
2899                        return "'" . addcslashes($this->vars[$matches[1]]['id'], "'") . "'";
2900                    }
2901
2902                    return $this->vars[$matches[1]]['id'];
2903                }
2904
2905                Log::addErrorLog(sprintf('Undefined variable $%s in report', $matches[1]));
2906
2907                return '$' . $matches[1];
2908            },
2909            $expression
2910        );
2911    }
2912}
2913