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 * XML <style> 288 * 289 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML <Doc> 329 * Sets up the basics of the document proparties 330 * 331 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML </Doc> 424 * 425 * @return void 426 */ 427 protected function docEndHandler(): void 428 { 429 $this->wt_report->run(); 430 } 431 432 /** 433 * XML <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 * XML <bodyStartHandler> 446 * 447 * @return void 448 */ 449 protected function bodyStartHandler(): void 450 { 451 $this->wt_report->setProcessing('B'); 452 } 453 454 /** 455 * XML <footerStartHandler> 456 * 457 * @return void 458 */ 459 protected function footerStartHandler(): void 460 { 461 $this->wt_report->setProcessing('F'); 462 } 463 464 /** 465 * XML <Cell> 466 * 467 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML </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 * XML <Now /> element handler 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 * XML <PageNum /> element handler 646 * 647 * @return void 648 */ 649 protected function pageNumStartHandler(): void 650 { 651 $this->current_element->addText('#PAGENUM#'); 652 } 653 654 /** 655 * XML <TotalPages /> element handler 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 * XML <textBoxStartHandler> 745 * 746 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML <textBoxEndHandler> 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 * XML </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 * XML <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 * XML <GedcomValue/> 1013 * 1014 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML <RepeatTag> 1089 * 1090 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML </ 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 * XML <Facts> 1302 * 1303 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML </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 * XML <if > start element 1516 * 1517 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML <if /> end element 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 * XML <Footnote > start element 1599 * Collect the Footnote links 1600 * GEDCOM Records that are protected by Privacy setting will be ignore 1601 * 1602 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML <Footnote /> end element 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 * XML <FootnoteTexts /> element 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 * XML <sp />element Forced space handler 1673 * 1674 * @return void 1675 */ 1676 protected function spStartHandler(): void 1677 { 1678 if ($this->print_data && $this->process_gedcoms === 0) { 1679 $this->current_element->addText(' '); 1680 } 1681 } 1682 1683 /** 1684 * XML <HighlightedImage/> 1685 * 1686 * @param string[] $attrs an array of key value pairs for the attributes 1687 * 1688 * @return void 1689 */ 1690 protected function highlightedImageStartHandler(array $attrs): void 1691 { 1692 $id = ''; 1693 if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) { 1694 $id = $match[1]; 1695 } 1696 1697 // Position the top corner of this box on the page 1698 $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION); 1699 1700 // Position the left corner of this box on the page 1701 $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION); 1702 1703 // string Align the image in left, center, right (or empty to use x/y position). 1704 $align = $attrs['align'] ?? ''; 1705 1706 // string Next Line should be T:next to the image, N:next line 1707 $ln = $attrs['ln'] ?? 'T'; 1708 1709 // Width, height (or both). 1710 $width = (float) ($attrs['width'] ?? 0.0); 1711 $height = (float) ($attrs['height'] ?? 0.0); 1712 1713 $person = Individual::getInstance($id, $this->tree); 1714 $media_file = $person->findHighlightedMediaFile(); 1715 1716 if ($media_file instanceof MediaFile && $media_file->fileExists($this->data_filesystem)) { 1717 $image = imagecreatefromstring($media_file->fileContents($this->data_filesystem)); 1718 $attributes = [imagesx($image), imagesy($image)]; 1719 1720 if ($width > 0 && $height == 0) { 1721 $perc = $width / $attributes[0]; 1722 $height = round($attributes[1] * $perc); 1723 } elseif ($height > 0 && $width == 0) { 1724 $perc = $height / $attributes[1]; 1725 $width = round($attributes[0] * $perc); 1726 } else { 1727 $width = $attributes[0]; 1728 $height = $attributes[1]; 1729 } 1730 $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln, $this->data_filesystem); 1731 $this->wt_report->addElement($image); 1732 } 1733 } 1734 1735 /** 1736 * XML <Image/> 1737 * 1738 * @param string[] $attrs an array of key value pairs for the attributes 1739 * 1740 * @return void 1741 */ 1742 protected function imageStartHandler(array $attrs): void 1743 { 1744 // Position the top corner of this box on the page. the default is the current position 1745 $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION); 1746 1747 // mixed Position the left corner of this box on the page. the default is the current position 1748 $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION); 1749 1750 // string Align the image in left, center, right (or empty to use x/y position). 1751 $align = $attrs['align'] ?? ''; 1752 1753 // string Next Line should be T:next to the image, N:next line 1754 $ln = $attrs['ln'] ?? 'T'; 1755 1756 // Width, height (or both). 1757 $width = (float) ($attrs['width'] ?? 0.0); 1758 $height = (float) ($attrs['height'] ?? 0.0); 1759 1760 $file = $attrs['file'] ?? ''; 1761 1762 if ($file === '@FILE') { 1763 $match = []; 1764 if (preg_match("/\d OBJE @(.+)@/", $this->gedrec, $match)) { 1765 $mediaobject = Media::getInstance($match[1], $this->tree); 1766 $media_file = $mediaobject->firstImageFile(); 1767 1768 if ($media_file instanceof MediaFile && $media_file->fileExists($this->data_filesystem)) { 1769 $image = imagecreatefromstring($media_file->fileContents($this->data_filesystem)); 1770 $attributes = [imagesx($image), imagesy($image)]; 1771 1772 if ($width > 0 && $height == 0) { 1773 $perc = $width / $attributes[0]; 1774 $height = round($attributes[1] * $perc); 1775 } elseif ($height > 0 && $width == 0) { 1776 $perc = $height / $attributes[1]; 1777 $width = round($attributes[0] * $perc); 1778 } else { 1779 $width = $attributes[0]; 1780 $height = $attributes[1]; 1781 } 1782 $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln, $this->data_filesystem); 1783 $this->wt_report->addElement($image); 1784 } 1785 } 1786 } else { 1787 if (file_exists($file) && preg_match('/(jpg|jpeg|png|gif)$/i', $file)) { 1788 $size = getimagesize($file); 1789 if ($width > 0 && $height == 0) { 1790 $perc = $width / $size[0]; 1791 $height = round($size[1] * $perc); 1792 } elseif ($height > 0 && $width == 0) { 1793 $perc = $height / $size[1]; 1794 $width = round($size[0] * $perc); 1795 } else { 1796 $width = $size[0]; 1797 $height = $size[1]; 1798 } 1799 $image = $this->report_root->createImage($file, $left, $top, $width, $height, $align, $ln); 1800 $this->wt_report->addElement($image); 1801 } 1802 } 1803 } 1804 1805 /** 1806 * XML <Line> element handler 1807 * 1808 * @param string[] $attrs an array of key value pairs for the attributes 1809 * 1810 * @return void 1811 */ 1812 protected function lineStartHandler(array $attrs): void 1813 { 1814 // Start horizontal position, current position (default) 1815 $x1 = ReportBaseElement::CURRENT_POSITION; 1816 if (isset($attrs['x1'])) { 1817 if ($attrs['x1'] === '0') { 1818 $x1 = 0; 1819 } elseif ($attrs['x1'] === '.') { 1820 $x1 = ReportBaseElement::CURRENT_POSITION; 1821 } elseif (!empty($attrs['x1'])) { 1822 $x1 = (float) $attrs['x1']; 1823 } 1824 } 1825 // Start vertical position, current position (default) 1826 $y1 = ReportBaseElement::CURRENT_POSITION; 1827 if (isset($attrs['y1'])) { 1828 if ($attrs['y1'] === '0') { 1829 $y1 = 0; 1830 } elseif ($attrs['y1'] === '.') { 1831 $y1 = ReportBaseElement::CURRENT_POSITION; 1832 } elseif (!empty($attrs['y1'])) { 1833 $y1 = (float) $attrs['y1']; 1834 } 1835 } 1836 // End horizontal position, maximum width (default) 1837 $x2 = ReportBaseElement::CURRENT_POSITION; 1838 if (isset($attrs['x2'])) { 1839 if ($attrs['x2'] === '0') { 1840 $x2 = 0; 1841 } elseif ($attrs['x2'] === '.') { 1842 $x2 = ReportBaseElement::CURRENT_POSITION; 1843 } elseif (!empty($attrs['x2'])) { 1844 $x2 = (float) $attrs['x2']; 1845 } 1846 } 1847 // End vertical position 1848 $y2 = ReportBaseElement::CURRENT_POSITION; 1849 if (isset($attrs['y2'])) { 1850 if ($attrs['y2'] === '0') { 1851 $y2 = 0; 1852 } elseif ($attrs['y2'] === '.') { 1853 $y2 = ReportBaseElement::CURRENT_POSITION; 1854 } elseif (!empty($attrs['y2'])) { 1855 $y2 = (float) $attrs['y2']; 1856 } 1857 } 1858 1859 $line = $this->report_root->createLine($x1, $y1, $x2, $y2); 1860 $this->wt_report->addElement($line); 1861 } 1862 1863 /** 1864 * XML <List> 1865 * 1866 * @param string[] $attrs an array of key value pairs for the attributes 1867 * 1868 * @return void 1869 */ 1870 protected function listStartHandler(array $attrs): void 1871 { 1872 $this->process_repeats++; 1873 if ($this->process_repeats > 1) { 1874 return; 1875 } 1876 1877 $match = []; 1878 if (isset($attrs['sortby'])) { 1879 $sortby = $attrs['sortby']; 1880 if (preg_match("/\\$(\w+)/", $sortby, $match)) { 1881 $sortby = $this->vars[$match[1]]['id']; 1882 $sortby = trim($sortby); 1883 } 1884 } else { 1885 $sortby = 'NAME'; 1886 } 1887 1888 $listname = $attrs['list'] ?? 'individual'; 1889 1890 // Some filters/sorts can be applied using SQL, while others require PHP 1891 switch ($listname) { 1892 case 'pending': 1893 $xrefs = DB::table('change') 1894 ->whereIn('change_id', function (Builder $query): void { 1895 $query->select(new Expression('MAX(change_id)')) 1896 ->from('change') 1897 ->where('gedcom_id', '=', $this->tree->id()) 1898 ->where('status', '=', 'pending') 1899 ->groupBy(['xref']); 1900 }) 1901 ->pluck('xref'); 1902 1903 $this->list = []; 1904 foreach ($xrefs as $xref) { 1905 $this->list[] = GedcomRecord::getInstance($xref, $this->tree); 1906 } 1907 break; 1908 case 'individual': 1909 $query = DB::table('individuals') 1910 ->where('i_file', '=', $this->tree->id()) 1911 ->select(['i_id AS xref', 'i_gedcom AS gedcom']) 1912 ->distinct(); 1913 1914 foreach ($attrs as $attr => $value) { 1915 if (strpos($attr, 'filter') === 0 && $value) { 1916 $value = $this->substituteVars($value, false); 1917 // Convert the various filters into SQL 1918 if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) { 1919 $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void { 1920 $join 1921 ->on($attr . '.d_gid', '=', 'i_id') 1922 ->on($attr . '.d_file', '=', 'i_file'); 1923 }); 1924 1925 $query->where($attr . '.d_fact', '=', $match[1]); 1926 1927 $date = new Date($match[3]); 1928 1929 if ($match[2] === 'LTE') { 1930 $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay()); 1931 } else { 1932 $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay()); 1933 } 1934 1935 // This filter has been fully processed 1936 unset($attrs[$attr]); 1937 } elseif (preg_match('/^NAME CONTAINS (.+)$/', $value, $match)) { 1938 $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void { 1939 $join 1940 ->on($attr . '.n_id', '=', 'i_id') 1941 ->on($attr . '.n_file', '=', 'i_file'); 1942 }); 1943 // Search the DB only if there is any name supplied 1944 $names = explode(' ', $match[1]); 1945 foreach ($names as $n => $name) { 1946 $query->whereContains($attr . '.n_full', $name); 1947 } 1948 1949 // This filter has been fully processed 1950 unset($attrs[$attr]); 1951 } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) { 1952 // Convert newline escape sequences to actual new lines 1953 $match[1] = str_replace('\n', "\n", $match[1]); 1954 1955 $query->where('i_gedcom', 'LIKE', $match[1]); 1956 1957 // This filter has been fully processed 1958 unset($attrs[$attr]); 1959 } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) { 1960 // Don't unset this filter. This is just initial filtering for performance 1961 $query 1962 ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void { 1963 $join 1964 ->on($attr . 'a.pl_file', '=', 'i_file') 1965 ->on($attr . 'a.pl_gid', '=', 'i_id'); 1966 }) 1967 ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void { 1968 $join 1969 ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file') 1970 ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id'); 1971 }) 1972 ->whereContains($attr . 'b.p_place', $match[1]); 1973 } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) { 1974 // Don't unset this filter. This is just initial filtering for performance 1975 $match[3] = strtr($match[3], ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']); 1976 $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%'; 1977 $query->where('i_gedcom', 'LIKE', $like); 1978 } elseif (preg_match('/^(\w+) CONTAINS (.+)$/', $value, $match)) { 1979 // Don't unset this filter. This is just initial filtering for performance 1980 $match[2] = strtr($match[2], ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']); 1981 $like = "%\n1 " . $match[1] . '%' . $match[2] . '%'; 1982 $query->where('i_gedcom', 'LIKE', $like); 1983 } 1984 } 1985 } 1986 1987 $this->list = []; 1988 1989 foreach ($query->get() as $row) { 1990 $this->list[$row->xref] = Individual::getInstance($row->xref, $this->tree, $row->gedcom); 1991 } 1992 break; 1993 1994 case 'family': 1995 $query = DB::table('families') 1996 ->where('f_file', '=', $this->tree->id()) 1997 ->select(['f_id AS xref', 'f_gedcom AS gedcom']) 1998 ->distinct(); 1999 2000 foreach ($attrs as $attr => $value) { 2001 if (strpos($attr, 'filter') === 0 && $value) { 2002 $value = $this->substituteVars($value, false); 2003 // Convert the various filters into SQL 2004 if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) { 2005 $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void { 2006 $join 2007 ->on($attr . '.d_gid', '=', 'f_id') 2008 ->on($attr . '.d_file', '=', 'f_file'); 2009 }); 2010 2011 $query->where($attr . '.d_fact', '=', $match[1]); 2012 2013 $date = new Date($match[3]); 2014 2015 if ($match[2] === 'LTE') { 2016 $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay()); 2017 } else { 2018 $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay()); 2019 } 2020 2021 // This filter has been fully processed 2022 unset($attrs[$attr]); 2023 } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) { 2024 // Convert newline escape sequences to actual new lines 2025 $match[1] = str_replace('\n', "\n", $match[1]); 2026 2027 $query->where('f_gedcom', 'LIKE', $match[1]); 2028 2029 // This filter has been fully processed 2030 unset($attrs[$attr]); 2031 } elseif (preg_match('/^NAME CONTAINS (.*)$/', $value, $match)) { 2032 if ($sortby === 'NAME' || $match[1] !== '') { 2033 $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void { 2034 $join 2035 ->on($attr . '.n_file', '=', 'f_file') 2036 ->where(static function (Builder $query): void { 2037 $query 2038 ->whereColumn('n_id', '=', 'f_husb') 2039 ->orWhereColumn('n_id', '=', 'f_wife'); 2040 }); 2041 }); 2042 // Search the DB only if there is any name supplied 2043 if ($match[1] != '') { 2044 $names = explode(' ', $match[1]); 2045 foreach ($names as $n => $name) { 2046 $query->whereContains($attr . '.n_full', $name); 2047 } 2048 } 2049 } 2050 2051 // This filter has been fully processed 2052 unset($attrs[$attr]); 2053 } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) { 2054 // Don't unset this filter. This is just initial filtering for performance 2055 $query 2056 ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void { 2057 $join 2058 ->on($attr . 'a.pl_file', '=', 'f_file') 2059 ->on($attr . 'a.pl_gid', '=', 'f_id'); 2060 }) 2061 ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void { 2062 $join 2063 ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file') 2064 ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id'); 2065 }) 2066 ->whereContains($attr . 'b.p_place', $match[1]); 2067 } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) { 2068 // Don't unset this filter. This is just initial filtering for performance 2069 $match[3] = strtr($match[3], ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']); 2070 $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%'; 2071 $query->where('f_gedcom', 'LIKE', $like); 2072 } elseif (preg_match('/^(\w+) CONTAINS (.+)$/', $value, $match)) { 2073 // Don't unset this filter. This is just initial filtering for performance 2074 $match[2] = strtr($match[2], ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']); 2075 $like = "%\n1 " . $match[1] . '%' . $match[2] . '%'; 2076 $query->where('f_gedcom', 'LIKE', $like); 2077 } 2078 } 2079 } 2080 2081 $this->list = []; 2082 2083 foreach ($query->get() as $row) { 2084 $this->list[$row->xref] = Family::getInstance($row->xref, $this->tree, $row->gedcom); 2085 } 2086 break; 2087 2088 default: 2089 throw new DomainException('Invalid list name: ' . $listname); 2090 } 2091 2092 $filters = []; 2093 $filters2 = []; 2094 if (isset($attrs['filter1']) && count($this->list) > 0) { 2095 foreach ($attrs as $key => $value) { 2096 if (preg_match("/filter(\d)/", $key)) { 2097 $condition = $value; 2098 if (preg_match("/@(\w+)/", $condition, $match)) { 2099 $id = $match[1]; 2100 $value = "''"; 2101 if ($id === 'ID') { 2102 if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) { 2103 $value = "'" . $match[1] . "'"; 2104 } 2105 } elseif ($id === 'fact') { 2106 $value = "'" . $this->fact . "'"; 2107 } elseif ($id === 'desc') { 2108 $value = "'" . $this->desc . "'"; 2109 } else { 2110 if (preg_match("/\d $id (.+)/", $this->gedrec, $match)) { 2111 $value = "'" . str_replace('@', '', trim($match[1])) . "'"; 2112 } 2113 } 2114 $condition = preg_replace("/@$id/", $value, $condition); 2115 } 2116 //-- handle regular expressions 2117 if (preg_match("/([A-Z:]+)\s*([^\s]+)\s*(.+)/", $condition, $match)) { 2118 $tag = trim($match[1]); 2119 $expr = trim($match[2]); 2120 $val = trim($match[3]); 2121 if (preg_match("/\\$(\w+)/", $val, $match)) { 2122 $val = $this->vars[$match[1]]['id']; 2123 $val = trim($val); 2124 } 2125 if ($val) { 2126 $searchstr = ''; 2127 $tags = explode(':', $tag); 2128 //-- only limit to a level number if we are specifically looking at a level 2129 if (count($tags) > 1) { 2130 $level = 1; 2131 $t = 'XXXX'; 2132 foreach ($tags as $t) { 2133 if (!empty($searchstr)) { 2134 $searchstr .= "[^\n]*(\n[2-9][^\n]*)*\n"; 2135 } 2136 //-- search for both EMAIL and _EMAIL... silly double gedcom standard 2137 if ($t === 'EMAIL' || $t === '_EMAIL') { 2138 $t = '_?EMAIL'; 2139 } 2140 $searchstr .= $level . ' ' . $t; 2141 $level++; 2142 } 2143 } else { 2144 if ($tag === 'EMAIL' || $tag === '_EMAIL') { 2145 $tag = '_?EMAIL'; 2146 } 2147 $t = $tag; 2148 $searchstr = '1 ' . $tag; 2149 } 2150 switch ($expr) { 2151 case 'CONTAINS': 2152 if ($t === 'PLAC') { 2153 $searchstr .= "[^\n]*[, ]*" . $val; 2154 } else { 2155 $searchstr .= "[^\n]*" . $val; 2156 } 2157 $filters[] = $searchstr; 2158 break; 2159 default: 2160 $filters2[] = [ 2161 'tag' => $tag, 2162 'expr' => $expr, 2163 'val' => $val, 2164 ]; 2165 break; 2166 } 2167 } 2168 } 2169 } 2170 } 2171 } 2172 //-- apply other filters to the list that could not be added to the search string 2173 if ($filters) { 2174 foreach ($this->list as $key => $record) { 2175 foreach ($filters as $filter) { 2176 if (!preg_match('/' . $filter . '/i', $record->privatizeGedcom(Auth::accessLevel($this->tree)))) { 2177 unset($this->list[$key]); 2178 break; 2179 } 2180 } 2181 } 2182 } 2183 if ($filters2) { 2184 $mylist = []; 2185 foreach ($this->list as $indi) { 2186 $key = $indi->xref(); 2187 $grec = $indi->privatizeGedcom(Auth::accessLevel($this->tree)); 2188 $keep = true; 2189 foreach ($filters2 as $filter) { 2190 if ($keep) { 2191 $tag = $filter['tag']; 2192 $expr = $filter['expr']; 2193 $val = $filter['val']; 2194 if ($val === "''") { 2195 $val = ''; 2196 } 2197 $tags = explode(':', $tag); 2198 $t = end($tags); 2199 $v = $this->getGedcomValue($tag, 1, $grec); 2200 //-- check for EMAIL and _EMAIL (silly double gedcom standard :P) 2201 if ($t === 'EMAIL' && empty($v)) { 2202 $tag = str_replace('EMAIL', '_EMAIL', $tag); 2203 $tags = explode(':', $tag); 2204 $t = end($tags); 2205 $v = Functions::getSubRecord(1, $tag, $grec); 2206 } 2207 2208 switch ($expr) { 2209 case 'GTE': 2210 if ($t === 'DATE') { 2211 $date1 = new Date($v); 2212 $date2 = new Date($val); 2213 $keep = (Date::compare($date1, $date2) >= 0); 2214 } elseif ($val >= $v) { 2215 $keep = true; 2216 } 2217 break; 2218 case 'LTE': 2219 if ($t === 'DATE') { 2220 $date1 = new Date($v); 2221 $date2 = new Date($val); 2222 $keep = (Date::compare($date1, $date2) <= 0); 2223 } elseif ($val >= $v) { 2224 $keep = true; 2225 } 2226 break; 2227 default: 2228 if ($v == $val) { 2229 $keep = true; 2230 } else { 2231 $keep = false; 2232 } 2233 break; 2234 } 2235 } 2236 } 2237 if ($keep) { 2238 $mylist[$key] = $indi; 2239 } 2240 } 2241 $this->list = $mylist; 2242 } 2243 2244 switch ($sortby) { 2245 case 'NAME': 2246 uasort($this->list, GedcomRecord::nameComparator()); 2247 break; 2248 case 'CHAN': 2249 uasort($this->list, GedcomRecord::lastChangeComparator()); 2250 break; 2251 case 'BIRT:DATE': 2252 uasort($this->list, Individual::birthDateComparator()); 2253 break; 2254 case 'DEAT:DATE': 2255 uasort($this->list, Individual::deathDateComparator()); 2256 break; 2257 case 'MARR:DATE': 2258 uasort($this->list, Family::marriageDateComparator()); 2259 break; 2260 default: 2261 // unsorted or already sorted by SQL 2262 break; 2263 } 2264 2265 $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes]; 2266 $this->repeat_bytes = xml_get_current_line_number($this->parser) + 1; 2267 } 2268 2269 /** 2270 * XML <List> 2271 * 2272 * @return void 2273 */ 2274 protected function listEndHandler(): void 2275 { 2276 $this->process_repeats--; 2277 if ($this->process_repeats > 0) { 2278 return; 2279 } 2280 2281 // Check if there is any list 2282 if (count($this->list) > 0) { 2283 $lineoffset = 0; 2284 foreach ($this->repeats_stack as $rep) { 2285 $lineoffset += $rep[1]; 2286 } 2287 //-- read the xml from the file 2288 $lines = file($this->report); 2289 while ((strpos($lines[$lineoffset + $this->repeat_bytes], '<List') === false) && (($lineoffset + $this->repeat_bytes) > 0)) { 2290 $lineoffset--; 2291 } 2292 $lineoffset++; 2293 $reportxml = "<tempdoc>\n"; 2294 $line_nr = $lineoffset + $this->repeat_bytes; 2295 // List Level counter 2296 $count = 1; 2297 while (0 < $count) { 2298 if (strpos($lines[$line_nr], '<List') !== false) { 2299 $count++; 2300 } elseif (strpos($lines[$line_nr], '</List') !== false) { 2301 $count--; 2302 } 2303 if (0 < $count) { 2304 $reportxml .= $lines[$line_nr]; 2305 } 2306 $line_nr++; 2307 } 2308 // No need to drag this 2309 unset($lines); 2310 $reportxml .= '</tempdoc>'; 2311 // Save original values 2312 $this->parser_stack[] = $this->parser; 2313 $oldgedrec = $this->gedrec; 2314 2315 $this->list_total = count($this->list); 2316 $this->list_private = 0; 2317 foreach ($this->list as $record) { 2318 if ($record->canShow()) { 2319 $this->gedrec = $record->privatizeGedcom(Auth::accessLevel($record->tree())); 2320 //-- start the sax parser 2321 $repeat_parser = xml_parser_create(); 2322 $this->parser = $repeat_parser; 2323 xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false); 2324 2325 xml_set_element_handler( 2326 $repeat_parser, 2327 function ($parser, string $name, array $attrs): void { 2328 $this->startElement($parser, $name, $attrs); 2329 }, 2330 function ($parser, string $name): void { 2331 $this->endElement($parser, $name); 2332 } 2333 ); 2334 2335 xml_set_character_data_handler( 2336 $repeat_parser, 2337 function ($parser, string $data): void { 2338 $this->characterData($parser, $data); 2339 } 2340 ); 2341 2342 if (!xml_parse($repeat_parser, $reportxml, true)) { 2343 throw new DomainException(sprintf( 2344 'ListEHandler XML error: %s at line %d', 2345 xml_error_string(xml_get_error_code($repeat_parser)), 2346 xml_get_current_line_number($repeat_parser) 2347 )); 2348 } 2349 xml_parser_free($repeat_parser); 2350 } else { 2351 $this->list_private++; 2352 } 2353 } 2354 $this->list = []; 2355 $this->parser = array_pop($this->parser_stack); 2356 $this->gedrec = $oldgedrec; 2357 } 2358 [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack); 2359 } 2360 2361 /** 2362 * XML <ListTotal> element handler 2363 * Prints the total number of records in a list 2364 * The total number is collected from 2365 * 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 * XML <Relatives> 2380 * 2381 * @param string[] $attrs an array of key value pairs for the attributes 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 * XML </ 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 * XML <Generation /> element handler 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 * XML <NewPage /> element handler 2599 * Has to be placed in an element (header, pageheader, 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 * XML </titleEndHandler> 2611 * 2612 * @return void 2613 */ 2614 protected function titleEndHandler(): void 2615 { 2616 $this->report_root->addTitle($this->text); 2617 } 2618 2619 /** 2620 * XML </descriptionEndHandler> 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