Passed
Pull Request — main (#4945)
by
unknown
15:00
created

ReportParserGenerate::varStartHandler()   F

Complexity

Conditions 19
Paths 1261

Size

Total Lines 59
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 38
nc 1261
nop 1
dl 0
loc 59
rs 0.3499
c 0
b 0
f 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
    private array $mfrelation = [];
186
187
    private Tree $tree;
188
189
    /**
190
     * Create a parser for a report
191
     *
192
     * @param string               $report The XML filename
193
     * @param AbstractRenderer     $report_root
194
     * @param array<array<string>> $vars
195
     * @param Tree                 $tree
196
     */
197
    public function __construct(string $report, AbstractRenderer $report_root, array $vars, Tree $tree)
198
    {
199
        $this->report          = $report;
200
        $this->report_root     = $report_root;
201
        $this->wt_report       = $report_root;
202
        $this->current_element = new ReportBaseElement();
203
        $this->vars            = $vars;
204
        $this->tree            = $tree;
205
206
        parent::__construct($report);
207
    }
208
209
    /**
210
     * get a gedcom subrecord
211
     *
212
     * searches a gedcom record and returns a subrecord of it. A subrecord is defined starting at a
213
     * line with level N and all subsequent lines greater than N until the next N level is reached.
214
     * For example, the following is a BIRT subrecord:
215
     * <code>1 BIRT
216
     * 2 DATE 1 JAN 1900
217
     * 2 PLAC Phoenix, Maricopa, Arizona</code>
218
     * The following example is the DATE subrecord of the above BIRT subrecord:
219
     * <code>2 DATE 1 JAN 1900</code>
220
     *
221
     * @param int    $level   the N level of the subrecord to get
222
     * @param string $tag     a gedcom tag or string to search for in the record (ie 1 BIRT or 2 DATE)
223
     * @param string $gedrec  the parent gedcom record to search in
224
     * @param int    $num     this allows you to specify which matching <var>$tag</var> to get. Oftentimes a
225
     *                        gedcom record will have more that 1 of the same type of subrecord. An individual may have
226
     *                        multiple events for example. Passing $num=1 would get the first 1. Passing $num=2 would get the
227
     *                        second one, etc.
228
     *
229
     * @return string the subrecord that was found or an empty string "" if not found.
230
     */
231
    public static function getSubRecord(int $level, string $tag, string $gedrec, int $num = 1): string
232
    {
233
        if ($gedrec === '') {
234
            return '';
235
        }
236
        // -- adding \n before and after gedrec
237
        $gedrec       = "\n" . $gedrec . "\n";
238
        $tag          = trim($tag);
239
        $searchTarget = "~[\n]" . $tag . "[\s]~";
240
        $ct           = preg_match_all($searchTarget, $gedrec, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
241
        if ($ct === 0) {
242
            return '';
243
        }
244
        if ($ct < $num) {
245
            return '';
246
        }
247
        $pos1 = $match[$num - 1][0][1];
248
        $pos2 = strpos($gedrec, "\n$level", $pos1 + 1);
249
        if (!$pos2) {
250
            $pos2 = strpos($gedrec, "\n1", $pos1 + 1);
251
        }
252
        if (!$pos2) {
253
            $pos2 = strpos($gedrec, "\nWT_", $pos1 + 1); // WT_SPOUSE, WT_FAMILY_ID ...
254
        }
255
        if (!$pos2) {
256
            return ltrim(substr($gedrec, $pos1));
257
        }
258
        $subrec = substr($gedrec, $pos1, $pos2 - $pos1);
259
260
        return ltrim($subrec);
261
    }
262
263
    /**
264
     * get CONT lines
265
     *
266
     * get the N+1 CONT or CONC lines of a gedcom subrecord
267
     *
268
     * @param int    $nlevel the level of the CONT lines to get
269
     * @param string $nrec   the gedcom subrecord to search in
270
     *
271
     * @return string a string with all CONT lines merged
272
     */
273
    public static function getCont(int $nlevel, string $nrec): string
274
    {
275
        $text = '';
276
277
        $subrecords = explode("\n", $nrec);
278
        foreach ($subrecords as $thisSubrecord) {
279
            if (substr($thisSubrecord, 0, 2) !== $nlevel . ' ') {
280
                continue;
281
            }
282
            $subrecordType = substr($thisSubrecord, 2, 4);
283
            if ($subrecordType === 'CONT') {
284
                $text .= "\n" . substr($thisSubrecord, 7);
285
            }
286
        }
287
288
        return $text;
289
    }
290
291
    /**
292
     * XML start element handler
293
     * This function is called whenever a starting element is reached
294
     * The element handler will be called if found, otherwise it must be HTML
295
     *
296
     * @param resource      $parser the resource handler for the XML parser
297
     * @param string        $name   the name of the XML element parsed
298
     * @param array<string> $attrs  an array of key value pairs for the attributes
299
     *
300
     * @return void
301
     */
302
    protected function startElement($parser, string $name, array $attrs): void
303
    {
304
        $newattrs = [];
305
306
        foreach ($attrs as $key => $value) {
307
            if (preg_match("/^\\$(\w+)$/", $value, $match)) {
308
                if (isset($this->vars[$match[1]]['id']) && !isset($this->vars[$match[1]]['gedcom'])) {
309
                    $value = $this->vars[$match[1]]['id'];
310
                }
311
            }
312
            $newattrs[$key] = $value;
313
        }
314
        $attrs = $newattrs;
315
        if ($this->process_footnote && ($this->process_ifs === 0 || $name === 'if') && ($this->process_gedcoms === 0 || $name === 'Gedcom') && ($this->process_repeats === 0 || $name === 'Facts' || $name === 'RepeatTag')) {
316
            $method = $name . 'StartHandler';
317
318
            if (method_exists($this, $method)) {
319
                $this->{$method}($attrs);
320
            }
321
        }
322
    }
323
324
    /**
325
     * XML end element handler
326
     * This function is called whenever an ending element is reached
327
     * The element handler will be called if found, otherwise it must be HTML
328
     *
329
     * @param resource $parser the resource handler for the XML parser
330
     * @param string   $name   the name of the XML element parsed
331
     *
332
     * @return void
333
     */
334
    protected function endElement($parser, string $name): void
335
    {
336
        if (($this->process_footnote || $name === 'Footnote') && ($this->process_ifs === 0 || $name === 'if') && ($this->process_gedcoms === 0 || $name === 'Gedcom') && ($this->process_repeats === 0 || $name === 'Facts' || $name === 'RepeatTag' || $name === 'List' || $name === 'Relatives')) {
337
            $method = $name . 'EndHandler';
338
339
            if (method_exists($this, $method)) {
340
                $this->{$method}();
341
            }
342
        }
343
    }
344
345
    /**
346
     * XML character data handler
347
     *
348
     * @param resource $parser the resource handler for the XML parser
349
     * @param string   $data   the name of the XML element parsed
350
     *
351
     * @return void
352
     */
353
    protected function characterData($parser, string $data): void
354
    {
355
        if ($this->print_data && $this->process_gedcoms === 0 && $this->process_ifs === 0 && $this->process_repeats === 0) {
356
            $this->current_element->addText($data);
357
        }
358
    }
359
360
    /**
361
     * Handle <style>
362
     *
363
     * @param array<string> $attrs
364
     *
365
     * @return void
366
     */
367
    protected function styleStartHandler(array $attrs): void
368
    {
369
        if (empty($attrs['name'])) {
370
            throw new DomainException('REPORT ERROR Style: The "name" of the style is missing or not set in the XML file.');
371
        }
372
373
        $style = [
374
            'name'  => $attrs['name'],
375
            'font'  => $attrs['font'] ?? $this->wt_report->default_font,
376
            'size'  => (float) ($attrs['size'] ?? $this->wt_report->default_font_size),
377
            'style' => $attrs['style'] ?? '',
378
        ];
379
380
        $this->wt_report->addStyle($style);
381
    }
382
383
    /**
384
     * Handle <doc>
385
     * Sets up the basics of the document proparties
386
     *
387
     * @param array<string> $attrs
388
     *
389
     * @return void
390
     */
391
    protected function docStartHandler(array $attrs): void
392
    {
393
        $this->parser = $this->xml_parser;
394
395
        // Custom page width
396
        if (!empty($attrs['customwidth'])) {
397
            $this->wt_report->page_width = (float) $attrs['customwidth'];
398
        }
399
        // Custom Page height
400
        if (!empty($attrs['customheight'])) {
401
            $this->wt_report->page_height = (float) $attrs['customheight'];
402
        }
403
404
        // Left Margin
405
        if (isset($attrs['leftmargin'])) {
406
            if ($attrs['leftmargin'] === '0') {
407
                $this->wt_report->left_margin = 0;
408
            } elseif (!empty($attrs['leftmargin'])) {
409
                $this->wt_report->left_margin = (float) $attrs['leftmargin'];
410
            }
411
        }
412
        // Right Margin
413
        if (isset($attrs['rightmargin'])) {
414
            if ($attrs['rightmargin'] === '0') {
415
                $this->wt_report->right_margin = 0;
416
            } elseif (!empty($attrs['rightmargin'])) {
417
                $this->wt_report->right_margin = (float) $attrs['rightmargin'];
418
            }
419
        }
420
        // Top Margin
421
        if (isset($attrs['topmargin'])) {
422
            if ($attrs['topmargin'] === '0') {
423
                $this->wt_report->top_margin = 0;
424
            } elseif (!empty($attrs['topmargin'])) {
425
                $this->wt_report->top_margin = (float) $attrs['topmargin'];
426
            }
427
        }
428
        // Bottom Margin
429
        if (isset($attrs['bottommargin'])) {
430
            if ($attrs['bottommargin'] === '0') {
431
                $this->wt_report->bottom_margin = 0;
432
            } elseif (!empty($attrs['bottommargin'])) {
433
                $this->wt_report->bottom_margin = (float) $attrs['bottommargin'];
434
            }
435
        }
436
        // Header Margin
437
        if (isset($attrs['headermargin'])) {
438
            if ($attrs['headermargin'] === '0') {
439
                $this->wt_report->header_margin = 0;
440
            } elseif (!empty($attrs['headermargin'])) {
441
                $this->wt_report->header_margin = (float) $attrs['headermargin'];
442
            }
443
        }
444
        // Footer Margin
445
        if (isset($attrs['footermargin'])) {
446
            if ($attrs['footermargin'] === '0') {
447
                $this->wt_report->footer_margin = 0;
448
            } elseif (!empty($attrs['footermargin'])) {
449
                $this->wt_report->footer_margin = (float) $attrs['footermargin'];
450
            }
451
        }
452
453
        // Page Orientation
454
        if (!empty($attrs['orientation'])) {
455
            if ($attrs['orientation'] === 'landscape') {
456
                $this->wt_report->orientation = 'landscape';
457
            } elseif ($attrs['orientation'] === 'portrait') {
458
                $this->wt_report->orientation = 'portrait';
459
            }
460
        }
461
        // Page Size
462
        if (!empty($attrs['pageSize'])) {
463
            $this->wt_report->page_format = $attrs['pageSize'];
464
        }
465
466
        // Show Generated By...
467
        if (isset($attrs['showGeneratedBy'])) {
468
            if ($attrs['showGeneratedBy'] === '0') {
469
                $this->wt_report->show_generated_by = false;
470
            } elseif ($attrs['showGeneratedBy'] === '1') {
471
                $this->wt_report->show_generated_by = true;
472
            }
473
        }
474
475
        $this->wt_report->setup();
476
    }
477
478
    /**
479
     * Handle </doc>
480
     *
481
     * @return void
482
     */
483
    protected function docEndHandler(): void
484
    {
485
        $this->wt_report->run();
486
    }
487
488
    /**
489
     * Handle <header>
490
     *
491
     * @return void
492
     */
493
    protected function headerStartHandler(): void
494
    {
495
        // Clear the Header before any new elements are added
496
        $this->wt_report->clearHeader();
497
        $this->wt_report->setProcessing('H');
498
    }
499
500
    /**
501
     * Handle <body>
502
     *
503
     * @return void
504
     */
505
    protected function bodyStartHandler(): void
506
    {
507
        $this->wt_report->setProcessing('B');
508
    }
509
510
    /**
511
     * Handle <footer>
512
     *
513
     * @return void
514
     */
515
    protected function footerStartHandler(): void
516
    {
517
        $this->wt_report->setProcessing('F');
518
    }
519
520
    /**
521
     * Handle <cell>
522
     *
523
     * @param array<string,string> $attrs
524
     *
525
     * @return void
526
     */
527
    protected function cellStartHandler(array $attrs): void
528
    {
529
        // string The text alignment of the text in this box.
530
        $align = $attrs['align'] ?? '';
531
        // RTL supported left/right alignment
532
        if ($align === 'rightrtl') {
533
            if ($this->wt_report->rtl) {
534
                $align = 'left';
535
            } else {
536
                $align = 'right';
537
            }
538
        } elseif ($align === 'leftrtl') {
539
            if ($this->wt_report->rtl) {
540
                $align = 'right';
541
            } else {
542
                $align = 'left';
543
            }
544
        }
545
546
        // The color to fill the background of this cell
547
        $bgcolor = $attrs['bgcolor'] ?? '';
548
549
        // Whether the background should be painted
550
        $fill = (bool) ($attrs['fill'] ?? '0');
551
552
        // If true reset the last cell height
553
        $reseth = (bool) ($attrs['reseth'] ?? '1');
554
555
        // Whether a border should be printed around this box
556
        $border = $attrs['border'] ?? '';
557
558
        // string Border color in HTML code
559
        $bocolor = $attrs['bocolor'] ?? '';
560
561
        // Cell height (expressed in points) The starting height of this cell. If the text wraps the height will automatically be adjusted.
562
        $height = (int) ($attrs['height'] ?? '0');
563
564
        // int Cell width (expressed in points) Setting the width to 0 will make it the width from the current location to the right margin.
565
        $width = (int) ($attrs['width'] ?? '0');
566
567
        // Stretch character mode
568
        $stretch = (int) ($attrs['stretch'] ?? '0');
569
570
        // mixed Position the left corner of this box on the page. The default is the current position.
571
        $left = ReportBaseElement::CURRENT_POSITION;
572
        if (isset($attrs['left'])) {
573
            if ($attrs['left'] === '.') {
574
                $left = ReportBaseElement::CURRENT_POSITION;
575
            } elseif (!empty($attrs['left'])) {
576
                $left = (float) $attrs['left'];
577
            } elseif ($attrs['left'] === '0') {
578
                $left = 0.0;
579
            }
580
        }
581
        // mixed Position the top corner of this box on the page. the default is the current position
582
        $top = ReportBaseElement::CURRENT_POSITION;
583
        if (isset($attrs['top'])) {
584
            if ($attrs['top'] === '.') {
585
                $top = ReportBaseElement::CURRENT_POSITION;
586
            } elseif (!empty($attrs['top'])) {
587
                $top = (float) $attrs['top'];
588
            } elseif ($attrs['top'] === '0') {
589
                $top = 0.0;
590
            }
591
        }
592
593
        // The name of the Style that should be used to render the text.
594
        $style = $attrs['style'] ?? '';
595
596
        // string Text color in html code
597
        $tcolor = $attrs['tcolor'] ?? '';
598
599
        // int Indicates where the current position should go after the call.
600
        $ln = 0;
601
        if (isset($attrs['newline'])) {
602
            if (!empty($attrs['newline'])) {
603
                $ln = (int) $attrs['newline'];
604
            } elseif ($attrs['newline'] === '0') {
605
                $ln = 0;
606
            }
607
        }
608
609
        if ($align === 'left') {
610
            $align = 'L';
611
        } elseif ($align === 'right') {
612
            $align = 'R';
613
        } elseif ($align === 'center') {
614
            $align = 'C';
615
        } elseif ($align === 'justify') {
616
            $align = 'J';
617
        }
618
619
        $this->print_data_stack[] = $this->print_data;
620
        $this->print_data         = true;
621
622
        $this->current_element = $this->report_root->createCell(
623
            (int) $width,
624
            (int) $height,
625
            $border,
626
            $align,
627
            $bgcolor,
628
            $style,
629
            $ln,
630
            $top,
631
            $left,
632
            $fill,
633
            $stretch,
634
            $bocolor,
635
            $tcolor,
636
            $reseth
637
        );
638
    }
639
640
    /**
641
     * Handle </cell>
642
     *
643
     * @return void
644
     */
645
    protected function cellEndHandler(): void
646
    {
647
        $this->print_data = array_pop($this->print_data_stack);
648
        $this->wt_report->addElement($this->current_element);
649
    }
650
651
    /**
652
     * Handle <now />
653
     *
654
     * @return void
655
     */
656
    protected function nowStartHandler(): void
657
    {
658
        $this->current_element->addText(Registry::timestampFactory()->now()->isoFormat('LLLL'));
659
    }
660
661
    /**
662
     * Handle <pageNum />
663
     *
664
     * @return void
665
     */
666
    protected function pageNumStartHandler(): void
667
    {
668
        $this->current_element->addText('#PAGENUM#');
669
    }
670
671
    /**
672
     * Handle <totalPages />
673
     *
674
     * @return void
675
     */
676
    protected function totalPagesStartHandler(): void
677
    {
678
        $this->current_element->addText('{{:ptp:}}');
679
    }
680
681
    /**
682
     * Called at the start of an element.
683
     *
684
     * @param array<string> $attrs an array of key value pairs for the attributes
685
     *
686
     * @return void
687
     */
688
    protected function gedcomStartHandler(array $attrs): void
689
    {
690
        if ($this->process_gedcoms > 0) {
691
            $this->process_gedcoms++;
692
693
            return;
694
        }
695
696
        $tag       = $attrs['id'];
697
        $tag       = str_replace('@fact', $this->fact, $tag);
698
        $tags      = explode(':', $tag);
699
        $newgedrec = '';
700
        if (count($tags) < 2) {
701
            $tmp       = Registry::gedcomRecordFactory()->make($attrs['id'], $this->tree);
702
            $newgedrec = $tmp ? $tmp->privatizeGedcom(Auth::accessLevel($this->tree)) : '';
703
        }
704
        if (empty($newgedrec)) {
705
            $tgedrec   = $this->gedrec;
706
            $newgedrec = '';
707
            foreach ($tags as $tag) {
708
                if (preg_match('/\$(.+)/', $tag, $match)) {
709
                    if (isset($this->vars[$match[1]]['gedcom'])) {
710
                        $newgedrec = $this->vars[$match[1]]['gedcom'];
711
                    } else {
712
                        $tmp       = Registry::gedcomRecordFactory()->make($match[1], $this->tree);
713
                        $newgedrec = $tmp ? $tmp->privatizeGedcom(Auth::accessLevel($this->tree)) : '';
714
                    }
715
                } else {
716
                    if (preg_match('/@(.+)/', $tag, $match)) {
717
                        $gmatch = [];
718
                        if (preg_match("/\d $match[1] @([^@]+)@/", $tgedrec, $gmatch)) {
719
                            $tmp       = Registry::gedcomRecordFactory()->make($gmatch[1], $this->tree);
720
                            $newgedrec = $tmp ? $tmp->privatizeGedcom(Auth::accessLevel($this->tree)) : '';
721
                            $tgedrec   = $newgedrec;
722
                        } else {
723
                            $newgedrec = '';
724
                            break;
725
                        }
726
                    } else {
727
                        $level     = 1 + (int) explode(' ', trim($tgedrec))[0];
728
                        $newgedrec = self::getSubRecord($level, "$level $tag", $tgedrec);
729
                        $tgedrec   = $newgedrec;
730
                    }
731
                }
732
            }
733
        }
734
        if (!empty($newgedrec)) {
735
            $this->gedrec_stack[] = [$this->gedrec, $this->fact, $this->desc];
736
            $this->gedrec         = $newgedrec;
737
            if (preg_match("/(\d+) (_?[A-Z0-9]+) (.*)/", $this->gedrec, $match)) {
738
                $this->fact = $match[2];
739
                $this->desc = trim($match[3]);
740
            }
741
        } else {
742
            $this->process_gedcoms++;
743
        }
744
    }
745
746
    /**
747
     * Called at the end of an element.
748
     *
749
     * @return void
750
     */
751
    protected function gedcomEndHandler(): void
752
    {
753
        if ($this->process_gedcoms > 0) {
754
            $this->process_gedcoms--;
755
        } else {
756
            [$this->gedrec, $this->fact, $this->desc] = array_pop($this->gedrec_stack);
757
        }
758
    }
759
760
    /**
761
     * Handle <textBox>
762
     *
763
     * @param array<string> $attrs
764
     *
765
     * @return void
766
     */
767
    protected function textBoxStartHandler(array $attrs): void
768
    {
769
        // string Background color code
770
        $bgcolor = '';
771
        if (!empty($attrs['bgcolor'])) {
772
            $bgcolor = $attrs['bgcolor'];
773
        }
774
775
        // boolean Wether or not fill the background color
776
        $fill = true;
777
        if (isset($attrs['fill'])) {
778
            if ($attrs['fill'] === '0') {
779
                $fill = false;
780
            } elseif ($attrs['fill'] === '1') {
781
                $fill = true;
782
            }
783
        }
784
785
        // var boolean Whether or not a border should be printed around this box. 0 = no border, 1 = border. Default is 0
786
        $border = false;
787
        if (isset($attrs['border'])) {
788
            if ($attrs['border'] === '1') {
789
                $border = true;
790
            } elseif ($attrs['border'] === '0') {
791
                $border = false;
792
            }
793
        }
794
795
        // int The starting height of this cell. If the text wraps the height will automatically be adjusted
796
        $height = 0;
797
        if (!empty($attrs['height'])) {
798
            $height = (int) $attrs['height'];
799
        }
800
        // int Setting the width to 0 will make it the width from the current location to the margin
801
        $width = 0;
802
        if (!empty($attrs['width'])) {
803
            $width = (int) $attrs['width'];
804
        }
805
806
        // mixed Position the left corner of this box on the page. The default is the current position.
807
        $left = ReportBaseElement::CURRENT_POSITION;
808
        if (isset($attrs['left'])) {
809
            if ($attrs['left'] === '.') {
810
                $left = ReportBaseElement::CURRENT_POSITION;
811
            } elseif (!empty($attrs['left'])) {
812
                $left = (int) $attrs['left'];
813
            } elseif ($attrs['left'] === '0') {
814
                $left = 0;
815
            }
816
        }
817
        // mixed Position the top corner of this box on the page. the default is the current position
818
        $top = ReportBaseElement::CURRENT_POSITION;
819
        if (isset($attrs['top'])) {
820
            if ($attrs['top'] === '.') {
821
                $top = ReportBaseElement::CURRENT_POSITION;
822
            } elseif (!empty($attrs['top'])) {
823
                $top = (int) $attrs['top'];
824
            } elseif ($attrs['top'] === '0') {
825
                $top = 0;
826
            }
827
        }
828
        // position of box absolute or relative, and possibly top and height
829
        if (isset($attrs['pos'])) {
830
            $pos = $attrs['pos'];
831
            if (substr($pos,0,3) == 'abs') {
832
                //-- check absolute or relative position
833
                $top += -222000;
834
            }
835
            if (substr($pos,0,3) == 'rel') {
836
                //-- check absolute or relative position
837
                $top = -100000;
838
            }
839
            if (substr($pos,3,3) == '_fh') {
840
                $top = -100012;
841
            }
842
            if (substr($pos,3,3) == '_f2') {
843
                $top = -100018;
844
            }
845
            if (substr($pos,6,5) == '_html') {
846
                $top = -90012;
847
            }
848
        }
849
        // 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
850
        $newline = false;
851
        if (isset($attrs['newline'])) {
852
            if ($attrs['newline'] === '1') {
853
                $newline = true;
854
            } elseif ($attrs['newline'] === '0') {
855
                $newline = false;
856
            }
857
        }
858
        // boolean
859
        $pagecheck = true;
860
        if (isset($attrs['pagecheck'])) {
861
            if ($attrs['pagecheck'] === '0') {
862
                $pagecheck = false;
863
            } elseif ($attrs['pagecheck'] === '1') {
864
                $pagecheck = true;
865
            }
866
        }
867
        // boolean Cell padding
868
        $padding = true;
869
        if (isset($attrs['padding'])) {
870
            if ($attrs['padding'] === '0') {
871
                $padding = false;
872
            } elseif ($attrs['padding'] === '1') {
873
                $padding = true;
874
            }
875
        }
876
        // boolean Reset this box Height
877
        $reseth = false;
878
        if (isset($attrs['reseth'])) {
879
            if ($attrs['reseth'] === '1') {
880
                $reseth = true;
881
            } elseif ($attrs['reseth'] === '0') {
882
                $reseth = false;
883
            }
884
        }
885
886
        // string Style of rendering
887
        $style = '';
888
889
        $this->print_data_stack[] = $this->print_data;
890
        $this->print_data         = false;
891
892
        $this->wt_report_stack[] = $this->wt_report;
893
        $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...
894
            $width,
895
            $height,
896
            $border,
897
            $bgcolor,
898
            $newline,
899
            $left,
900
            $top,
901
            $pagecheck,
902
            $style,
903
            $fill,
904
            $padding,
905
            $reseth
906
        );
907
    }
908
909
    /**
910
     * Handle <textBox>
911
     *
912
     * @return void
913
     */
914
    protected function textBoxEndHandler(): void
915
    {
916
        $this->print_data      = array_pop($this->print_data_stack);
917
        $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...
918
919
        // The TextBox handler is mis-using the wt_report attribute to store an element.
920
        // Until this can be re-designed, we need this assertion to help static analysis tools.
921
        assert($this->current_element instanceof ReportBaseElement, new LogicException());
922
923
        $this->wt_report = array_pop($this->wt_report_stack);
924
        $this->wt_report->addElement($this->current_element);
925
    }
926
927
    /**
928
     * XLM <Text>.
929
     *
930
     * @param array<string> $attrs an array of key value pairs for the attributes
931
     *
932
     * @return void
933
     */
934
    protected function textStartHandler(array $attrs): void
935
    {
936
        $this->print_data_stack[] = $this->print_data;
937
        $this->print_data         = true;
938
939
        // string The name of the Style that should be used to render the text.
940
        $style = '';
941
        if (isset($attrs['style'])) {
942
            $style = $attrs['style'];
943
        }
944
945
        // string  The color of the text - Keep the black color as default
946
        $color = '';
947
        if (isset($attrs['color'])) {
948
            $color = $attrs['color'];
949
        }
950
951
/*
952
        // string The text alignment of the text in this box.
953
        $align = $attrs['align'] ?? '';
954
        // RTL supported left/right alignment
955
        if ($align === 'rightrtl') {
956
            if ($this->wt_report->rtl) {
957
                $align = 'left';
958
            } else {
959
                $align = 'right';
960
            }
961
        } elseif ($align === 'leftrtl') {
962
            if ($this->wt_report->rtl) {
963
                $align = 'right';
964
            } else {
965
                $align = 'left';
966
            }
967
        }
968
*/
969
970
        $this->current_element = $this->report_root->createText($style, $color);
971
    }
972
973
    /**
974
     * Handle </text>
975
     *
976
     * @return void
977
     */
978
    protected function textEndHandler(): void
979
    {
980
        $this->print_data = array_pop($this->print_data_stack);
981
        $this->wt_report->addElement($this->current_element);
982
    }
983
984
    /**
985
     * Handle <getPersonName />
986
     * Get the name
987
     * 1. id is empty - current GEDCOM record
988
     * 2. id is set with a record id
989
     *
990
     * @param array<string> $attrs an array of key value pairs for the attributes
991
     *
992
     * @return void
993
     */
994
    protected function getPersonNameStartHandler(array $attrs): void
995
    {
996
        $id    = '';
997
        $match = [];
998
        if (empty($attrs['id'])) {
999
            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1000
                $id = $match[1];
1001
            }
1002
        } else {
1003
            if (preg_match('/\$(.+)/', $attrs['id'], $match)) {
1004
                if (isset($this->vars[$match[1]]['id'])) {
1005
                    $id = $this->vars[$match[1]]['id'];
1006
                }
1007
            } else {
1008
                if (preg_match('/@(.+)/', $attrs['id'], $match)) {
1009
                    $gmatch = [];
1010
                    if (preg_match("/\d $match[1] @([^@]+)@/", $this->gedrec, $gmatch)) {
1011
                        $id = $gmatch[1];
1012
                    }
1013
                } else {
1014
                    $id = $attrs['id'];
1015
                }
1016
            }
1017
        }
1018
        $nameselect = "";
1019
        if ( isset($attrs['select']) ) {
1020
            $nameselect = $attrs['select'];
1021
        }
1022
        $famrel = false;
1023
        if ( isset($attrs['fam_relation']) ) {
1024
            $famrel = true;
1025
        }
1026
        if (!empty($id)) {
1027
            $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1028
            if ($record === null) {
1029
                return;
1030
            }
1031
            if (!$record->canShowName()) {
1032
                $this->current_element->addText(I18N::translate('Private'));
1033
            } else if ( $nameselect == 'latest' ) {
1034
                $tmp = $record->getAllNames();
1035
                $name  = strip_tags($tmp[count($tmp)-1]['full']);
1036
                $this->current_element->addText(trim($name));
1037
            } else if ( $nameselect == 'combined' ) {
1038
                $tmp = $record->getAllNames();
1039
                $name = $tmp[count($tmp)-1]['full'];
1040
                if ($ix1 = strpos($name,'<span class="starredname">')) {   // '«' and '»' mark text for underlining
1041
                    $name = substr_replace($name, '«', $ix1, 26);
1042
                    $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

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

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

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

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

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

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