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