Passed
Pull Request — main (#4945)
by
unknown
06:16
created

ReportParserGenerate::generationStartHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2023 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 <https://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Report;
21
22
use DomainException;
23
use Fisharebest\Webtrees\Auth;
24
use Fisharebest\Webtrees\Date;
25
use Fisharebest\Webtrees\DB;
26
use Fisharebest\Webtrees\Elements\UnknownElement;
27
use Fisharebest\Webtrees\Factories\MarkdownFactory;
28
use Fisharebest\Webtrees\Family;
29
use Fisharebest\Webtrees\Gedcom;
30
use Fisharebest\Webtrees\GedcomRecord;
31
use Fisharebest\Webtrees\I18N;
32
use Fisharebest\Webtrees\Individual;
33
use Fisharebest\Webtrees\Log;
34
use Fisharebest\Webtrees\MediaFile;
35
use Fisharebest\Webtrees\Note;
36
use Fisharebest\Webtrees\Place;
37
use Fisharebest\Webtrees\Registry;
38
use Fisharebest\Webtrees\Tree;
39
use Illuminate\Database\Query\Builder;
40
use Illuminate\Database\Query\Expression;
41
use Illuminate\Database\Query\JoinClause;
42
use Illuminate\Support\Str;
43
use LogicException;
44
use Symfony\Component\Cache\Adapter\NullAdapter;
45
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
46
use XMLParser;
47
48
use function addcslashes;
49
use function addslashes;
50
use function array_pop;
51
use function array_shift;
52
use function assert;
53
use function count;
54
use function end;
55
use function explode;
56
use function file;
57
use function file_exists;
58
use function getimagesize;
59
use function imagecreatefromstring;
60
use function imagesx;
61
use function imagesy;
62
use function in_array;
63
use function ltrim;
64
use function method_exists;
65
use function preg_match;
66
use function preg_match_all;
67
use function preg_replace;
68
use function preg_replace_callback;
69
use function preg_split;
70
use function reset;
71
use function round;
72
use function sprintf;
73
use function str_contains;
74
use function str_ends_with;
75
use function str_replace;
76
use function str_starts_with;
77
use function strip_tags;
78
use function strlen;
79
use function strpos;
80
use function strtoupper;
81
use function substr;
82
use function substr_replace;
83
use function trim;
84
use function uasort;
85
use function xml_error_string;
86
use function xml_get_current_line_number;
87
use function xml_get_error_code;
88
use function xml_parse;
89
use function xml_parser_create;
90
use function xml_parser_free;
91
use function xml_parser_set_option;
92
use function xml_set_character_data_handler;
93
use function xml_set_element_handler;
94
95
use const PREG_OFFSET_CAPTURE;
96
use const PREG_SET_ORDER;
97
use const XML_OPTION_CASE_FOLDING;
98
99
/**
100
 * Class ReportParserGenerate - parse a report.xml file and generate the report.
101
 */
102
class ReportParserGenerate extends ReportParserBase
103
{
104
    /** Are we collecting data from <Footnote> elements */
105
    private bool $process_footnote = true;
106
107
    /** Are we currently outputting data? */
108
    private bool $print_data = false;
109
110
    /** @var array<int,bool> Push-down stack of $print_data */
111
    private array $print_data_stack = [];
112
113
    /** Are we processing GEDCOM data */
114
    private int $process_gedcoms = 0;
115
116
    /** Are we processing conditionals */
117
    private int $process_ifs = 0;
118
119
    /** Are we processing repeats */
120
    private int $process_repeats = 0;
121
122
    /** Quantity of data to repeat during loops */
123
    private int $repeat_bytes = 0;
124
125
    /** @var array<string> Repeated data when iterating over loops */
126
    private array $repeats = [];
127
128
    /** @var array<int,array<int,array<string>|int>> Nested repeating data */
129
    private array $repeats_stack = [];
130
131
    /** @var array<AbstractRenderer> Nested repeating data */
132
    private array $wt_report_stack = [];
133
134
    // Nested repeating data
135
    private XMLParser $parser;
136
137
    /** @var XMLParser[] (resource[] before PHP 8.0) Nested repeating data */
138
    private array $parser_stack = [];
139
140
    /** The current GEDCOM record */
141
    private string $gedrec = '';
142
143
    /** @var array<int,array<int,string>> Nested GEDCOM records */
144
    private array $gedrec_stack = [];
145
146
    /** @var ReportBaseElement The currently processed element */
147
    private $current_element;
148
149
    /** @var ReportBaseElement The currently processed element */
150
    private $footnote_element;
151
152
    /** The GEDCOM fact currently being processed */
153
    private string $fact = '';
154
155
    /** The GEDCOM value currently being processed */
156
    private string $desc = '';
157
158
    /** The GEDCOM type currently being processed */
159
    private string $type = '';
160
161
    /** The current generational level */
162
    private int $generation = 1;
163
164
    /** @var array<static|GedcomRecord> Source data for processing lists */
165
    private array $list = [];
166
167
    /** Number of items in lists */
168
    private int $list_total = 0;
169
170
    /** Number of items filtered from lists */
171
    private int $list_private = 0;
172
173
    /** @var string The filename of the XML report */
174
    protected $report;
175
176
    /** @var AbstractRenderer A factory for creating report elements */
177
    private $report_root;
178
179
    /** @var AbstractRenderer Nested report elements */
180
    private $wt_report;
181
182
    /** @var array<array<string>> Variables defined in the report at run-time */
183
    private array $vars;
184
185
    private array $mfrelation = [];
186
187
    private Tree $tree;
188
189
    /**
190
     * Create a parser for a report
191
     *
192
     * @param string               $report The XML filename
193
     * @param AbstractRenderer     $report_root
194
     * @param array<array<string>> $vars
195
     * @param Tree                 $tree
196
     */
197
    public function __construct(string $report, AbstractRenderer $report_root, array $vars, Tree $tree)
198
    {
199
        $this->report          = $report;
200
        $this->report_root     = $report_root;
201
        $this->wt_report       = $report_root;
202
        $this->current_element = new ReportBaseElement();
203
        $this->vars            = $vars;
204
        $this->tree            = $tree;
205
206
        parent::__construct($report);
207
    }
208
209
    /**
210
     * get a gedcom subrecord
211
     *
212
     * searches a gedcom record and returns a subrecord of it. A subrecord is defined starting at a
213
     * line with level N and all subsequent lines greater than N until the next N level is reached.
214
     * For example, the following is a BIRT subrecord:
215
     * <code>1 BIRT
216
     * 2 DATE 1 JAN 1900
217
     * 2 PLAC Phoenix, Maricopa, Arizona</code>
218
     * The following example is the DATE subrecord of the above BIRT subrecord:
219
     * <code>2 DATE 1 JAN 1900</code>
220
     *
221
     * @param int    $level   the N level of the subrecord to get
222
     * @param string $tag     a gedcom tag or string to search for in the record (ie 1 BIRT or 2 DATE)
223
     * @param string $gedrec  the parent gedcom record to search in
224
     * @param int    $num     this allows you to specify which matching <var>$tag</var> to get. Oftentimes a
225
     *                        gedcom record will have more that 1 of the same type of subrecord. An individual may have
226
     *                        multiple events for example. Passing $num=1 would get the first 1. Passing $num=2 would get the
227
     *                        second one, etc.
228
     *
229
     * @return string the subrecord that was found or an empty string "" if not found.
230
     */
231
    public static function getSubRecord(int $level, string $tag, string $gedrec, int $num = 1): string
232
    {
233
        if ($gedrec === '') {
234
            return '';
235
        }
236
        // -- adding \n before and after gedrec
237
        $gedrec       = "\n" . $gedrec . "\n";
238
        $tag          = trim($tag);
239
        $searchTarget = "~[\n]" . $tag . "[\s]~";
240
        $ct           = preg_match_all($searchTarget, $gedrec, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
241
        if ($ct === 0) {
242
            return '';
243
        }
244
        if ($ct < $num) {
245
            return '';
246
        }
247
        $pos1 = $match[$num - 1][0][1];
248
        $pos2 = strpos($gedrec, "\n$level", $pos1 + 1);
249
        if (!$pos2) {
250
            $pos2 = strpos($gedrec, "\n1", $pos1 + 1);
251
        }
252
        if (!$pos2) {
253
            $pos2 = strpos($gedrec, "\nWT_", $pos1 + 1); // WT_SPOUSE, WT_FAMILY_ID ...
254
        }
255
        if (!$pos2) {
256
            return ltrim(substr($gedrec, $pos1));
257
        }
258
        $subrec = substr($gedrec, $pos1, $pos2 - $pos1);
259
260
        return ltrim($subrec);
261
    }
262
263
    /**
264
     * get CONT lines
265
     *
266
     * get the N+1 CONT or CONC lines of a gedcom subrecord
267
     *
268
     * @param int    $nlevel the level of the CONT lines to get
269
     * @param string $nrec   the gedcom subrecord to search in
270
     *
271
     * @return string a string with all CONT lines merged
272
     */
273
    public static function getCont(int $nlevel, string $nrec): string
274
    {
275
        $text = '';
276
277
        $subrecords = explode("\n", $nrec);
278
        foreach ($subrecords as $thisSubrecord) {
279
            if (substr($thisSubrecord, 0, 2) !== $nlevel . ' ') {
280
                continue;
281
            }
282
            $subrecordType = substr($thisSubrecord, 2, 4);
283
            if ($subrecordType === 'CONT') {
284
                $text .= "\n" . substr($thisSubrecord, 7);
285
            }
286
        }
287
288
        return $text;
289
    }
290
291
    /**
292
     * XML start element handler
293
     * This function is called whenever a starting element is reached
294
     * The element handler will be called if found, otherwise it must be HTML
295
     *
296
     * @param resource      $parser the resource handler for the XML parser
297
     * @param string        $name   the name of the XML element parsed
298
     * @param array<string> $attrs  an array of key value pairs for the attributes
299
     *
300
     * @return void
301
     */
302
    protected function startElement($parser, string $name, array $attrs): void
303
    {
304
        $newattrs = [];
305
306
        foreach ($attrs as $key => $value) {
307
            if (preg_match("/^\\$(\w+)$/", $value, $match)) {
308
                if (isset($this->vars[$match[1]]['id']) && !isset($this->vars[$match[1]]['gedcom'])) {
309
                    $value = $this->vars[$match[1]]['id'];
310
                }
311
            }
312
            $newattrs[$key] = $value;
313
        }
314
        $attrs = $newattrs;
315
        if ($this->process_footnote && ($this->process_ifs === 0 || $name === 'if') && ($this->process_gedcoms === 0 || $name === 'Gedcom') && ($this->process_repeats === 0 || $name === 'Facts' || $name === 'RepeatTag')) {
316
            $method = $name . 'StartHandler';
317
318
            if (method_exists($this, $method)) {
319
                $this->{$method}($attrs);
320
            }
321
        }
322
    }
323
324
    /**
325
     * XML end element handler
326
     * This function is called whenever an ending element is reached
327
     * The element handler will be called if found, otherwise it must be HTML
328
     *
329
     * @param resource $parser the resource handler for the XML parser
330
     * @param string   $name   the name of the XML element parsed
331
     *
332
     * @return void
333
     */
334
    protected function endElement($parser, string $name): void
335
    {
336
        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')) {
337
            $method = $name . 'EndHandler';
338
339
            if (method_exists($this, $method)) {
340
                $this->{$method}();
341
            }
342
        }
343
    }
344
345
    /**
346
     * XML character data handler
347
     *
348
     * @param resource $parser the resource handler for the XML parser
349
     * @param string   $data   the name of the XML element parsed
350
     *
351
     * @return void
352
     */
353
    protected function characterData($parser, string $data): void
354
    {
355
        if ($this->print_data && $this->process_gedcoms === 0 && $this->process_ifs === 0 && $this->process_repeats === 0) {
356
            $this->current_element->addText($data);
357
        }
358
    }
359
360
    /**
361
     * Handle <style>
362
     *
363
     * @param array<string> $attrs
364
     *
365
     * @return void
366
     */
367
    protected function styleStartHandler(array $attrs): void
368
    {
369
        if (empty($attrs['name'])) {
370
            throw new DomainException('REPORT ERROR Style: The "name" of the style is missing or not set in the XML file.');
371
        }
372
373
        $style = [
374
            'name'  => $attrs['name'],
375
            'font'  => $attrs['font'] ?? $this->wt_report->default_font,
376
            'size'  => (float) ($attrs['size'] ?? $this->wt_report->default_font_size),
377
            'style' => $attrs['style'] ?? '',
378
        ];
379
380
        $this->wt_report->addStyle($style);
381
    }
382
383
    /**
384
     * Handle <doc>
385
     * Sets up the basics of the document proparties
386
     *
387
     * @param array<string> $attrs
388
     *
389
     * @return void
390
     */
391
    protected function docStartHandler(array $attrs): void
392
    {
393
        $this->parser = $this->xml_parser;
394
395
        // Custom page width
396
        if (!empty($attrs['customwidth'])) {
397
            $this->wt_report->page_width = (float) $attrs['customwidth'];
398
        }
399
        // Custom Page height
400
        if (!empty($attrs['customheight'])) {
401
            $this->wt_report->page_height = (float) $attrs['customheight'];
402
        }
403
404
        // Left Margin
405
        if (isset($attrs['leftmargin'])) {
406
            if ($attrs['leftmargin'] === '0') {
407
                $this->wt_report->left_margin = 0;
408
            } elseif (!empty($attrs['leftmargin'])) {
409
                $this->wt_report->left_margin = (float) $attrs['leftmargin'];
410
            }
411
        }
412
        // Right Margin
413
        if (isset($attrs['rightmargin'])) {
414
            if ($attrs['rightmargin'] === '0') {
415
                $this->wt_report->right_margin = 0;
416
            } elseif (!empty($attrs['rightmargin'])) {
417
                $this->wt_report->right_margin = (float) $attrs['rightmargin'];
418
            }
419
        }
420
        // Top Margin
421
        if (isset($attrs['topmargin'])) {
422
            if ($attrs['topmargin'] === '0') {
423
                $this->wt_report->top_margin = 0;
424
            } elseif (!empty($attrs['topmargin'])) {
425
                $this->wt_report->top_margin = (float) $attrs['topmargin'];
426
            }
427
        }
428
        // Bottom Margin
429
        if (isset($attrs['bottommargin'])) {
430
            if ($attrs['bottommargin'] === '0') {
431
                $this->wt_report->bottom_margin = 0;
432
            } elseif (!empty($attrs['bottommargin'])) {
433
                $this->wt_report->bottom_margin = (float) $attrs['bottommargin'];
434
            }
435
        }
436
        // Header Margin
437
        if (isset($attrs['headermargin'])) {
438
            if ($attrs['headermargin'] === '0') {
439
                $this->wt_report->header_margin = 0;
440
            } elseif (!empty($attrs['headermargin'])) {
441
                $this->wt_report->header_margin = (float) $attrs['headermargin'];
442
            }
443
        }
444
        // Footer Margin
445
        if (isset($attrs['footermargin'])) {
446
            if ($attrs['footermargin'] === '0') {
447
                $this->wt_report->footer_margin = 0;
448
            } elseif (!empty($attrs['footermargin'])) {
449
                $this->wt_report->footer_margin = (float) $attrs['footermargin'];
450
            }
451
        }
452
453
        // Page Orientation
454
        if (!empty($attrs['orientation'])) {
455
            if ($attrs['orientation'] === 'landscape') {
456
                $this->wt_report->orientation = 'landscape';
457
            } elseif ($attrs['orientation'] === 'portrait') {
458
                $this->wt_report->orientation = 'portrait';
459
            }
460
        }
461
        // Page Size
462
        if (!empty($attrs['pageSize'])) {
463
            $this->wt_report->page_format = $attrs['pageSize'];
464
        }
465
466
        // Show Generated By...
467
        if (isset($attrs['showGeneratedBy'])) {
468
            if ($attrs['showGeneratedBy'] === '0') {
469
                $this->wt_report->show_generated_by = false;
470
            } elseif ($attrs['showGeneratedBy'] === '1') {
471
                $this->wt_report->show_generated_by = true;
472
            }
473
        }
474
475
        $this->wt_report->setup();
476
    }
477
478
    /**
479
     * Handle </doc>
480
     *
481
     * @return void
482
     */
483
    protected function docEndHandler(): void
484
    {
485
        $this->wt_report->run();
486
    }
487
488
    /**
489
     * Handle <header>
490
     *
491
     * @return void
492
     */
493
    protected function headerStartHandler(): void
494
    {
495
        // Clear the Header before any new elements are added
496
        $this->wt_report->clearHeader();
497
        $this->wt_report->setProcessing('H');
498
    }
499
500
    /**
501
     * Handle <body>
502
     *
503
     * @return void
504
     */
505
    protected function bodyStartHandler(): void
506
    {
507
        $this->wt_report->setProcessing('B');
508
    }
509
510
    /**
511
     * Handle <footer>
512
     *
513
     * @return void
514
     */
515
    protected function footerStartHandler(): void
516
    {
517
        $this->wt_report->setProcessing('F');
518
    }
519
520
    /**
521
     * Handle <cell>
522
     *
523
     * @param array<string,string> $attrs
524
     *
525
     * @return void
526
     */
527
    protected function cellStartHandler(array $attrs): void
528
    {
529
        // string The text alignment of the text in this box.
530
        $align = $attrs['align'] ?? '';
531
        // RTL supported left/right alignment
532
        if ($align === 'rightrtl') {
533
            if ($this->wt_report->rtl) {
534
                $align = 'left';
535
            } else {
536
                $align = 'right';
537
            }
538
        } elseif ($align === 'leftrtl') {
539
            if ($this->wt_report->rtl) {
540
                $align = 'right';
541
            } else {
542
                $align = 'left';
543
            }
544
        }
545
546
        // The color to fill the background of this cell
547
        $bgcolor = $attrs['bgcolor'] ?? '';
548
549
        // Whether the background should be painted
550
        $fill = (bool) ($attrs['fill'] ?? '0');
551
552
        // If true reset the last cell height
553
        $reseth = (bool) ($attrs['reseth'] ?? '1');
554
555
        // Whether a border should be printed around this box
556
        $border = $attrs['border'] ?? '';
557
558
        // string Border color in HTML code
559
        $bocolor = $attrs['bocolor'] ?? '';
560
561
        // Cell height (expressed in points) The starting height of this cell. If the text wraps the height will automatically be adjusted.
562
        $height = (int) ($attrs['height'] ?? '0');
563
564
        // int Cell width (expressed in points) Setting the width to 0 will make it the width from the current location to the right margin.
565
        $width = (int) ($attrs['width'] ?? '0');
566
567
        // Stretch character mode
568
        $stretch = (int) ($attrs['stretch'] ?? '0');
569
570
        // mixed Position the left corner of this box on the page. The default is the current position.
571
        $left = ReportBaseElement::CURRENT_POSITION;
572
        if (isset($attrs['left'])) {
573
            if ($attrs['left'] === '.') {
574
                $left = ReportBaseElement::CURRENT_POSITION;
575
            } elseif (!empty($attrs['left'])) {
576
                $left = (float) $attrs['left'];
577
            } elseif ($attrs['left'] === '0') {
578
                $left = 0.0;
579
            }
580
        }
581
        // mixed Position the top corner of this box on the page. the default is the current position
582
        $top = ReportBaseElement::CURRENT_POSITION;
583
        if (isset($attrs['top'])) {
584
            if ($attrs['top'] === '.') {
585
                $top = ReportBaseElement::CURRENT_POSITION;
586
            } elseif (!empty($attrs['top'])) {
587
                $top = (float) $attrs['top'];
588
            } elseif ($attrs['top'] === '0') {
589
                $top = 0.0;
590
            }
591
        }
592
593
        // The name of the Style that should be used to render the text.
594
        $style = $attrs['style'] ?? '';
595
596
        // string Text color in html code
597
        $tcolor = $attrs['tcolor'] ?? '';
598
599
        // int Indicates where the current position should go after the call.
600
        $ln = 0;
601
        if (isset($attrs['newline'])) {
602
            if (!empty($attrs['newline'])) {
603
                $ln = (int) $attrs['newline'];
604
            } elseif ($attrs['newline'] === '0') {
605
                $ln = 0;
606
            }
607
        }
608
609
        if ($align === 'left') {
610
            $align = 'L';
611
        } elseif ($align === 'right') {
612
            $align = 'R';
613
        } elseif ($align === 'center') {
614
            $align = 'C';
615
        } elseif ($align === 'justify') {
616
            $align = 'J';
617
        }
618
619
        $this->print_data_stack[] = $this->print_data;
620
        $this->print_data         = true;
621
622
        $this->current_element = $this->report_root->createCell(
623
            (int) $width,
624
            (int) $height,
625
            $border,
626
            $align,
627
            $bgcolor,
628
            $style,
629
            $ln,
630
            $top,
631
            $left,
632
            $fill,
633
            $stretch,
634
            $bocolor,
635
            $tcolor,
636
            $reseth
637
        );
638
639
        // set string URL to be a link
640
        if (isset($attrs['url'])) {
641
            $url = $attrs['url'];
642
            $this->current_element->setUrl($url);
643
            error_log("RPG ".__LINE__." seturl=".$url."\n",3,"url.log");
644
        } else {
645
            $url = "";
0 ignored issues
show
Unused Code introduced by
The assignment to $url is dead and can be removed.
Loading history...
646
        }
647
    }
648
649
    /**
650
     * Handle </cell>
651
     *
652
     * @return void
653
     */
654
    protected function cellEndHandler(): void
655
    {
656
        $this->print_data = array_pop($this->print_data_stack);
657
        $this->wt_report->addElement($this->current_element);
658
    }
659
660
    /**
661
     * Handle <now />
662
     *
663
     * @return void
664
     */
665
    protected function nowStartHandler(): void
666
    {
667
        $this->current_element->addText(Registry::timestampFactory()->now()->isoFormat('LLLL'));
668
    }
669
670
    /**
671
     * Handle <pageNum />
672
     *
673
     * @return void
674
     */
675
    protected function pageNumStartHandler(): void
676
    {
677
        $this->current_element->addText('#PAGENUM#');
678
    }
679
680
    /**
681
     * Handle <totalPages />
682
     *
683
     * @return void
684
     */
685
    protected function totalPagesStartHandler(): void
686
    {
687
        $this->current_element->addText('{{:ptp:}}');
688
    }
689
690
    /**
691
     * Called at the start of an element.
692
     *
693
     * @param array<string> $attrs an array of key value pairs for the attributes
694
     *
695
     * @return void
696
     */
697
    protected function gedcomStartHandler(array $attrs): void
698
    {
699
        if ($this->process_gedcoms > 0) {
700
            $this->process_gedcoms++;
701
702
            return;
703
        }
704
705
        $tag       = $attrs['id'];
706
        $tag       = str_replace('@fact', $this->fact, $tag);
707
        $tags      = explode(':', $tag);
708
        $newgedrec = '';
709
        if (count($tags) < 2) {
710
            $tmp       = Registry::gedcomRecordFactory()->make($attrs['id'], $this->tree);
711
            $newgedrec = $tmp ? $tmp->privatizeGedcom(Auth::accessLevel($this->tree)) : '';
712
        }
713
        if (empty($newgedrec)) {
714
            $tgedrec   = $this->gedrec;
715
            $newgedrec = '';
716
            foreach ($tags as $tag) {
717
                if (preg_match('/\$(.+)/', $tag, $match)) {
718
                    if (isset($this->vars[$match[1]]['gedcom'])) {
719
                        $newgedrec = $this->vars[$match[1]]['gedcom'];
720
                    } else {
721
                        $tmp       = Registry::gedcomRecordFactory()->make($match[1], $this->tree);
722
                        $newgedrec = $tmp ? $tmp->privatizeGedcom(Auth::accessLevel($this->tree)) : '';
723
                    }
724
                } else {
725
                    if (preg_match('/@(.+)/', $tag, $match)) {
726
                        $gmatch = [];
727
                        if (preg_match("/\d $match[1] @([^@]+)@/", $tgedrec, $gmatch)) {
728
                            $tmp       = Registry::gedcomRecordFactory()->make($gmatch[1], $this->tree);
729
                            $newgedrec = $tmp ? $tmp->privatizeGedcom(Auth::accessLevel($this->tree)) : '';
730
                            $tgedrec   = $newgedrec;
731
                        } else {
732
                            $newgedrec = '';
733
                            break;
734
                        }
735
                    } else {
736
                        $level     = 1 + (int) explode(' ', trim($tgedrec))[0];
737
                        $newgedrec = self::getSubRecord($level, "$level $tag", $tgedrec);
738
                        $tgedrec   = $newgedrec;
739
                    }
740
                }
741
            }
742
        }
743
        if (!empty($newgedrec)) {
744
            $this->gedrec_stack[] = [$this->gedrec, $this->fact, $this->desc];
745
            $this->gedrec         = $newgedrec;
746
            if (preg_match("/(\d+) (_?[A-Z0-9]+) (.*)/", $this->gedrec, $match)) {
747
                $this->fact = $match[2];
748
                $this->desc = trim($match[3]);
749
            }
750
        } else {
751
            $this->process_gedcoms++;
752
        }
753
    }
754
755
    /**
756
     * Called at the end of an element.
757
     *
758
     * @return void
759
     */
760
    protected function gedcomEndHandler(): void
761
    {
762
        if ($this->process_gedcoms > 0) {
763
            $this->process_gedcoms--;
764
        } else {
765
            [$this->gedrec, $this->fact, $this->desc] = array_pop($this->gedrec_stack);
766
        }
767
    }
768
769
    /**
770
     * Handle <textBox>
771
     *
772
     * @param array<string> $attrs
773
     *
774
     * @return void
775
     */
776
    protected function textBoxStartHandler(array $attrs): void
777
    {
778
        // string Background color code
779
        $bgcolor = '';
780
        if (!empty($attrs['bgcolor'])) {
781
            $bgcolor = $attrs['bgcolor'];
782
        }
783
784
        // boolean Wether or not fill the background color
785
        $fill = true;
786
        if (isset($attrs['fill'])) {
787
            if ($attrs['fill'] === '0') {
788
                $fill = false;
789
            } elseif ($attrs['fill'] === '1') {
790
                $fill = true;
791
            }
792
        }
793
794
        // var boolean Whether or not a border should be printed around this box. 0 = no border, 1 = border. Default is 0
795
        $border = false;
796
        if (isset($attrs['border'])) {
797
            if ($attrs['border'] === '1') {
798
                $border = true;
799
            } elseif ($attrs['border'] === '0') {
800
                $border = false;
801
            }
802
        }
803
804
        // int The starting height of this cell. If the text wraps the height will automatically be adjusted
805
        $height = 0;
806
        if (!empty($attrs['height'])) {
807
            $height = (int) $attrs['height'];
808
        }
809
        // int Setting the width to 0 will make it the width from the current location to the margin
810
        $width = 0;
811
        if (!empty($attrs['width'])) {
812
            $width = (int) $attrs['width'];
813
        }
814
815
        // mixed Position the left corner of this box on the page. The default is the current position.
816
        $left = ReportBaseElement::CURRENT_POSITION;
817
        if (isset($attrs['left'])) {
818
            if ($attrs['left'] === '.') {
819
                $left = ReportBaseElement::CURRENT_POSITION;
820
            } elseif (!empty($attrs['left'])) {
821
                $left = (int) $attrs['left'];
822
            } elseif ($attrs['left'] === '0') {
823
                $left = 0;
824
            }
825
        }
826
        // mixed Position the top corner of this box on the page. the default is the current position
827
        $top = ReportBaseElement::CURRENT_POSITION;
828
        if (isset($attrs['top'])) {
829
            if ($attrs['top'] === '.') {
830
                $top = ReportBaseElement::CURRENT_POSITION;
831
            } elseif (!empty($attrs['top'])) {
832
                $top = (int) $attrs['top'];
833
            } elseif ($attrs['top'] === '0') {
834
                $top = 0;
835
            }
836
        }
837
        // position of box absolute or relative, and possibly top and height
838
        if (isset($attrs['pos'])) {
839
            $pos = $attrs['pos'];
840
            if (substr($pos, 0, 3) == 'abs') {
841
                //-- check absolute or relative position
842
                $top += -222000;
843
            }
844
            if (substr($pos, 0, 3) == 'rel') {
845
                //-- check absolute or relative position
846
                $top = -100000;
847
            }
848
            if (substr($pos, 3, 3) == '_fh') {
849
                $top = -100012;
850
            }
851
            if (substr($pos, 3, 3) == '_f2') {
852
                $top = -100018;
853
            }
854
            if (substr($pos, 6, 5) == '_html') {
855
                $top = -90012;
856
            }
857
        }
858
        // 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
859
        $newline = false;
860
        if (isset($attrs['newline'])) {
861
            if ($attrs['newline'] === '1') {
862
                $newline = true;
863
            } elseif ($attrs['newline'] === '0') {
864
                $newline = false;
865
            }
866
        }
867
        // boolean
868
        $pagecheck = true;
869
        if (isset($attrs['pagecheck'])) {
870
            if ($attrs['pagecheck'] === '0') {
871
                $pagecheck = false;
872
            } elseif ($attrs['pagecheck'] === '1') {
873
                $pagecheck = true;
874
            }
875
        }
876
        // boolean Cell padding
877
        $padding = true;
878
        if (isset($attrs['padding'])) {
879
            if ($attrs['padding'] === '0') {
880
                $padding = false;
881
            } elseif ($attrs['padding'] === '1') {
882
                $padding = true;
883
            }
884
        }
885
        // boolean Reset this box Height
886
        $reseth = false;
887
        if (isset($attrs['reseth'])) {
888
            if ($attrs['reseth'] === '1') {
889
                $reseth = true;
890
            } elseif ($attrs['reseth'] === '0') {
891
                $reseth = false;
892
            }
893
        }
894
895
        // string Style of rendering
896
        $style = '';
897
898
        $this->print_data_stack[] = $this->print_data;
899
        $this->print_data         = false;
900
901
        $this->wt_report_stack[] = $this->wt_report;
902
        $this->wt_report         = $this->report_root->createTextBox(
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->report_root->crea...ill, $padding, $reseth) of type Fisharebest\Webtrees\Report\ReportBaseTextbox is incompatible with the declared type Fisharebest\Webtrees\Report\AbstractRenderer of property $wt_report.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
903
            $width,
904
            $height,
905
            $border,
906
            $bgcolor,
907
            $newline,
908
            $left,
909
            $top,
910
            $pagecheck,
911
            $style,
912
            $fill,
913
            $padding,
914
            $reseth
915
        );
916
    }
917
918
    /**
919
     * Handle <textBox>
920
     *
921
     * @return void
922
     */
923
    protected function textBoxEndHandler(): void
924
    {
925
        $this->print_data      = array_pop($this->print_data_stack);
926
        $this->current_element = $this->wt_report;
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->wt_report of type Fisharebest\Webtrees\Report\AbstractRenderer is incompatible with the declared type Fisharebest\Webtrees\Report\ReportBaseElement of property $current_element.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
927
928
        // The TextBox handler is mis-using the wt_report attribute to store an element.
929
        // Until this can be re-designed, we need this assertion to help static analysis tools.
930
        assert($this->current_element instanceof ReportBaseElement, new LogicException());
931
932
        $this->wt_report = array_pop($this->wt_report_stack);
933
        $this->wt_report->addElement($this->current_element);
934
    }
935
936
    /**
937
     * XLM <Text>.
938
     *
939
     * @param array<string> $attrs an array of key value pairs for the attributes
940
     *
941
     * @return void
942
     */
943
    protected function textStartHandler(array $attrs): void
944
    {
945
        $this->print_data_stack[] = $this->print_data;
946
        $this->print_data         = true;
947
948
        // string The name of the Style that should be used to render the text.
949
        $style = '';
950
        if (isset($attrs['style'])) {
951
            $style = $attrs['style'];
952
        }
953
954
        // string  The color of the text - Keep the black color as default
955
        $color = '';
956
        if (isset($attrs['color'])) {
957
            $color = $attrs['color'];
958
        }
959
960
        $this->current_element = $this->report_root->createText($style, $color);
961
    }
962
963
    /**
964
     * Handle </text>
965
     *
966
     * @return void
967
     */
968
    protected function textEndHandler(): void
969
    {
970
        $this->print_data = array_pop($this->print_data_stack);
971
        $this->wt_report->addElement($this->current_element);
972
    }
973
974
    /**
975
     * Handle <getPersonName />
976
     * Get the name
977
     * 1. id is empty - current GEDCOM record
978
     * 2. id is set with a record id
979
     *
980
     * @param array<string> $attrs an array of key value pairs for the attributes
981
     *
982
     * @return void
983
     */
984
    protected function getPersonNameStartHandler(array $attrs): void
985
    {
986
        $id    = '';
987
        $match = [];
988
        if (empty($attrs['id'])) {
989
            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
990
                $id = $match[1];
991
            }
992
        } else {
993
            if (preg_match('/\$(.+)/', $attrs['id'], $match)) {
994
                if (isset($this->vars[$match[1]]['id'])) {
995
                    $id = $this->vars[$match[1]]['id'];
996
                }
997
            } else {
998
                if (preg_match('/@(.+)/', $attrs['id'], $match)) {
999
                    $gmatch = [];
1000
                    if (preg_match("/\d $match[1] @([^@]+)@/", $this->gedrec, $gmatch)) {
1001
                        $id = $gmatch[1];
1002
                    }
1003
                } else {
1004
                    $id = $attrs['id'];
1005
                }
1006
            }
1007
        }
1008
        $nameselect = "";
1009
        if (isset($attrs['select'])) {
1010
            $nameselect = $attrs['select'];
1011
        }
1012
        $famrel = false;
1013
        if (isset($attrs['fam_relation'])) {
1014
            $famrel = true;
1015
        }
1016
        if (!empty($id)) {
1017
            $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1018
            if ($record === null) {
1019
                return;
1020
            }
1021
            if (!$record->canShowName()) {
1022
                $this->current_element->addText(I18N::translate('Private'));
1023
            } elseif ($nameselect == 'latest') {
1024
                $tmp = $record->getAllNames();
1025
                $name  = strip_tags($tmp[count($tmp) - 1]['full']);
1026
                $this->current_element->addText(trim($name));
1027
            } elseif ($nameselect == 'combined') {
1028
                $tmp = $record->getAllNames();
1029
                $name = $tmp[count($tmp) - 1]['full'];
1030
                if ($ix1 = strpos($name, '<span class="starredname">')) {   // '«' and '»' mark text for underlining
1031
                    $name = substr_replace($name, '«', $ix1, 26);
1032
                    $ix1 = strpos($name, '</span>', $ix1);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type array; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1032
                    $ix1 = strpos(/** @scrutinizer ignore-type */ $name, '</span>', $ix1);
Loading history...
1033
                    $name = substr_replace($name, '»', $ix1, 7);
1034
                }
1035
                $addname = strip_tags((string) $tmp[0]['surn']);
1036
                if (!empty($addname) && !($addname === '@N.N.') && !str_contains($name, $addname)) {
1037
                    $name .= " " . I18N::translate('b.') . " " . $addname;
1038
                }
1039
                $this->current_element->addText(trim($name));
1040
            } else {
1041
                $name = $record->fullName();
1042
                $name = strip_tags($name);
1043
                if (!empty($attrs['truncate'])) {
1044
                    if ((int) $attrs['truncate'] > 0) {
1045
                        $name = Str::limit($name, (int) $attrs['truncate'], I18N::translate('…'));
1046
                    }
1047
                } else {
1048
                    $addname = (string) $record->alternateName();
1049
                    $addname = strip_tags($addname);
1050
                    if (!empty($addname)) {
1051
                        $name .= ' ' . $addname;
1052
                    }
1053
                }
1054
                $this->current_element->addText(trim($name));
1055
            }
1056
        }
1057
        if ($famrel && ($this->mfrelation[$record->xref()] != "")) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $record does not seem to be defined for all execution paths leading up to this point.
Loading history...
1058
            $this->current_element->addText(" (" . (string) $this->mfrelation[$record->xref()] . ")");
1059
        }
1060
    }
1061
1062
    /**
1063
     * Handle <gedcomValue />
1064
     *
1065
     * @param array<string> $attrs
1066
     *
1067
     * @return void
1068
     */
1069
    protected function gedcomValueStartHandler(array $attrs): void
1070
    {
1071
        $id    = '';
1072
        $match = [];
1073
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1074
            $id = $match[1];
1075
        }
1076
1077
        if (isset($attrs['newline']) && $attrs['newline'] === '1') {
1078
            $useBreak = '1';
1079
        } else {
1080
            $useBreak = '0';
1081
        }
1082
1083
        $tag = $attrs['tag'];
1084
        if (!empty($tag)) {
1085
            if ($tag === '@desc') {
1086
                $value = $this->desc;
1087
                $value = trim($value);
1088
                $this->current_element->addText($value);
1089
            }
1090
            if ($tag === '@id') {
1091
                $this->current_element->addText($id);
1092
            } else {
1093
                $tag = str_replace('@fact', $this->fact, $tag);
1094
                if (empty($attrs['level'])) {
1095
                    $level = (int) explode(' ', trim($this->gedrec))[0];
1096
                    if ($level === 0) {
1097
                        $level++;
1098
                    }
1099
                } else {
1100
                    $level = (int) $attrs['level'];
1101
                }
1102
                $tags  = preg_split('/[: ]/', $tag);
1103
                $value = $this->getGedcomValue($tag, $level, $this->gedrec);
1104
                switch (end($tags)) {
1105
                    case 'DATE':
1106
                        $tmp   = new Date($value);
1107
                        $dfmt = "%j %F %Y";
1108
                        if (!empty($attrs['truncate'])) {
1109
                            if ($attrs['truncate'] === "d") {
1110
                                $dfmt = "%j %M %Y";
1111
                            }
1112
                            if ($attrs['truncate'] === "Y") {
1113
                                $dfmt = "%Y";
1114
                            }
1115
                        }
1116
                        $value = strip_tags($tmp->display(null, $dfmt));
1117
                        break;
1118
                    case 'PLAC':
1119
                        $tmp   = new Place($value, $this->tree);
1120
                        $value = $tmp->shortName();
1121
                        break;
1122
                }
1123
                if ($useBreak === '1') {
1124
                    // Insert <br> when multiple dates exist.
1125
                    // This works around a TCPDF bug that incorrectly wraps RTL dates on LTR pages
1126
                    $value = str_replace('(', '<br>(', $value);
1127
                    $value = str_replace('<span dir="ltr"><br>', '<br><span dir="ltr">', $value);
1128
                    $value = str_replace('<span dir="rtl"><br>', '<br><span dir="rtl">', $value);
1129
                    if (substr($value, 0, 4) === '<br>') {
1130
                        $value = substr($value, 4);
1131
                    }
1132
                }
1133
                $tmp = explode(':', $tag);
1134
                if (in_array(end($tmp), ['NOTE', 'TEXT'], true)) {
1135
                    if ($this->tree->getPreference('FORMAT_TEXT') === 'xxmarkdown') {
1136
                        $value = strip_tags(Registry::markdownFactory()->markdown($value, $this->tree), ['br']);
1137
                    } else {
1138
                        $value = str_replace("\n", "<br>", $value);
1139
                        //$value = strip_tags(Registry::markdownFactory()->autolink($value, $this->tree), ['br']);
1140
                    }
1141
                    $value = strtr($value, [MarkdownFactory::BREAK => ' ']);
1142
                }
1143
1144
                if (isset($attrs['lcfirst'])) {
1145
                    $value = lcfirst($value);
1146
                    $value = str_replace(["Å","Ä","Ö"], ["å","ä","ö"], $value);
1147
                }
1148
1149
                if (!empty($attrs['truncate'])) {
1150
                    $value = strip_tags($value);
1151
                    if ((int) $attrs['truncate'] > 0) {
1152
                        $value = Str::limit($value, (int) $attrs['truncate'], I18N::translate('…'));
1153
                    }
1154
                }
1155
                $this->current_element->addText($value);
1156
            }
1157
        }
1158
    }
1159
1160
    /**
1161
     * Handle <repeatTag>
1162
     *
1163
     * @param array<string> $attrs
1164
     *
1165
     * @return void
1166
     */
1167
    protected function repeatTagStartHandler(array $attrs): void
1168
    {
1169
        $this->process_repeats++;
1170
        if ($this->process_repeats > 1) {
1171
            return;
1172
        }
1173
1174
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1175
        $this->repeats         = [];
1176
        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1177
1178
        $tag = $attrs['tag'] ?? '';
1179
        if (!empty($tag)) {
1180
            if ($tag === '@desc') {
1181
                $value = $this->desc;
1182
                $value = trim($value);
1183
                $this->current_element->addText($value);
1184
            } else {
1185
                $tag   = str_replace('@fact', $this->fact, $tag);
1186
                $tags  = explode(':', $tag);
1187
                $level = (int) explode(' ', trim($this->gedrec))[0];
1188
                if ($level === 0) {
1189
                    $level++;
1190
                }
1191
                $subrec = $this->gedrec;
1192
                $t      = $tag;
1193
                $count  = count($tags);
1194
                $i      = 0;
1195
                while ($i < $count) {
1196
                    $t = $tags[$i];
1197
                    if (!empty($t)) {
1198
                        if ($i < ($count - 1)) {
1199
                            $subrec = self::getSubRecord($level, "$level $t", $subrec);
1200
                            if (empty($subrec)) {
1201
                                $level--;
1202
                                $subrec = self::getSubRecord($level, "@ $t", $this->gedrec);
1203
                                if (empty($subrec)) {
1204
                                    return;
1205
                                }
1206
                            }
1207
                        }
1208
                        $level++;
1209
                    }
1210
                    $i++;
1211
                }
1212
                $level--;
1213
                $count = preg_match_all("/$level $t(.*)/", $subrec, $match, PREG_SET_ORDER);
1214
                $i     = 0;
1215
                while ($i < $count) {
1216
                    $i++;
1217
                    // Privacy check - is this a link, and are we allowed to view the linked object?
1218
                    $subrecord = self::getSubRecord($level, "$level $t", $subrec, $i);
1219
                    if (preg_match('/^\d ' . Gedcom::REGEX_TAG . ' @(' . Gedcom::REGEX_XREF . ')@/', $subrecord, $xref_match)) {
1220
                        $linked_object = Registry::gedcomRecordFactory()->make($xref_match[1], $this->tree);
1221
                        if ($linked_object && !$linked_object->canShow()) {
1222
                            //continue;
1223
                        }
1224
                    }
1225
                    $this->repeats[] = $subrecord;
1226
                }
1227
            }
1228
        }
1229
    }
1230
1231
    /**
1232
     * Handle </repeatTag>
1233
     *
1234
     * @return void
1235
     */
1236
    protected function repeatTagEndHandler(): void
1237
    {
1238
        $this->process_repeats--;
1239
        if ($this->process_repeats > 0) {
1240
            return;
1241
        }
1242
1243
        $nnnn = count($this->repeats);
0 ignored issues
show
Unused Code introduced by
The assignment to $nnnn is dead and can be removed.
Loading history...
1244
        $rpt1 = isset($this->repeats[0]) ? $this->repeats[0] : "";
0 ignored issues
show
Unused Code introduced by
The assignment to $rpt1 is dead and can be removed.
Loading history...
1245
        // Check if there is anything to repeat
1246
        if (count($this->repeats) > 0) {
1247
            // No need to load them if not used...
1248
1249
            //-- read the xml from the file
1250
            $lines = file($this->report);
1251
            $lineoffset = 0;
1252
            foreach ($this->repeats_stack as $rep) {
1253
                $lineoffset += $rep[1] - 1;
1254
            }
1255
            while (!str_contains($lines[$lineoffset + $this->repeat_bytes], '<RepeatTag')) {
1256
                $lineoffset--;
1257
            }
1258
            $lineoffset++;
1259
            $reportxml = "<tempdoc>\n";
1260
            $line_nr   = $lineoffset + $this->repeat_bytes;
1261
            $lnnn = $line_nr;
0 ignored issues
show
Unused Code introduced by
The assignment to $lnnn is dead and can be removed.
Loading history...
1262
            // RepeatTag Level counter
1263
            $count = 1;
1264
            while (0 < $count) {
1265
                if (str_contains($lines[$line_nr], '<RepeatTag')) {
1266
                    $count++;
1267
                } elseif (str_contains($lines[$line_nr], '</RepeatTag')) {
1268
                    $count--;
1269
                }
1270
                if (0 < $count) {
1271
                    $reportxml .= $lines[$line_nr];
1272
                }
1273
                $line_nr++;
1274
            }
1275
            // No need to drag this
1276
            unset($lines);
1277
            $reportxml .= "</tempdoc>\n";
1278
            // Save original values
1279
            $this->parser_stack[] = $this->parser;
1280
            $oldgedrec            = $this->gedrec;
1281
            foreach ($this->repeats as $gedrec) {
1282
                $this->gedrec  = $gedrec;
1283
                $repeat_parser = xml_parser_create();
1284
                $this->parser  = $repeat_parser;
1285
                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
1286
1287
                xml_set_element_handler(
1288
                    $repeat_parser,
1289
                    function ($parser, string $name, array $attrs): void {
1290
                        $this->startElement($parser, $name, $attrs);
1291
                    },
1292
                    function ($parser, string $name): void {
1293
                        $this->endElement($parser, $name);
1294
                    }
1295
                );
1296
1297
                xml_set_character_data_handler(
1298
                    $repeat_parser,
1299
                    function ($parser, string $data): void {
1300
                        $this->characterData($parser, $data);
1301
                    }
1302
                );
1303
1304
                if (!xml_parse($repeat_parser, $reportxml, true)) {
1305
                    throw new DomainException(sprintf(
1306
                        'RepeatTagEHandler XML error: %s at line %d',
1307
                        xml_error_string(xml_get_error_code($repeat_parser)),
1308
                        xml_get_current_line_number($repeat_parser)
1309
                    ));
1310
                }
1311
                xml_parser_free($repeat_parser);
1312
            }
1313
            // Restore original values
1314
            $this->gedrec = $oldgedrec;
1315
            $this->parser = array_pop($this->parser_stack);
1316
        }
1317
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1318
    }
1319
1320
    /**
1321
     * Variable lookup
1322
     * Retrieve predefined variables :
1323
     * @ desc GEDCOM fact description, example:
1324
     *        1 EVEN This is a description
1325
     * @ fact GEDCOM fact tag, such as BIRT, DEAT etc.
1326
     * $ I18N::translate('....')
1327
     * $ language_settings[]
1328
     *
1329
     * @param array<string> $attrs an array of key value pairs for the attributes
1330
     *
1331
     * @return void
1332
     */
1333
    protected function varStartHandler(array $attrs): void
1334
    {
1335
        if (!isset($attrs['var'])) {
1336
            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));
1337
        }
1338
1339
        $var = $attrs['var'];
1340
        // SetVar element preset variables
1341
        if (!empty($this->vars[$var]['id'])) {
1342
            $var = $this->vars[$var]['id'];
1343
        } else {
1344
            $tfact = $this->fact;
1345
            if (($this->fact === 'EVEN' || $this->fact === 'FACT') && $this->type !== '') {
1346
                // Use :
1347
                // n TYPE This text if string
1348
                $tfact = $this->type;
1349
            } else {
1350
                foreach ([Individual::RECORD_TYPE, Family::RECORD_TYPE] as $record_type) {
1351
                    $element = Registry::elementFactory()->make($record_type . ':' . $this->fact);
1352
1353
                    if (!$element instanceof UnknownElement) {
1354
                        $tfact = $element->label();
1355
                        break;
1356
                    }
1357
                }
1358
            }
1359
1360
            $var = strtr($var, ['@desc' => $this->desc, '@fact' => $tfact]);
1361
1362
            if (preg_match('/^I18N::number\((.+)\)$/', $var, $match)) {
1363
                $var = I18N::number((int) $match[1]);
1364
            } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $var, $match)) {
1365
                $var = I18N::translate($match[1]);
1366
            } elseif (preg_match('/^I18N::translate\(\$(.+)\)$/', $var, $match)) {
1367
                $var = I18N::translate($this->vars[$match[1]]['id']);
1368
            } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $var, $match)) {
1369
                $var = I18N::translateContext($match[1], $match[2]);
1370
            }
1371
        }
1372
        // Check if variable is set as a date and reformat the date
1373
        if (isset($attrs['date'])) {
1374
            if ($attrs['date'] === '1') {
1375
                $g   = new Date($var);
1376
                $var = $g->display();
1377
            }
1378
        }
1379
        if (isset($attrs['amp'])) {
1380
            $var = str_replace("%26", '&', $var);
1381
        }
1382
        if (isset($attrs['cut'])) {
1383
            $cut = (int) $attrs['cut'];
1384
            $var = $cut > 0 ? substr($var, 0, $cut) : substr($var, $cut);
1385
            if ($cut == 0) {
1386
                $var = "";
1387
            }
1388
        }
1389
        if (isset($attrs['lcfirst'])) {
1390
            $var = lcfirst($var);
1391
        }
1392
        $this->current_element->addText($var);
1393
        $this->text = $var; // Used for title/description
1394
    }
1395
1396
    /**
1397
     * Handle <facts>
1398
     *
1399
     * @param array<string> $attrs
1400
     *
1401
     * @return void
1402
     */
1403
    protected function factsStartHandler(array $attrs): void
1404
    {
1405
        $this->process_repeats++;
1406
        if ($this->process_repeats > 1) {
1407
            return;
1408
        }
1409
1410
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1411
        $this->repeats         = [];
1412
        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1413
1414
        $id    = '';
1415
        $match = [];
1416
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1417
            $id = $match[1];
1418
        }
1419
        $tag = '';
1420
        if (isset($attrs['ignore'])) {
1421
            $tag .= $attrs['ignore'];
1422
        }
1423
        if (preg_match('/\$(.+)/', $tag, $match)) {
1424
            $tag = $this->vars[$match[1]]['id'];
1425
        }
1426
1427
        $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1428
        if (empty($attrs['diff']) && !empty($id)) {
1429
            $facts = $record->facts([], true);
1430
            $this->repeats = [];
1431
            $nonfacts      = explode(',', $tag);
1432
            foreach ($facts as $fact) {
1433
                $tag = explode(':', $fact->tag())[1];
1434
1435
                if (!in_array($tag, $nonfacts, true)) {
1436
                    $this->repeats[] = $fact->gedcom();
1437
                }
1438
            }
1439
        } else {
1440
            foreach ($record->facts() as $fact) {
1441
                if (($fact->isPendingAddition() || $fact->isPendingDeletion()) && !str_ends_with($fact->tag(), ':CHAN')) {
1442
                    $this->repeats[] = $fact->gedcom();
1443
                }
1444
            }
1445
        }
1446
1447
        // Add fact/event for FAM:DIV and for death of spouse
1448
        foreach ($this->repeats as $key => $fact) {
1449
            $jdarr[$key] = 0;
1450
            if (preg_match('/1 FAMS @(.+)@/', $fact, $match)) {
1451
                $famid = $match[1];
1452
                $fam = Registry::familyFactory()->make($match[1], $this->tree);
1453
                $dt = $this->getGedcomValue("MARR:DATE", 0, $fam->gedcom());
1454
                if ($dt == "") {
1455
                    $dt = $this->getGedcomValue("ENGA:DATE", 0, $fam->gedcom());
1456
                }
1457
                if ($dt == "" && $this->getGedcomValue("EVEN:TYPE", 0, $fam->gedcom()) == "Sambo") {
1458
                    $dt = $this->getGedcomValue("EVEN:DATE", 0, $fam->gedcom());
1459
                }
1460
                $date = new Date($dt);
1461
                $jd = $date->julianDay();
1462
                $jdarr[$key] = $jd;
1463
                // Divorce
1464
                $dt = $this->getGedcomValue("DIV:DATE", 0, $fam->gedcom());
1465
                if ($dt != "") {
1466
                    $this->repeats[] = "1 DIV\n2 DATE " . $dt . "\n";
1467
                }
1468
                // Separation // Doesn't work!! getGedComValue only reports the first event!! I.e. no match here
1469
                if ($this->getGedcomValue("EVEN:TYPE", 0, $fam->gedcom()) == "Separation") {
1470
                    $dt = $this->getGedcomValue("EVEN:DATE", 0, $fam->gedcom());
1471
                    if ($dt != "") {
1472
                        $this->repeats[] = "1 EVEN\n2 TYPE Separation\n2 DATE " . $dt . "\n";
1473
                    }
1474
                }
1475
                // death of husband / wife
1476
                $husb = $fam->husband();
1477
                $wife = $fam->wife();
1478
                if ($this->getGedcomValue("SEX", 0, $this->gedrec) == "M") {
1479
                    $spouse = $wife;
1480
                } else {
1481
                    $spouse = $husb;
1482
                }
1483
                if ($spouse) {
1484
                    $dt = $this->getGedcomValue("DEAT:DATE", 0, $spouse->gedcom());
1485
                } else {
1486
                    $dt = "";
1487
                }
1488
                if ($dt != "") {
1489
                    $this->repeats[] = "1 _SP_DEAT\n2 DATE " . $dt . "\n2 _O_FAM " . $famid . "\n";
1490
                }
1491
            }
1492
        }
1493
        // Find the dates for the facts that are found
1494
        foreach ($this->repeats as $key => $fact) {
1495
            if (preg_match('/[234] DATE ([^\n]+)/', $fact, $match)) {
1496
                $date = new Date($match[1]);
1497
                $jd = $date->julianDay();
1498
                $jdarr[$key] = $jd;
1499
            }
1500
        }
1501
1502
        // Resort facts in chronological order, if possible
1503
        $m = count($this->repeats) - 1;
1504
        $prevd = 0;
1505
        for ($i = 0; $i <= $m; $i++) { // keep undated events after previous dated event
1506
            if ($jdarr[$i] === 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $jdarr seems to be defined by a foreach iteration on line 1448. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
1507
                $jdarr[$i] = $prevd;
1508
            } else {
1509
                $prevd = $jdarr[$i];
1510
            }
1511
        }
1512
1513
        while ($m > 1) {
1514
            $n = count($this->repeats);
1515
            while ($n > 1) {
1516
                if ($jdarr[$n - 2] > $jdarr[$n - 1] && $jdarr[$n - 1] !== 0) {
1517
                    $s = $this->repeats[$n - 1];
1518
                    $this->repeats[$n - 1] = $this->repeats[$n - 2];
1519
                    $this->repeats[$n - 2] = $s;
1520
                    $s = $jdarr[$n - 1];
1521
                    $jdarr[$n - 1] = $jdarr[$n - 2];
1522
                    $jdarr[$n - 2] = $s;
1523
                }
1524
                $n -= 1;
1525
            }
1526
            $m -= 1;
1527
        }
1528
1529
        // Remove spouse deaths that are too late: after new marriage or own death
1530
        $currfam = "";
1531
        for ($i = 0; $i <= count($this->repeats) - 1; $i++) {
1532
            if (preg_match('/[1234] FAMS @(.+)@/', $this->repeats[$i], $match)) {
1533
                $currfam = $match[1];
1534
            }
1535
            if (preg_match('/_SP_DEAT.*\n2 DATE (.*)\n.*_O_FAM (.+)\n/', $this->repeats[$i], $match)) {
1536
                if ($currfam != $match[2] || $i == count($this->repeats) - 1) {
1537
                    $this->repeats[$i] = "1 _XXX\n";
1538
                } // ignore fact
1539
            }
1540
        }
1541
    }
1542
1543
    /**
1544
     * Handle </facts>
1545
     *
1546
     * @return void
1547
     */
1548
    protected function factsEndHandler(): void
1549
    {
1550
        $this->process_repeats--;
1551
        if ($this->process_repeats > 0) {
1552
            return;
1553
        }
1554
1555
        // Check if there is anything to repeat
1556
        if (count($this->repeats) > 0) {
1557
            $line       = xml_get_current_line_number($this->parser) - 1;
1558
            $lineoffset = 0;
1559
            foreach ($this->repeats_stack as $rep) {
1560
                $lineoffset += $rep[1] - 1;
1561
            }
1562
1563
            //-- read the xml from the file
1564
            $lines = file($this->report);
1565
            while ($lineoffset + $this->repeat_bytes > 0 && !str_contains($lines[$lineoffset + $this->repeat_bytes], '<Facts ')) {
1566
                $lineoffset--;
1567
            }
1568
            $lineoffset++;
1569
            $reportxml = "<tempdoc>\n";
1570
            $i         = $line + $lineoffset;
1571
            $line_nr   = $this->repeat_bytes + $lineoffset;
1572
            while ($line_nr < $i) {
1573
                $reportxml .= $lines[$line_nr];
1574
                $line_nr++;
1575
            }
1576
            // No need to drag this
1577
            unset($lines);
1578
            $reportxml .= "</tempdoc>\n";
1579
            // Save original values
1580
            $this->parser_stack[] = $this->parser;
1581
            $oldgedrec = $this->gedrec;
1582
            $count = count($this->repeats);
1583
            $i = 0;
1584
            while ($i < $count) {
1585
                if (!isset($this->repeats[$i])) {
1586
                    $i++;
1587
                    continue; // this fact has been removed above, occured too late
1588
                }
1589
                $this->gedrec = $this->repeats[$i];
1590
                $this->fact = '';
1591
                $this->desc = '';
1592
                if (preg_match('/1 (\w+)(.*)/', $this->gedrec, $match)) {
1593
                    $this->fact = $match[1];
1594
                    if ($this->fact === 'EVEN' || $this->fact === 'FACT') {
1595
                        $tmatch = [];
1596
                        if (preg_match('/2 TYPE (.+)/', $this->gedrec, $tmatch)) {
1597
                            $this->type = trim($tmatch[1]);
1598
                        } else {
1599
                            $this->type = ' ';
1600
                        }
1601
                    }
1602
                    $this->desc = trim($match[2]);
1603
                    $this->desc .= self::getCont(2, $this->gedrec);
1604
                }
1605
                $repeat_parser = xml_parser_create();
1606
                $this->parser  = $repeat_parser;
1607
                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
1608
1609
                xml_set_element_handler(
1610
                    $repeat_parser,
1611
                    function ($parser, string $name, array $attrs): void {
1612
                        $this->startElement($parser, $name, $attrs);
1613
                    },
1614
                    function ($parser, string $name): void {
1615
                        $this->endElement($parser, $name);
1616
                    }
1617
                );
1618
1619
                xml_set_character_data_handler(
1620
                    $repeat_parser,
1621
                    function ($parser, string $data): void {
1622
                        $this->characterData($parser, $data);
1623
                    }
1624
                );
1625
1626
                if (!xml_parse($repeat_parser, $reportxml, true)) {
1627
                    throw new DomainException(sprintf(
1628
                        'FactsEHandler XML error: %s at line %d',
1629
                        xml_error_string(xml_get_error_code($repeat_parser)),
1630
                        xml_get_current_line_number($repeat_parser)
1631
                    ));
1632
                }
1633
                xml_parser_free($repeat_parser);
1634
                $i++;
1635
            }
1636
            // Restore original values
1637
            $this->parser = array_pop($this->parser_stack);
1638
            $this->gedrec = $oldgedrec;
1639
        }
1640
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1641
    }
1642
1643
    /**
1644
     * Setting upp or changing variables in the XML
1645
     * The XML variable name and value is stored in $this->vars
1646
     *
1647
     * @param array<string> $attrs an array of key value pairs for the attributes
1648
     *
1649
     * @return void
1650
     */
1651
    protected function setVarStartHandler(array $attrs): void
1652
    {
1653
        if (empty($attrs['name'])) {
1654
            throw new DomainException('REPORT ERROR var: The attribute "name" is missing or not set in the XML file');
1655
        }
1656
1657
        $name  = $attrs['name'];
1658
        $value = $attrs['value'];
1659
        if (isset($attrs['dumpvar'])) {
1660
            $dumpvar = $attrs['dumpvar'];
1661
        } else {
1662
            $dumpvar = "";
1663
        }
1664
        $match = [];
1665
        // Current GEDCOM record strings
1666
        if ($value === '@ID') {
1667
            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1668
                $value = $match[1];
1669
            }
1670
        } elseif ($value === '@fact') {
1671
            $value = $this->fact;
1672
        } elseif ($value === '@desc') {
1673
            $value = $this->desc;
1674
        } elseif ($value === '@format') {
1675
            if (isset($_GET["format"])) {
1676
                $value = $_GET["format"];
1677
            } else {
1678
                $value = "";
1679
            }
1680
        } elseif ($value === '@generation') {
1681
            $value = (string) $this->generation;
1682
        } elseif ($value === '@base_url') {
1683
            $value = (string) $_SERVER["HTTP_REFERER"];
1684
            $i = strpos($value, "%2Freport%2F");
1685
            if ($i === false) {
1686
                $i = strpos($value, "/report/");
1687
            }
1688
            if ($i !== false) {
1689
                $value = substr($value, 0, $i);
1690
            }
1691
        } elseif ($value === '@relation') {
1692
            if (isset($this->mfrelation[$this->xref()])) {
0 ignored issues
show
Bug introduced by
The method xref() does not exist on Fisharebest\Webtrees\Report\ReportParserGenerate. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1692
            if (isset($this->mfrelation[$this->/** @scrutinizer ignore-call */ xref()])) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1693
                $value = (string) $this->mfrelation[$this->xref()];
1694
            } else {
1695
                $value = "";
1696
            }
1697
        } elseif (preg_match("/@(\w+)/", $value, $match)) {
1698
            $gmatch = [];
1699
            if (preg_match("/\d $match[1] (.+)/", $this->gedrec, $gmatch)) {
1700
                $value = str_replace('@', '', trim($gmatch[1]));
1701
            }
1702
        } elseif (preg_match("/@\\$(\w+)/", $value, $match)) {
1703
            if ($match[1] == "dump" && $this->vars['dval']['id'] > 0) {
1704
                // if ($this->vars[ 'dval' ]['id'] == 1001)
1705
                if ($dumpvar == "gedrec") {
1706
                    error_log("\n---- setvar start  " . date("Y-m-d H:i:s") . " RPG " . __LINE__ . "  " . $name . "  gedcom=\n" . $this->gedrec . "\n", 3, "my-errors.log");
1707
                } elseif ($dumpvar != "") {
1708
                    error_log("var: " . $dumpvar . " = " . $this->vars[$dumpvar]['id'] . "\n", 3, "my-errors.log");
1709
                } else {
1710
                    if (isset($this->vars['dval']['id'])) {
1711
                        $nnn = $this->vars['dval']['id'];
1712
                    } else {
1713
                        $nnn = 0;
1714
                    }
1715
                    error_log("\n---- setvar start  " . date("Y-m-d H:i:s") . " RPG " . __LINE__ . "  " . $name . "  -----\n", 3, "my-errors.log");
1716
                    foreach ($this->vars as $key => $val) {
1717
                        if ($nnn-- < 0) {
1718
                            error_log($key . "='" . $val['id'] . "'\n", 3, "my-errors.log");
1719
                        }
1720
                    }
1721
                }
1722
            }
1723
            $value = $this->vars[$match[1]]['id'];
1724
            if (isset($this->vars[$value]['id'])) {
1725
                $value = '$' . $this->vars[$match[1]]['id'];
1726
            } else {
1727
                $value = "0";
1728
            }
1729
        }
1730
        if (isset($attrs['trim'])) {
1731
            $value = str_replace($attrs['trim'], '', $value);
1732
        }
1733
        if (preg_match("/\\$(\w+)/", $name, $match)) {
1734
            $name = $this->vars["'" . $match[1] . "'"]['id'];
1735
        }
1736
        $count = preg_match_all("/\\$(\w+)/", $value, $match, PREG_SET_ORDER);
1737
        $i     = 0;
1738
        while ($i < $count) {
1739
            $t     = $this->vars[$match[$i][1]]['id'];
1740
            $value = preg_replace('/\$' . $match[$i][1] . '/', $t, $value, 1);
1741
            $i++;
1742
        }
1743
        if (preg_match('/^I18N::number\((.+)\)$/', $value, $match)) {
1744
            $value = I18N::number((int) $match[1]);
1745
        } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $value, $match)) {
1746
            $value = I18N::translate($match[1]);
1747
        } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $value, $match)) {
1748
            $value = I18N::translateContext($match[1], $match[2]);
1749
        }
1750
        if (isset($attrs['lcfirst'])) { // set 1st char to lower case
1751
            $value = lcfirst($value);
1752
        }
1753
1754
        // Arithmetic functions
1755
        if (preg_match("/(\d+)\s*([-+*\/])\s*(\d+)/", $value, $match)) {
1756
            // Create an expression language with the functions used by our reports.
1757
            $expression_provider  = new ReportExpressionLanguageProvider();
1758
            $expression_cache     = new NullAdapter();
1759
            $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1760
1761
            $value = (string) $expression_language->evaluate($value);
1762
        }
1763
1764
        if (str_contains($value, '@')) {
1765
            $value = '';
1766
        }
1767
        $this->vars[$name]['id'] = $value;
1768
        if ($name == 'title') {
1769
            $this->wt_report->title = $value;
1770
        }
1771
    }
1772
1773
    /**
1774
     * Handle <if>
1775
     *
1776
     * @param array<string> $attrs
1777
     *
1778
     * @return void
1779
     */
1780
    protected function ifStartHandler(array $attrs): void
1781
    {
1782
        if ($this->process_ifs > 0) {
1783
            $this->process_ifs++;
1784
1785
            return;
1786
        }
1787
1788
        $condition = $attrs['condition'];
1789
        $condition = $this->substituteVars($condition, true);
1790
        $condition = str_replace([
1791
            ' LT ',
1792
            ' GT ',
1793
        ], [
1794
            '<',
1795
            '>',
1796
        ], $condition);
1797
        // Replace the first occurrence only once of @fact:DATE or in any other combinations to the current fact, such as BIRT
1798
        $condition = str_replace('@fact:', $this->fact . ':', $condition);
1799
        $match     = [];
1800
        $count     = preg_match_all("/@([\w:.]+)/", $condition, $match, PREG_SET_ORDER);
1801
        $i         = 0;
1802
        while ($i < $count) {
1803
            $id    = $match[$i][1];
1804
            $value = '""';
1805
            if ($id === 'ID') {
1806
                if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1807
                    $value = "'" . $match[1] . "'";
1808
                }
1809
            } elseif ($id === 'fact') {
1810
                $value = '"' . $this->fact . '"';
1811
            } elseif ($id === 'desc') {
1812
                $value = '"' . addslashes($this->desc) . '"';
1813
            } elseif ($id === 'generation') {
1814
                $value = '"' . $this->generation . '"';
1815
            } else {
1816
                $level = (int) explode(' ', trim($this->gedrec))[0];
1817
                if ($level === 0) {
1818
                    $level++;
1819
                }
1820
                $value = $this->getGedcomValue($id, $level, $this->gedrec);
1821
                if (empty($value)) {
1822
                    $level++;
1823
                    $value = $this->getGedcomValue($id, $level, $this->gedrec);
1824
                }
1825
                $value = preg_replace('/^@(' . Gedcom::REGEX_XREF . ')@$/', '$1', $value);
1826
                $value = '"' . addslashes($value) . '"';
1827
            }
1828
            $condition = str_replace("@$id", $value, $condition);
1829
            $i++;
1830
        }
1831
1832
        // Create an expression language with the functions used by our reports.
1833
        $expression_provider  = new ReportExpressionLanguageProvider();
1834
        $expression_cache     = new NullAdapter();
1835
        $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1836
1837
        $ret = $expression_language->evaluate($condition);
1838
1839
        if (!$ret) {
1840
            $this->process_ifs++;
1841
        }
1842
    }
1843
1844
    /**
1845
     * Handle </if>
1846
     *
1847
     * @return void
1848
     */
1849
    protected function ifEndHandler(): void
1850
    {
1851
        if ($this->process_ifs > 0) {
1852
            $this->process_ifs--;
1853
        }
1854
    }
1855
1856
    /**
1857
     * Handle <footnote>
1858
     * Collect the Footnote links
1859
     * GEDCOM Records that are protected by Privacy setting will be ignored
1860
     *
1861
     * @param array<string> $attrs
1862
     *
1863
     * @return void
1864
     */
1865
    protected function footnoteStartHandler(array $attrs): void
1866
    {
1867
        $id = '';
1868
        if (preg_match('/[0-9] (.+) @(.+)@/', $this->gedrec, $match)) {
1869
            $id = $match[2];
1870
        }
1871
        $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1872
        if ($record && $record->canShow()) {
1873
            $this->print_data_stack[] = $this->print_data;
1874
            $this->print_data         = true;
1875
            $style                    = '';
1876
            if (!empty($attrs['style'])) {
1877
                $style = $attrs['style'];
1878
            }
1879
            $this->footnote_element = $this->current_element;
1880
            $this->current_element  = $this->report_root->createFootnote($style);
1881
        } else {
1882
            $this->print_data       = false;
1883
            $this->process_footnote = false;
1884
        }
1885
    }
1886
1887
    /**
1888
     * Handle </footnote>
1889
     * Print the collected Footnote data
1890
     *
1891
     * @return void
1892
     */
1893
    protected function footnoteEndHandler(): void
1894
    {
1895
        if ($this->process_footnote) {
1896
            $this->print_data = array_pop($this->print_data_stack);
1897
            $temp             = trim($this->current_element->getValue());
1898
            if (strlen($temp) > 3) {
1899
                $this->wt_report->addElement($this->current_element);
1900
            }
1901
            $this->current_element = $this->footnote_element;
1902
        } else {
1903
            $this->process_footnote = true;
1904
        }
1905
    }
1906
1907
    /**
1908
     * Handle <footnoteTexts />
1909
     *
1910
     * @return void
1911
     */
1912
    protected function footnoteTextsStartHandler(): void
1913
    {
1914
        $temp = 'footnotetexts';
1915
        $this->wt_report->addElement($temp);
1916
    }
1917
1918
    /**
1919
     * XML element Forced line break handler - HTML code
1920
     *
1921
     * @return void
1922
     */
1923
    protected function brStartHandler(): void
1924
    {
1925
        if ($this->print_data && $this->process_gedcoms === 0) {
1926
            $this->current_element->addText('<br>');
1927
        }
1928
    }
1929
1930
    /**
1931
     * Handle <sp />
1932
     * Forced space
1933
     *
1934
     * @return void
1935
     */
1936
    protected function spStartHandler(): void
1937
    {
1938
        if ($this->print_data && $this->process_gedcoms === 0) {
1939
            $this->current_element->addText(' ');
1940
        }
1941
    }
1942
1943
    /**
1944
     * Handle <highlightedImage />
1945
     *
1946
     * @param array<string> $attrs
1947
     *
1948
     * @return void
1949
     */
1950
    protected function highlightedImageStartHandler(array $attrs): void
1951
    {
1952
        $id = '';
1953
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1954
            $id = $match[1];
1955
        }
1956
1957
        // Position the top corner of this box on the page
1958
        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
1959
1960
        // Position the left corner of this box on the page
1961
        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
1962
1963
        // string Align the image in left, center, right (or empty to use x/y position).
1964
        $align = $attrs['align'] ?? '';
1965
1966
        // string Next Line should be T:next to the image, N:next line
1967
        $ln = $attrs['ln'] ?? 'T';
1968
1969
        // Width, height (or both).
1970
        $width  = (float) ($attrs['width'] ?? 0.0);
1971
        $height = (float) ($attrs['height'] ?? 0.0);
1972
1973
        $person     = Registry::individualFactory()->make($id, $this->tree);
1974
        $media_file = $person->findHighlightedMediaFile();
1975
1976
        if ($media_file instanceof MediaFile && $media_file->fileExists()) {
1977
            $image      = imagecreatefromstring($media_file->fileContents());
1978
            $attributes = [imagesx($image), imagesy($image)];
1979
1980
            if ($width > 0 && $height == 0) {
1981
                $perc   = $width / $attributes[0];
1982
                $height = round($attributes[1] * $perc);
1983
            } elseif ($height > 0 && $width == 0) {
1984
                $perc  = $height / $attributes[1];
1985
                $width = round($attributes[0] * $perc);
1986
            } else {
1987
                $width  = (float) $attributes[0];
1988
                $height = (float) $attributes[1];
1989
            }
1990
            $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
1991
            $this->wt_report->addElement($image);
1992
        }
1993
    }
1994
1995
    /**
1996
     * Handle <image/>
1997
     *
1998
     * @param array<string> $attrs
1999
     *
2000
     * @return void
2001
     */
2002
    protected function imageStartHandler(array $attrs): void
2003
    {
2004
        // Position the top corner of this box on the page. the default is the current position
2005
        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
2006
2007
        // mixed Position the left corner of this box on the page. the default is the current position
2008
        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
2009
2010
        // string Align the image in left, center, right (or empty to use x/y position).
2011
        $align = $attrs['align'] ?? '';
2012
2013
        // string Next Line should be T:next to the image, N:next line
2014
        $ln = $attrs['ln'] ?? 'T';
2015
2016
        // Width, height (or both).
2017
        $width  = (float) ($attrs['width'] ?? 0.0);
2018
        $height = (float) ($attrs['height'] ?? 0.0);
2019
2020
        $file = $attrs['file'] ?? '';
2021
2022
        if ($file === '@FILE') {
2023
            $match = [];
2024
            if (preg_match("/\d OBJE @(.+)@/", $this->gedrec, $match)) {
2025
                $mediaobject = Registry::mediaFactory()->make($match[1], $this->tree);
2026
                $media_file  = $mediaobject->firstImageFile();
2027
2028
                if ($media_file instanceof MediaFile && $media_file->fileExists()) {
2029
                    $image      = imagecreatefromstring($media_file->fileContents());
2030
                    $attributes = [imagesx($image), imagesy($image)];
2031
2032
                    if ($width > 0 && $height == 0) {
2033
                        $perc   = $width / $attributes[0];
2034
                        $height = round($attributes[1] * $perc);
2035
                    } elseif ($height > 0 && $width == 0) {
2036
                        $perc  = $height / $attributes[1];
2037
                        $width = round($attributes[0] * $perc);
2038
                    } else {
2039
                        $width  = (float) $attributes[0];
2040
                        $height = (float) $attributes[1];
2041
                    }
2042
                    $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
2043
                    $this->wt_report->addElement($image);
2044
                }
2045
            }
2046
        } else {
2047
            if (file_exists($file) && preg_match('/(jpg|jpeg|png|gif)$/i', $file)) {
2048
                $size = getimagesize($file);
2049
                if ($width > 0 && $height == 0) {
2050
                    $perc   = $width / $size[0];
2051
                    $height = round($size[1] * $perc);
2052
                } elseif ($height > 0 && $width == 0) {
2053
                    $perc  = $height / $size[1];
2054
                    $width = round($size[0] * $perc);
2055
                } else {
2056
                    $width  = $size[0];
2057
                    $height = $size[1];
2058
                }
2059
                $image = $this->report_root->createImage($file, $left, $top, $width, $height, $align, $ln);
2060
                $this->wt_report->addElement($image);
2061
            }
2062
        }
2063
    }
2064
2065
    /**
2066
     * Handle <line>
2067
     *
2068
     * @param array<string> $attrs
2069
     *
2070
     * @return void
2071
     */
2072
    protected function lineStartHandler(array $attrs): void
2073
    {
2074
        // Start horizontal position, current position (default)
2075
        $x1 = ReportBaseElement::CURRENT_POSITION;
2076
        if (isset($attrs['x1'])) {
2077
            if ($attrs['x1'] === '0') {
2078
                $x1 = 0;
2079
            } elseif ($attrs['x1'] === '.') {
2080
                $x1 = ReportBaseElement::CURRENT_POSITION;
2081
            } elseif (!empty($attrs['x1'])) {
2082
                $x1 = (float) $attrs['x1'];
2083
            }
2084
        }
2085
        // Start vertical position, current position (default)
2086
        $y1 = ReportBaseElement::CURRENT_POSITION;
2087
        if (isset($attrs['y1'])) {
2088
            if ($attrs['y1'] === '0') {
2089
                $y1 = 0;
2090
            } elseif ($attrs['y1'] === '.') {
2091
                $y1 = ReportBaseElement::CURRENT_POSITION;
2092
            } elseif (!empty($attrs['y1'])) {
2093
                $y1 = (float) $attrs['y1'];
2094
            }
2095
        }
2096
        // End horizontal position, maximum width (default)
2097
        $x2 = ReportBaseElement::CURRENT_POSITION;
2098
        if (isset($attrs['x2'])) {
2099
            if ($attrs['x2'] === '0') {
2100
                $x2 = 0;
2101
            } elseif ($attrs['x2'] === '.') {
2102
                $x2 = ReportBaseElement::CURRENT_POSITION;
2103
            } elseif (!empty($attrs['x2'])) {
2104
                $x2 = (float) $attrs['x2'];
2105
            }
2106
        }
2107
        // End vertical position
2108
        $y2 = ReportBaseElement::CURRENT_POSITION;
2109
        if (isset($attrs['y2'])) {
2110
            if ($attrs['y2'] === '0') {
2111
                $y2 = 0;
2112
            } elseif ($attrs['y2'] === '.') {
2113
                $y2 = ReportBaseElement::CURRENT_POSITION;
2114
            } elseif (!empty($attrs['y2'])) {
2115
                $y2 = (float) $attrs['y2'];
2116
            }
2117
        }
2118
2119
        $line = $this->report_root->createLine($x1, $y1, $x2, $y2);
2120
        $this->wt_report->addElement($line);
2121
    }
2122
2123
    /**
2124
     * Handle <list>
2125
     *
2126
     * @param array<string> $attrs
2127
     *
2128
     * @return void
2129
     */
2130
    protected function listStartHandler(array $attrs): void
2131
    {
2132
        $this->process_repeats++;
2133
        if ($this->process_repeats > 1) {
2134
            return;
2135
        }
2136
2137
        $match = [];
2138
        if (isset($attrs['sortby'])) {
2139
            $sortby = $attrs['sortby'];
2140
            if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2141
                $sortby = $this->vars[$match[1]]['id'];
2142
                $sortby = trim($sortby);
2143
            }
2144
        } else {
2145
            $sortby = 'NAME';
2146
        }
2147
2148
        $listname = $attrs['list'] ?? 'individual';
2149
2150
        // Some filters/sorts can be applied using SQL, while others require PHP
2151
        switch ($listname) {
2152
            case 'pending':
2153
                $this->list = DB::table('change')
2154
                    ->whereIn('change_id', function (Builder $query): void {
2155
                        $query->select([new Expression('MAX(change_id)')])
2156
                            ->from('change')
2157
                            ->where('gedcom_id', '=', $this->tree->id())
2158
                            ->where('status', '=', 'pending')
2159
                            ->groupBy(['xref']);
2160
                    })
2161
                    ->get()
2162
                    ->map(fn (object $row): ?GedcomRecord => Registry::gedcomRecordFactory()->make($row->xref, $this->tree, $row->new_gedcom ?: $row->old_gedcom))
2163
                    ->filter()
2164
                    ->all();
2165
                break;
2166
2167
            case 'individual':
2168
                $query = DB::table('individuals')
2169
                    ->where('i_file', '=', $this->tree->id())
2170
                    ->select(['i_id AS xref', 'i_gedcom AS gedcom'])
2171
                    ->distinct();
2172
2173
                foreach ($attrs as $attr => $value) {
2174
                    if (str_starts_with($attr, 'filter') && $value !== '') {
2175
                        $value = $this->substituteVars($value, false);
2176
                        // Convert the various filters into SQL
2177
                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
2178
                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2179
                                $join
2180
                                    ->on($attr . '.d_gid', '=', 'i_id')
2181
                                    ->on($attr . '.d_file', '=', 'i_file');
2182
                            });
2183
2184
                            $query->where($attr . '.d_fact', '=', $match[1]);
2185
2186
                            $date = new Date($match[3]);
2187
2188
                            if ($match[2] === 'LTE') {
2189
                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
2190
                            } else {
2191
                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
2192
                            }
2193
2194
                            // This filter has been fully processed
2195
                            unset($attrs[$attr]);
2196
                        } elseif (preg_match('/^NAME CONTAINS (.+)$/', $value, $match)) {
2197
                            $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2198
                                $join
2199
                                    ->on($attr . '.n_id', '=', 'i_id')
2200
                                    ->on($attr . '.n_file', '=', 'i_file');
2201
                            });
2202
                            // Search the DB only if there is any name supplied
2203
                            $names = explode(' ', $match[1]);
2204
                            foreach ($names as $name) {
2205
                                $query->where($attr . '.n_full', 'LIKE', '%' . addcslashes($name, '\\%_') . '%');
2206
                            }
2207
2208
                            // This filter has been fully processed
2209
                            unset($attrs[$attr]);
2210
                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
2211
                            // Convert newline escape sequences to actual new lines
2212
                            $match[1] = str_replace('\n', "\n", $match[1]);
2213
2214
                            $query->where('i_gedcom', 'LIKE', $match[1]);
2215
2216
                            // This filter has been fully processed
2217
                            unset($attrs[$attr]);
2218
                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
2219
                            // Don't unset this filter. This is just initial filtering for performance
2220
                            $query
2221
                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
2222
                                    $join
2223
                                        ->on($attr . 'a.pl_file', '=', 'i_file')
2224
                                        ->on($attr . 'a.pl_gid', '=', 'i_id');
2225
                                })
2226
                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
2227
                                    $join
2228
                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
2229
                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
2230
                                })
2231
                                ->where($attr . 'b.p_place', 'LIKE', '%' . addcslashes($match[1], '\\%_') . '%');
2232
                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
2233
                            // Don't unset this filter. This is just initial filtering for performance
2234
                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2235
                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
2236
                            $query->where('i_gedcom', 'LIKE', $like);
2237
                        } elseif (preg_match('/^(\w+) CONTAINS (.*)$/', $value, $match)) {
2238
                            // Don't unset this filter. This is just initial filtering for performance
2239
                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2240
                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
2241
                            $query->where('i_gedcom', 'LIKE', $like);
2242
                        }
2243
                    }
2244
                }
2245
2246
                $this->list = [];
2247
2248
                foreach ($query->get() as $row) {
2249
                    $this->list[$row->xref] = Registry::individualFactory()->make($row->xref, $this->tree, $row->gedcom);
2250
                }
2251
                break;
2252
2253
            case 'family':
2254
                $query = DB::table('families')
2255
                    ->where('f_file', '=', $this->tree->id())
2256
                    ->select(['f_id AS xref', 'f_gedcom AS gedcom'])
2257
                    ->distinct();
2258
2259
                foreach ($attrs as $attr => $value) {
2260
                    if (str_starts_with($attr, 'filter') && $value !== '') {
2261
                        $value = $this->substituteVars($value, false);
2262
                        // Convert the various filters into SQL
2263
                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
2264
                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2265
                                $join
2266
                                    ->on($attr . '.d_gid', '=', 'f_id')
2267
                                    ->on($attr . '.d_file', '=', 'f_file');
2268
                            });
2269
2270
                            $query->where($attr . '.d_fact', '=', $match[1]);
2271
2272
                            $date = new Date($match[3]);
2273
2274
                            if ($match[2] === 'LTE') {
2275
                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
2276
                            } else {
2277
                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
2278
                            }
2279
2280
                            // This filter has been fully processed
2281
                            unset($attrs[$attr]);
2282
                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
2283
                            // Convert newline escape sequences to actual new lines
2284
                            $match[1] = str_replace('\n', "\n", $match[1]);
2285
2286
                            $query->where('f_gedcom', 'LIKE', $match[1]);
2287
2288
                            // This filter has been fully processed
2289
                            unset($attrs[$attr]);
2290
                        } elseif (preg_match('/^NAME CONTAINS (.*)$/', $value, $match)) {
2291
                            if ($sortby === 'NAME' || $match[1] !== '') {
2292
                                $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2293
                                    $join
2294
                                        ->on($attr . '.n_file', '=', 'f_file')
2295
                                        ->where(static function (Builder $query): void {
2296
                                            $query
2297
                                                ->whereColumn('n_id', '=', 'f_husb')
2298
                                                ->orWhereColumn('n_id', '=', 'f_wife');
2299
                                        });
2300
                                });
2301
                                // Search the DB only if there is any name supplied
2302
                                if ($match[1] != '') {
2303
                                    $names = explode(' ', $match[1]);
2304
                                    foreach ($names as $name) {
2305
                                        $query->where($attr . '.n_full', 'LIKE', '%' . addcslashes($name, '\\%_') . '%');
2306
                                    }
2307
                                }
2308
                            }
2309
2310
                            // This filter has been fully processed
2311
                            unset($attrs[$attr]);
2312
                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
2313
                            // Don't unset this filter. This is just initial filtering for performance
2314
                            $query
2315
                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
2316
                                    $join
2317
                                        ->on($attr . 'a.pl_file', '=', 'f_file')
2318
                                        ->on($attr . 'a.pl_gid', '=', 'f_id');
2319
                                })
2320
                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
2321
                                    $join
2322
                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
2323
                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
2324
                                })
2325
                                ->where($attr . 'b.p_place', 'LIKE', '%' . addcslashes($match[1], '\\%_') . '%');
2326
                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
2327
                            // Don't unset this filter. This is just initial filtering for performance
2328
                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2329
                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
2330
                            $query->where('f_gedcom', 'LIKE', $like);
2331
                        } elseif (preg_match('/^(\w+) CONTAINS (.+)$/', $value, $match)) {
2332
                            // Don't unset this filter. This is just initial filtering for performance
2333
                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2334
                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
2335
                            $query->where('f_gedcom', 'LIKE', $like);
2336
                        }
2337
                    }
2338
                }
2339
2340
                $this->list = [];
2341
2342
                foreach ($query->get() as $row) {
2343
                    $this->list[$row->xref] = Registry::familyFactory()->make($row->xref, $this->tree, $row->gedcom);
2344
                }
2345
                break;
2346
2347
            default:
2348
                throw new DomainException('Invalid list name: ' . $listname);
2349
        }
2350
2351
        $filters  = [];
2352
        $filters2 = [];
2353
        if (isset($attrs['filter1']) && count($this->list) > 0) {
2354
            foreach ($attrs as $key => $value) {
2355
                if (preg_match("/filter(\d)/", $key)) {
2356
                    $condition = $value;
2357
                    if (preg_match("/@(\w+)/", $condition, $match)) {
2358
                        $id    = $match[1];
2359
                        $value = "''";
2360
                        if ($id === 'ID') {
2361
                            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
2362
                                $value = "'" . $match[1] . "'";
2363
                            }
2364
                        } elseif ($id === 'fact') {
2365
                            $value = "'" . $this->fact . "'";
2366
                        } elseif ($id === 'desc') {
2367
                            $value = "'" . $this->desc . "'";
2368
                        } else {
2369
                            if (preg_match("/\d $id (.+)/", $this->gedrec, $match)) {
2370
                                $value = "'" . str_replace('@', '', trim($match[1])) . "'";
2371
                            }
2372
                        }
2373
                        $condition = preg_replace("/@$id/", $value, $condition);
2374
                    }
2375
                    //-- handle regular expressions
2376
                    if (preg_match("/([A-Z:]+)\s*([^\s]+)\s*(.+)/", $condition, $match)) {
2377
                        $tag  = trim($match[1]);
2378
                        $expr = trim($match[2]);
2379
                        $val  = trim($match[3]);
2380
                        if (preg_match("/\\$(\w+)/", $val, $match)) {
2381
                            $val = $this->vars[$match[1]]['id'];
2382
                            $val = trim($val);
2383
                        }
2384
                        if ($val !== '') {
2385
                            $searchstr = '';
2386
                            $tags      = explode(':', $tag);
2387
                            //-- only limit to a level number if we are specifically looking at a level
2388
                            if (count($tags) > 1) {
2389
                                $level = 1;
2390
                                $t = 'XXXX';
2391
                                foreach ($tags as $t) {
2392
                                    if (!empty($searchstr)) {
2393
                                        $searchstr .= "[^\n]*(\n[2-9][^\n]*)*\n";
2394
                                    }
2395
                                    //-- search for both EMAIL and _EMAIL... silly double gedcom standard
2396
                                    if ($t === 'EMAIL' || $t === '_EMAIL') {
2397
                                        $t = '_?EMAIL';
2398
                                    }
2399
                                    $searchstr .= $level . ' ' . $t;
2400
                                    $level++;
2401
                                }
2402
                            } else {
2403
                                if ($tag === 'EMAIL' || $tag === '_EMAIL') {
2404
                                    $tag = '_?EMAIL';
2405
                                }
2406
                                $t         = $tag;
2407
                                $searchstr = '1 ' . $tag;
2408
                            }
2409
                            switch ($expr) {
2410
                                case 'CONTAINS':
2411
                                    if ($t === 'PLAC') {
2412
                                        $searchstr .= "[^\n]*[, ]*" . $val;
2413
                                    } else {
2414
                                        $searchstr .= "[^\n]*" . $val;
2415
                                    }
2416
                                    $filters[] = $searchstr;
2417
                                    break;
2418
                                default:
2419
                                    $filters2[] = [
2420
                                        'tag'  => $tag,
2421
                                        'expr' => $expr,
2422
                                        'val'  => $val,
2423
                                    ];
2424
                                    break;
2425
                            }
2426
                        }
2427
                    }
2428
                }
2429
            }
2430
        }
2431
        //-- apply other filters to the list that could not be added to the search string
2432
        if ($filters !== []) {
2433
            foreach ($this->list as $key => $record) {
2434
                foreach ($filters as $filter) {
2435
                    if (!preg_match('/' . $filter . '/i', $record->privatizeGedcom(Auth::accessLevel($this->tree)))) {
2436
                        unset($this->list[$key]);
2437
                        break;
2438
                    }
2439
                }
2440
            }
2441
        }
2442
        if ($filters2 !== []) {
2443
            $mylist = [];
2444
            foreach ($this->list as $indi) {
2445
                $key  = $indi->xref();
2446
                $grec = $indi->privatizeGedcom(Auth::accessLevel($this->tree));
2447
                $keep = true;
2448
                foreach ($filters2 as $filter) {
2449
                    if ($keep) {
2450
                        $tag  = $filter['tag'];
2451
                        $expr = $filter['expr'];
2452
                        $val  = $filter['val'];
2453
                        if ($val === "''") {
2454
                            $val = '';
2455
                        }
2456
                        $tags = explode(':', $tag);
2457
                        $t    = end($tags);
2458
                        $v    = $this->getGedcomValue($tag, 1, $grec);
2459
                        //-- check for EMAIL and _EMAIL (silly double gedcom standard :P)
2460
                        if ($t === 'EMAIL' && empty($v)) {
2461
                            $tag  = str_replace('EMAIL', '_EMAIL', $tag);
2462
                            $tags = explode(':', $tag);
2463
                            $t    = end($tags);
2464
                            $v    = self::getSubRecord(1, $tag, $grec);
2465
                        }
2466
2467
                        switch ($expr) {
2468
                            case 'GTE':
2469
                                if ($t === 'DATE') {
2470
                                    $date1 = new Date($v);
2471
                                    $date2 = new Date($val);
2472
                                    $keep  = (Date::compare($date1, $date2) >= 0);
2473
                                } elseif ($val >= $v) {
2474
                                    $keep = true;
2475
                                }
2476
                                break;
2477
                            case 'LTE':
2478
                                if ($t === 'DATE') {
2479
                                    $date1 = new Date($v);
2480
                                    $date2 = new Date($val);
2481
                                    $keep  = (Date::compare($date1, $date2) <= 0);
2482
                                } elseif ($val >= $v) {
2483
                                    $keep = true;
2484
                                }
2485
                                break;
2486
                            default:
2487
                                if ($v == $val) {
2488
                                    $keep = true;
2489
                                } else {
2490
                                    $keep = false;
2491
                                }
2492
                                break;
2493
                        }
2494
                    }
2495
                }
2496
                if ($keep) {
2497
                    $mylist[$key] = $indi;
2498
                }
2499
            }
2500
            $this->list = $mylist;
2501
        }
2502
2503
        switch ($sortby) {
2504
            case 'NAME':
2505
                uasort($this->list, GedcomRecord::nameComparator());
2506
                break;
2507
            case 'CHAN':
2508
                uasort($this->list, GedcomRecord::lastChangeComparator());
2509
                break;
2510
            case 'BIRT:DATE':
2511
                uasort($this->list, Individual::birthDateComparator());
2512
                break;
2513
            case 'DEAT:DATE':
2514
                uasort($this->list, Individual::deathDateComparator());
2515
                break;
2516
            case 'MARR:DATE':
2517
                uasort($this->list, Family::marriageDateComparator());
2518
                break;
2519
            default:
2520
                // unsorted or already sorted by SQL
2521
                break;
2522
        }
2523
2524
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2525
        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2526
    }
2527
2528
    /**
2529
     * Handle </list>
2530
     *
2531
     * @return void
2532
     */
2533
    protected function listEndHandler(): void
2534
    {
2535
        $this->process_repeats--;
2536
        if ($this->process_repeats > 0) {
2537
            return;
2538
        }
2539
2540
        // Check if there is any list
2541
        if (count($this->list) > 0) {
2542
            $lineoffset = 0;
2543
            foreach ($this->repeats_stack as $rep) {
2544
                $lineoffset += $rep[1] - 1;
2545
            }
2546
            //-- read the xml from the file
2547
            $lines = file($this->report);
2548
            while ((!str_contains($lines[$lineoffset + $this->repeat_bytes], '<List')) && (($lineoffset + $this->repeat_bytes) > 0)) {
2549
                $lineoffset--;
2550
            }
2551
            $lineoffset++;
2552
            $reportxml = "<tempdoc>\n";
2553
            $line_nr   = $lineoffset + $this->repeat_bytes;
2554
            // List Level counter
2555
            $count = 1;
2556
            while (0 < $count) {
2557
                if (str_contains($lines[$line_nr], '<List')) {
2558
                    $count++;
2559
                } elseif (str_contains($lines[$line_nr], '</List')) {
2560
                    $count--;
2561
                }
2562
                if (0 < $count) {
2563
                    $reportxml .= $lines[$line_nr];
2564
                }
2565
                $line_nr++;
2566
            }
2567
            // No need to drag this
2568
            unset($lines);
2569
            $reportxml .= '</tempdoc>';
2570
            // Save original values
2571
            $this->parser_stack[] = $this->parser;
2572
            $oldgedrec            = $this->gedrec;
2573
2574
            $this->list_total   = count($this->list);
2575
            $this->list_private = 0;
2576
            foreach ($this->list as $record) {
2577
                if ($record->canShow()) {
2578
                    $this->gedrec = $record->privatizeGedcom(Auth::accessLevel($record->tree()));
2579
                    //-- start the sax parser
2580
                    $repeat_parser = xml_parser_create();
2581
                    $this->parser  = $repeat_parser;
2582
                    xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
2583
2584
                    xml_set_element_handler(
2585
                        $repeat_parser,
2586
                        function ($parser, string $name, array $attrs): void {
2587
                            $this->startElement($parser, $name, $attrs);
2588
                        },
2589
                        function ($parser, string $name): void {
2590
                            $this->endElement($parser, $name);
2591
                        }
2592
                    );
2593
2594
                    xml_set_character_data_handler(
2595
                        $repeat_parser,
2596
                        function ($parser, string $data): void {
2597
                            $this->characterData($parser, $data);
2598
                        }
2599
                    );
2600
2601
                    if (!xml_parse($repeat_parser, $reportxml, true)) {
2602
                        throw new DomainException(sprintf(
2603
                            'ListEHandler XML error: %s at line %d',
2604
                            xml_error_string(xml_get_error_code($repeat_parser)),
2605
                            xml_get_current_line_number($repeat_parser)
2606
                        ));
2607
                    }
2608
                    xml_parser_free($repeat_parser);
2609
                } else {
2610
                    $this->list_private++;
2611
                }
2612
            }
2613
            $this->list   = [];
2614
            $this->parser = array_pop($this->parser_stack);
2615
            $this->gedrec = $oldgedrec;
2616
        }
2617
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2618
    }
2619
2620
    /**
2621
     * Handle <listTotal>
2622
     * Prints the total number of records in a list
2623
     * The total number is collected from <list> and <relatives>
2624
     *
2625
     * @return void
2626
     */
2627
    protected function listTotalStartHandler(): void
2628
    {
2629
        if ($this->list_private == 0) {
2630
            $this->current_element->addText((string) $this->list_total);
2631
        } else {
2632
            $this->current_element->addText(($this->list_total - $this->list_private) . ' / ' . $this->list_total);
2633
        }
2634
    }
2635
2636
    /**
2637
     * Handle <relatives>
2638
     *
2639
     * @param array<string> $attrs
2640
     *
2641
     * @return void
2642
     */
2643
    protected function relativesStartHandler(array $attrs): void
2644
    {
2645
        $this->process_repeats++;
2646
        if ($this->process_repeats > 1) {
2647
            return;
2648
        }
2649
2650
        $sortby = $attrs['sortby'] ?? 'NAME';
2651
2652
        $match = [];
2653
        if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2654
            $sortby = $this->vars[$match[1]]['id'];
2655
            $sortby = trim($sortby);
2656
        }
2657
2658
        $maxgen = -1;
2659
        if (isset($attrs['maxgen'])) {
2660
            $maxgen = (int) $attrs['maxgen'];
2661
        }
2662
2663
        $group = $attrs['group'] ?? 'child-family';
2664
2665
        if (preg_match("/\\$(\w+)/", $group, $match)) {
2666
            $group = $this->vars[$match[1]]['id'];
2667
            $group = trim($group);
2668
        }
2669
2670
        $id = $attrs['id'] ?? '';
2671
2672
        if (preg_match("/\\$(\w+)/", $id, $match)) {
2673
            $id = $this->vars[$match[1]]['id'];
2674
            $id = trim($id);
2675
        }
2676
2677
        $this->list = [];
2678
        $person     = Registry::individualFactory()->make($id, $this->tree);
2679
        if ($person instanceof Individual) {
2680
            $this->list[$id] = $person;
2681
            $this->mfrelation[$id] = "";
2682
            $nam = $person->getAllNames()[0]['fullNN'];
0 ignored issues
show
Unused Code introduced by
The assignment to $nam is dead and can be removed.
Loading history...
2683
            switch ($group) {
2684
                case 'child-family':
2685
                    foreach ($person->childFamilies() as $family) {
2686
                        foreach ($family->spouses() as $spouse) {
2687
                            $this->list[$spouse->xref()] = $spouse;
2688
                        }
2689
2690
                        foreach ($family->children() as $child) {
2691
                            $this->list[$child->xref()] = $child;
2692
                        }
2693
                    }
2694
                    break;
2695
                case 'spouse-family':
2696
                    foreach ($person->spouseFamilies() as $family) {
2697
                        foreach ($family->spouses() as $spouse) {
2698
                            $this->list[$spouse->xref()] = $spouse;
2699
                        }
2700
2701
                        foreach ($family->children() as $child) {
2702
                            $this->list[$child->xref()] = $child;
2703
                        }
2704
                    }
2705
                    break;
2706
                case 'direct-ancestors':
2707
                    $this->addAncestors($this->list, $id, false, $maxgen);
2708
                    break;
2709
                case 'ancestors':
2710
                    $this->addAncestors($this->list, $id, true, $maxgen);
2711
                    break;
2712
                case 'descendants':
2713
                    $this->list[$id]->generation = 1;
2714
                    $this->addDescendancy($this->list, $id, false, $maxgen);
2715
                    break;
2716
                case 'all':
2717
                    $this->addAncestors($this->list, $id, true, $maxgen);
2718
                    $this->addDescendancy($this->list, $id, true, $maxgen);
2719
                    break;
2720
            }
2721
        }
2722
2723
        switch ($sortby) {
2724
            case 'NAME':
2725
                uasort($this->list, GedcomRecord::nameComparator());
2726
                break;
2727
            case 'BIRT:DATE':
2728
                uasort($this->list, Individual::birthDateComparator());
2729
                break;
2730
            case 'DEAT:DATE':
2731
                uasort($this->list, Individual::deathDateComparator());
2732
                break;
2733
            case 'generation':
2734
                $newarray = [];
2735
                reset($this->list);
2736
                $genCounter = 1;
2737
                while (count($newarray) < count($this->list)) {
2738
                    foreach ($this->list as $key => $value) {
2739
                        if ($value->generation < 0) { // indication of husband or wife
2740
                            $this->generation = -$value->generation;
2741
                        }
2742
                        else {
2743
                            $this->generation = $value->generation;
2744
                        }
2745
                        if ($this->generation == $genCounter) {
2746
                            $newarray[$key] = (object) ['generation' => $this->generation];
2747
                        }
2748
                    }
2749
                    $genCounter++;
2750
                }
2751
                $this->list = $newarray;
2752
                break;
2753
            default:
2754
                // unsorted
2755
                break;
2756
        }
2757
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2758
        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2759
    }
2760
2761
    /**
2762
     * Handle </relatives>
2763
     *
2764
     * @return void
2765
     */
2766
    protected function relativesEndHandler(): void
2767
    {
2768
        $this->process_repeats--;
2769
        if ($this->process_repeats > 0) {
2770
            return;
2771
        }
2772
2773
        // Check if there is any relatives
2774
        if (count($this->list) > 0) {
2775
            $lineoffset = 0;
2776
            foreach ($this->repeats_stack as $rep) {
2777
                $lineoffset += $rep[1] - 1;
2778
            }
2779
            //-- read the xml from the file
2780
            $lines = file($this->report);
2781
            while (!str_contains($lines[$lineoffset + $this->repeat_bytes], '<Relatives') && $lineoffset + $this->repeat_bytes > 0) {
2782
                $lineoffset--;
2783
            }
2784
            $lineoffset++;
2785
            $reportxml = "<tempdoc>\n";
2786
            $line_nr   = $lineoffset + $this->repeat_bytes;
2787
            // Relatives Level counter
2788
            $count = 1;
2789
            while (0 < $count) {
2790
                if (str_contains($lines[$line_nr], '<Relatives')) {
2791
                    $count++;
2792
                } elseif (str_contains($lines[$line_nr], '</Relatives')) {
2793
                    $count--;
2794
                }
2795
                if (0 < $count) {
2796
                    $reportxml .= $lines[$line_nr];
2797
                }
2798
                $line_nr++;
2799
            }
2800
            // No need to drag this
2801
            unset($lines);
2802
            $reportxml .= "</tempdoc>\n";
2803
            // Save original values
2804
            $this->parser_stack[] = $this->parser;
2805
            $oldgedrec            = $this->gedrec;
2806
2807
            $this->list_total   = count($this->list);
2808
            $this->list_private = 0;
2809
            foreach ($this->list as $key => $value) {
2810
                if (isset($value->generation)) {
2811
                    $this->generation = $value->generation;
2812
                }
2813
                $xref = $key;
2814
                $this->vars["dupl"]["id"] = "no";
2815
                if (substr($key, 0, 2) == "D_") {
2816
                    $xref = substr($key, strrpos($key, "_") + 1);
2817
                    $this->vars["dupl"]["id"] = "yes";
2818
                }
2819
                $tmp          = Registry::gedcomRecordFactory()->make((string) $xref, $this->tree);
2820
                $this->gedrec = $tmp->privatizeGedcom(Auth::accessLevel($this->tree));
2821
2822
                $repeat_parser = xml_parser_create();
2823
                $this->parser  = $repeat_parser;
2824
                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
2825
2826
                xml_set_element_handler(
2827
                    $repeat_parser,
2828
                    function ($parser, string $name, array $attrs): void {
2829
                        $this->startElement($parser, $name, $attrs);
2830
                    },
2831
                    function ($parser, string $name): void {
2832
                        $this->endElement($parser, $name);
2833
                    }
2834
                );
2835
2836
                xml_set_character_data_handler(
2837
                    $repeat_parser,
2838
                    function ($parser, string $data): void {
2839
                        $this->characterData($parser, $data);
2840
                    }
2841
                );
2842
2843
                if (!xml_parse($repeat_parser, $reportxml, true)) {
2844
                    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)));
2845
                }
2846
                xml_parser_free($repeat_parser);
2847
            }
2848
            // Clean up the list array
2849
            $this->list   = [];
2850
            $this->parser = array_pop($this->parser_stack);
2851
            $this->gedrec = $oldgedrec;
2852
        }
2853
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2854
    }
2855
2856
    /**
2857
     * Handle <generation />
2858
     * Prints the number of generations
2859
     *
2860
     * @return void
2861
     */
2862
    protected function generationStartHandler(): void
2863
    {
2864
        $this->current_element->addText((string) $this->generation);
2865
    }
2866
2867
    /**
2868
     * Handle <newPage />
2869
     * Has to be placed in an element (header, body or footer)
2870
     *
2871
     * @return void
2872
     */
2873
    protected function newPageStartHandler(): void
2874
    {
2875
        $temp = 'addpage';
2876
        $this->wt_report->addElement($temp);
2877
    }
2878
2879
    /**
2880
     * Handle </title>
2881
     *
2882
     * @return void
2883
     */
2884
    protected function titleEndHandler(): void
2885
    {
2886
        $this->report_root->addTitle($this->text);
2887
    }
2888
2889
    /**
2890
     * Handle </description>
2891
     *
2892
     * @return void
2893
     */
2894
    protected function descriptionEndHandler(): void
2895
    {
2896
        $this->report_root->addDescription($this->text);
2897
    }
2898
2899
    /**
2900
     * Create a list of all descendants.
2901
     *
2902
     * @param array<Individual> $list
2903
     * @param string            $pid
2904
     * @param bool              $parents
2905
     * @param int               $generations
2906
     *
2907
     * @return void
2908
     */
2909
    private function addDescendancy(&$list, $pid, $parents = false, $generations = -1): void
2910
    {
2911
        $person = Registry::individualFactory()->make($pid, $this->tree);
2912
        if ($person === null) {
2913
            return;
2914
        }
2915
2916
        static $focusperson = true;
2917
        static $dupl = 1;
2918
        $sx = $person->sex();
2919
        $rl = "x"; // unknown
2920
        if ($sx == "M") {
2921
            $rl = "s";
2922
        } // son
2923
        if ($sx == "F") {
2924
            $rl = "d";
0 ignored issues
show
Unused Code introduced by
The assignment to $rl is dead and can be removed.
Loading history...
2925
        } // daughter
2926
        if ($focusperson) {
2927
            $this->mfrelation[$pid] = "";
2928
        }
2929
        $nam = $person->getAllNames()[0]['fullNN'];
0 ignored issues
show
Unused Code introduced by
The assignment to $nam is dead and can be removed.
Loading history...
2930
2931
        $newpid = $pid;
2932
        if (!isset($list[$pid])) {
2933
            $list[$pid] = $person;
2934
        } elseif (!$focusperson) {
2935
            $newpid = "D_" . $dupl . "_" . $pid;
2936
            $list[$newpid] = $person;
2937
        }
2938
        if (!isset($list[$newpid]->generation)) {
2939
            $list[$newpid]->generation = 0;
2940
        }
2941
        $focusperson = false;
2942
        foreach ($person->spouseFamilies() as $family) {
2943
            if ($parents) {
2944
                $husband = $family->husband();
2945
                $wife    = $family->wife();
2946
                if ($husband) {
2947
                    $list[$husband->xref()] = $husband;
2948
                    if (isset($list[$pid]->generation)) {
2949
                        $list[$husband->xref()]->generation = $list[$pid]->generation - 1;
2950
                    } else {
2951
                        $list[$husband->xref()]->generation = 1;
2952
                    }
2953
                }
2954
                if ($wife) {
2955
                    $list[$wife->xref()] = $wife;
2956
                    if (isset($list[$pid]->generation)) {
2957
                        $list[$wife->xref()]->generation = $list[$pid]->generation - 1;
2958
                    } else {
2959
                        $list[$wife->xref()]->generation = 1;
2960
                    }
2961
                }
2962
            }
2963
            $husband = $family->husband();
2964
            $wife = $family->wife();
2965
2966
            if ($husband && $wife) {
2967
                if ($husband->xref() == $person->xref()) {
2968
                    $this->mfrelation[$wife->xref()] = $this->mfrelation[$person->xref()] . "x";
2969
                    if ($wife->canShow()) {
2970
                        $list[$wife->xref()] = $wife;
2971
                    }
2972
                    if (!isset($wife->generation)) {
2973
                        $wife->generation = $person->generation;
2974
                    }
2975
                    $nam = $wife->getAllNames()[0]['fullNN'];
2976
                } else {
2977
                    $this->mfrelation[$husband->xref()] = $this->mfrelation[$person->xref()] . "x";
2978
                    if ($husband->canShow()) {
2979
                        $list[$husband->xref()] = $husband;
2980
                    }
2981
                    if (!isset($husband->generation)) {
2982
                        $husband->generation = $person->generation;
2983
                    }
2984
                    $nam = $husband->getAllNames()[0]['fullNN'];
2985
                }
2986
            }
2987
2988
            $children = $family->children();
2989
            foreach ($children as $child) {
2990
                if ($child) {
2991
                    $sx = $child->sex();
2992
                    $rl = "x"; // unknown
2993
                    if ($sx == "M") {
2994
                        $rl = "s";
2995
                    } // son
2996
                    if ($sx == "F") {
2997
                        $rl = "d";
2998
                    } // daughter
2999
                    $rl = $this->mfrelation[$person->xref()] . $rl;
3000
                    $this->mfrelation[$child->xref()] = $rl;
3001
                    if (isset($list[$pid]->generation)) {
3002
                        $child->generation = $list[$pid]->generation + 1;
3003
                    } else {
3004
                        $child->generation = 2;
3005
                    }
3006
                }
3007
            }
3008
            if ($generations == -1 || $list[$pid]->generation < $generations) {
3009
                foreach ($children as $child) {
3010
                    if ($child->canShow()) {
3011
                        $this->addDescendancy($list, $child->xref(), $parents, $generations);
3012
                    } // recurse on the childs family
3013
                }
3014
            }
3015
        }
3016
        $focusperson = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $focusperson is dead and can be removed.
Loading history...
3017
    }
3018
3019
    /**
3020
     * Create a list of all ancestors.
3021
     *
3022
     * @param array<Individual> $list
3023
     * @param string            $pid
3024
     * @param bool              $children
3025
     * @param int               $generations
3026
     *
3027
     * @return void
3028
     */
3029
    private function addAncestors(array &$list, string $pid, bool $children = false, int $generations = -1): void
3030
    {
3031
        $genlist                = [$pid];
3032
        $list[$pid]->generation = 1;
3033
        while (count($genlist) > 0) {
3034
            $id = array_shift($genlist);
3035
            if (str_starts_with($id, 'empty')) {
3036
                continue; // id can be something like “empty7”
3037
            }
3038
            if (!isset($this->mfrelation[$id])) {
3039
                $this->mfrelation[$id] = "";
3040
            }
3041
            $person = Registry::individualFactory()->make($id, $this->tree);
3042
            foreach ($person->childFamilies() as $family) {
3043
                $husband = $family->husband();
3044
                $wife    = $family->wife();
3045
                if ($husband) {
3046
                    $list[$husband->xref()]             = $husband;
3047
                    $list[$husband->xref()]->generation = $list[$id]->generation + 1;
3048
                    $this->mfrelation[$husband->xref()] = $this->mfrelation[$id] . "f";
3049
                }
3050
                if ($wife) {
3051
                    $list[$wife->xref()]             = $wife;
3052
                    $list[$wife->xref()]->generation = $list[$id]->generation + 1;
3053
                    $this->mfrelation[$wife->xref()] = $this->mfrelation[$id] . "m";
3054
                }
3055
                if ($generations == -1 || $list[$id]->generation + 1 < $generations) {
3056
                    if ($husband) {
3057
                        $genlist[] = $husband->xref();
3058
                    }
3059
                    if ($wife) {
3060
                        $genlist[] = $wife->xref();
3061
                    }
3062
                }
3063
                if ($children) {
3064
                    foreach ($family->children() as $child) {
3065
                        $list[$child->xref()] = $child;
3066
                        $child->generation = $list[$id]->generation ?? 1;
3067
                        if ($child->xref() != $person->xref()) {
3068
                            $this->mfrelation[$child->xref()] = $this->mfrelation[$id] . "x";
3069
                        }
3070
                    }
3071
                }
3072
            }
3073
        }
3074
    }
3075
3076
    /**
3077
     * get gedcom tag value
3078
     *
3079
     * @param string $tag    The tag to find, use : to delineate subtags
3080
     * @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
3081
     * @param string $gedrec The gedcom record to get the value from
3082
     *
3083
     * @return string the value of a gedcom tag from the given gedcom record
3084
     */
3085
    private function getGedcomValue(string $tag, int $level, string $gedrec): string
3086
    {
3087
        if ($gedrec === '') {
3088
            return '';
3089
        }
3090
        $tags      = explode(':', $tag);
3091
        $origlevel = $level;
3092
        if ($level === 0) {
3093
            $level = $gedrec[0] + 1;
3094
        }
3095
3096
        $subrec = $gedrec;
3097
        $t = 'XXXX';
3098
        foreach ($tags as $t) {
3099
            $lastsubrec = $subrec;
3100
            $subrec     = self::getSubRecord($level, "$level $t", $subrec);
3101
            if (empty($subrec) && $origlevel == 0) {
3102
                $level--;
3103
                $subrec = self::getSubRecord($level, "$level $t", $lastsubrec);
3104
            }
3105
            if (empty($subrec)) {
3106
                if ($t === 'TITL') {
3107
                    $subrec = self::getSubRecord($level, "$level ABBR", $lastsubrec);
3108
                    if (!empty($subrec)) {
3109
                        $t = 'ABBR';
3110
                    }
3111
                }
3112
                if ($subrec === '') {
3113
                    if ($level > 0) {
3114
                        $level--;
3115
                    }
3116
                    $subrec = self::getSubRecord($level, "@ $t", $gedrec);
3117
                    if ($subrec === '') {
3118
                        return '';
3119
                    }
3120
                }
3121
            }
3122
            $level++;
3123
        }
3124
        $level--;
3125
        $ct = preg_match("/$level $t(.*)/", $subrec, $match);
3126
        if ($ct === 0) {
3127
            $ct = preg_match("/$level @.+@ (.+)/", $subrec, $match);
3128
        }
3129
        if ($ct === 0) {
3130
            $ct = preg_match("/@ $t (.+)/", $subrec, $match);
3131
        }
3132
        if ($ct > 0) {
3133
            $value = trim($match[1]);
3134
            if ($t === 'NOTE' && preg_match('/^@(.+)@$/', $value, $match)) {
3135
                $note = Registry::noteFactory()->make($match[1], $this->tree);
3136
                if ($note instanceof Note) {
3137
                    $value = $note->getNote();
3138
                } else {
3139
                    //-- set the value to the id without the @
3140
                    $value = $match[1];
3141
                }
3142
            }
3143
            if ($level !== 0 || $t !== 'NOTE') {
3144
                $value .= self::getCont($level + 1, $subrec);
3145
            }
3146
3147
            if ($tag === 'NAME' || $tag === '_MARNM' || $tag === '_AKA') {
3148
                return strtr($value, ['/' => '']);
3149
            }
3150
3151
            if ($tag === 'NAME' || $tag === '_MARNM' || $tag === '_AKA') {
3152
                return strtr($value, ['/' => '']);
3153
            }
3154
3155
            return $value;
3156
        }
3157
3158
        return '';
3159
    }
3160
3161
    /**
3162
     * Replace variable identifiers with their values.
3163
     *
3164
     * @param string $expression An expression such as "$foo == 123"
3165
     * @param bool   $quote      Whether to add quotation marks
3166
     *
3167
     * @return string
3168
     */
3169
    private function substituteVars($expression, $quote): string
3170
    {
3171
        return preg_replace_callback(
3172
            '/\$(\w+)/',
3173
            function (array $matches) use ($quote): string {
3174
                if (isset($this->vars[$matches[1]]['id'])) {
3175
                    if ($quote) {
3176
                        return "'" . addcslashes($this->vars[$matches[1]]['id'], "'") . "'";
3177
                    }
3178
3179
                    return $this->vars[$matches[1]]['id'];
3180
                }
3181
3182
                Log::addErrorLog(sprintf('Undefined variable $%s in report', $matches[1]));
3183
3184
                return '$' . $matches[1];
3185
            },
3186
            $expression
3187
        );
3188
    }
3189
}
3190