Passed
Pull Request — main (#4945)
by
unknown
08:24
created

ReportParserGenerate::factsStartHandler()   F

Complexity

Conditions 38
Paths > 20000

Size

Total Lines 139
Code Lines 94

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 38
eloc 94
c 5
b 0
f 0
nc 1965601
nop 1
dl 0
loc 139
rs 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
    /** @var array<string> Family relationship */
186
    private array $mfrelation = [];
187
188
    private Tree $tree;
189
190
    /**
191
     * Create a parser for a report
192
     *
193
     * @param string               $report The XML filename
194
     * @param AbstractRenderer     $report_root
195
     * @param array<array<string>> $vars
196
     * @param Tree                 $tree
197
     */
198
    public function __construct(string $report, AbstractRenderer $report_root, array $vars, Tree $tree)
199
    {
200
        $this->report          = $report;
201
        $this->report_root     = $report_root;
202
        $this->wt_report       = $report_root;
203
        $this->current_element = new ReportBaseElement();
204
        $this->vars            = $vars;
205
        $this->tree            = $tree;
206
207
        parent::__construct($report);
208
    }
209
210
    /**
211
     * get a gedcom subrecord
212
     *
213
     * searches a gedcom record and returns a subrecord of it. A subrecord is defined starting at a
214
     * line with level N and all subsequent lines greater than N until the next N level is reached.
215
     * For example, the following is a BIRT subrecord:
216
     * <code>1 BIRT
217
     * 2 DATE 1 JAN 1900
218
     * 2 PLAC Phoenix, Maricopa, Arizona</code>
219
     * The following example is the DATE subrecord of the above BIRT subrecord:
220
     * <code>2 DATE 1 JAN 1900</code>
221
     *
222
     * @param int    $level   the N level of the subrecord to get
223
     * @param string $tag     a gedcom tag or string to search for in the record (ie 1 BIRT or 2 DATE)
224
     * @param string $gedrec  the parent gedcom record to search in
225
     * @param int    $num     this allows you to specify which matching <var>$tag</var> to get. Oftentimes a
226
     *                        gedcom record will have more that 1 of the same type of subrecord. An individual may have
227
     *                        multiple events for example. Passing $num=1 would get the first 1. Passing $num=2 would get the
228
     *                        second one, etc.
229
     *
230
     * @return string the subrecord that was found or an empty string "" if not found.
231
     */
232
    public static function getSubRecord(int $level, string $tag, string $gedrec, int $num = 1): string
233
    {
234
        if ($gedrec === '') {
235
            return '';
236
        }
237
        // -- adding \n before and after gedrec
238
        $gedrec       = "\n" . $gedrec . "\n";
239
        $tag          = trim($tag);
240
        $searchTarget = "~[\n]" . $tag . "[\s]~";
241
        $ct           = preg_match_all($searchTarget, $gedrec, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
242
        if ($ct === 0) {
243
            return '';
244
        }
245
        if ($ct < $num) {
246
            return '';
247
        }
248
        $pos1 = $match[$num - 1][0][1];
249
        $pos2 = strpos($gedrec, "\n$level", $pos1 + 1);
250
        if (!$pos2) {
251
            $pos2 = strpos($gedrec, "\n1", $pos1 + 1);
252
        }
253
        if (!$pos2) {
254
            $pos2 = strpos($gedrec, "\nWT_", $pos1 + 1); // WT_SPOUSE, WT_FAMILY_ID ...
255
        }
256
        if (!$pos2) {
257
            return ltrim(substr($gedrec, $pos1));
258
        }
259
        $subrec = substr($gedrec, $pos1, $pos2 - $pos1);
260
261
        return ltrim($subrec);
262
    }
263
264
    /**
265
     * get CONT lines
266
     *
267
     * get the N+1 CONT or CONC lines of a gedcom subrecord
268
     *
269
     * @param int    $nlevel the level of the CONT lines to get
270
     * @param string $nrec   the gedcom subrecord to search in
271
     *
272
     * @return string a string with all CONT lines merged
273
     */
274
    public static function getCont(int $nlevel, string $nrec): string
275
    {
276
        $text = '';
277
278
        $subrecords = explode("\n", $nrec);
279
        foreach ($subrecords as $thisSubrecord) {
280
            if (substr($thisSubrecord, 0, 2) !== $nlevel . ' ') {
281
                continue;
282
            }
283
            $subrecordType = substr($thisSubrecord, 2, 4);
284
            if ($subrecordType === 'CONT') {
285
                $text .= "\n" . substr($thisSubrecord, 7);
286
            }
287
        }
288
289
        return $text;
290
    }
291
292
    /**
293
     * XML start element handler
294
     * This function is called whenever a starting element is reached
295
     * The element handler will be called if found, otherwise it must be HTML
296
     *
297
     * @param resource      $parser the resource handler for the XML parser
298
     * @param string        $name   the name of the XML element parsed
299
     * @param array<string> $attrs  an array of key value pairs for the attributes
300
     *
301
     * @return void
302
     */
303
    protected function startElement($parser, string $name, array $attrs): void
304
    {
305
        $newattrs = [];
306
307
        foreach ($attrs as $key => $value) {
308
            if (preg_match("/^\\$(\w+)$/", $value, $match)) {
309
                if (isset($this->vars[$match[1]]['id']) && !isset($this->vars[$match[1]]['gedcom'])) {
310
                    $value = $this->vars[$match[1]]['id'];
311
                }
312
            }
313
            $newattrs[$key] = $value;
314
        }
315
        $attrs = $newattrs;
316
        if ($this->process_footnote && ($this->process_ifs === 0 || $name === 'if') && ($this->process_gedcoms === 0 || $name === 'Gedcom') && ($this->process_repeats === 0 || $name === 'Facts' || $name === 'RepeatTag')) {
317
            $method = $name . 'StartHandler';
318
319
            if (method_exists($this, $method)) {
320
                $this->{$method}($attrs);
321
            }
322
        }
323
    }
324
325
    /**
326
     * XML end element handler
327
     * This function is called whenever an ending element is reached
328
     * The element handler will be called if found, otherwise it must be HTML
329
     *
330
     * @param resource $parser the resource handler for the XML parser
331
     * @param string   $name   the name of the XML element parsed
332
     *
333
     * @return void
334
     */
335
    protected function endElement($parser, string $name): void
336
    {
337
        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')) {
338
            $method = $name . 'EndHandler';
339
340
            if (method_exists($this, $method)) {
341
                $this->{$method}();
342
            }
343
        }
344
    }
345
346
    /**
347
     * XML character data handler
348
     *
349
     * @param resource $parser the resource handler for the XML parser
350
     * @param string   $data   the name of the XML element parsed
351
     *
352
     * @return void
353
     */
354
    protected function characterData($parser, string $data): void
355
    {
356
        if ($this->print_data && $this->process_gedcoms === 0 && $this->process_ifs === 0 && $this->process_repeats === 0) {
357
            $this->current_element->addText($data);
358
        }
359
    }
360
361
    /**
362
     * Handle <style>
363
     *
364
     * @param array<string> $attrs
365
     *
366
     * @return void
367
     */
368
    protected function styleStartHandler(array $attrs): void
369
    {
370
        if (empty($attrs['name'])) {
371
            throw new DomainException('REPORT ERROR Style: The "name" of the style is missing or not set in the XML file.');
372
        }
373
374
        $style = [
375
            'name'  => $attrs['name'],
376
            'font'  => $attrs['font'] ?? $this->wt_report->default_font,
377
            'size'  => (float) ($attrs['size'] ?? $this->wt_report->default_font_size),
378
            'style' => $attrs['style'] ?? '',
379
        ];
380
381
        $this->wt_report->addStyle($style);
382
    }
383
384
    /**
385
     * Handle <doc>
386
     * Sets up the basics of the document proparties
387
     *
388
     * @param array<string> $attrs
389
     *
390
     * @return void
391
     */
392
    protected function docStartHandler(array $attrs): void
393
    {
394
        $this->parser = $this->xml_parser;
395
396
        // Custom page width
397
        if (!empty($attrs['customwidth'])) {
398
            $this->wt_report->page_width = (float) $attrs['customwidth'];
399
        }
400
        // Custom Page height
401
        if (!empty($attrs['customheight'])) {
402
            $this->wt_report->page_height = (float) $attrs['customheight'];
403
        }
404
405
        // Left Margin
406
        if (isset($attrs['leftmargin'])) {
407
            if ($attrs['leftmargin'] === '0') {
408
                $this->wt_report->left_margin = 0;
409
            } elseif (!empty($attrs['leftmargin'])) {
410
                $this->wt_report->left_margin = (float) $attrs['leftmargin'];
411
            }
412
        }
413
        // Right Margin
414
        if (isset($attrs['rightmargin'])) {
415
            if ($attrs['rightmargin'] === '0') {
416
                $this->wt_report->right_margin = 0;
417
            } elseif (!empty($attrs['rightmargin'])) {
418
                $this->wt_report->right_margin = (float) $attrs['rightmargin'];
419
            }
420
        }
421
        // Top Margin
422
        if (isset($attrs['topmargin'])) {
423
            if ($attrs['topmargin'] === '0') {
424
                $this->wt_report->top_margin = 0;
425
            } elseif (!empty($attrs['topmargin'])) {
426
                $this->wt_report->top_margin = (float) $attrs['topmargin'];
427
            }
428
        }
429
        // Bottom Margin
430
        if (isset($attrs['bottommargin'])) {
431
            if ($attrs['bottommargin'] === '0') {
432
                $this->wt_report->bottom_margin = 0;
433
            } elseif (!empty($attrs['bottommargin'])) {
434
                $this->wt_report->bottom_margin = (float) $attrs['bottommargin'];
435
            }
436
        }
437
        // Header Margin
438
        if (isset($attrs['headermargin'])) {
439
            if ($attrs['headermargin'] === '0') {
440
                $this->wt_report->header_margin = 0;
441
            } elseif (!empty($attrs['headermargin'])) {
442
                $this->wt_report->header_margin = (float) $attrs['headermargin'];
443
            }
444
        }
445
        // Footer Margin
446
        if (isset($attrs['footermargin'])) {
447
            if ($attrs['footermargin'] === '0') {
448
                $this->wt_report->footer_margin = 0;
449
            } elseif (!empty($attrs['footermargin'])) {
450
                $this->wt_report->footer_margin = (float) $attrs['footermargin'];
451
            }
452
        }
453
454
        // Page Orientation
455
        if (!empty($attrs['orientation'])) {
456
            if ($attrs['orientation'] === 'landscape') {
457
                $this->wt_report->orientation = 'landscape';
458
            } elseif ($attrs['orientation'] === 'portrait') {
459
                $this->wt_report->orientation = 'portrait';
460
            }
461
        }
462
        // Page Size
463
        if (!empty($attrs['pageSize'])) {
464
            $this->wt_report->page_format = $attrs['pageSize'];
465
        }
466
467
        // Show Generated By...
468
        if (isset($attrs['showGeneratedBy'])) {
469
            if ($attrs['showGeneratedBy'] === '0') {
470
                $this->wt_report->show_generated_by = false;
471
            } elseif ($attrs['showGeneratedBy'] === '1') {
472
                $this->wt_report->show_generated_by = true;
473
            }
474
        }
475
476
        $this->wt_report->setup();
477
    }
478
479
    /**
480
     * Handle </doc>
481
     *
482
     * @return void
483
     */
484
    protected function docEndHandler(): void
485
    {
486
        $this->wt_report->run();
487
    }
488
489
    /**
490
     * Handle <header>
491
     *
492
     * @return void
493
     */
494
    protected function headerStartHandler(): void
495
    {
496
        // Clear the Header before any new elements are added
497
        $this->wt_report->clearHeader();
498
        $this->wt_report->setProcessing('H');
499
    }
500
501
    /**
502
     * Handle <body>
503
     *
504
     * @return void
505
     */
506
    protected function bodyStartHandler(): void
507
    {
508
        $this->wt_report->setProcessing('B');
509
    }
510
511
    /**
512
     * Handle <footer>
513
     *
514
     * @return void
515
     */
516
    protected function footerStartHandler(): void
517
    {
518
        $this->wt_report->setProcessing('F');
519
    }
520
521
    /**
522
     * Handle <cell>
523
     *
524
     * @param array<string,string> $attrs
525
     *
526
     * @return void
527
     */
528
    protected function cellStartHandler(array $attrs): void
529
    {
530
        // string The text alignment of the text in this box.
531
        $align = $attrs['align'] ?? '';
532
        // RTL supported left/right alignment
533
        if ($align === 'rightrtl') {
534
            if ($this->wt_report->rtl) {
535
                $align = 'left';
536
            } else {
537
                $align = 'right';
538
            }
539
        } elseif ($align === 'leftrtl') {
540
            if ($this->wt_report->rtl) {
541
                $align = 'right';
542
            } else {
543
                $align = 'left';
544
            }
545
        }
546
547
        // The color to fill the background of this cell
548
        $bgcolor = $attrs['bgcolor'] ?? '';
549
550
        // Whether the background should be painted
551
        $fill = (bool) ($attrs['fill'] ?? '0');
552
553
        // If true reset the last cell height
554
        $reseth = (bool) ($attrs['reseth'] ?? '1');
555
556
        // Whether a border should be printed around this box
557
        $border = $attrs['border'] ?? '';
558
559
        // string Border color in HTML code
560
        $bocolor = $attrs['bocolor'] ?? '';
561
562
        // Cell height (expressed in points) The starting height of this cell. If the text wraps the height will automatically be adjusted.
563
        $height = (int) ($attrs['height'] ?? '0');
564
565
        // int Cell width (expressed in points) Setting the width to 0 will make it the width from the current location to the right margin.
566
        $width = (int) ($attrs['width'] ?? '0');
567
568
        // Stretch character mode
569
        $stretch = (int) ($attrs['stretch'] ?? '0');
570
571
        // mixed Position the left corner of this box on the page. The default is the current position.
572
        $left = ReportBaseElement::CURRENT_POSITION;
573
        if (isset($attrs['left'])) {
574
            if ($attrs['left'] === '.') {
575
                $left = ReportBaseElement::CURRENT_POSITION;
576
            } elseif (!empty($attrs['left'])) {
577
                $left = (float) $attrs['left'];
578
            } elseif ($attrs['left'] === '0') {
579
                $left = 0.0;
580
            }
581
        }
582
        // mixed Position the top corner of this box on the page. the default is the current position
583
        $top = ReportBaseElement::CURRENT_POSITION;
584
        if (isset($attrs['top'])) {
585
            if ($attrs['top'] === '.') {
586
                $top = ReportBaseElement::CURRENT_POSITION;
587
            } elseif (!empty($attrs['top'])) {
588
                $top = (float) $attrs['top'];
589
            } elseif ($attrs['top'] === '0') {
590
                $top = 0.0;
591
            }
592
        }
593
594
        // The name of the Style that should be used to render the text.
595
        $style = $attrs['style'] ?? '';
596
597
        // string Text color in html code
598
        $tcolor = $attrs['tcolor'] ?? '';
599
600
        // int Indicates where the current position should go after the call.
601
        $ln = 0;
602
        if (isset($attrs['newline'])) {
603
            if (!empty($attrs['newline'])) {
604
                $ln = (int) $attrs['newline'];
605
            } elseif ($attrs['newline'] === '0') {
606
                $ln = 0;
607
            }
608
        }
609
610
        if ($align === 'left') {
611
            $align = 'L';
612
        } elseif ($align === 'right') {
613
            $align = 'R';
614
        } elseif ($align === 'center') {
615
            $align = 'C';
616
        } elseif ($align === 'justify') {
617
            $align = 'J';
618
        }
619
620
        $this->print_data_stack[] = $this->print_data;
621
        $this->print_data         = true;
622
623
        $this->current_element = $this->report_root->createCell(
624
            (int) $width,
625
            (int) $height,
626
            $border,
627
            $align,
628
            $bgcolor,
629
            $style,
630
            $ln,
631
            $top,
632
            $left,
633
            $fill,
634
            $stretch,
635
            $bocolor,
636
            $tcolor,
637
            $reseth
638
        );
639
640
        // set string URL to be a link
641
        if (isset($attrs['url'])) {
642
            $url = $attrs['url'];
643
            $this->current_element->setUrl($url);
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
                $ix1 = strpos($name, '<span class="starredname">');
1031
                if ($ix1 !== false) {   // '«' and '»' mark text for underlining
1032
                    $name = substr_replace($name, '«', $ix1, 26);
1033
                    $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

1033
                    $ix1 = strpos(/** @scrutinizer ignore-type */ $name, '</span>', $ix1);
Loading history...
1034
                    if ($ix1 !== false) {   // '«' and '»' mark text for underlining
1035
                        $name = substr_replace($name, '»', $ix1, 7);
1036
                    }
1037
                }
1038
                $addname = strip_tags((string) $tmp[0]['surn']);
1039
                if (!empty($addname) && !($addname === '@N.N.') && !str_contains($name, $addname)) {
1040
                    $name .= " " . I18N::translate('b.') . " " . $addname;
1041
                }
1042
                $this->current_element->addText(trim($name));
1043
            } else {
1044
                $name = $record->fullName();
1045
                $name = strip_tags($name);
1046
                if (!empty($attrs['truncate'])) {
1047
                    if ((int) $attrs['truncate'] > 0) {
1048
                        $name = Str::limit($name, (int) $attrs['truncate'], I18N::translate('…'));
1049
                    }
1050
                } else {
1051
                    $addname = (string) $record->alternateName();
1052
                    $addname = strip_tags($addname);
1053
                    if (!empty($addname)) {
1054
                        $name .= ' ' . $addname;
1055
                    }
1056
                }
1057
                $this->current_element->addText(trim($name));
1058
            }
1059
        }
1060
        if (isset($record) && $famrel && ($this->mfrelation[$record->xref()] != "")) {
1061
            $this->current_element->addText(" (" . (string) $this->mfrelation[$record->xref()] . ")");
1062
        }
1063
    }
1064
1065
    /**
1066
     * Handle <gedcomValue />
1067
     *
1068
     * @param array<string> $attrs
1069
     *
1070
     * @return void
1071
     */
1072
    protected function gedcomValueStartHandler(array $attrs): void
1073
    {
1074
        $id    = '';
1075
        $match = [];
1076
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1077
            $id = $match[1];
1078
        }
1079
1080
        if (isset($attrs['newline']) && $attrs['newline'] === '1') {
1081
            $useBreak = '1';
1082
        } else {
1083
            $useBreak = '0';
1084
        }
1085
1086
        $tag = $attrs['tag'];
1087
        if (!empty($tag)) {
1088
            if ($tag === '@desc') {
1089
                $value = $this->desc;
1090
                $value = trim($value);
1091
                $this->current_element->addText($value);
1092
            }
1093
            if ($tag === '@id') {
1094
                $this->current_element->addText($id);
1095
            } else {
1096
                $tag = str_replace('@fact', $this->fact, $tag);
1097
                if (empty($attrs['level'])) {
1098
                    $level = (int) explode(' ', trim($this->gedrec))[0];
1099
                    if ($level === 0) {
1100
                        $level++;
1101
                    }
1102
                } else {
1103
                    $level = (int) $attrs['level'];
1104
                }
1105
                $tags  = preg_split('/[: ]/', $tag);
1106
                $value = $this->getGedcomValue($tag, $level, $this->gedrec);
1107
                switch (end($tags)) {
1108
                    case 'DATE':
1109
                        $tmp   = new Date($value);
1110
                        $dfmt = "%j %F %Y";
1111
                        if (!empty($attrs['truncate'])) {
1112
                            if ($attrs['truncate'] === "d") {
1113
                                $dfmt = "%j %M %Y";
1114
                            }
1115
                            if ($attrs['truncate'] === "Y") {
1116
                                $dfmt = "%Y";
1117
                            }
1118
                        }
1119
                        $value = strip_tags($tmp->display(null, $dfmt));
1120
                        break;
1121
                    case 'PLAC':
1122
                        $tmp   = new Place($value, $this->tree);
1123
                        $value = $tmp->shortName();
1124
                        break;
1125
                }
1126
                if ($useBreak === '1') {
1127
                    // Insert <br> when multiple dates exist.
1128
                    // This works around a TCPDF bug that incorrectly wraps RTL dates on LTR pages
1129
                    $value = str_replace('(', '<br>(', $value);
1130
                    $value = str_replace('<span dir="ltr"><br>', '<br><span dir="ltr">', $value);
1131
                    $value = str_replace('<span dir="rtl"><br>', '<br><span dir="rtl">', $value);
1132
                    if (substr($value, 0, 4) === '<br>') {
1133
                        $value = substr($value, 4);
1134
                    }
1135
                }
1136
                $tmp = explode(':', $tag);
1137
                if (in_array(end($tmp), ['NOTE', 'TEXT'], true)) {
1138
                    if ($this->tree->getPreference('FORMAT_TEXT') === 'xxmarkdown') {
1139
                        $value = strip_tags(Registry::markdownFactory()->markdown($value, $this->tree), ['br']);
1140
                    } else {
1141
                        $value = str_replace("\n", "<br>", $value);
1142
                        //$value = strip_tags(Registry::markdownFactory()->autolink($value, $this->tree), ['br']);
1143
                    }
1144
                    $value = strtr($value, [MarkdownFactory::BREAK => ' ']);
1145
                }
1146
1147
                if (isset($attrs['lcfirst'])) {
1148
                    $value = lcfirst($value);
1149
                    $value = str_replace(["Å","Ä","Ö"], ["å","ä","ö"], $value);
1150
                }
1151
1152
                if (!empty($attrs['truncate'])) {
1153
                    $value = strip_tags($value);
1154
                    if ((int) $attrs['truncate'] > 0) {
1155
                        $value = Str::limit($value, (int) $attrs['truncate'], I18N::translate('…'));
1156
                    }
1157
                }
1158
                $this->current_element->addText($value);
1159
            }
1160
        }
1161
    }
1162
1163
    /**
1164
     * Handle <repeatTag>
1165
     *
1166
     * @param array<string> $attrs
1167
     *
1168
     * @return void
1169
     */
1170
    protected function repeatTagStartHandler(array $attrs): void
1171
    {
1172
        $this->process_repeats++;
1173
        if ($this->process_repeats > 1) {
1174
            return;
1175
        }
1176
1177
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1178
        $this->repeats         = [];
1179
        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1180
1181
        $tag = $attrs['tag'] ?? '';
1182
        if (!empty($tag)) {
1183
            if ($tag === '@desc') {
1184
                $value = $this->desc;
1185
                $value = trim($value);
1186
                $this->current_element->addText($value);
1187
            } else {
1188
                $tag   = str_replace('@fact', $this->fact, $tag);
1189
                $tags  = explode(':', $tag);
1190
                $level = (int) explode(' ', trim($this->gedrec))[0];
1191
                if ($level === 0) {
1192
                    $level++;
1193
                }
1194
                $subrec = $this->gedrec;
1195
                $t      = $tag;
1196
                $count  = count($tags);
1197
                $i      = 0;
1198
                while ($i < $count) {
1199
                    $t = $tags[$i];
1200
                    if (!empty($t)) {
1201
                        if ($i < ($count - 1)) {
1202
                            $subrec = self::getSubRecord($level, "$level $t", $subrec);
1203
                            if (empty($subrec)) {
1204
                                $level--;
1205
                                $subrec = self::getSubRecord($level, "@ $t", $this->gedrec);
1206
                                if (empty($subrec)) {
1207
                                    return;
1208
                                }
1209
                            }
1210
                        }
1211
                        $level++;
1212
                    }
1213
                    $i++;
1214
                }
1215
                $level--;
1216
                $count = preg_match_all("/$level $t(.*)/", $subrec, $match, PREG_SET_ORDER);
1217
                $i     = 0;
1218
                while ($i < $count) {
1219
                    $i++;
1220
                    // Privacy check - is this a link, and are we allowed to view the linked object?
1221
                    $subrecord = self::getSubRecord($level, "$level $t", $subrec, $i);
1222
                    if (preg_match('/^\d ' . Gedcom::REGEX_TAG . ' @(' . Gedcom::REGEX_XREF . ')@/', $subrecord, $xref_match)) {
1223
                        $linked_object = Registry::gedcomRecordFactory()->make($xref_match[1], $this->tree);
1224
                        if ($linked_object && !$linked_object->canShow()) {
1225
                            //continue;
1226
                        }
1227
                    }
1228
                    $this->repeats[] = $subrecord;
1229
                }
1230
            }
1231
        }
1232
    }
1233
1234
    /**
1235
     * Handle </repeatTag>
1236
     *
1237
     * @return void
1238
     */
1239
    protected function repeatTagEndHandler(): void
1240
    {
1241
        $this->process_repeats--;
1242
        if ($this->process_repeats > 0) {
1243
            return;
1244
        }
1245
1246
        $nnnn = count($this->repeats);
0 ignored issues
show
Unused Code introduced by
The assignment to $nnnn is dead and can be removed.
Loading history...
1247
        $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...
1248
        // Check if there is anything to repeat
1249
        if (count($this->repeats) > 0) {
1250
            // No need to load them if not used...
1251
1252
            //-- read the xml from the file
1253
            $lines = file($this->report);
1254
            if (empty($lines)) {
1255
                error_log(__FILE__ . ":" . __LINE__ . " impossible error!? \n");
1256
                // this can not happen! phpstan forces me to add stupid code
1257
                // we come here because the xml file exists! Is it possible to tell phpstan the $lines *is* an array ??
1258
                die("can not happen!!!");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1259
            }
1260
            $lineoffset = 0;
1261
            foreach ($this->repeats_stack as $rep) {
1262
                if (!empty($rep[1])) {
1263
                    $lineoffset = $lineoffset + (int) ($rep[1]) - 1;
1264
                }
1265
            }
1266
            while (!str_contains($lines[$lineoffset + $this->repeat_bytes], '<RepeatTag')) {
1267
                $lineoffset--;
1268
            }
1269
            $lineoffset++;
1270
            $reportxml = "<tempdoc>\n";
1271
            $line_nr   = $lineoffset + $this->repeat_bytes;
1272
            $lnnn = $line_nr;
0 ignored issues
show
Unused Code introduced by
The assignment to $lnnn is dead and can be removed.
Loading history...
1273
            // RepeatTag Level counter
1274
            $count = 1;
1275
            while (0 < $count) {
1276
                if (str_contains($lines[$line_nr], '<RepeatTag')) {
1277
                    $count++;
1278
                } elseif (str_contains($lines[$line_nr], '</RepeatTag')) {
1279
                    $count--;
1280
                }
1281
                if (0 < $count) {
1282
                    $reportxml .= $lines[$line_nr];
1283
                }
1284
                $line_nr++;
1285
            }
1286
            // No need to drag this
1287
            unset($lines);
1288
            $reportxml .= "</tempdoc>\n";
1289
            // Save original values
1290
            $this->parser_stack[] = $this->parser;
1291
            $oldgedrec            = $this->gedrec;
1292
            foreach ($this->repeats as $gedrec) {
1293
                $this->gedrec  = $gedrec;
1294
                $repeat_parser = xml_parser_create();
1295
                $this->parser  = $repeat_parser;
1296
                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
1297
1298
                xml_set_element_handler(
1299
                    $repeat_parser,
1300
                    function ($parser, string $name, array $attrs): void {
1301
                        $this->startElement($parser, $name, $attrs);
1302
                    },
1303
                    function ($parser, string $name): void {
1304
                        $this->endElement($parser, $name);
1305
                    }
1306
                );
1307
1308
                xml_set_character_data_handler(
1309
                    $repeat_parser,
1310
                    function ($parser, string $data): void {
1311
                        $this->characterData($parser, $data);
1312
                    }
1313
                );
1314
1315
                if (!xml_parse($repeat_parser, $reportxml, true)) {
1316
                    throw new DomainException(sprintf(
1317
                        'RepeatTagEHandler XML error: %s at line %d',
1318
                        xml_error_string(xml_get_error_code($repeat_parser)),
1319
                        xml_get_current_line_number($repeat_parser)
1320
                    ));
1321
                }
1322
                xml_parser_free($repeat_parser);
1323
            }
1324
            // Restore original values
1325
            $this->gedrec = $oldgedrec;
1326
            $this->parser = array_pop($this->parser_stack);
1327
        }
1328
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1329
    }
1330
1331
    /**
1332
     * Variable lookup
1333
     * Retrieve predefined variables :
1334
     * @ desc GEDCOM fact description, example:
1335
     *        1 EVEN This is a description
1336
     * @ fact GEDCOM fact tag, such as BIRT, DEAT etc.
1337
     * $ I18N::translate('....')
1338
     * $ language_settings[]
1339
     *
1340
     * @param array<string> $attrs an array of key value pairs for the attributes
1341
     *
1342
     * @return void
1343
     */
1344
    protected function varStartHandler(array $attrs): void
1345
    {
1346
        if (!isset($attrs['var'])) {
1347
            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));
1348
        }
1349
1350
        $var = $attrs['var'];
1351
        // SetVar element preset variables
1352
        if (!empty($this->vars[$var]['id'])) {
1353
            $var = $this->vars[$var]['id'];
1354
        } else {
1355
            $tfact = $this->fact;
1356
            if (($this->fact === 'EVEN' || $this->fact === 'FACT') && $this->type !== '') {
1357
                // Use :
1358
                // n TYPE This text if string
1359
                $tfact = $this->type;
1360
            } else {
1361
                foreach ([Individual::RECORD_TYPE, Family::RECORD_TYPE] as $record_type) {
1362
                    $element = Registry::elementFactory()->make($record_type . ':' . $this->fact);
1363
1364
                    if (!$element instanceof UnknownElement) {
1365
                        $tfact = $element->label();
1366
                        break;
1367
                    }
1368
                }
1369
            }
1370
1371
            $var = strtr($var, ['@desc' => $this->desc, '@fact' => $tfact]);
1372
1373
            if (preg_match('/^I18N::number\((.+)\)$/', $var, $match)) {
1374
                $var = I18N::number((int) $match[1]);
1375
            } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $var, $match)) {
1376
                $var = I18N::translate($match[1]);
1377
            } elseif (preg_match('/^I18N::translate\(\$(.+)\)$/', $var, $match)) {
1378
                $var = I18N::translate($this->vars[$match[1]]['id']);
1379
            } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $var, $match)) {
1380
                $var = I18N::translateContext($match[1], $match[2]);
1381
            }
1382
        }
1383
        // Check if variable is set as a date and reformat the date
1384
        if (isset($attrs['date'])) {
1385
            if ($attrs['date'] === '1') {
1386
                $g   = new Date($var);
1387
                $var = $g->display();
1388
            }
1389
        }
1390
        if (isset($attrs['amp'])) {
1391
            $var = str_replace("%26", '&', $var);
1392
        }
1393
        if (isset($attrs['cut'])) {
1394
            $cut = (int) $attrs['cut'];
1395
            $var = $cut > 0 ? substr($var, 0, $cut) : substr($var, $cut);
1396
            if ($cut == 0) {
1397
                $var = "";
1398
            }
1399
        }
1400
        if (isset($attrs['lcfirst'])) {
1401
            $var = lcfirst($var);
1402
        }
1403
        $this->current_element->addText($var);
1404
        $this->text = $var; // Used for title/description
1405
    }
1406
1407
    /**
1408
     * Handle <facts>
1409
     *
1410
     * @param array<string> $attrs
1411
     *
1412
     * @return void
1413
     */
1414
    protected function factsStartHandler(array $attrs): void
1415
    {
1416
        $this->process_repeats++;
1417
        if ($this->process_repeats > 1) {
1418
            return;
1419
        }
1420
1421
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1422
        $this->repeats         = [];
1423
        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1424
1425
        $id    = '';
1426
        $match = [];
1427
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1428
            $id = $match[1];
1429
        }
1430
        $tag = '';
1431
        if (isset($attrs['ignore'])) {
1432
            $tag .= $attrs['ignore'];
1433
        }
1434
        if (preg_match('/\$(.+)/', $tag, $match)) {
1435
            $tag = $this->vars[$match[1]]['id'];
1436
        }
1437
1438
        $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1439
        if (empty($attrs['diff']) && !empty($id)) {
1440
            $facts = $record->facts([], true);
1441
            $this->repeats = [];
1442
            $nonfacts      = explode(',', $tag);
1443
            foreach ($facts as $fact) {
1444
                $tag = explode(':', $fact->tag())[1];
1445
1446
                if (!in_array($tag, $nonfacts, true)) {
1447
                    $this->repeats[] = $fact->gedcom();
1448
                }
1449
            }
1450
        } else {
1451
            foreach ($record->facts() as $fact) {
1452
                if (($fact->isPendingAddition() || $fact->isPendingDeletion()) && !str_ends_with($fact->tag(), ':CHAN')) {
1453
                    $this->repeats[] = $fact->gedcom();
1454
                }
1455
            }
1456
        }
1457
1458
        $jdarr = [];
1459
        // Add fact/event for FAM:DIV and for death of spouse
1460
        foreach ($this->repeats as $key => $fact) {
1461
            $jdarr[$key] = 0;
1462
            if (preg_match('/1 FAMS @(.+)@/', $fact, $match)) {
1463
                $famid = $match[1];
1464
                $fam = Registry::familyFactory()->make($match[1], $this->tree);
1465
                if ($fam === null) {
1466
                    continue;
1467
                }
1468
                $dt = $this->getGedcomValue("MARR:DATE", 0, $fam->gedcom());
1469
                if ($dt == "") {
1470
                    $dt = $this->getGedcomValue("ENGA:DATE", 0, $fam->gedcom());
1471
                }
1472
                if ($dt == "" && $this->getGedcomValue("EVEN:TYPE", 0, $fam->gedcom()) == "Sambo") {
1473
                    $dt = $this->getGedcomValue("EVEN:DATE", 0, $fam->gedcom());
1474
                }
1475
                $date = new Date($dt);
1476
                $jd = $date->julianDay();
1477
                $jdarr[$key] = $jd;
1478
                // Divorce
1479
                $dt = $this->getGedcomValue("DIV:DATE", 0, $fam->gedcom());
1480
                if ($dt != "") {
1481
                    $this->repeats[] = "1 DIV\n2 DATE " . $dt . "\n";
1482
                }
1483
                // Separation // Doesn't work!! getGedComValue only reports the first event!! I.e. no match here
1484
                if ($this->getGedcomValue("EVEN:TYPE", 0, $fam->gedcom()) == "Separation") {
1485
                    $dt = $this->getGedcomValue("EVEN:DATE", 0, $fam->gedcom());
1486
                    if ($dt != "") {
1487
                        $this->repeats[] = "1 EVEN\n2 TYPE Separation\n2 DATE " . $dt . "\n";
1488
                    }
1489
                }
1490
                // death of husband / wife
1491
                $husb = $fam->husband();
1492
                $wife = $fam->wife();
1493
                if ($this->getGedcomValue("SEX", 0, $this->gedrec) == "M") {
1494
                    $spouse = $wife;
1495
                } else {
1496
                    $spouse = $husb;
1497
                }
1498
                if ($spouse) {
1499
                    $dt = $this->getGedcomValue("DEAT:DATE", 0, $spouse->gedcom());
1500
                } else {
1501
                    $dt = "";
1502
                }
1503
                if ($dt != "") {
1504
                    $this->repeats[] = "1 _SP_DEAT\n2 DATE " . $dt . "\n2 _O_FAM " . $famid . "\n";
1505
                }
1506
            }
1507
        }
1508
        // Find the dates for the facts that are found
1509
        foreach ($this->repeats as $key => $fact) {
1510
            if (preg_match('/[234] DATE ([^\n]+)/', $fact, $match)) {
1511
                $date = new Date($match[1]);
1512
                $jd = $date->julianDay();
1513
                $jdarr[$key] = $jd;
1514
            }
1515
        }
1516
1517
        // Sort facts in chronological order, if possible
1518
        $m = count($this->repeats) - 1;
1519
        $prevd = 0;
1520
        for ($i = 0; $i <= $m; $i++) { // keep undated events after previous dated event
1521
            if ($jdarr[$i] === 0) {
1522
                $jdarr[$i] = $prevd;
1523
            } else {
1524
                $prevd = $jdarr[$i];
1525
            }
1526
        }
1527
1528
        while ($m > 1) {
1529
            $n = count($this->repeats);
1530
            while ($n > 1) {
1531
                if ($jdarr[$n - 2] > $jdarr[$n - 1] && $jdarr[$n - 1] !== 0) {
1532
                    $s = $this->repeats[$n - 1];
1533
                    $this->repeats[$n - 1] = $this->repeats[$n - 2];
1534
                    $this->repeats[$n - 2] = $s;
1535
                    $s = $jdarr[$n - 1];
1536
                    $jdarr[$n - 1] = $jdarr[$n - 2];
1537
                    $jdarr[$n - 2] = $s;
1538
                }
1539
                $n -= 1;
1540
            }
1541
            $m -= 1;
1542
        }
1543
1544
        // Remove spouse deaths that are too late: after new marriage or own death
1545
        $currfam = "";
1546
        for ($i = 0; $i <= count($this->repeats) - 1; $i++) {
1547
            if (preg_match('/[1234] FAMS @(.+)@/', $this->repeats[$i], $match)) {
1548
                $currfam = $match[1];
1549
            }
1550
            if (preg_match('/_SP_DEAT.*\n2 DATE (.*)\n.*_O_FAM (.+)\n/', $this->repeats[$i], $match)) {
1551
                if ($currfam != $match[2] || $i == count($this->repeats) - 1) {
1552
                    $this->repeats[$i] = "1 _XXX\n";
1553
                } // ignore fact
1554
            }
1555
        }
1556
    }
1557
1558
    /**
1559
     * Handle </facts>
1560
     *
1561
     * @return void
1562
     */
1563
    protected function factsEndHandler(): void
1564
    {
1565
        $this->process_repeats--;
1566
        if ($this->process_repeats > 0) {
1567
            return;
1568
        }
1569
1570
        // Check if there is anything to repeat
1571
        if (count($this->repeats) > 0) {
1572
            $line       = xml_get_current_line_number($this->parser) - 1;
1573
            $lineoffset = 0;
1574
            foreach ($this->repeats_stack as $rep) {
1575
                $lineoffset = $lineoffset + (int) ($rep[1]) - 1;
1576
            }
1577
1578
            //-- read the xml from the file
1579
            $lines = file($this->report);
1580
            if (empty($lines)) {
1581
                error_log(__FILE__ . ":" . __LINE__ . " impossible error!? \n");
1582
                // this can not happen! phpstan forces me to add stupid code
1583
                // we come here because the xml file exists! Is it possible to tell phpstan the $lines *is* an array ??
1584
                die("can not happen!!!");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1585
            }
1586
            while ($lineoffset + $this->repeat_bytes > 0 && !str_contains($lines[$lineoffset + $this->repeat_bytes], '<Facts ')) {
1587
                $lineoffset--;
1588
            }
1589
            $lineoffset++;
1590
            $reportxml = "<tempdoc>\n";
1591
            $i         = $line + $lineoffset;
1592
            $line_nr   = $this->repeat_bytes + $lineoffset;
1593
            while ($line_nr < $i) {
1594
                $reportxml .= $lines[$line_nr];
1595
                $line_nr++;
1596
            }
1597
            // No need to drag this
1598
            unset($lines);
1599
            $reportxml .= "</tempdoc>\n";
1600
            // Save original values
1601
            $this->parser_stack[] = $this->parser;
1602
            $oldgedrec = $this->gedrec;
1603
            $count = count($this->repeats);
1604
            $i = 0;
1605
            while ($i < $count) {
1606
                if (!isset($this->repeats[$i])) {
1607
                    $i++;
1608
                    continue; // this fact has been removed above, occured too late
1609
                }
1610
                $this->gedrec = $this->repeats[$i];
1611
                $this->fact = '';
1612
                $this->desc = '';
1613
                if (preg_match('/1 (\w+)(.*)/', $this->gedrec, $match)) {
1614
                    $this->fact = $match[1];
1615
                    if ($this->fact === 'EVEN' || $this->fact === 'FACT') {
1616
                        $tmatch = [];
1617
                        if (preg_match('/2 TYPE (.+)/', $this->gedrec, $tmatch)) {
1618
                            $this->type = trim($tmatch[1]);
1619
                        } else {
1620
                            $this->type = ' ';
1621
                        }
1622
                    }
1623
                    $this->desc = trim($match[2]);
1624
                    $this->desc .= self::getCont(2, $this->gedrec);
1625
                }
1626
                $repeat_parser = xml_parser_create();
1627
                $this->parser  = $repeat_parser;
1628
                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
1629
1630
                xml_set_element_handler(
1631
                    $repeat_parser,
1632
                    function ($parser, string $name, array $attrs): void {
1633
                        $this->startElement($parser, $name, $attrs);
1634
                    },
1635
                    function ($parser, string $name): void {
1636
                        $this->endElement($parser, $name);
1637
                    }
1638
                );
1639
1640
                xml_set_character_data_handler(
1641
                    $repeat_parser,
1642
                    function ($parser, string $data): void {
1643
                        $this->characterData($parser, $data);
1644
                    }
1645
                );
1646
1647
                if (!xml_parse($repeat_parser, $reportxml, true)) {
1648
                    throw new DomainException(sprintf(
1649
                        'FactsEHandler XML error: %s at line %d',
1650
                        xml_error_string(xml_get_error_code($repeat_parser)),
1651
                        xml_get_current_line_number($repeat_parser)
1652
                    ));
1653
                }
1654
                xml_parser_free($repeat_parser);
1655
                $i++;
1656
            }
1657
            // Restore original values
1658
            $this->parser = array_pop($this->parser_stack);
1659
            $this->gedrec = $oldgedrec;
1660
        }
1661
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1662
    }
1663
1664
    /**
1665
     * Setting upp or changing variables in the XML
1666
     * The XML variable name and value is stored in $this->vars
1667
     *
1668
     * @param array<string> $attrs an array of key value pairs for the attributes
1669
     *
1670
     * @return void
1671
     */
1672
    protected function setVarStartHandler(array $attrs): void
1673
    {
1674
        if (empty($attrs['name'])) {
1675
            throw new DomainException('REPORT ERROR var: The attribute "name" is missing or not set in the XML file');
1676
        }
1677
1678
        $name  = $attrs['name'];
1679
        $value = $attrs['value'];
1680
        if (isset($attrs['dumpvar'])) {
1681
            $dumpvar = $attrs['dumpvar'];
1682
        } else {
1683
            $dumpvar = "";
1684
        }
1685
        $curr_id = "";
1686
        $match = [];
1687
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1688
            $curr_id = $match[1];
1689
        }
1690
        $match = [];
1691
        // Current GEDCOM record strings
1692
        if ($value === '@ID') {
1693
            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1694
                $value = $match[1];
1695
            }
1696
        } elseif ($value === '@fact') {
1697
            $value = $this->fact;
1698
        } elseif ($value === '@desc') {
1699
            $value = $this->desc;
1700
        } elseif ($value === '@format') {
1701
            if (isset($_GET["format"])) {
1702
                $value = $_GET["format"];
1703
            } else {
1704
                $value = "";
1705
            }
1706
        } elseif ($value === '@generation') {
1707
            $value = (string) $this->generation;
1708
        } elseif ($value === '@base_url') {
1709
            $value = "";
1710
            if (array_key_exists("REQUEST_URI", $_SERVER)) {
1711
                $value = urldecode($_SERVER["REQUEST_URI"]);
1712
            }
1713
            $url1 = "";
1714
            $i = strpos($value, "route=");
1715
            if ($i !== false) {
1716
                $url1 = substr($value, 0, $i + 6);
1717
                $value = substr($value, $i + 6);
1718
            }
1719
            $i = strpos($value, "/report");
1720
            if ($i !== false) {
1721
                $value = substr($value, 0, $i);
1722
            }
1723
            $value = $url1 . $value;
1724
        } elseif ($value === '@relation') {
1725
            if (isset($this->mfrelation[$curr_id]) && $curr_id != "") {
1726
                $value = (string) $this->mfrelation[$curr_id];
1727
            } else {
1728
                $value = "";
1729
            }
1730
        } elseif (preg_match("/@(\w+)/", $value, $match)) {
1731
            $gmatch = [];
1732
            if (preg_match("/\d $match[1] (.+)/", $this->gedrec, $gmatch)) {
1733
                $value = str_replace('@', '', trim($gmatch[1]));
1734
            }
1735
        } elseif (preg_match("/@\\$(\w+)/", $value, $match)) {
1736
            if ($match[1] == "dump" && $this->vars['dval']['id'] > 0) {
1737
                // if ($this->vars[ 'dval' ]['id'] == 1001)
1738
                if ($dumpvar == "gedrec") {
1739
                    error_log("\n---- setvar start  " . date("Y-m-d H:i:s") . " RPG " . __LINE__ . "  " . $name . "  gedcom=\n" . $this->gedrec . "\n", 3, "my-errors.log");
1740
                } elseif ($dumpvar != "") {
1741
                    error_log("var: " . $dumpvar . " = " . $this->vars[$dumpvar]['id'] . "\n", 3, "my-errors.log");
1742
                } else {
1743
                    if (array_key_exists('dval', $this->vars)) {
1744
                        $nnn = $this->vars['dval']['id'];
1745
                    } else {
1746
                        $nnn = 0;
1747
                    }
1748
                    error_log("\n---- setvar start  " . date("Y-m-d H:i:s") . " RPG " . __LINE__ . "  " . $name . "  -----\n", 3, "my-errors.log");
1749
                    foreach ($this->vars as $key => $val) {
1750
                        if ($nnn-- < 0) {
1751
                            error_log($key . "='" . $val['id'] . "'\n", 3, "my-errors.log");
1752
                        }
1753
                    }
1754
                }
1755
            }
1756
            $value = $this->vars[$match[1]]['id'];
1757
            if (isset($this->vars[$value]['id'])) {
1758
                $value = '$' . $this->vars[$match[1]]['id'];
1759
            } else {
1760
                $value = "0";
1761
            }
1762
        }
1763
        if (isset($attrs['trim'])) {
1764
            $value = str_replace($attrs['trim'], '', $value);
1765
        }
1766
        if (preg_match("/\\$(\w+)/", $name, $match)) {
1767
            $name = $this->vars["'" . $match[1] . "'"]['id'];
1768
        }
1769
        $count = preg_match_all("/\\$(\w+)/", $value, $match, PREG_SET_ORDER);
1770
        $i     = 0;
1771
        while ($i < $count) {
1772
            $t     = $this->vars[$match[$i][1]]['id'];
1773
            $value = preg_replace('/\$' . $match[$i][1] . '/', $t, $value, 1);
1774
            $i++;
1775
        }
1776
        if (preg_match('/^I18N::number\((.+)\)$/', $value, $match)) {
1777
            $value = I18N::number((int) $match[1]);
1778
        } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $value, $match)) {
1779
            $value = I18N::translate($match[1]);
1780
        } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $value, $match)) {
1781
            $value = I18N::translateContext($match[1], $match[2]);
1782
        }
1783
        if (isset($attrs['lcfirst'])) { // set 1st char to lower case
1784
            $value = lcfirst($value);
1785
        }
1786
1787
        // Arithmetic functions
1788
        if (preg_match("/(\d+)\s*([-+*\/])\s*(\d+)/", $value, $match)) {
1789
            // Create an expression language with the functions used by our reports.
1790
            $expression_provider  = new ReportExpressionLanguageProvider();
1791
            $expression_cache     = new NullAdapter();
1792
            $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1793
1794
            $value = (string) $expression_language->evaluate($value);
1795
        }
1796
1797
        if (str_contains($value, '@')) {
1798
            $value = '';
1799
        }
1800
        $this->vars[$name]['id'] = $value;
1801
        if ($name == 'title') {
1802
            $this->wt_report->title = $value;
1803
        }
1804
    }
1805
1806
    /**
1807
     * Handle <if>
1808
     *
1809
     * @param array<string> $attrs
1810
     *
1811
     * @return void
1812
     */
1813
    protected function ifStartHandler(array $attrs): void
1814
    {
1815
        if ($this->process_ifs > 0) {
1816
            $this->process_ifs++;
1817
1818
            return;
1819
        }
1820
1821
        $condition = $attrs['condition'];
1822
        $condition = $this->substituteVars($condition, true);
1823
        $condition = str_replace([
1824
            ' LT ',
1825
            ' GT ',
1826
        ], [
1827
            '<',
1828
            '>',
1829
        ], $condition);
1830
        // Replace the first occurrence only once of @fact:DATE or in any other combinations to the current fact, such as BIRT
1831
        $condition = str_replace('@fact:', $this->fact . ':', $condition);
1832
        $match     = [];
1833
        $count     = preg_match_all("/@([\w:.]+)/", $condition, $match, PREG_SET_ORDER);
1834
        $i         = 0;
1835
        while ($i < $count) {
1836
            $id    = $match[$i][1];
1837
            $value = '""';
1838
            if ($id === 'ID') {
1839
                if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1840
                    $value = "'" . $match[1] . "'";
1841
                }
1842
            } elseif ($id === 'fact') {
1843
                $value = '"' . $this->fact . '"';
1844
            } elseif ($id === 'desc') {
1845
                $value = '"' . addslashes($this->desc) . '"';
1846
            } elseif ($id === 'generation') {
1847
                $value = '"' . $this->generation . '"';
1848
            } else {
1849
                $level = (int) explode(' ', trim($this->gedrec))[0];
1850
                if ($level === 0) {
1851
                    $level++;
1852
                }
1853
                $value = $this->getGedcomValue($id, $level, $this->gedrec);
1854
                if (empty($value)) {
1855
                    $level++;
1856
                    $value = $this->getGedcomValue($id, $level, $this->gedrec);
1857
                }
1858
                $value = preg_replace('/^@(' . Gedcom::REGEX_XREF . ')@$/', '$1', $value);
1859
                $value = '"' . addslashes($value) . '"';
1860
            }
1861
            $condition = str_replace("@$id", $value, $condition);
1862
            $i++;
1863
        }
1864
1865
        // Create an expression language with the functions used by our reports.
1866
        $expression_provider  = new ReportExpressionLanguageProvider();
1867
        $expression_cache     = new NullAdapter();
1868
        $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1869
1870
        $ret = $expression_language->evaluate($condition);
1871
1872
        if (!$ret) {
1873
            $this->process_ifs++;
1874
        }
1875
    }
1876
1877
    /**
1878
     * Handle </if>
1879
     *
1880
     * @return void
1881
     */
1882
    protected function ifEndHandler(): void
1883
    {
1884
        if ($this->process_ifs > 0) {
1885
            $this->process_ifs--;
1886
        }
1887
    }
1888
1889
    /**
1890
     * Handle <footnote>
1891
     * Collect the Footnote links
1892
     * GEDCOM Records that are protected by Privacy setting will be ignored
1893
     *
1894
     * @param array<string> $attrs
1895
     *
1896
     * @return void
1897
     */
1898
    protected function footnoteStartHandler(array $attrs): void
1899
    {
1900
        $id = '';
1901
        if (preg_match('/[0-9] (.+) @(.+)@/', $this->gedrec, $match)) {
1902
            $id = $match[2];
1903
        }
1904
        $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1905
        if ($record && $record->canShow()) {
1906
            $this->print_data_stack[] = $this->print_data;
1907
            $this->print_data         = true;
1908
            $style                    = '';
1909
            if (!empty($attrs['style'])) {
1910
                $style = $attrs['style'];
1911
            }
1912
            $this->footnote_element = $this->current_element;
1913
            $this->current_element  = $this->report_root->createFootnote($style);
1914
        } else {
1915
            $this->print_data       = false;
1916
            $this->process_footnote = false;
1917
        }
1918
    }
1919
1920
    /**
1921
     * Handle </footnote>
1922
     * Print the collected Footnote data
1923
     *
1924
     * @return void
1925
     */
1926
    protected function footnoteEndHandler(): void
1927
    {
1928
        if ($this->process_footnote) {
1929
            $this->print_data = array_pop($this->print_data_stack);
1930
            $temp             = trim($this->current_element->getValue());
1931
            if (strlen($temp) > 3) {
1932
                $this->wt_report->addElement($this->current_element);
1933
            }
1934
            $this->current_element = $this->footnote_element;
1935
        } else {
1936
            $this->process_footnote = true;
1937
        }
1938
    }
1939
1940
    /**
1941
     * Handle <footnoteTexts />
1942
     *
1943
     * @return void
1944
     */
1945
    protected function footnoteTextsStartHandler(): void
1946
    {
1947
        $temp = 'footnotetexts';
1948
        $this->wt_report->addElement($temp);
1949
    }
1950
1951
    /**
1952
     * XML element Forced line break handler - HTML code
1953
     *
1954
     * @return void
1955
     */
1956
    protected function brStartHandler(): void
1957
    {
1958
        if ($this->print_data && $this->process_gedcoms === 0) {
1959
            $this->current_element->addText('<br>');
1960
        }
1961
    }
1962
1963
    /**
1964
     * Handle <sp />
1965
     * Forced space
1966
     *
1967
     * @return void
1968
     */
1969
    protected function spStartHandler(): void
1970
    {
1971
        if ($this->print_data && $this->process_gedcoms === 0) {
1972
            $this->current_element->addText(' ');
1973
        }
1974
    }
1975
1976
    /**
1977
     * Handle <highlightedImage />
1978
     *
1979
     * @param array<string> $attrs
1980
     *
1981
     * @return void
1982
     */
1983
    protected function highlightedImageStartHandler(array $attrs): void
1984
    {
1985
        $id = '';
1986
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1987
            $id = $match[1];
1988
        }
1989
1990
        // Position the top corner of this box on the page
1991
        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
1992
1993
        // Position the left corner of this box on the page
1994
        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
1995
1996
        // string Align the image in left, center, right (or empty to use x/y position).
1997
        $align = $attrs['align'] ?? '';
1998
1999
        // string Next Line should be T:next to the image, N:next line
2000
        $ln = $attrs['ln'] ?? 'T';
2001
2002
        // Width, height (or both).
2003
        $width  = (float) ($attrs['width'] ?? 0.0);
2004
        $height = (float) ($attrs['height'] ?? 0.0);
2005
2006
        $person     = Registry::individualFactory()->make($id, $this->tree);
2007
        $media_file = $person->findHighlightedMediaFile();
2008
2009
        if ($media_file instanceof MediaFile && $media_file->fileExists()) {
2010
            $image      = imagecreatefromstring($media_file->fileContents());
2011
            $attributes = [imagesx($image), imagesy($image)];
2012
2013
            if ($width > 0 && $height == 0) {
2014
                $perc   = $width / $attributes[0];
2015
                $height = round($attributes[1] * $perc);
2016
            } elseif ($height > 0 && $width == 0) {
2017
                $perc  = $height / $attributes[1];
2018
                $width = round($attributes[0] * $perc);
2019
            } else {
2020
                $width  = (float) $attributes[0];
2021
                $height = (float) $attributes[1];
2022
            }
2023
            $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
2024
            $this->wt_report->addElement($image);
2025
        }
2026
    }
2027
2028
    /**
2029
     * Handle <image/>
2030
     *
2031
     * @param array<string> $attrs
2032
     *
2033
     * @return void
2034
     */
2035
    protected function imageStartHandler(array $attrs): void
2036
    {
2037
        // Position the top corner of this box on the page. the default is the current position
2038
        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
2039
2040
        // mixed Position the left corner of this box on the page. the default is the current position
2041
        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
2042
2043
        // string Align the image in left, center, right (or empty to use x/y position).
2044
        $align = $attrs['align'] ?? '';
2045
2046
        // string Next Line should be T:next to the image, N:next line
2047
        $ln = $attrs['ln'] ?? 'T';
2048
2049
        // Width, height (or both).
2050
        $width  = (float) ($attrs['width'] ?? 0.0);
2051
        $height = (float) ($attrs['height'] ?? 0.0);
2052
2053
        $file = $attrs['file'] ?? '';
2054
2055
        if ($file === '@FILE') {
2056
            $match = [];
2057
            if (preg_match("/\d OBJE @(.+)@/", $this->gedrec, $match)) {
2058
                $mediaobject = Registry::mediaFactory()->make($match[1], $this->tree);
2059
                $media_file  = $mediaobject->firstImageFile();
2060
2061
                if ($media_file instanceof MediaFile && $media_file->fileExists()) {
2062
                    $image      = imagecreatefromstring($media_file->fileContents());
2063
                    $attributes = [imagesx($image), imagesy($image)];
2064
2065
                    if ($width > 0 && $height == 0) {
2066
                        $perc   = $width / $attributes[0];
2067
                        $height = round($attributes[1] * $perc);
2068
                    } elseif ($height > 0 && $width == 0) {
2069
                        $perc  = $height / $attributes[1];
2070
                        $width = round($attributes[0] * $perc);
2071
                    } else {
2072
                        $width  = (float) $attributes[0];
2073
                        $height = (float) $attributes[1];
2074
                    }
2075
                    $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
2076
                    $this->wt_report->addElement($image);
2077
                }
2078
            }
2079
        } else {
2080
            if (file_exists($file) && preg_match('/(jpg|jpeg|png|gif)$/i', $file)) {
2081
                $size = getimagesize($file);
2082
                if ($width > 0 && $height == 0) {
2083
                    $perc   = $width / $size[0];
2084
                    $height = round($size[1] * $perc);
2085
                } elseif ($height > 0 && $width == 0) {
2086
                    $perc  = $height / $size[1];
2087
                    $width = round($size[0] * $perc);
2088
                } else {
2089
                    $width  = $size[0];
2090
                    $height = $size[1];
2091
                }
2092
                $image = $this->report_root->createImage($file, $left, $top, $width, $height, $align, $ln);
2093
                $this->wt_report->addElement($image);
2094
            }
2095
        }
2096
    }
2097
2098
    /**
2099
     * Handle <line>
2100
     *
2101
     * @param array<string> $attrs
2102
     *
2103
     * @return void
2104
     */
2105
    protected function lineStartHandler(array $attrs): void
2106
    {
2107
        // Start horizontal position, current position (default)
2108
        $x1 = ReportBaseElement::CURRENT_POSITION;
2109
        if (isset($attrs['x1'])) {
2110
            if ($attrs['x1'] === '0') {
2111
                $x1 = 0;
2112
            } elseif ($attrs['x1'] === '.') {
2113
                $x1 = ReportBaseElement::CURRENT_POSITION;
2114
            } elseif (!empty($attrs['x1'])) {
2115
                $x1 = (float) $attrs['x1'];
2116
            }
2117
        }
2118
        // Start vertical position, current position (default)
2119
        $y1 = ReportBaseElement::CURRENT_POSITION;
2120
        if (isset($attrs['y1'])) {
2121
            if ($attrs['y1'] === '0') {
2122
                $y1 = 0;
2123
            } elseif ($attrs['y1'] === '.') {
2124
                $y1 = ReportBaseElement::CURRENT_POSITION;
2125
            } elseif (!empty($attrs['y1'])) {
2126
                $y1 = (float) $attrs['y1'];
2127
            }
2128
        }
2129
        // End horizontal position, maximum width (default)
2130
        $x2 = ReportBaseElement::CURRENT_POSITION;
2131
        if (isset($attrs['x2'])) {
2132
            if ($attrs['x2'] === '0') {
2133
                $x2 = 0;
2134
            } elseif ($attrs['x2'] === '.') {
2135
                $x2 = ReportBaseElement::CURRENT_POSITION;
2136
            } elseif (!empty($attrs['x2'])) {
2137
                $x2 = (float) $attrs['x2'];
2138
            }
2139
        }
2140
        // End vertical position
2141
        $y2 = ReportBaseElement::CURRENT_POSITION;
2142
        if (isset($attrs['y2'])) {
2143
            if ($attrs['y2'] === '0') {
2144
                $y2 = 0;
2145
            } elseif ($attrs['y2'] === '.') {
2146
                $y2 = ReportBaseElement::CURRENT_POSITION;
2147
            } elseif (!empty($attrs['y2'])) {
2148
                $y2 = (float) $attrs['y2'];
2149
            }
2150
        }
2151
2152
        $line = $this->report_root->createLine($x1, $y1, $x2, $y2);
2153
        $this->wt_report->addElement($line);
2154
    }
2155
2156
    /**
2157
     * Handle <list>
2158
     *
2159
     * @param array<string> $attrs
2160
     *
2161
     * @return void
2162
     */
2163
    protected function listStartHandler(array $attrs): void
2164
    {
2165
        $this->process_repeats++;
2166
        if ($this->process_repeats > 1) {
2167
            return;
2168
        }
2169
2170
        $match = [];
2171
        if (isset($attrs['sortby'])) {
2172
            $sortby = $attrs['sortby'];
2173
            if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2174
                $sortby = $this->vars[$match[1]]['id'];
2175
                $sortby = trim($sortby);
2176
            }
2177
        } else {
2178
            $sortby = 'NAME';
2179
        }
2180
2181
        $listname = $attrs['list'] ?? 'individual';
2182
2183
        // Some filters/sorts can be applied using SQL, while others require PHP
2184
        switch ($listname) {
2185
            case 'pending':
2186
                $this->list = DB::table('change')
2187
                    ->whereIn('change_id', function (Builder $query): void {
2188
                        $query->select([new Expression('MAX(change_id)')])
2189
                            ->from('change')
2190
                            ->where('gedcom_id', '=', $this->tree->id())
2191
                            ->where('status', '=', 'pending')
2192
                            ->groupBy(['xref']);
2193
                    })
2194
                    ->get()
2195
                    ->map(fn (object $row): ?GedcomRecord => Registry::gedcomRecordFactory()->make($row->xref, $this->tree, $row->new_gedcom ?: $row->old_gedcom))
2196
                    ->filter()
2197
                    ->all();
2198
                break;
2199
2200
            case 'individual':
2201
                $query = DB::table('individuals')
2202
                    ->where('i_file', '=', $this->tree->id())
2203
                    ->select(['i_id AS xref', 'i_gedcom AS gedcom'])
2204
                    ->distinct();
2205
2206
                foreach ($attrs as $attr => $value) {
2207
                    if (str_starts_with($attr, 'filter') && $value !== '') {
2208
                        $value = $this->substituteVars($value, false);
2209
                        // Convert the various filters into SQL
2210
                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
2211
                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2212
                                $join
2213
                                    ->on($attr . '.d_gid', '=', 'i_id')
2214
                                    ->on($attr . '.d_file', '=', 'i_file');
2215
                            });
2216
2217
                            $query->where($attr . '.d_fact', '=', $match[1]);
2218
2219
                            $date = new Date($match[3]);
2220
2221
                            if ($match[2] === 'LTE') {
2222
                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
2223
                            } else {
2224
                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
2225
                            }
2226
2227
                            // This filter has been fully processed
2228
                            unset($attrs[$attr]);
2229
                        } elseif (preg_match('/^NAME CONTAINS (.+)$/', $value, $match)) {
2230
                            $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2231
                                $join
2232
                                    ->on($attr . '.n_id', '=', 'i_id')
2233
                                    ->on($attr . '.n_file', '=', 'i_file');
2234
                            });
2235
                            // Search the DB only if there is any name supplied
2236
                            $names = explode(' ', $match[1]);
2237
                            foreach ($names as $name) {
2238
                                $query->where($attr . '.n_full', 'LIKE', '%' . addcslashes($name, '\\%_') . '%');
2239
                            }
2240
2241
                            // This filter has been fully processed
2242
                            unset($attrs[$attr]);
2243
                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
2244
                            // Convert newline escape sequences to actual new lines
2245
                            $match[1] = str_replace('\n', "\n", $match[1]);
2246
2247
                            $query->where('i_gedcom', 'LIKE', $match[1]);
2248
2249
                            // This filter has been fully processed
2250
                            unset($attrs[$attr]);
2251
                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
2252
                            // Don't unset this filter. This is just initial filtering for performance
2253
                            $query
2254
                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
2255
                                    $join
2256
                                        ->on($attr . 'a.pl_file', '=', 'i_file')
2257
                                        ->on($attr . 'a.pl_gid', '=', 'i_id');
2258
                                })
2259
                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
2260
                                    $join
2261
                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
2262
                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
2263
                                })
2264
                                ->where($attr . 'b.p_place', 'LIKE', '%' . addcslashes($match[1], '\\%_') . '%');
2265
                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
2266
                            // Don't unset this filter. This is just initial filtering for performance
2267
                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2268
                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
2269
                            $query->where('i_gedcom', 'LIKE', $like);
2270
                        } elseif (preg_match('/^(\w+) CONTAINS (.*)$/', $value, $match)) {
2271
                            // Don't unset this filter. This is just initial filtering for performance
2272
                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2273
                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
2274
                            $query->where('i_gedcom', 'LIKE', $like);
2275
                        }
2276
                    }
2277
                }
2278
2279
                $this->list = [];
2280
2281
                foreach ($query->get() as $row) {
2282
                    $this->list[$row->xref] = Registry::individualFactory()->make($row->xref, $this->tree, $row->gedcom);
2283
                }
2284
                break;
2285
2286
            case 'family':
2287
                $query = DB::table('families')
2288
                    ->where('f_file', '=', $this->tree->id())
2289
                    ->select(['f_id AS xref', 'f_gedcom AS gedcom'])
2290
                    ->distinct();
2291
2292
                foreach ($attrs as $attr => $value) {
2293
                    if (str_starts_with($attr, 'filter') && $value !== '') {
2294
                        $value = $this->substituteVars($value, false);
2295
                        // Convert the various filters into SQL
2296
                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
2297
                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2298
                                $join
2299
                                    ->on($attr . '.d_gid', '=', 'f_id')
2300
                                    ->on($attr . '.d_file', '=', 'f_file');
2301
                            });
2302
2303
                            $query->where($attr . '.d_fact', '=', $match[1]);
2304
2305
                            $date = new Date($match[3]);
2306
2307
                            if ($match[2] === 'LTE') {
2308
                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
2309
                            } else {
2310
                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
2311
                            }
2312
2313
                            // This filter has been fully processed
2314
                            unset($attrs[$attr]);
2315
                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
2316
                            // Convert newline escape sequences to actual new lines
2317
                            $match[1] = str_replace('\n', "\n", $match[1]);
2318
2319
                            $query->where('f_gedcom', 'LIKE', $match[1]);
2320
2321
                            // This filter has been fully processed
2322
                            unset($attrs[$attr]);
2323
                        } elseif (preg_match('/^NAME CONTAINS (.*)$/', $value, $match)) {
2324
                            if ($sortby === 'NAME' || $match[1] !== '') {
2325
                                $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2326
                                    $join
2327
                                        ->on($attr . '.n_file', '=', 'f_file')
2328
                                        ->where(static function (Builder $query): void {
2329
                                            $query
2330
                                                ->whereColumn('n_id', '=', 'f_husb')
2331
                                                ->orWhereColumn('n_id', '=', 'f_wife');
2332
                                        });
2333
                                });
2334
                                // Search the DB only if there is any name supplied
2335
                                if ($match[1] != '') {
2336
                                    $names = explode(' ', $match[1]);
2337
                                    foreach ($names as $name) {
2338
                                        $query->where($attr . '.n_full', 'LIKE', '%' . addcslashes($name, '\\%_') . '%');
2339
                                    }
2340
                                }
2341
                            }
2342
2343
                            // This filter has been fully processed
2344
                            unset($attrs[$attr]);
2345
                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
2346
                            // Don't unset this filter. This is just initial filtering for performance
2347
                            $query
2348
                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
2349
                                    $join
2350
                                        ->on($attr . 'a.pl_file', '=', 'f_file')
2351
                                        ->on($attr . 'a.pl_gid', '=', 'f_id');
2352
                                })
2353
                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
2354
                                    $join
2355
                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
2356
                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
2357
                                })
2358
                                ->where($attr . 'b.p_place', 'LIKE', '%' . addcslashes($match[1], '\\%_') . '%');
2359
                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
2360
                            // Don't unset this filter. This is just initial filtering for performance
2361
                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2362
                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
2363
                            $query->where('f_gedcom', 'LIKE', $like);
2364
                        } elseif (preg_match('/^(\w+) CONTAINS (.+)$/', $value, $match)) {
2365
                            // Don't unset this filter. This is just initial filtering for performance
2366
                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2367
                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
2368
                            $query->where('f_gedcom', 'LIKE', $like);
2369
                        }
2370
                    }
2371
                }
2372
2373
                $this->list = [];
2374
2375
                foreach ($query->get() as $row) {
2376
                    $this->list[$row->xref] = Registry::familyFactory()->make($row->xref, $this->tree, $row->gedcom);
2377
                }
2378
                break;
2379
2380
            default:
2381
                throw new DomainException('Invalid list name: ' . $listname);
2382
        }
2383
2384
        $filters  = [];
2385
        $filters2 = [];
2386
        if (isset($attrs['filter1']) && count($this->list) > 0) {
2387
            foreach ($attrs as $key => $value) {
2388
                if (preg_match("/filter(\d)/", $key)) {
2389
                    $condition = $value;
2390
                    if (preg_match("/@(\w+)/", $condition, $match)) {
2391
                        $id    = $match[1];
2392
                        $value = "''";
2393
                        if ($id === 'ID') {
2394
                            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
2395
                                $value = "'" . $match[1] . "'";
2396
                            }
2397
                        } elseif ($id === 'fact') {
2398
                            $value = "'" . $this->fact . "'";
2399
                        } elseif ($id === 'desc') {
2400
                            $value = "'" . $this->desc . "'";
2401
                        } else {
2402
                            if (preg_match("/\d $id (.+)/", $this->gedrec, $match)) {
2403
                                $value = "'" . str_replace('@', '', trim($match[1])) . "'";
2404
                            }
2405
                        }
2406
                        $condition = preg_replace("/@$id/", $value, $condition);
2407
                    }
2408
                    //-- handle regular expressions
2409
                    if (preg_match("/([A-Z:]+)\s*([^\s]+)\s*(.+)/", $condition, $match)) {
2410
                        $tag  = trim($match[1]);
2411
                        $expr = trim($match[2]);
2412
                        $val  = trim($match[3]);
2413
                        if (preg_match("/\\$(\w+)/", $val, $match)) {
2414
                            $val = $this->vars[$match[1]]['id'];
2415
                            $val = trim($val);
2416
                        }
2417
                        if ($val !== '') {
2418
                            $searchstr = '';
2419
                            $tags      = explode(':', $tag);
2420
                            //-- only limit to a level number if we are specifically looking at a level
2421
                            if (count($tags) > 1) {
2422
                                $level = 1;
2423
                                $t = 'XXXX';
2424
                                foreach ($tags as $t) {
2425
                                    if (!empty($searchstr)) {
2426
                                        $searchstr .= "[^\n]*(\n[2-9][^\n]*)*\n";
2427
                                    }
2428
                                    //-- search for both EMAIL and _EMAIL... silly double gedcom standard
2429
                                    if ($t === 'EMAIL' || $t === '_EMAIL') {
2430
                                        $t = '_?EMAIL';
2431
                                    }
2432
                                    $searchstr .= $level . ' ' . $t;
2433
                                    $level++;
2434
                                }
2435
                            } else {
2436
                                if ($tag === 'EMAIL' || $tag === '_EMAIL') {
2437
                                    $tag = '_?EMAIL';
2438
                                }
2439
                                $t         = $tag;
2440
                                $searchstr = '1 ' . $tag;
2441
                            }
2442
                            switch ($expr) {
2443
                                case 'CONTAINS':
2444
                                    if ($t === 'PLAC') {
2445
                                        $searchstr .= "[^\n]*[, ]*" . $val;
2446
                                    } else {
2447
                                        $searchstr .= "[^\n]*" . $val;
2448
                                    }
2449
                                    $filters[] = $searchstr;
2450
                                    break;
2451
                                default:
2452
                                    $filters2[] = [
2453
                                        'tag'  => $tag,
2454
                                        'expr' => $expr,
2455
                                        'val'  => $val,
2456
                                    ];
2457
                                    break;
2458
                            }
2459
                        }
2460
                    }
2461
                }
2462
            }
2463
        }
2464
        //-- apply other filters to the list that could not be added to the search string
2465
        if ($filters !== []) {
2466
            foreach ($this->list as $key => $record) {
2467
                foreach ($filters as $filter) {
2468
                    if (!preg_match('/' . $filter . '/i', $record->privatizeGedcom(Auth::accessLevel($this->tree)))) {
2469
                        unset($this->list[$key]);
2470
                        break;
2471
                    }
2472
                }
2473
            }
2474
        }
2475
        if ($filters2 !== []) {
2476
            $mylist = [];
2477
            foreach ($this->list as $indi) {
2478
                $key  = $indi->xref();
2479
                $grec = $indi->privatizeGedcom(Auth::accessLevel($this->tree));
2480
                $keep = true;
2481
                foreach ($filters2 as $filter) {
2482
                    if ($keep) {
2483
                        $tag  = $filter['tag'];
2484
                        $expr = $filter['expr'];
2485
                        $val  = $filter['val'];
2486
                        if ($val === "''") {
2487
                            $val = '';
2488
                        }
2489
                        $tags = explode(':', $tag);
2490
                        $t    = end($tags);
2491
                        $v    = $this->getGedcomValue($tag, 1, $grec);
2492
                        //-- check for EMAIL and _EMAIL (silly double gedcom standard :P)
2493
                        if ($t === 'EMAIL' && empty($v)) {
2494
                            $tag  = str_replace('EMAIL', '_EMAIL', $tag);
2495
                            $tags = explode(':', $tag);
2496
                            $t    = end($tags);
2497
                            $v    = self::getSubRecord(1, $tag, $grec);
2498
                        }
2499
2500
                        switch ($expr) {
2501
                            case 'GTE':
2502
                                if ($t === 'DATE') {
2503
                                    $date1 = new Date($v);
2504
                                    $date2 = new Date($val);
2505
                                    $keep  = (Date::compare($date1, $date2) >= 0);
2506
                                } elseif ($val >= $v) {
2507
                                    $keep = true;
2508
                                }
2509
                                break;
2510
                            case 'LTE':
2511
                                if ($t === 'DATE') {
2512
                                    $date1 = new Date($v);
2513
                                    $date2 = new Date($val);
2514
                                    $keep  = (Date::compare($date1, $date2) <= 0);
2515
                                } elseif ($val >= $v) {
2516
                                    $keep = true;
2517
                                }
2518
                                break;
2519
                            default:
2520
                                if ($v == $val) {
2521
                                    $keep = true;
2522
                                } else {
2523
                                    $keep = false;
2524
                                }
2525
                                break;
2526
                        }
2527
                    }
2528
                }
2529
                if ($keep) {
2530
                    $mylist[$key] = $indi;
2531
                }
2532
            }
2533
            $this->list = $mylist;
2534
        }
2535
2536
        switch ($sortby) {
2537
            case 'NAME':
2538
                uasort($this->list, GedcomRecord::nameComparator());
2539
                break;
2540
            case 'CHAN':
2541
                uasort($this->list, GedcomRecord::lastChangeComparator());
2542
                break;
2543
            case 'BIRT:DATE':
2544
                uasort($this->list, Individual::birthDateComparator());
2545
                break;
2546
            case 'DEAT:DATE':
2547
                uasort($this->list, Individual::deathDateComparator());
2548
                break;
2549
            case 'MARR:DATE':
2550
                uasort($this->list, Family::marriageDateComparator());
2551
                break;
2552
            default:
2553
                // unsorted or already sorted by SQL
2554
                break;
2555
        }
2556
2557
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2558
        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2559
    }
2560
2561
    /**
2562
     * Handle </list>
2563
     *
2564
     * @return void
2565
     */
2566
    protected function listEndHandler(): void
2567
    {
2568
        $this->process_repeats--;
2569
        if ($this->process_repeats > 0) {
2570
            return;
2571
        }
2572
2573
        // Check if there is any list
2574
        if (count($this->list) > 0) {
2575
            $lineoffset = 0;
2576
            foreach ($this->repeats_stack as $rep) {
2577
                $lineoffset = $lineoffset + (int) ($rep[1]) - 1;
2578
            }
2579
            //-- read the xml from the file
2580
            $lines = file($this->report);
2581
            if (empty($lines)) {
2582
                error_log(__FILE__ . ":" . __LINE__ . " impossible error!? \n");
2583
                // this can not happen! phpstan forces me to add stupid code
2584
                // we come here because the xml file exists! Is it possible to tell phpstan the $lines *is* an array ??
2585
                die("can not happen!!!");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
2586
            }
2587
            while ((!str_contains($lines[$lineoffset + $this->repeat_bytes], '<List')) && (($lineoffset + $this->repeat_bytes) > 0)) {
2588
                $lineoffset--;
2589
            }
2590
            $lineoffset++;
2591
            $reportxml = "<tempdoc>\n";
2592
            $line_nr   = $lineoffset + $this->repeat_bytes;
2593
            // List Level counter
2594
            $count = 1;
2595
            while (0 < $count) {
2596
                if (str_contains($lines[$line_nr], '<List')) {
2597
                    $count++;
2598
                } elseif (str_contains($lines[$line_nr], '</List')) {
2599
                    $count--;
2600
                }
2601
                if (0 < $count) {
2602
                    $reportxml .= $lines[$line_nr];
2603
                }
2604
                $line_nr++;
2605
            }
2606
            // No need to drag this
2607
            unset($lines);
2608
            $reportxml .= '</tempdoc>';
2609
            // Save original values
2610
            $this->parser_stack[] = $this->parser;
2611
            $oldgedrec            = $this->gedrec;
2612
2613
            $this->list_total   = count($this->list);
2614
            $this->list_private = 0;
2615
            foreach ($this->list as $record) {
2616
                if ($record->canShow()) {
2617
                    $this->gedrec = $record->privatizeGedcom(Auth::accessLevel($record->tree()));
2618
                    //-- start the sax parser
2619
                    $repeat_parser = xml_parser_create();
2620
                    $this->parser  = $repeat_parser;
2621
                    xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
2622
2623
                    xml_set_element_handler(
2624
                        $repeat_parser,
2625
                        function ($parser, string $name, array $attrs): void {
2626
                            $this->startElement($parser, $name, $attrs);
2627
                        },
2628
                        function ($parser, string $name): void {
2629
                            $this->endElement($parser, $name);
2630
                        }
2631
                    );
2632
2633
                    xml_set_character_data_handler(
2634
                        $repeat_parser,
2635
                        function ($parser, string $data): void {
2636
                            $this->characterData($parser, $data);
2637
                        }
2638
                    );
2639
2640
                    if (!xml_parse($repeat_parser, $reportxml, true)) {
2641
                        throw new DomainException(sprintf(
2642
                            'ListEHandler XML error: %s at line %d',
2643
                            xml_error_string(xml_get_error_code($repeat_parser)),
2644
                            xml_get_current_line_number($repeat_parser)
2645
                        ));
2646
                    }
2647
                    xml_parser_free($repeat_parser);
2648
                } else {
2649
                    $this->list_private++;
2650
                }
2651
            }
2652
            $this->list   = [];
2653
            $this->parser = array_pop($this->parser_stack);
2654
            $this->gedrec = $oldgedrec;
2655
        }
2656
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2657
    }
2658
2659
    /**
2660
     * Handle <listTotal>
2661
     * Prints the total number of records in a list
2662
     * The total number is collected from <list> and <relatives>
2663
     *
2664
     * @return void
2665
     */
2666
    protected function listTotalStartHandler(): void
2667
    {
2668
        if ($this->list_private == 0) {
2669
            $this->current_element->addText((string) $this->list_total);
2670
        } else {
2671
            $this->current_element->addText(($this->list_total - $this->list_private) . ' / ' . $this->list_total);
2672
        }
2673
    }
2674
2675
    /**
2676
     * Handle <relatives>
2677
     *
2678
     * @param array<string> $attrs
2679
     *
2680
     * @return void
2681
     */
2682
    protected function relativesStartHandler(array $attrs): void
2683
    {
2684
        $this->process_repeats++;
2685
        if ($this->process_repeats > 1) {
2686
            return;
2687
        }
2688
2689
        $sortby = $attrs['sortby'] ?? 'NAME';
2690
2691
        $match = [];
2692
        if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2693
            $sortby = $this->vars[$match[1]]['id'];
2694
            $sortby = trim($sortby);
2695
        }
2696
2697
        $maxgen = -1;
2698
        if (isset($attrs['maxgen'])) {
2699
            $maxgen = (int) $attrs['maxgen'];
2700
        }
2701
2702
        $group = $attrs['group'] ?? 'child-family';
2703
2704
        if (preg_match("/\\$(\w+)/", $group, $match)) {
2705
            $group = $this->vars[$match[1]]['id'];
2706
            $group = trim($group);
2707
        }
2708
2709
        $id = $attrs['id'] ?? '';
2710
2711
        if (preg_match("/\\$(\w+)/", $id, $match)) {
2712
            $id = $this->vars[$match[1]]['id'];
2713
            $id = trim($id);
2714
        }
2715
2716
        $this->list = [];
2717
        $person     = Registry::individualFactory()->make($id, $this->tree);
2718
        if ($person instanceof Individual) {
2719
            $this->list[$id] = $person;
2720
            $this->mfrelation[$id] = "";
2721
            $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...
2722
            switch ($group) {
2723
                case 'child-family':
2724
                    foreach ($person->childFamilies() as $family) {
2725
                        foreach ($family->spouses() as $spouse) {
2726
                            $this->list[$spouse->xref()] = $spouse;
2727
                        }
2728
2729
                        foreach ($family->children() as $child) {
2730
                            $this->list[$child->xref()] = $child;
2731
                        }
2732
                    }
2733
                    break;
2734
                case 'spouse-family':
2735
                    foreach ($person->spouseFamilies() as $family) {
2736
                        foreach ($family->spouses() as $spouse) {
2737
                            $this->list[$spouse->xref()] = $spouse;
2738
                        }
2739
2740
                        foreach ($family->children() as $child) {
2741
                            $this->list[$child->xref()] = $child;
2742
                        }
2743
                    }
2744
                    break;
2745
                case 'direct-ancestors':
2746
                    $this->addAncestors($this->list, $id, false, $maxgen);
2747
                    break;
2748
                case 'ancestors':
2749
                    $this->addAncestors($this->list, $id, true, $maxgen);
2750
                    break;
2751
                case 'descendants':
2752
                    $this->list[$id]->generation = 1;
2753
                    $this->addDescendancy($this->list, $id, false, $maxgen);
2754
                    break;
2755
                case 'all':
2756
                    $this->addAncestors($this->list, $id, true, $maxgen);
2757
                    $this->addDescendancy($this->list, $id, true, $maxgen);
2758
                    break;
2759
            }
2760
        }
2761
2762
        switch ($sortby) {
2763
            case 'NAME':
2764
                uasort($this->list, GedcomRecord::nameComparator());
2765
                break;
2766
            case 'BIRT:DATE':
2767
                uasort($this->list, Individual::birthDateComparator());
2768
                break;
2769
            case 'DEAT:DATE':
2770
                uasort($this->list, Individual::deathDateComparator());
2771
                break;
2772
            case 'generation':
2773
                $newarray = [];
2774
                reset($this->list);
2775
                $genCounter = 1;
2776
                while (count($newarray) < count($this->list)) {
2777
                    foreach ($this->list as $key => $value) {
2778
                        if ($value->generation < 0) {
2779
                            // indication of husband or wife
2780
                            $this->generation = -$value->generation;
2781
                        } else {
2782
                            $this->generation = $value->generation;
2783
                        }
2784
                        if ($this->generation == $genCounter) {
2785
                            $newarray[$key] = (object) ['generation' => $this->generation];
2786
                        }
2787
                    }
2788
                    $genCounter++;
2789
                }
2790
                $this->list = $newarray;
2791
                break;
2792
            default:
2793
                // unsorted
2794
                break;
2795
        }
2796
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2797
        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2798
    }
2799
2800
    /**
2801
     * Handle </relatives>
2802
     *
2803
     * @return void
2804
     */
2805
    protected function relativesEndHandler(): void
2806
    {
2807
        $this->process_repeats--;
2808
        if ($this->process_repeats > 0) {
2809
            return;
2810
        }
2811
2812
        // Check if there is any relatives
2813
        if (count($this->list) > 0) {
2814
            $lineoffset = 0;
2815
            foreach ($this->repeats_stack as $rep) {
2816
                $lineoffset = $lineoffset + (int) ($rep[1]) - 1;
2817
            }
2818
            //-- read the xml from the file
2819
            $lines = file($this->report);
2820
            if (empty($lines)) {
2821
                error_log(__FILE__ . ":" . __LINE__ . " impossible error!? \n");
2822
                // this can not happen! phpstan forces me to add stupid code
2823
                // we come here because the xml file exists! Is it possible to tell phpstan the $lines *is* an array ??
2824
                die("can not happen!!!");
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
2825
            }
2826
            while (!str_contains($lines[$lineoffset + $this->repeat_bytes], '<Relatives') && $lineoffset + $this->repeat_bytes > 0) {
2827
                $lineoffset--;
2828
            }
2829
            $lineoffset++;
2830
            $reportxml = "<tempdoc>\n";
2831
            $line_nr   = $lineoffset + $this->repeat_bytes;
2832
            // Relatives Level counter
2833
            $count = 1;
2834
            while (0 < $count) {
2835
                if (str_contains($lines[$line_nr], '<Relatives')) {
2836
                    $count++;
2837
                } elseif (str_contains($lines[$line_nr], '</Relatives')) {
2838
                    $count--;
2839
                }
2840
                if (0 < $count) {
2841
                    $reportxml .= $lines[$line_nr];
2842
                }
2843
                $line_nr++;
2844
            }
2845
            // No need to drag this
2846
            unset($lines);
2847
            $reportxml .= "</tempdoc>\n";
2848
            // Save original values
2849
            $this->parser_stack[] = $this->parser;
2850
            $oldgedrec            = $this->gedrec;
2851
2852
            $this->list_total   = count($this->list);
2853
            $this->list_private = 0;
2854
            foreach ($this->list as $key => $value) {
2855
                if (isset($value->generation)) {
2856
                    $this->generation = $value->generation;
2857
                }
2858
                $xref = $key;
2859
                $this->vars["dupl"]["id"] = "no";
2860
                if (substr($key, 0, 2) == "D_") {
2861
                    $xref = substr($key, strrpos($key, "_") + 1);
2862
                    $this->vars["dupl"]["id"] = "yes";
2863
                }
2864
                $tmp          = Registry::gedcomRecordFactory()->make((string) $xref, $this->tree);
2865
                $this->gedrec = $tmp->privatizeGedcom(Auth::accessLevel($this->tree));
2866
2867
                $repeat_parser = xml_parser_create();
2868
                $this->parser  = $repeat_parser;
2869
                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
2870
2871
                xml_set_element_handler(
2872
                    $repeat_parser,
2873
                    function ($parser, string $name, array $attrs): void {
2874
                        $this->startElement($parser, $name, $attrs);
2875
                    },
2876
                    function ($parser, string $name): void {
2877
                        $this->endElement($parser, $name);
2878
                    }
2879
                );
2880
2881
                xml_set_character_data_handler(
2882
                    $repeat_parser,
2883
                    function ($parser, string $data): void {
2884
                        $this->characterData($parser, $data);
2885
                    }
2886
                );
2887
2888
                if (!xml_parse($repeat_parser, $reportxml, true)) {
2889
                    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)));
2890
                }
2891
                xml_parser_free($repeat_parser);
2892
            }
2893
            // Clean up the list array
2894
            $this->list   = [];
2895
            $this->parser = array_pop($this->parser_stack);
2896
            $this->gedrec = $oldgedrec;
2897
        }
2898
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2899
    }
2900
2901
    /**
2902
     * Handle <generation />
2903
     * Prints the number of generations
2904
     *
2905
     * @return void
2906
     */
2907
    protected function generationStartHandler(): void
2908
    {
2909
        $this->current_element->addText((string) $this->generation);
2910
    }
2911
2912
    /**
2913
     * Handle <newPage />
2914
     * Has to be placed in an element (header, body or footer)
2915
     *
2916
     * @return void
2917
     */
2918
    protected function newPageStartHandler(): void
2919
    {
2920
        $temp = 'addpage';
2921
        $this->wt_report->addElement($temp);
2922
    }
2923
2924
    /**
2925
     * Handle </title>
2926
     *
2927
     * @return void
2928
     */
2929
    protected function titleEndHandler(): void
2930
    {
2931
        $this->report_root->addTitle($this->text);
2932
    }
2933
2934
    /**
2935
     * Handle </description>
2936
     *
2937
     * @return void
2938
     */
2939
    protected function descriptionEndHandler(): void
2940
    {
2941
        $this->report_root->addDescription($this->text);
2942
    }
2943
2944
    /**
2945
     * Create a list of all descendants.
2946
     *
2947
     * @param array<Individual> $list
2948
     * @param string            $pid
2949
     * @param bool              $parents
2950
     * @param int               $generations
2951
     *
2952
     * @return void
2953
     */
2954
    private function addDescendancy(&$list, $pid, $parents = false, $generations = -1): void
2955
    {
2956
        $person = Registry::individualFactory()->make($pid, $this->tree);
2957
        if ($person === null) {
2958
            return;
2959
        }
2960
2961
        static $focusperson = true;
2962
        static $dupl = 1;
2963
        $sx = $person->sex();
2964
        $rl = "x"; // unknown
2965
        if ($sx == "M") {
2966
            $rl = "s";
2967
        } // son
2968
        if ($sx == "F") {
2969
            $rl = "d";
0 ignored issues
show
Unused Code introduced by
The assignment to $rl is dead and can be removed.
Loading history...
2970
        } // daughter
2971
        if ($focusperson) {
2972
            $this->mfrelation[$pid] = "";
2973
        }
2974
        $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...
2975
2976
        $newpid = $pid;
2977
        if (!isset($list[$pid])) {
2978
            $list[$pid] = $person;
2979
        } elseif (!$focusperson) {
2980
            $newpid = "D_" . $dupl . "_" . $pid;
2981
            $list[$newpid] = $person;
2982
        }
2983
        if (!isset($list[$newpid]->generation)) {
2984
            $list[$newpid]->generation = 0;
2985
        }
2986
        $focusperson = false;
2987
        foreach ($person->spouseFamilies() as $family) {
2988
            if ($parents) {
2989
                $husband = $family->husband();
2990
                $wife    = $family->wife();
2991
                if ($husband) {
2992
                    $list[$husband->xref()] = $husband;
2993
                    if (isset($list[$pid]->generation)) {
2994
                        $list[$husband->xref()]->generation = $list[$pid]->generation - 1;
2995
                    } else {
2996
                        $list[$husband->xref()]->generation = 1;
2997
                    }
2998
                }
2999
                if ($wife) {
3000
                    $list[$wife->xref()] = $wife;
3001
                    if (isset($list[$pid]->generation)) {
3002
                        $list[$wife->xref()]->generation = $list[$pid]->generation - 1;
3003
                    } else {
3004
                        $list[$wife->xref()]->generation = 1;
3005
                    }
3006
                }
3007
            }
3008
            $husband = $family->husband();
3009
            $wife = $family->wife();
3010
3011
            if ($husband && $wife) {
3012
                if ($husband->xref() == $person->xref()) {
3013
                    $this->mfrelation[$wife->xref()] = $this->mfrelation[$person->xref()] . "x";
3014
                    if ($wife->canShow()) {
3015
                        $list[$wife->xref()] = $wife;
3016
                    }
3017
                    if (!isset($wife->generation)) {
3018
                        $wife->generation = $person->generation;
3019
                    }
3020
                    $nam = $wife->getAllNames()[0]['fullNN'];
3021
                } else {
3022
                    $this->mfrelation[$husband->xref()] = $this->mfrelation[$person->xref()] . "x";
3023
                    if ($husband->canShow()) {
3024
                        $list[$husband->xref()] = $husband;
3025
                    }
3026
                    if (!isset($husband->generation)) {
3027
                        $husband->generation = $person->generation;
3028
                    }
3029
                    $nam = $husband->getAllNames()[0]['fullNN'];
3030
                }
3031
            }
3032
3033
            $children = $family->children();
3034
            foreach ($children as $child) {
3035
                if ($child) {
3036
                    $sx = $child->sex();
3037
                    $rl = "x"; // unknown
3038
                    if ($sx == "M") {
3039
                        $rl = "s";
3040
                    } // son
3041
                    if ($sx == "F") {
3042
                        $rl = "d";
3043
                    } // daughter
3044
                    $rl = $this->mfrelation[$person->xref()] . $rl;
3045
                    $this->mfrelation[$child->xref()] = $rl;
3046
                    if (isset($list[$pid]->generation)) {
3047
                        $child->generation = $list[$pid]->generation + 1;
3048
                    } else {
3049
                        $child->generation = 2;
3050
                    }
3051
                }
3052
            }
3053
            if ($generations == -1 || $list[$pid]->generation < $generations) {
3054
                foreach ($children as $child) {
3055
                    if ($child->canShow()) {
3056
                        $this->addDescendancy($list, $child->xref(), $parents, $generations);
3057
                    } // recurse on the childs family
3058
                }
3059
            }
3060
        }
3061
        $focusperson = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $focusperson is dead and can be removed.
Loading history...
3062
    }
3063
3064
    /**
3065
     * Create a list of all ancestors.
3066
     *
3067
     * @param array<Individual> $list
3068
     * @param string            $pid
3069
     * @param bool              $children
3070
     * @param int               $generations
3071
     *
3072
     * @return void
3073
     */
3074
    private function addAncestors(array &$list, string $pid, bool $children = false, int $generations = -1): void
3075
    {
3076
        $genlist                = [$pid];
3077
        $list[$pid]->generation = 1;
3078
        while (count($genlist) > 0) {
3079
            $id = array_shift($genlist);
3080
            if (str_starts_with($id, 'empty')) {
3081
                continue; // id can be something like “empty7”
3082
            }
3083
            if (!isset($this->mfrelation[$id])) {
3084
                $this->mfrelation[$id] = "";
3085
            }
3086
            $person = Registry::individualFactory()->make($id, $this->tree);
3087
            foreach ($person->childFamilies() as $family) {
3088
                $husband = $family->husband();
3089
                $wife    = $family->wife();
3090
                if ($husband) {
3091
                    $list[$husband->xref()]             = $husband;
3092
                    $list[$husband->xref()]->generation = $list[$id]->generation + 1;
3093
                    $this->mfrelation[$husband->xref()] = $this->mfrelation[$id] . "f";
3094
                }
3095
                if ($wife) {
3096
                    $list[$wife->xref()]             = $wife;
3097
                    $list[$wife->xref()]->generation = $list[$id]->generation + 1;
3098
                    $this->mfrelation[$wife->xref()] = $this->mfrelation[$id] . "m";
3099
                }
3100
                if ($generations == -1 || $list[$id]->generation + 1 < $generations) {
3101
                    if ($husband) {
3102
                        $genlist[] = $husband->xref();
3103
                    }
3104
                    if ($wife) {
3105
                        $genlist[] = $wife->xref();
3106
                    }
3107
                }
3108
                if ($children && isset($person)) {
3109
                    // unnecessary test of $person to satisfy phpstan!
3110
                    foreach ($family->children() as $child) {
3111
                        $list[$child->xref()] = $child;
3112
                        $child->generation = $list[$id]->generation ?? 1;
3113
                        if ($child->xref() != $person->xref()) {
3114
                            $this->mfrelation[$child->xref()] = $this->mfrelation[$id] . "x";
3115
                        }
3116
                    }
3117
                }
3118
            }
3119
        }
3120
    }
3121
3122
    /**
3123
     * get gedcom tag value
3124
     *
3125
     * @param string $tag    The tag to find, use : to delineate subtags
3126
     * @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
3127
     * @param string $gedrec The gedcom record to get the value from
3128
     *
3129
     * @return string the value of a gedcom tag from the given gedcom record
3130
     */
3131
    private function getGedcomValue(string $tag, int $level, string $gedrec): string
3132
    {
3133
        if ($gedrec === '') {
3134
            return '';
3135
        }
3136
        $tags      = explode(':', $tag);
3137
        $origlevel = $level;
3138
        if ($level === 0) {
3139
            $level = $gedrec[0] + 1;
3140
        }
3141
3142
        $subrec = $gedrec;
3143
        $t = 'XXXX';
3144
        foreach ($tags as $t) {
3145
            $lastsubrec = $subrec;
3146
            $subrec     = self::getSubRecord($level, "$level $t", $subrec);
3147
            if (empty($subrec) && $origlevel == 0) {
3148
                $level--;
3149
                $subrec = self::getSubRecord($level, "$level $t", $lastsubrec);
3150
            }
3151
            if (empty($subrec)) {
3152
                if ($t === 'TITL') {
3153
                    $subrec = self::getSubRecord($level, "$level ABBR", $lastsubrec);
3154
                    if (!empty($subrec)) {
3155
                        $t = 'ABBR';
3156
                    }
3157
                }
3158
                if ($subrec === '') {
3159
                    if ($level > 0) {
3160
                        $level--;
3161
                    }
3162
                    $subrec = self::getSubRecord($level, "@ $t", $gedrec);
3163
                    if ($subrec === '') {
3164
                        return '';
3165
                    }
3166
                }
3167
            }
3168
            $level++;
3169
        }
3170
        $level--;
3171
        $ct = preg_match("/$level $t(.*)/", $subrec, $match);
3172
        if ($ct === 0) {
3173
            $ct = preg_match("/$level @.+@ (.+)/", $subrec, $match);
3174
        }
3175
        if ($ct === 0) {
3176
            $ct = preg_match("/@ $t (.+)/", $subrec, $match);
3177
        }
3178
        if ($ct > 0) {
3179
            $value = trim($match[1]);
3180
            if ($t === 'NOTE' && preg_match('/^@(.+)@$/', $value, $match)) {
3181
                $note = Registry::noteFactory()->make($match[1], $this->tree);
3182
                if ($note instanceof Note) {
3183
                    $value = $note->getNote();
3184
                } else {
3185
                    //-- set the value to the id without the @
3186
                    $value = $match[1];
3187
                }
3188
            }
3189
            if ($level !== 0 || $t !== 'NOTE') {
3190
                $value .= self::getCont($level + 1, $subrec);
3191
            }
3192
3193
            if ($tag === 'NAME' || $tag === '_MARNM' || $tag === '_AKA') {
3194
                return strtr($value, ['/' => '']);
3195
            }
3196
3197
            if ($tag === 'NAME' || $tag === '_MARNM' || $tag === '_AKA') {
3198
                return strtr($value, ['/' => '']);
3199
            }
3200
3201
            return $value;
3202
        }
3203
3204
        return '';
3205
    }
3206
3207
    /**
3208
     * Replace variable identifiers with their values.
3209
     *
3210
     * @param string $expression An expression such as "$foo == 123"
3211
     * @param bool   $quote      Whether to add quotation marks
3212
     *
3213
     * @return string
3214
     */
3215
    private function substituteVars($expression, $quote): string
3216
    {
3217
        return preg_replace_callback(
3218
            '/\$(\w+)/',
3219
            function (array $matches) use ($quote): string {
3220
                if (isset($this->vars[$matches[1]]['id'])) {
3221
                    if ($quote) {
3222
                        return "'" . addcslashes($this->vars[$matches[1]]['id'], "'") . "'";
3223
                    }
3224
3225
                    return $this->vars[$matches[1]]['id'];
3226
                }
3227
3228
                Log::addErrorLog(sprintf('Undefined variable $%s in report', $matches[1]));
3229
3230
                return '$' . $matches[1];
3231
            },
3232
            $expression
3233
        );
3234
    }
3235
}
3236