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