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