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