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