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