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