xref: /webtrees/app/Report/ReportParserGenerate.php (revision bba27599b02e0b6f90f62348bb4fa32bd74056d0)
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
1610		if ($media_file !== null && $media_file->fileExists()) {
1611			$attributes = getimagesize($media_file->getServerFilename()) ?: [0, 0];
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	 * XML <Image/>
1629	 *
1630	 * @param array $attrs an array of key value pairs for the attributes
1631	 */
1632	private function imageStartHandler($attrs) {
1633		// mixed Position the top corner of this box on the page. the default is the current position
1634		$top = '.';
1635		if (isset($attrs['top'])) {
1636			if ($attrs['top'] === '0') {
1637				$top = 0;
1638			} elseif ($attrs['top'] === '.') {
1639				$top = '.';
1640			} elseif (!empty($attrs['top'])) {
1641				$top = (int) $attrs['top'];
1642			}
1643		}
1644
1645		// mixed Position the left corner of this box on the page. the default is the current position
1646		$left = '.';
1647		if (isset($attrs['left'])) {
1648			if ($attrs['left'] === '0') {
1649				$left = 0;
1650			} elseif ($attrs['left'] === '.') {
1651				$left = '.';
1652			} elseif (!empty($attrs['left'])) {
1653				$left = (int) $attrs['left'];
1654			}
1655		}
1656
1657		// string Align the image in left, center, right
1658		$align = '';
1659		if (!empty($attrs['align'])) {
1660			$align = $attrs['align'];
1661		}
1662
1663		// string Next Line should be T:next to the image, N:next line
1664		$ln = 'T';
1665		if (!empty($attrs['ln'])) {
1666			$ln = $attrs['ln'];
1667		}
1668
1669		$width  = 0;
1670		$height = 0;
1671		if (!empty($attrs['width'])) {
1672			$width = (int) $attrs['width'];
1673		}
1674		if (!empty($attrs['height'])) {
1675			$height = (int) $attrs['height'];
1676		}
1677
1678		$file = '';
1679		if (!empty($attrs['file'])) {
1680			$file = $attrs['file'];
1681		}
1682		if ($file == '@FILE') {
1683			$match = [];
1684			if (preg_match("/\d OBJE @(.+)@/", $this->gedrec, $match)) {
1685				$mediaobject = Media::getInstance($match[1], $this->tree);
1686				$media_file  = $mediaobject->firstImageFile();
1687
1688				if ($media_file !== null && $media_file->fileExists()) {
1689					$attributes = getimagesize($media_file->getServerFilename()) ?: [0, 0];
1690					if ($width > 0 && $height == 0) {
1691						$perc   = $width / $attributes[0];
1692						$height = round($attributes[1] * $perc);
1693					} elseif ($height > 0 && $width == 0) {
1694						$perc  = $height / $attributes[1];
1695						$width = round($attributes[0] * $perc);
1696					} else {
1697						$width  = $attributes[0];
1698						$height = $attributes[1];
1699					}
1700					$image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
1701					$this->wt_report->addElement($image);
1702				}
1703			}
1704		} else {
1705			if (file_exists($file) && preg_match('/(jpg|jpeg|png|gif)$/i', $file)) {
1706				$size = getimagesize($file);
1707				if ($width > 0 && $height == 0) {
1708					$perc   = $width / $size[0];
1709					$height = round($size[1] * $perc);
1710				} elseif ($height > 0 && $width == 0) {
1711					$perc  = $height / $size[1];
1712					$width = round($size[0] * $perc);
1713				} else {
1714					$width  = $size[0];
1715					$height = $size[1];
1716				}
1717				$image = $this->report_root->createImage($file, $left, $top, $width, $height, $align, $ln);
1718				$this->wt_report->addElement($image);
1719			}
1720		}
1721	}
1722
1723	/**
1724	 * XML <Line> element handler
1725	 *
1726	 * @param array $attrs an array of key value pairs for the attributes
1727	 */
1728	private function lineStartHandler($attrs) {
1729		// Start horizontal position, current position (default)
1730		$x1 = '.';
1731		if (isset($attrs['x1'])) {
1732			if ($attrs['x1'] === '0') {
1733				$x1 = 0;
1734			} elseif ($attrs['x1'] === '.') {
1735				$x1 = '.';
1736			} elseif (!empty($attrs['x1'])) {
1737				$x1 = (int) $attrs['x1'];
1738			}
1739		}
1740		// Start vertical position, current position (default)
1741		$y1 = '.';
1742		if (isset($attrs['y1'])) {
1743			if ($attrs['y1'] === '0') {
1744				$y1 = 0;
1745			} elseif ($attrs['y1'] === '.') {
1746				$y1 = '.';
1747			} elseif (!empty($attrs['y1'])) {
1748				$y1 = (int) $attrs['y1'];
1749			}
1750		}
1751		// End horizontal position, maximum width (default)
1752		$x2 = '.';
1753		if (isset($attrs['x2'])) {
1754			if ($attrs['x2'] === '0') {
1755				$x2 = 0;
1756			} elseif ($attrs['x2'] === '.') {
1757				$x2 = '.';
1758			} elseif (!empty($attrs['x2'])) {
1759				$x2 = (int) $attrs['x2'];
1760			}
1761		}
1762		// End vertical position
1763		$y2 = '.';
1764		if (isset($attrs['y2'])) {
1765			if ($attrs['y2'] === '0') {
1766				$y2 = 0;
1767			} elseif ($attrs['y2'] === '.') {
1768				$y2 = '.';
1769			} elseif (!empty($attrs['y2'])) {
1770				$y2 = (int) $attrs['y2'];
1771			}
1772		}
1773
1774		$line = $this->report_root->createLine($x1, $y1, $x2, $y2);
1775		$this->wt_report->addElement($line);
1776	}
1777
1778	/**
1779	 * XML <List>
1780	 *
1781	 * @param array $attrs an array of key value pairs for the attributes
1782	 */
1783	private function listStartHandler($attrs) {
1784		$this->process_repeats++;
1785		if ($this->process_repeats > 1) {
1786			return;
1787		}
1788
1789		$match = [];
1790		if (isset($attrs['sortby'])) {
1791			$sortby = $attrs['sortby'];
1792			if (preg_match("/\\$(\w+)/", $sortby, $match)) {
1793				$sortby = $this->vars[$match[1]]['id'];
1794				$sortby = trim($sortby);
1795			}
1796		} else {
1797			$sortby = 'NAME';
1798		}
1799
1800		if (isset($attrs['list'])) {
1801			$listname = $attrs['list'];
1802		} else {
1803			$listname = 'individual';
1804		}
1805		// Some filters/sorts can be applied using SQL, while others require PHP
1806		switch ($listname) {
1807			case 'pending':
1808				$rows = Database::prepare(
1809					"SELECT xref, CASE new_gedcom WHEN '' THEN old_gedcom ELSE new_gedcom END AS gedcom" .
1810					" FROM `##change`" . " WHERE (xref, change_id) IN (" .
1811					"  SELECT xref, MAX(change_id)" .
1812					"  FROM `##change`" .
1813					"  WHERE status = 'pending' AND gedcom_id = :tree_id" .
1814					"  GROUP BY xref" .
1815					" )"
1816				)->execute([
1817					'tree_id' => $this->tree->getTreeId(),
1818				])->fetchAll();
1819				$this->list = [];
1820				foreach ($rows as $row) {
1821					$this->list[] = GedcomRecord::getInstance($row->xref, $this->tree, $row->gedcom);
1822				}
1823				break;
1824			case 'individual':
1825				$sql_select   = "SELECT i_id AS xref, i_gedcom AS gedcom FROM `##individuals` ";
1826				$sql_join     = "";
1827				$sql_where    = " WHERE i_file = :tree_id";
1828				$sql_order_by = "";
1829				$sql_params   = ['tree_id' => $this->tree->getTreeId()];
1830				foreach ($attrs as $attr => $value) {
1831					if (strpos($attr, 'filter') === 0 && $value) {
1832						$value = $this->substituteVars($value, false);
1833						// Convert the various filters into SQL
1834						if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
1835							$sql_join .= " JOIN `##dates` AS {$attr} ON ({$attr}.d_file=i_file AND {$attr}.d_gid=i_id)";
1836							$sql_where .= " AND {$attr}.d_fact = :{$attr}fact";
1837							$sql_params[$attr . 'fact'] = $match[1];
1838							$date                       = new Date($match[3]);
1839							if ($match[2] == 'LTE') {
1840								$sql_where .= " AND {$attr}.d_julianday2 <= :{$attr}date";
1841								$sql_params[$attr . 'date'] = $date->maximumJulianDay();
1842							} else {
1843								$sql_where .= " AND {$attr}.d_julianday1 >= :{$attr}date";
1844								$sql_params[$attr . 'date'] = $date->minimumJulianDay();
1845							}
1846							if ($sortby == $match[1]) {
1847								$sortby = "";
1848								$sql_order_by .= ($sql_order_by ? ", " : " ORDER BY ") . "{$attr}.d_julianday1";
1849							}
1850							unset($attrs[$attr]); // This filter has been fully processed
1851						} elseif (preg_match('/^NAME CONTAINS (.*)$/', $value, $match)) {
1852							// Do nothing, unless you have to
1853							if ($match[1] != '' || $sortby == 'NAME') {
1854								$sql_join .= " JOIN `##name` AS {$attr} ON (n_file=i_file AND n_id=i_id)";
1855								// Search the DB only if there is any name supplied
1856								if ($match[1] != '') {
1857									$names = explode(' ', $match[1]);
1858									foreach ($names as $n => $name) {
1859										$sql_where .= " AND {$attr}.n_full LIKE CONCAT('%', :{$attr}name{$n}, '%')";
1860										$sql_params[$attr . 'name' . $n] = $name;
1861									}
1862								}
1863								// Let the DB do the name sorting even when no name was entered
1864								if ($sortby == 'NAME') {
1865									$sortby = '';
1866									$sql_order_by .= ($sql_order_by ? ', ' : ' ORDER BY ') . "{$attr}.n_sort";
1867								}
1868							}
1869							unset($attrs[$attr]); // This filter has been fully processed
1870						} elseif (preg_match('/^REGEXP \/(.+)\//', $value, $match)) {
1871							$sql_where .= " AND i_gedcom REGEXP :{$attr}gedcom";
1872							// PDO helpfully escapes backslashes for us, preventing us from matching "\n1 FACT"
1873							$sql_params[$attr . 'gedcom'] = str_replace('\n', "\n", $match[1]);
1874							unset($attrs[$attr]); // This filter has been fully processed
1875						} elseif (preg_match('/^(?:\w+):PLAC CONTAINS (.+)$/', $value, $match)) {
1876							$sql_join .= " JOIN `##places` AS {$attr}a ON ({$attr}a.p_file = i_file)";
1877							$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)";
1878							$sql_where .= " AND {$attr}a.p_place LIKE CONCAT('%', :{$attr}place, '%')";
1879							$sql_params[$attr . 'place'] = $match[1];
1880							// Don't unset this filter. This is just initial filtering
1881						} elseif (preg_match('/^(\w*):*(\w*) CONTAINS (.+)$/', $value, $match)) {
1882							$sql_where .= " AND i_gedcom LIKE CONCAT('%', :{$attr}contains1, '%', :{$attr}contains2, '%', :{$attr}contains3, '%')";
1883							$sql_params[$attr . 'contains1'] = $match[1];
1884							$sql_params[$attr . 'contains2'] = $match[2];
1885							$sql_params[$attr . 'contains3'] = $match[3];
1886							// Don't unset this filter. This is just initial filtering
1887						}
1888					}
1889				}
1890
1891				$this->list = [];
1892				$rows       = Database::prepare(
1893					$sql_select . $sql_join . $sql_where . $sql_order_by
1894				)->execute($sql_params)->fetchAll();
1895
1896				foreach ($rows as $row) {
1897					$this->list[$row->xref] = Individual::getInstance($row->xref, $this->tree, $row->gedcom);
1898				}
1899				break;
1900
1901			case 'family':
1902				$sql_select   = "SELECT f_id AS xref, f_gedcom AS gedcom FROM `##families`";
1903				$sql_join     = "";
1904				$sql_where    = " WHERE f_file = :tree_id";
1905				$sql_order_by = "";
1906				$sql_params   = ['tree_id' => $this->tree->getTreeId()];
1907				foreach ($attrs as $attr => $value) {
1908					if (strpos($attr, 'filter') === 0 && $value) {
1909						$value = $this->substituteVars($value, false);
1910						// Convert the various filters into SQL
1911						if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
1912							$sql_join .= " JOIN `##dates` AS {$attr} ON ({$attr}.d_file=f_file AND {$attr}.d_gid=f_id)";
1913							$sql_where .= " AND {$attr}.d_fact = :{$attr}fact";
1914							$sql_params[$attr . 'fact'] = $match[1];
1915							$date                       = new Date($match[3]);
1916							if ($match[2] == 'LTE') {
1917								$sql_where .= " AND {$attr}.d_julianday2 <= :{$attr}date";
1918								$sql_params[$attr . 'date'] = $date->maximumJulianDay();
1919							} else {
1920								$sql_where .= " AND {$attr}.d_julianday1 >= :{$attr}date";
1921								$sql_params[$attr . 'date'] = $date->minimumJulianDay();
1922							}
1923							if ($sortby == $match[1]) {
1924								$sortby = '';
1925								$sql_order_by .= ($sql_order_by ? ', ' : ' ORDER BY ') . "{$attr}.d_julianday1";
1926							}
1927							unset($attrs[$attr]); // This filter has been fully processed
1928						} elseif (preg_match('/^REGEXP \/(.+)\//', $value, $match)) {
1929							$sql_where .= " AND f_gedcom REGEXP :{$attr}gedcom";
1930							// PDO helpfully escapes backslashes for us, preventing us from matching "\n1 FACT"
1931							$sql_params[$attr . 'gedcom'] = str_replace('\n', "\n", $match[1]);
1932							unset($attrs[$attr]); // This filter has been fully processed
1933						} elseif (preg_match('/^NAME CONTAINS (.+)$/', $value, $match)) {
1934							// Do nothing, unless you have to
1935							if ($match[1] != '' || $sortby == 'NAME') {
1936								$sql_join .= " JOIN `##name` AS {$attr} ON n_file = f_file AND n_id IN (f_husb, f_wife)";
1937								// Search the DB only if there is any name supplied
1938								if ($match[1] != '') {
1939									$names = explode(' ', $match[1]);
1940									foreach ($names as $n => $name) {
1941										$sql_where .= " AND {$attr}.n_full LIKE CONCAT('%', :{$attr}name{$n}, '%')";
1942										$sql_params[$attr . 'name' . $n] = $name;
1943									}
1944								}
1945								// Let the DB do the name sorting even when no name was entered
1946								if ($sortby == 'NAME') {
1947									$sortby = '';
1948									$sql_order_by .= ($sql_order_by ? ', ' : ' ORDER BY ') . "{$attr}.n_sort";
1949								}
1950							}
1951							unset($attrs[$attr]); // This filter has been fully processed
1952						} elseif (preg_match('/^(?:\w+):PLAC CONTAINS (.+)$/', $value, $match)) {
1953							$sql_join .= " JOIN `##places` AS {$attr}a ON ({$attr}a.p_file=f_file)";
1954							$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)";
1955							$sql_where .= " AND {$attr}a.p_place LIKE CONCAT('%', :{$attr}place, '%')";
1956							$sql_params[$attr . 'place'] = $match[1];
1957							// Don't unset this filter. This is just initial filtering
1958						} elseif (preg_match('/^(\w*):*(\w*) CONTAINS (.+)$/', $value, $match)) {
1959							$sql_where .= " AND f_gedcom LIKE CONCAT('%', :{$attr}contains1, '%', :{$attr}contains2, '%', :{$attr}contains3, '%')";
1960							$sql_params[$attr . 'contains1'] = $match[1];
1961							$sql_params[$attr . 'contains2'] = $match[2];
1962							$sql_params[$attr . 'contains3'] = $match[3];
1963							// Don't unset this filter. This is just initial filtering
1964						}
1965					}
1966				}
1967
1968				$this->list = [];
1969				$rows       = Database::prepare(
1970					$sql_select . $sql_join . $sql_where . $sql_order_by
1971				)->execute($sql_params)->fetchAll();
1972
1973				foreach ($rows as $row) {
1974					$this->list[$row->xref] = Family::getInstance($row->xref, $this->tree, $row->gedcom);
1975				}
1976				break;
1977
1978			default:
1979				throw new \DomainException('Invalid list name: ' . $listname);
1980		}
1981
1982		$filters  = [];
1983		$filters2 = [];
1984		if (isset($attrs['filter1']) && count($this->list) > 0) {
1985			foreach ($attrs as $key => $value) {
1986				if (preg_match("/filter(\d)/", $key)) {
1987					$condition = $value;
1988					if (preg_match("/@(\w+)/", $condition, $match)) {
1989						$id    = $match[1];
1990						$value = "''";
1991						if ($id == 'ID') {
1992							if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1993								$value = "'" . $match[1] . "'";
1994							}
1995						} elseif ($id == 'fact') {
1996							$value = "'" . $this->fact . "'";
1997						} elseif ($id == 'desc') {
1998							$value = "'" . $this->desc . "'";
1999						} else {
2000							if (preg_match("/\d $id (.+)/", $this->gedrec, $match)) {
2001								$value = "'" . str_replace('@', '', trim($match[1])) . "'";
2002							}
2003						}
2004						$condition = preg_replace("/@$id/", $value, $condition);
2005					}
2006					//-- handle regular expressions
2007					if (preg_match("/([A-Z:]+)\s*([^\s]+)\s*(.+)/", $condition, $match)) {
2008						$tag  = trim($match[1]);
2009						$expr = trim($match[2]);
2010						$val  = trim($match[3]);
2011						if (preg_match("/\\$(\w+)/", $val, $match)) {
2012							$val = $this->vars[$match[1]]['id'];
2013							$val = trim($val);
2014						}
2015						if ($val) {
2016							$searchstr = '';
2017							$tags      = explode(':', $tag);
2018							//-- only limit to a level number if we are specifically looking at a level
2019							if (count($tags) > 1) {
2020								$level = 1;
2021								foreach ($tags as $t) {
2022									if (!empty($searchstr)) {
2023										$searchstr .= "[^\n]*(\n[2-9][^\n]*)*\n";
2024									}
2025									//-- search for both EMAIL and _EMAIL... silly double gedcom standard
2026									if ($t == 'EMAIL' || $t == '_EMAIL') {
2027										$t = '_?EMAIL';
2028									}
2029									$searchstr .= $level . ' ' . $t;
2030									$level++;
2031								}
2032							} else {
2033								if ($tag == 'EMAIL' || $tag == '_EMAIL') {
2034									$tag = '_?EMAIL';
2035								}
2036								$t         = $tag;
2037								$searchstr = '1 ' . $tag;
2038							}
2039							switch ($expr) {
2040								case 'CONTAINS':
2041									if ($t == 'PLAC') {
2042										$searchstr .= "[^\n]*[, ]*" . $val;
2043									} else {
2044										$searchstr .= "[^\n]*" . $val;
2045									}
2046									$filters[] = $searchstr;
2047									break;
2048								default:
2049									$filters2[] = ['tag' => $tag, 'expr' => $expr, 'val' => $val];
2050									break;
2051							}
2052						}
2053					}
2054				}
2055			}
2056		}
2057		//-- apply other filters to the list that could not be added to the search string
2058		if ($filters) {
2059			foreach ($this->list as $key => $record) {
2060				foreach ($filters as $filter) {
2061					if (!preg_match('/' . $filter . '/i', $record->privatizeGedcom(Auth::accessLevel($this->tree)))) {
2062						unset($this->list[$key]);
2063						break;
2064					}
2065				}
2066			}
2067		}
2068		if ($filters2) {
2069			$mylist = [];
2070			foreach ($this->list as $indi) {
2071				$key  = $indi->getXref();
2072				$grec = $indi->privatizeGedcom(Auth::accessLevel($this->tree));
2073				$keep = true;
2074				foreach ($filters2 as $filter) {
2075					if ($keep) {
2076						$tag  = $filter['tag'];
2077						$expr = $filter['expr'];
2078						$val  = $filter['val'];
2079						if ($val == "''") {
2080							$val = '';
2081						}
2082						$tags = explode(':', $tag);
2083						$t    = end($tags);
2084						$v    = $this->getGedcomValue($tag, 1, $grec);
2085						//-- check for EMAIL and _EMAIL (silly double gedcom standard :P)
2086						if ($t == 'EMAIL' && empty($v)) {
2087							$tag  = str_replace('EMAIL', '_EMAIL', $tag);
2088							$tags = explode(':', $tag);
2089							$t    = end($tags);
2090							$v    = Functions::getSubRecord(1, $tag, $grec);
2091						}
2092
2093						switch ($expr) {
2094							case 'GTE':
2095								if ($t == 'DATE') {
2096									$date1 = new Date($v);
2097									$date2 = new Date($val);
2098									$keep  = (Date::compare($date1, $date2) >= 0);
2099								} elseif ($val >= $v) {
2100									$keep = true;
2101								}
2102								break;
2103							case 'LTE':
2104								if ($t == 'DATE') {
2105									$date1 = new Date($v);
2106									$date2 = new Date($val);
2107									$keep  = (Date::compare($date1, $date2) <= 0);
2108								} elseif ($val >= $v) {
2109									$keep = true;
2110								}
2111								break;
2112							default:
2113								if ($v == $val) {
2114									$keep = true;
2115								} else {
2116									$keep = false;
2117								}
2118								break;
2119						}
2120					}
2121				}
2122				if ($keep) {
2123					$mylist[$key] = $indi;
2124				}
2125			}
2126			$this->list = $mylist;
2127		}
2128
2129		switch ($sortby) {
2130			case 'NAME':
2131				uasort($this->list, '\Fisharebest\Webtrees\GedcomRecord::compare');
2132				break;
2133			case 'CHAN':
2134				uasort($this->list, function (GedcomRecord $x, GedcomRecord $y) {
2135					return $y->lastChangeTimestamp(true) - $x->lastChangeTimestamp(true);
2136				});
2137				break;
2138			case 'BIRT:DATE':
2139				uasort($this->list, '\Fisharebest\Webtrees\Individual::compareBirthDate');
2140				break;
2141			case 'DEAT:DATE':
2142				uasort($this->list, '\Fisharebest\Webtrees\Individual::compareDeathDate');
2143				break;
2144			case 'MARR:DATE':
2145				uasort($this->list, '\Fisharebest\Webtrees\Family::compareMarrDate');
2146				break;
2147			default:
2148				// unsorted or already sorted by SQL
2149				break;
2150		}
2151
2152		array_push($this->repeats_stack, [$this->repeats, $this->repeat_bytes]);
2153		$this->repeat_bytes = xml_get_current_line_number($this->parser) + 1;
2154	}
2155
2156	/**
2157	 * XML <List>
2158	 */
2159	private function listEndHandler() {
2160		$this->process_repeats--;
2161		if ($this->process_repeats > 0) {
2162			return;
2163		}
2164
2165		// Check if there is any list
2166		if (count($this->list) > 0) {
2167			$lineoffset = 0;
2168			foreach ($this->repeats_stack as $rep) {
2169				$lineoffset += $rep[1];
2170			}
2171			//-- read the xml from the file
2172			$lines = file($this->report);
2173			while ((strpos($lines[$lineoffset + $this->repeat_bytes], '<List') === false) && (($lineoffset + $this->repeat_bytes) > 0)) {
2174				$lineoffset--;
2175			}
2176			$lineoffset++;
2177			$reportxml = "<tempdoc>\n";
2178			$line_nr   = $lineoffset + $this->repeat_bytes;
2179			// List Level counter
2180			$count = 1;
2181			while (0 < $count) {
2182				if (strpos($lines[$line_nr], '<List') !== false) {
2183					$count++;
2184				} elseif (strpos($lines[$line_nr], '</List') !== false) {
2185					$count--;
2186				}
2187				if (0 < $count) {
2188					$reportxml .= $lines[$line_nr];
2189				}
2190				$line_nr++;
2191			}
2192			// No need to drag this
2193			unset($lines);
2194			$reportxml .= '</tempdoc>';
2195			// Save original values
2196			array_push($this->parser_stack, $this->parser);
2197			$oldgedrec = $this->gedrec;
2198
2199			$this->list_total   = count($this->list);
2200			$this->list_private = 0;
2201			foreach ($this->list as $record) {
2202				if ($record->canShow()) {
2203					$this->gedrec = $record->privatizeGedcom(Auth::accessLevel($record->getTree()));
2204					//-- start the sax parser
2205					$repeat_parser = xml_parser_create();
2206					$this->parser  = $repeat_parser;
2207					xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
2208					xml_set_element_handler($repeat_parser, [$this, 'startElement'], [$this, 'endElement']);
2209					xml_set_character_data_handler($repeat_parser, [$this, 'characterData']);
2210					if (!xml_parse($repeat_parser, $reportxml, true)) {
2211						throw new \DomainException(sprintf(
2212							'ListEHandler XML error: %s at line %d',
2213							xml_error_string(xml_get_error_code($repeat_parser)),
2214							xml_get_current_line_number($repeat_parser)
2215						));
2216					}
2217					xml_parser_free($repeat_parser);
2218				} else {
2219					$this->list_private++;
2220				}
2221			}
2222			$this->list   = [];
2223			$this->parser = array_pop($this->parser_stack);
2224			$this->gedrec = $oldgedrec;
2225		}
2226		list($this->repeats, $this->repeat_bytes) = array_pop($this->repeats_stack);
2227	}
2228
2229	/**
2230	 * XML <ListTotal> element handler
2231	 *
2232	 * Prints the total number of records in a list
2233	 * The total number is collected from
2234	 * List and Relatives
2235	 */
2236	private function listTotalStartHandler() {
2237		if ($this->list_private == 0) {
2238			$this->current_element->addText($this->list_total);
2239		} else {
2240			$this->current_element->addText(($this->list_total - $this->list_private) . ' / ' . $this->list_total);
2241		}
2242	}
2243
2244	/**
2245	 * XML <Relatives>
2246	 *
2247	 * @param array $attrs an array of key value pairs for the attributes
2248	 */
2249	private function relativesStartHandler($attrs) {
2250		$this->process_repeats++;
2251		if ($this->process_repeats > 1) {
2252			return;
2253		}
2254
2255		$sortby = 'NAME';
2256		if (isset($attrs['sortby'])) {
2257			$sortby = $attrs['sortby'];
2258		}
2259		$match = [];
2260		if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2261			$sortby = $this->vars[$match[1]]['id'];
2262			$sortby = trim($sortby);
2263		}
2264
2265		$maxgen = -1;
2266		if (isset($attrs['maxgen'])) {
2267			$maxgen = $attrs['maxgen'];
2268		}
2269		if ($maxgen == '*') {
2270			$maxgen = -1;
2271		}
2272
2273		$group = 'child-family';
2274		if (isset($attrs['group'])) {
2275			$group = $attrs['group'];
2276		}
2277		if (preg_match("/\\$(\w+)/", $group, $match)) {
2278			$group = $this->vars[$match[1]]['id'];
2279			$group = trim($group);
2280		}
2281
2282		$id = '';
2283		if (isset($attrs['id'])) {
2284			$id = $attrs['id'];
2285		}
2286		if (preg_match("/\\$(\w+)/", $id, $match)) {
2287			$id = $this->vars[$match[1]]['id'];
2288			$id = trim($id);
2289		}
2290
2291		$this->list = [];
2292		$person     = Individual::getInstance($id, $this->tree);
2293		if (!empty($person)) {
2294			$this->list[$id] = $person;
2295			switch ($group) {
2296				case 'child-family':
2297					foreach ($person->getChildFamilies() as $family) {
2298						$husband = $family->getHusband();
2299						$wife    = $family->getWife();
2300						if (!empty($husband)) {
2301							$this->list[$husband->getXref()] = $husband;
2302						}
2303						if (!empty($wife)) {
2304							$this->list[$wife->getXref()] = $wife;
2305						}
2306						$children = $family->getChildren();
2307						foreach ($children as $child) {
2308							if (!empty($child)) {
2309								$this->list[$child->getXref()] = $child;
2310							}
2311						}
2312					}
2313					break;
2314				case 'spouse-family':
2315					foreach ($person->getSpouseFamilies() as $family) {
2316						$husband = $family->getHusband();
2317						$wife    = $family->getWife();
2318						if (!empty($husband)) {
2319							$this->list[$husband->getXref()] = $husband;
2320						}
2321						if (!empty($wife)) {
2322							$this->list[$wife->getXref()] = $wife;
2323						}
2324						$children = $family->getChildren();
2325						foreach ($children as $child) {
2326							if (!empty($child)) {
2327								$this->list[$child->getXref()] = $child;
2328							}
2329						}
2330					}
2331					break;
2332				case 'direct-ancestors':
2333					$this->addAncestors($this->list, $id, false, $maxgen);
2334					break;
2335				case 'ancestors':
2336					$this->addAncestors($this->list, $id, true, $maxgen);
2337					break;
2338				case 'descendants':
2339					$this->list[$id]->generation = 1;
2340					$this->addDescendancy($this->list, $id, false, $maxgen);
2341					break;
2342				case 'all':
2343					$this->addAncestors($this->list, $id, true, $maxgen);
2344					$this->addDescendancy($this->list, $id, true, $maxgen);
2345					break;
2346			}
2347		}
2348
2349		switch ($sortby) {
2350			case 'NAME':
2351				uasort($this->list, '\Fisharebest\Webtrees\GedcomRecord::compare');
2352				break;
2353			case 'BIRT:DATE':
2354				uasort($this->list, '\Fisharebest\Webtrees\Individual::compareBirthDate');
2355				break;
2356			case 'DEAT:DATE':
2357				uasort($this->list, '\Fisharebest\Webtrees\Individual::compareDeathDate');
2358				break;
2359			case 'generation':
2360				$newarray = [];
2361				reset($this->list);
2362				$genCounter = 1;
2363				while (count($newarray) < count($this->list)) {
2364					foreach ($this->list as $key => $value) {
2365						$this->generation = $value->generation;
2366						if ($this->generation == $genCounter) {
2367							$newarray[$key]             = new \stdClass;
2368							$newarray[$key]->generation = $this->generation;
2369						}
2370					}
2371					$genCounter++;
2372				}
2373				$this->list = $newarray;
2374				break;
2375			default:
2376				// unsorted
2377				break;
2378		}
2379		array_push($this->repeats_stack, [$this->repeats, $this->repeat_bytes]);
2380		$this->repeat_bytes = xml_get_current_line_number($this->parser) + 1;
2381	}
2382
2383	/**
2384	 * XML </ Relatives>
2385	 */
2386	private function relativesEndHandler() {
2387		$this->process_repeats--;
2388		if ($this->process_repeats > 0) {
2389			return;
2390		}
2391
2392		// Check if there is any relatives
2393		if (count($this->list) > 0) {
2394			$lineoffset = 0;
2395			foreach ($this->repeats_stack as $rep) {
2396				$lineoffset += $rep[1];
2397			}
2398			//-- read the xml from the file
2399			$lines = file($this->report);
2400			while ((strpos($lines[$lineoffset + $this->repeat_bytes], '<Relatives') === false) && (($lineoffset + $this->repeat_bytes) > 0)) {
2401				$lineoffset--;
2402			}
2403			$lineoffset++;
2404			$reportxml = "<tempdoc>\n";
2405			$line_nr   = $lineoffset + $this->repeat_bytes;
2406			// Relatives Level counter
2407			$count = 1;
2408			while (0 < $count) {
2409				if (strpos($lines[$line_nr], '<Relatives') !== false) {
2410					$count++;
2411				} elseif (strpos($lines[$line_nr], '</Relatives') !== false) {
2412					$count--;
2413				}
2414				if (0 < $count) {
2415					$reportxml .= $lines[$line_nr];
2416				}
2417				$line_nr++;
2418			}
2419			// No need to drag this
2420			unset($lines);
2421			$reportxml .= "</tempdoc>\n";
2422			// Save original values
2423			array_push($this->parser_stack, $this->parser);
2424			$oldgedrec = $this->gedrec;
2425
2426			$this->list_total   = count($this->list);
2427			$this->list_private = 0;
2428			foreach ($this->list as $key => $value) {
2429				if (isset($value->generation)) {
2430					$this->generation = $value->generation;
2431				}
2432				$tmp          = GedcomRecord::getInstance($key, $this->tree);
2433				$this->gedrec = $tmp->privatizeGedcom(Auth::accessLevel($this->tree));
2434
2435				$repeat_parser = xml_parser_create();
2436				$this->parser  = $repeat_parser;
2437				xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
2438				xml_set_element_handler($repeat_parser, [$this, 'startElement'], [$this, 'endElement']);
2439				xml_set_character_data_handler($repeat_parser, [$this, 'characterData']);
2440
2441				if (!xml_parse($repeat_parser, $reportxml, true)) {
2442					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)));
2443				}
2444				xml_parser_free($repeat_parser);
2445			}
2446			// Clean up the list array
2447			$this->list   = [];
2448			$this->parser = array_pop($this->parser_stack);
2449			$this->gedrec = $oldgedrec;
2450		}
2451		list($this->repeats, $this->repeat_bytes) = array_pop($this->repeats_stack);
2452	}
2453
2454	/**
2455	 * XML <Generation /> element handler
2456	 *
2457	 * Prints the number of generations
2458	 */
2459	private function generationStartHandler() {
2460		$this->current_element->addText($this->generation);
2461	}
2462
2463	/**
2464	 * XML <NewPage /> element handler
2465	 *
2466	 * Has to be placed in an element (header, pageheader, body or footer)
2467	 */
2468	private function newPageStartHandler() {
2469		$temp = 'addpage';
2470		$this->wt_report->addElement($temp);
2471	}
2472
2473	/**
2474	 * XML <html>
2475	 *
2476	 * @param string  $tag   HTML tag name
2477	 * @param array[] $attrs an array of key value pairs for the attributes
2478	 */
2479	private function htmlStartHandler($tag, $attrs) {
2480		if ($tag === 'tempdoc') {
2481			return;
2482		}
2483		array_push($this->wt_report_stack, $this->wt_report);
2484		$this->wt_report       = $this->report_root->createHTML($tag, $attrs);
2485		$this->current_element = $this->wt_report;
2486
2487		array_push($this->print_data_stack, $this->print_data);
2488		$this->print_data = true;
2489	}
2490
2491	/**
2492	 * XML </html>
2493	 *
2494	 * @param string $tag
2495	 */
2496	private function htmlEndHandler($tag) {
2497		if ($tag === 'tempdoc') {
2498			return;
2499		}
2500
2501		$this->print_data      = array_pop($this->print_data_stack);
2502		$this->current_element = $this->wt_report;
2503		$this->wt_report       = array_pop($this->wt_report_stack);
2504		if (!is_null($this->wt_report)) {
2505			$this->wt_report->addElement($this->current_element);
2506		} else {
2507			$this->wt_report = $this->current_element;
2508		}
2509	}
2510
2511	/**
2512	 * Handle <Input>
2513	 */
2514	private function inputStartHandler() {
2515		// Dummy function, to prevent the default HtmlStartHandler() being called
2516	}
2517
2518	/**
2519	 * Handle </Input>
2520	 */
2521	private function inputEndHandler() {
2522		// Dummy function, to prevent the default HtmlEndHandler() being called
2523	}
2524
2525	/**
2526	 * Handle <Report>
2527	 */
2528	private function reportStartHandler() {
2529		// Dummy function, to prevent the default HtmlStartHandler() being called
2530	}
2531
2532	/**
2533	 * Handle </Report>
2534	 */
2535	private function reportEndHandler() {
2536		// Dummy function, to prevent the default HtmlEndHandler() being called
2537	}
2538
2539	/**
2540	 * XML </titleEndHandler>
2541	 */
2542	private function titleEndHandler() {
2543		$this->report_root->addTitle($this->text);
2544	}
2545
2546	/**
2547	 * XML </descriptionEndHandler>
2548	 */
2549	private function descriptionEndHandler() {
2550		$this->report_root->addDescription($this->text);
2551	}
2552
2553	/**
2554	 * Create a list of all descendants.
2555	 *
2556	 * @param string[] $list
2557	 * @param string   $pid
2558	 * @param bool  $parents
2559	 * @param int  $generations
2560	 */
2561	private function addDescendancy(&$list, $pid, $parents = false, $generations = -1) {
2562		$person = Individual::getInstance($pid, $this->tree);
2563		if ($person === null) {
2564			return;
2565		}
2566		if (!isset($list[$pid])) {
2567			$list[$pid] = $person;
2568		}
2569		if (!isset($list[$pid]->generation)) {
2570			$list[$pid]->generation = 0;
2571		}
2572		foreach ($person->getSpouseFamilies() as $family) {
2573			if ($parents) {
2574				$husband = $family->getHusband();
2575				$wife    = $family->getWife();
2576				if ($husband) {
2577					$list[$husband->getXref()] = $husband;
2578					if (isset($list[$pid]->generation)) {
2579						$list[$husband->getXref()]->generation = $list[$pid]->generation - 1;
2580					} else {
2581						$list[$husband->getXref()]->generation = 1;
2582					}
2583				}
2584				if ($wife) {
2585					$list[$wife->getXref()] = $wife;
2586					if (isset($list[$pid]->generation)) {
2587						$list[$wife->getXref()]->generation = $list[$pid]->generation - 1;
2588					} else {
2589						$list[$wife->getXref()]->generation = 1;
2590					}
2591				}
2592			}
2593			$children = $family->getChildren();
2594			foreach ($children as $child) {
2595				if ($child) {
2596					$list[$child->getXref()] = $child;
2597					if (isset($list[$pid]->generation)) {
2598						$list[$child->getXref()]->generation = $list[$pid]->generation + 1;
2599					} else {
2600						$list[$child->getXref()]->generation = 2;
2601					}
2602				}
2603			}
2604			if ($generations == -1 || $list[$pid]->generation + 1 < $generations) {
2605				foreach ($children as $child) {
2606					$this->addDescendancy($list, $child->getXref(), $parents, $generations); // recurse on the childs family
2607				}
2608			}
2609		}
2610	}
2611
2612	/**
2613	 * Create a list of all ancestors.
2614	 *
2615	 * @param string[] $list
2616	 * @param string   $pid
2617	 * @param bool  $children
2618	 * @param int  $generations
2619	 */
2620	private function addAncestors(&$list, $pid, $children = false, $generations = -1) {
2621		$genlist                = [$pid];
2622		$list[$pid]->generation = 1;
2623		while (count($genlist) > 0) {
2624			$id = array_shift($genlist);
2625			if (strpos($id, 'empty') === 0) {
2626				continue; // id can be something like “empty7”
2627			}
2628			$person = Individual::getInstance($id, $this->tree);
2629			foreach ($person->getChildFamilies() as $family) {
2630				$husband = $family->getHusband();
2631				$wife    = $family->getWife();
2632				if ($husband) {
2633					$list[$husband->getXref()]             = $husband;
2634					$list[$husband->getXref()]->generation = $list[$id]->generation + 1;
2635				}
2636				if ($wife) {
2637					$list[$wife->getXref()]             = $wife;
2638					$list[$wife->getXref()]->generation = $list[$id]->generation + 1;
2639				}
2640				if ($generations == -1 || $list[$id]->generation + 1 < $generations) {
2641					if ($husband) {
2642						array_push($genlist, $husband->getXref());
2643					}
2644					if ($wife) {
2645						array_push($genlist, $wife->getXref());
2646					}
2647				}
2648				if ($children) {
2649					foreach ($family->getChildren() as $child) {
2650						$list[$child->getXref()] = $child;
2651						if (isset($list[$id]->generation)) {
2652							$list[$child->getXref()]->generation = $list[$id]->generation;
2653						} else {
2654							$list[$child->getXref()]->generation = 1;
2655						}
2656					}
2657				}
2658			}
2659		}
2660	}
2661
2662	/**
2663	 * get gedcom tag value
2664	 *
2665	 * @param string  $tag    The tag to find, use : to delineate subtags
2666	 * @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
2667	 * @param string  $gedrec The gedcom record to get the value from
2668	 *
2669	 * @return string the value of a gedcom tag from the given gedcom record
2670	 */
2671	private function getGedcomValue($tag, $level, $gedrec) {
2672		if (empty($gedrec)) {
2673			return '';
2674		}
2675		$tags      = explode(':', $tag);
2676		$origlevel = $level;
2677		if ($level == 0) {
2678			$level = $gedrec[0] + 1;
2679		}
2680
2681		$subrec = $gedrec;
2682		foreach ($tags as $t) {
2683			$lastsubrec = $subrec;
2684			$subrec     = Functions::getSubRecord($level, "$level $t", $subrec);
2685			if (empty($subrec) && $origlevel == 0) {
2686				$level--;
2687				$subrec = Functions::getSubRecord($level, "$level $t", $lastsubrec);
2688			}
2689			if (empty($subrec)) {
2690				if ($t == 'TITL') {
2691					$subrec = Functions::getSubRecord($level, "$level ABBR", $lastsubrec);
2692					if (!empty($subrec)) {
2693						$t = 'ABBR';
2694					}
2695				}
2696				if (empty($subrec)) {
2697					if ($level > 0) {
2698						$level--;
2699					}
2700					$subrec = Functions::getSubRecord($level, "@ $t", $gedrec);
2701					if (empty($subrec)) {
2702						return '';
2703					}
2704				}
2705			}
2706			$level++;
2707		}
2708		$level--;
2709		$ct = preg_match("/$level $t(.*)/", $subrec, $match);
2710		if ($ct == 0) {
2711			$ct = preg_match("/$level @.+@ (.+)/", $subrec, $match);
2712		}
2713		if ($ct == 0) {
2714			$ct = preg_match("/@ $t (.+)/", $subrec, $match);
2715		}
2716		if ($ct > 0) {
2717			$value = trim($match[1]);
2718			if ($t == 'NOTE' && preg_match('/^@(.+)@$/', $value, $match)) {
2719				$note = Note::getInstance($match[1], $this->tree);
2720				if ($note) {
2721					$value = $note->getNote();
2722				} else {
2723					//-- set the value to the id without the @
2724					$value = $match[1];
2725				}
2726			}
2727			if ($level != 0 || $t != 'NOTE') {
2728				$value .= Functions::getCont($level + 1, $subrec);
2729			}
2730
2731			return $value;
2732		}
2733
2734		return '';
2735	}
2736
2737	/**
2738	 * Replace variable identifiers with their values.
2739	 *
2740	 * @param string $expression An expression such as "$foo == 123"
2741	 * @param bool   $quote      Whether to add quotation marks
2742	 *
2743	 * @return string
2744	 */
2745	private function substituteVars($expression, $quote) {
2746		return preg_replace_callback(
2747			'/\$(\w+)/',
2748			function ($matches) use ($quote) {
2749				if (isset($this->vars[$matches[1]]['id'])) {
2750					if ($quote) {
2751						return "'" . addcslashes($this->vars[$matches[1]]['id'], "'") . "'";
2752					} else {
2753						return $this->vars[$matches[1]]['id'];
2754					}
2755				} else {
2756					Log::addErrorLog(sprintf('Undefined variable $%s in report', $matches[1]));
2757
2758					return '$' . $matches[1];
2759				}
2760			},
2761			$expression
2762		);
2763	}
2764}
2765