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