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 foreach ($tags as $t) { 2132 if (!empty($searchstr)) { 2133 $searchstr .= "[^\n]*(\n[2-9][^\n]*)*\n"; 2134 } 2135 //-- search for both EMAIL and _EMAIL... silly double gedcom standard 2136 if ($t === 'EMAIL' || $t === '_EMAIL') { 2137 $t = '_?EMAIL'; 2138 } 2139 $searchstr .= $level . ' ' . $t; 2140 $level++; 2141 } 2142 } else { 2143 if ($tag === 'EMAIL' || $tag === '_EMAIL') { 2144 $tag = '_?EMAIL'; 2145 } 2146 $t = $tag; 2147 $searchstr = '1 ' . $tag; 2148 } 2149 switch ($expr) { 2150 case 'CONTAINS': 2151 if ($t === 'PLAC') { 2152 $searchstr .= "[^\n]*[, ]*" . $val; 2153 } else { 2154 $searchstr .= "[^\n]*" . $val; 2155 } 2156 $filters[] = $searchstr; 2157 break; 2158 default: 2159 $filters2[] = [ 2160 'tag' => $tag, 2161 'expr' => $expr, 2162 'val' => $val, 2163 ]; 2164 break; 2165 } 2166 } 2167 } 2168 } 2169 } 2170 } 2171 //-- apply other filters to the list that could not be added to the search string 2172 if ($filters) { 2173 foreach ($this->list as $key => $record) { 2174 foreach ($filters as $filter) { 2175 if (!preg_match('/' . $filter . '/i', $record->privatizeGedcom(Auth::accessLevel($this->tree)))) { 2176 unset($this->list[$key]); 2177 break; 2178 } 2179 } 2180 } 2181 } 2182 if ($filters2) { 2183 $mylist = []; 2184 foreach ($this->list as $indi) { 2185 $key = $indi->xref(); 2186 $grec = $indi->privatizeGedcom(Auth::accessLevel($this->tree)); 2187 $keep = true; 2188 foreach ($filters2 as $filter) { 2189 if ($keep) { 2190 $tag = $filter['tag']; 2191 $expr = $filter['expr']; 2192 $val = $filter['val']; 2193 if ($val === "''") { 2194 $val = ''; 2195 } 2196 $tags = explode(':', $tag); 2197 $t = end($tags); 2198 $v = $this->getGedcomValue($tag, 1, $grec); 2199 //-- check for EMAIL and _EMAIL (silly double gedcom standard :P) 2200 if ($t === 'EMAIL' && empty($v)) { 2201 $tag = str_replace('EMAIL', '_EMAIL', $tag); 2202 $tags = explode(':', $tag); 2203 $t = end($tags); 2204 $v = Functions::getSubRecord(1, $tag, $grec); 2205 } 2206 2207 switch ($expr) { 2208 case 'GTE': 2209 if ($t === 'DATE') { 2210 $date1 = new Date($v); 2211 $date2 = new Date($val); 2212 $keep = (Date::compare($date1, $date2) >= 0); 2213 } elseif ($val >= $v) { 2214 $keep = true; 2215 } 2216 break; 2217 case 'LTE': 2218 if ($t === 'DATE') { 2219 $date1 = new Date($v); 2220 $date2 = new Date($val); 2221 $keep = (Date::compare($date1, $date2) <= 0); 2222 } elseif ($val >= $v) { 2223 $keep = true; 2224 } 2225 break; 2226 default: 2227 if ($v == $val) { 2228 $keep = true; 2229 } else { 2230 $keep = false; 2231 } 2232 break; 2233 } 2234 } 2235 } 2236 if ($keep) { 2237 $mylist[$key] = $indi; 2238 } 2239 } 2240 $this->list = $mylist; 2241 } 2242 2243 switch ($sortby) { 2244 case 'NAME': 2245 uasort($this->list, GedcomRecord::nameComparator()); 2246 break; 2247 case 'CHAN': 2248 uasort($this->list, GedcomRecord::lastChangeComparator()); 2249 break; 2250 case 'BIRT:DATE': 2251 uasort($this->list, Individual::birthDateComparator()); 2252 break; 2253 case 'DEAT:DATE': 2254 uasort($this->list, Individual::deathDateComparator()); 2255 break; 2256 case 'MARR:DATE': 2257 uasort($this->list, Family::marriageDateComparator()); 2258 break; 2259 default: 2260 // unsorted or already sorted by SQL 2261 break; 2262 } 2263 2264 $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes]; 2265 $this->repeat_bytes = xml_get_current_line_number($this->parser) + 1; 2266 } 2267 2268 /** 2269 * XML <List> 2270 * 2271 * @return void 2272 */ 2273 protected function listEndHandler(): void 2274 { 2275 $this->process_repeats--; 2276 if ($this->process_repeats > 0) { 2277 return; 2278 } 2279 2280 // Check if there is any list 2281 if (count($this->list) > 0) { 2282 $lineoffset = 0; 2283 foreach ($this->repeats_stack as $rep) { 2284 $lineoffset += $rep[1]; 2285 } 2286 //-- read the xml from the file 2287 $lines = file($this->report); 2288 while ((strpos($lines[$lineoffset + $this->repeat_bytes], '<List') === false) && (($lineoffset + $this->repeat_bytes) > 0)) { 2289 $lineoffset--; 2290 } 2291 $lineoffset++; 2292 $reportxml = "<tempdoc>\n"; 2293 $line_nr = $lineoffset + $this->repeat_bytes; 2294 // List Level counter 2295 $count = 1; 2296 while (0 < $count) { 2297 if (strpos($lines[$line_nr], '<List') !== false) { 2298 $count++; 2299 } elseif (strpos($lines[$line_nr], '</List') !== false) { 2300 $count--; 2301 } 2302 if (0 < $count) { 2303 $reportxml .= $lines[$line_nr]; 2304 } 2305 $line_nr++; 2306 } 2307 // No need to drag this 2308 unset($lines); 2309 $reportxml .= '</tempdoc>'; 2310 // Save original values 2311 $this->parser_stack[] = $this->parser; 2312 $oldgedrec = $this->gedrec; 2313 2314 $this->list_total = count($this->list); 2315 $this->list_private = 0; 2316 foreach ($this->list as $record) { 2317 if ($record->canShow()) { 2318 $this->gedrec = $record->privatizeGedcom(Auth::accessLevel($record->tree())); 2319 //-- start the sax parser 2320 $repeat_parser = xml_parser_create(); 2321 $this->parser = $repeat_parser; 2322 xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false); 2323 2324 xml_set_element_handler( 2325 $repeat_parser, 2326 function ($parser, string $name, array $attrs): void { 2327 $this->startElement($parser, $name, $attrs); 2328 }, 2329 function ($parser, string $name): void { 2330 $this->endElement($parser, $name); 2331 } 2332 ); 2333 2334 xml_set_character_data_handler( 2335 $repeat_parser, 2336 function ($parser, string $data): void { 2337 $this->characterData($parser, $data); 2338 } 2339 ); 2340 2341 if (!xml_parse($repeat_parser, $reportxml, true)) { 2342 throw new DomainException(sprintf( 2343 'ListEHandler XML error: %s at line %d', 2344 xml_error_string(xml_get_error_code($repeat_parser)), 2345 xml_get_current_line_number($repeat_parser) 2346 )); 2347 } 2348 xml_parser_free($repeat_parser); 2349 } else { 2350 $this->list_private++; 2351 } 2352 } 2353 $this->list = []; 2354 $this->parser = array_pop($this->parser_stack); 2355 $this->gedrec = $oldgedrec; 2356 } 2357 [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack); 2358 } 2359 2360 /** 2361 * XML <ListTotal> element handler 2362 * Prints the total number of records in a list 2363 * The total number is collected from 2364 * List and Relatives 2365 * 2366 * @return void 2367 */ 2368 protected function listTotalStartHandler(): void 2369 { 2370 if ($this->list_private == 0) { 2371 $this->current_element->addText((string) $this->list_total); 2372 } else { 2373 $this->current_element->addText(($this->list_total - $this->list_private) . ' / ' . $this->list_total); 2374 } 2375 } 2376 2377 /** 2378 * XML <Relatives> 2379 * 2380 * @param string[] $attrs an array of key value pairs for the attributes 2381 * 2382 * @return void 2383 */ 2384 protected function relativesStartHandler(array $attrs): void 2385 { 2386 $this->process_repeats++; 2387 if ($this->process_repeats > 1) { 2388 return; 2389 } 2390 2391 $sortby = $attrs['sortby'] ?? 'NAME'; 2392 2393 $match = []; 2394 if (preg_match("/\\$(\w+)/", $sortby, $match)) { 2395 $sortby = $this->vars[$match[1]]['id']; 2396 $sortby = trim($sortby); 2397 } 2398 2399 $maxgen = -1; 2400 if (isset($attrs['maxgen'])) { 2401 $maxgen = (int) $attrs['maxgen']; 2402 } 2403 2404 $group = $attrs['group'] ?? 'child-family'; 2405 2406 if (preg_match("/\\$(\w+)/", $group, $match)) { 2407 $group = $this->vars[$match[1]]['id']; 2408 $group = trim($group); 2409 } 2410 2411 $id = $attrs['id'] ?? ''; 2412 2413 if (preg_match("/\\$(\w+)/", $id, $match)) { 2414 $id = $this->vars[$match[1]]['id']; 2415 $id = trim($id); 2416 } 2417 2418 $this->list = []; 2419 $person = Individual::getInstance($id, $this->tree); 2420 if ($person instanceof Individual) { 2421 $this->list[$id] = $person; 2422 switch ($group) { 2423 case 'child-family': 2424 foreach ($person->childFamilies() as $family) { 2425 foreach ($family->spouses() as $spouse) { 2426 $this->list[$spouse->xref()] = $spouse; 2427 } 2428 2429 foreach ($family->children() as $child) { 2430 $this->list[$child->xref()] = $child; 2431 } 2432 } 2433 break; 2434 case 'spouse-family': 2435 foreach ($person->spouseFamilies() as $family) { 2436 foreach ($family->spouses() as $spouse) { 2437 $this->list[$spouse->xref()] = $spouse; 2438 } 2439 2440 foreach ($family->children() as $child) { 2441 $this->list[$child->xref()] = $child; 2442 } 2443 } 2444 break; 2445 case 'direct-ancestors': 2446 $this->addAncestors($this->list, $id, false, $maxgen); 2447 break; 2448 case 'ancestors': 2449 $this->addAncestors($this->list, $id, true, $maxgen); 2450 break; 2451 case 'descendants': 2452 $this->list[$id]->generation = 1; 2453 $this->addDescendancy($this->list, $id, false, $maxgen); 2454 break; 2455 case 'all': 2456 $this->addAncestors($this->list, $id, true, $maxgen); 2457 $this->addDescendancy($this->list, $id, true, $maxgen); 2458 break; 2459 } 2460 } 2461 2462 switch ($sortby) { 2463 case 'NAME': 2464 uasort($this->list, GedcomRecord::nameComparator()); 2465 break; 2466 case 'BIRT:DATE': 2467 uasort($this->list, Individual::birthDateComparator()); 2468 break; 2469 case 'DEAT:DATE': 2470 uasort($this->list, Individual::deathDateComparator()); 2471 break; 2472 case 'generation': 2473 $newarray = []; 2474 reset($this->list); 2475 $genCounter = 1; 2476 while (count($newarray) < count($this->list)) { 2477 foreach ($this->list as $key => $value) { 2478 $this->generation = $value->generation; 2479 if ($this->generation == $genCounter) { 2480 $newarray[$key] = new stdClass(); 2481 $newarray[$key]->generation = $this->generation; 2482 } 2483 } 2484 $genCounter++; 2485 } 2486 $this->list = $newarray; 2487 break; 2488 default: 2489 // unsorted 2490 break; 2491 } 2492 $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes]; 2493 $this->repeat_bytes = xml_get_current_line_number($this->parser) + 1; 2494 } 2495 2496 /** 2497 * XML </ Relatives> 2498 * 2499 * @return void 2500 */ 2501 protected function relativesEndHandler(): void 2502 { 2503 $this->process_repeats--; 2504 if ($this->process_repeats > 0) { 2505 return; 2506 } 2507 2508 // Check if there is any relatives 2509 if (count($this->list) > 0) { 2510 $lineoffset = 0; 2511 foreach ($this->repeats_stack as $rep) { 2512 $lineoffset += $rep[1]; 2513 } 2514 //-- read the xml from the file 2515 $lines = file($this->report); 2516 while ((strpos($lines[$lineoffset + $this->repeat_bytes], '<Relatives') === false) && (($lineoffset + $this->repeat_bytes) > 0)) { 2517 $lineoffset--; 2518 } 2519 $lineoffset++; 2520 $reportxml = "<tempdoc>\n"; 2521 $line_nr = $lineoffset + $this->repeat_bytes; 2522 // Relatives Level counter 2523 $count = 1; 2524 while (0 < $count) { 2525 if (strpos($lines[$line_nr], '<Relatives') !== false) { 2526 $count++; 2527 } elseif (strpos($lines[$line_nr], '</Relatives') !== false) { 2528 $count--; 2529 } 2530 if (0 < $count) { 2531 $reportxml .= $lines[$line_nr]; 2532 } 2533 $line_nr++; 2534 } 2535 // No need to drag this 2536 unset($lines); 2537 $reportxml .= "</tempdoc>\n"; 2538 // Save original values 2539 $this->parser_stack[] = $this->parser; 2540 $oldgedrec = $this->gedrec; 2541 2542 $this->list_total = count($this->list); 2543 $this->list_private = 0; 2544 foreach ($this->list as $xref => $value) { 2545 if (isset($value->generation)) { 2546 $this->generation = $value->generation; 2547 } 2548 $tmp = GedcomRecord::getInstance((string) $xref, $this->tree); 2549 $this->gedrec = $tmp->privatizeGedcom(Auth::accessLevel($this->tree)); 2550 2551 $repeat_parser = xml_parser_create(); 2552 $this->parser = $repeat_parser; 2553 xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false); 2554 2555 xml_set_element_handler( 2556 $repeat_parser, 2557 function ($parser, string $name, array $attrs): void { 2558 $this->startElement($parser, $name, $attrs); 2559 }, 2560 function ($parser, string $name): void { 2561 $this->endElement($parser, $name); 2562 } 2563 ); 2564 2565 xml_set_character_data_handler( 2566 $repeat_parser, 2567 function ($parser, string $data): void { 2568 $this->characterData($parser, $data); 2569 } 2570 ); 2571 2572 if (!xml_parse($repeat_parser, $reportxml, true)) { 2573 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))); 2574 } 2575 xml_parser_free($repeat_parser); 2576 } 2577 // Clean up the list array 2578 $this->list = []; 2579 $this->parser = array_pop($this->parser_stack); 2580 $this->gedrec = $oldgedrec; 2581 } 2582 [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack); 2583 } 2584 2585 /** 2586 * XML <Generation /> element handler 2587 * Prints the number of generations 2588 * 2589 * @return void 2590 */ 2591 protected function generationStartHandler(): void 2592 { 2593 $this->current_element->addText((string) $this->generation); 2594 } 2595 2596 /** 2597 * XML <NewPage /> element handler 2598 * Has to be placed in an element (header, pageheader, body or footer) 2599 * 2600 * @return void 2601 */ 2602 protected function newPageStartHandler(): void 2603 { 2604 $temp = 'addpage'; 2605 $this->wt_report->addElement($temp); 2606 } 2607 2608 /** 2609 * XML </titleEndHandler> 2610 * 2611 * @return void 2612 */ 2613 protected function titleEndHandler(): void 2614 { 2615 $this->report_root->addTitle($this->text); 2616 } 2617 2618 /** 2619 * XML </descriptionEndHandler> 2620 * 2621 * @return void 2622 */ 2623 protected function descriptionEndHandler(): void 2624 { 2625 $this->report_root->addDescription($this->text); 2626 } 2627 2628 /** 2629 * Create a list of all descendants. 2630 * 2631 * @param string[] $list 2632 * @param string $pid 2633 * @param bool $parents 2634 * @param int $generations 2635 * 2636 * @return void 2637 */ 2638 private function addDescendancy(&$list, $pid, $parents = false, $generations = -1): void 2639 { 2640 $person = Individual::getInstance($pid, $this->tree); 2641 if ($person === null) { 2642 return; 2643 } 2644 if (!isset($list[$pid])) { 2645 $list[$pid] = $person; 2646 } 2647 if (!isset($list[$pid]->generation)) { 2648 $list[$pid]->generation = 0; 2649 } 2650 foreach ($person->spouseFamilies() as $family) { 2651 if ($parents) { 2652 $husband = $family->husband(); 2653 $wife = $family->wife(); 2654 if ($husband) { 2655 $list[$husband->xref()] = $husband; 2656 if (isset($list[$pid]->generation)) { 2657 $list[$husband->xref()]->generation = $list[$pid]->generation - 1; 2658 } else { 2659 $list[$husband->xref()]->generation = 1; 2660 } 2661 } 2662 if ($wife) { 2663 $list[$wife->xref()] = $wife; 2664 if (isset($list[$pid]->generation)) { 2665 $list[$wife->xref()]->generation = $list[$pid]->generation - 1; 2666 } else { 2667 $list[$wife->xref()]->generation = 1; 2668 } 2669 } 2670 } 2671 2672 $children = $family->children(); 2673 2674 foreach ($children as $child) { 2675 if ($child) { 2676 $list[$child->xref()] = $child; 2677 2678 if (isset($list[$pid]->generation)) { 2679 $list[$child->xref()]->generation = $list[$pid]->generation + 1; 2680 } else { 2681 $list[$child->xref()]->generation = 2; 2682 } 2683 } 2684 } 2685 if ($generations == -1 || $list[$pid]->generation + 1 < $generations) { 2686 foreach ($children as $child) { 2687 $this->addDescendancy($list, $child->xref(), $parents, $generations); // recurse on the childs family 2688 } 2689 } 2690 } 2691 } 2692 2693 /** 2694 * Create a list of all ancestors. 2695 * 2696 * @param stdClass[] $list 2697 * @param string $pid 2698 * @param bool $children 2699 * @param int $generations 2700 * 2701 * @return void 2702 */ 2703 private function addAncestors(array &$list, string $pid, bool $children = false, int $generations = -1): void 2704 { 2705 $genlist = [$pid]; 2706 $list[$pid]->generation = 1; 2707 while (count($genlist) > 0) { 2708 $id = array_shift($genlist); 2709 if (strpos($id, 'empty') === 0) { 2710 continue; // id can be something like “empty7” 2711 } 2712 $person = Individual::getInstance($id, $this->tree); 2713 foreach ($person->childFamilies() as $family) { 2714 $husband = $family->husband(); 2715 $wife = $family->wife(); 2716 if ($husband) { 2717 $list[$husband->xref()] = $husband; 2718 $list[$husband->xref()]->generation = $list[$id]->generation + 1; 2719 } 2720 if ($wife) { 2721 $list[$wife->xref()] = $wife; 2722 $list[$wife->xref()]->generation = $list[$id]->generation + 1; 2723 } 2724 if ($generations == -1 || $list[$id]->generation + 1 < $generations) { 2725 if ($husband) { 2726 $genlist[] = $husband->xref(); 2727 } 2728 if ($wife) { 2729 $genlist[] = $wife->xref(); 2730 } 2731 } 2732 if ($children) { 2733 foreach ($family->children() as $child) { 2734 $list[$child->xref()] = $child; 2735 $list[$child->xref()]->generation = $list[$id]->generation ?? 1; 2736 } 2737 } 2738 } 2739 } 2740 } 2741 2742 /** 2743 * get gedcom tag value 2744 * 2745 * @param string $tag The tag to find, use : to delineate subtags 2746 * @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 2747 * @param string $gedrec The gedcom record to get the value from 2748 * 2749 * @return string the value of a gedcom tag from the given gedcom record 2750 */ 2751 private function getGedcomValue(string $tag, int $level, string $gedrec): string 2752 { 2753 if ($gedrec === '') { 2754 return ''; 2755 } 2756 $tags = explode(':', $tag); 2757 $origlevel = $level; 2758 if ($level === 0) { 2759 $level = $gedrec[0] + 1; 2760 } 2761 2762 $subrec = $gedrec; 2763 foreach ($tags as $t) { 2764 $lastsubrec = $subrec; 2765 $subrec = Functions::getSubRecord($level, "$level $t", $subrec); 2766 if (empty($subrec) && $origlevel == 0) { 2767 $level--; 2768 $subrec = Functions::getSubRecord($level, "$level $t", $lastsubrec); 2769 } 2770 if (empty($subrec)) { 2771 if ($t === 'TITL') { 2772 $subrec = Functions::getSubRecord($level, "$level ABBR", $lastsubrec); 2773 if (!empty($subrec)) { 2774 $t = 'ABBR'; 2775 } 2776 } 2777 if ($subrec === '') { 2778 if ($level > 0) { 2779 $level--; 2780 } 2781 $subrec = Functions::getSubRecord($level, "@ $t", $gedrec); 2782 if ($subrec === '') { 2783 return ''; 2784 } 2785 } 2786 } 2787 $level++; 2788 } 2789 $level--; 2790 $ct = preg_match("/$level $t(.*)/", $subrec, $match); 2791 if ($ct == 0) { 2792 $ct = preg_match("/$level @.+@ (.+)/", $subrec, $match); 2793 } 2794 if ($ct == 0) { 2795 $ct = preg_match("/@ $t (.+)/", $subrec, $match); 2796 } 2797 if ($ct > 0) { 2798 $value = trim($match[1]); 2799 if ($t === 'NOTE' && preg_match('/^@(.+)@$/', $value, $match)) { 2800 $note = Note::getInstance($match[1], $this->tree); 2801 if ($note instanceof Note) { 2802 $value = $note->getNote(); 2803 } else { 2804 //-- set the value to the id without the @ 2805 $value = $match[1]; 2806 } 2807 } 2808 if ($level != 0 || $t != 'NOTE') { 2809 $value .= Functions::getCont($level + 1, $subrec); 2810 } 2811 2812 return $value; 2813 } 2814 2815 return ''; 2816 } 2817 2818 /** 2819 * Replace variable identifiers with their values. 2820 * 2821 * @param string $expression An expression such as "$foo == 123" 2822 * @param bool $quote Whether to add quotation marks 2823 * 2824 * @return string 2825 */ 2826 private function substituteVars($expression, $quote): string 2827 { 2828 return preg_replace_callback( 2829 '/\$(\w+)/', 2830 function (array $matches) use ($quote): string { 2831 if (isset($this->vars[$matches[1]]['id'])) { 2832 if ($quote) { 2833 return "'" . addcslashes($this->vars[$matches[1]]['id'], "'") . "'"; 2834 } 2835 2836 return $this->vars[$matches[1]]['id']; 2837 } 2838 2839 Log::addErrorLog(sprintf('Undefined variable $%s in report', $matches[1])); 2840 2841 return '$' . $matches[1]; 2842 }, 2843 $expression 2844 ); 2845 } 2846} 2847