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