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