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

ReportParserGenerate::factsStartHandler()   F

Complexity

Conditions 39
Paths > 20000

Size

Total Lines 141
Code Lines 95

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 39
eloc 95
c 4
b 0
f 0
nc 3931201
nop 1
dl 0
loc 141
rs 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

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

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

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

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

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

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

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

1033
                    $ix1 = strpos(/** @scrutinizer ignore-type */ $name, '</span>', $ix1);
Loading history...
1034
                    if ($ix1 !== false) {   // '«' and '»' mark text for underlining
1035
                        $name = substr_replace($name, '»', $ix1, 7);
1036
                    }
1037
                }
1038
                $addname = strip_tags((string) $tmp[0]['surn']);
1039
                if (!empty($addname) && !($addname === '@N.N.') && !str_contains($name, $addname)) {
1040
                    $name .= " " . I18N::translate('b.') . " " . $addname;
1041
                }
1042
                $this->current_element->addText(trim($name));
1043
            } else {
1044
                $name = $record->fullName();
1045
                $name = strip_tags($name);
1046
                if (!empty($attrs['truncate'])) {
1047
                    if ((int) $attrs['truncate'] > 0) {
1048
                        $name = Str::limit($name, (int) $attrs['truncate'], I18N::translate('…'));
1049
                    }
1050
                } else {
1051
                    $addname = (string) $record->alternateName();
1052
                    $addname = strip_tags($addname);
1053
                    if (!empty($addname)) {
1054
                        $name .= ' ' . $addname;
1055
                    }
1056
                }
1057
                $this->current_element->addText(trim($name));
1058
            }
1059
        }
1060
        if (isset($record) && $famrel && ($this->mfrelation[$record->xref()] != "")) {
1061
            $this->current_element->addText(" (" . (string) $this->mfrelation[$record->xref()] . ")");
1062
        }
1063
    }
1064
1065
    /**
1066
     * Handle <gedcomValue />
1067
     *
1068
     * @param array<string> $attrs
1069
     *
1070
     * @return void
1071
     */
1072
    protected function gedcomValueStartHandler(array $attrs): void
1073
    {
1074
        $id    = '';
1075
        $match = [];
1076
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1077
            $id = $match[1];
1078
        }
1079
1080
        if (isset($attrs['newline']) && $attrs['newline'] === '1') {
1081
            $useBreak = '1';
1082
        } else {
1083
            $useBreak = '0';
1084
        }
1085
1086
        $tag = $attrs['tag'];
1087
        if (!empty($tag)) {
1088
            if ($tag === '@desc') {
1089
                $value = $this->desc;
1090
                $value = trim($value);
1091
                $this->current_element->addText($value);
1092
            }
1093
            if ($tag === '@id') {
1094
                $this->current_element->addText($id);
1095
            } else {
1096
                $tag = str_replace('@fact', $this->fact, $tag);
1097
                if (empty($attrs['level'])) {
1098
                    $level = (int) explode(' ', trim($this->gedrec))[0];
1099
                    if ($level === 0) {
1100
                        $level++;
1101
                    }
1102
                } else {
1103
                    $level = (int) $attrs['level'];
1104
                }
1105
                $tags  = preg_split('/[: ]/', $tag);
1106
                $value = $this->getGedcomValue($tag, $level, $this->gedrec);
1107
                switch (end($tags)) {
1108
                    case 'DATE':
1109
                        $tmp   = new Date($value);
1110
                        $dfmt = "%j %F %Y";
1111
                        if (!empty($attrs['truncate'])) {
1112
                            if ($attrs['truncate'] === "d") {
1113
                                $dfmt = "%j %M %Y";
1114
                            }
1115
                            if ($attrs['truncate'] === "Y") {
1116
                                $dfmt = "%Y";
1117
                            }
1118
                        }
1119
                        $value = strip_tags($tmp->display(null, $dfmt));
1120
                        break;
1121
                    case 'PLAC':
1122
                        $tmp   = new Place($value, $this->tree);
1123
                        $value = $tmp->shortName();
1124
                        break;
1125
                }
1126
                if ($useBreak === '1') {
1127
                    // Insert <br> when multiple dates exist.
1128
                    // This works around a TCPDF bug that incorrectly wraps RTL dates on LTR pages
1129
                    $value = str_replace('(', '<br>(', $value);
1130
                    $value = str_replace('<span dir="ltr"><br>', '<br><span dir="ltr">', $value);
1131
                    $value = str_replace('<span dir="rtl"><br>', '<br><span dir="rtl">', $value);
1132
                    if (substr($value, 0, 4) === '<br>') {
1133
                        $value = substr($value, 4);
1134
                    }
1135
                }
1136
                $tmp = explode(':', $tag);
1137
                if (in_array(end($tmp), ['NOTE', 'TEXT'], true)) {
1138
                    if ($this->tree->getPreference('FORMAT_TEXT') === 'xxmarkdown') {
1139
                        $value = strip_tags(Registry::markdownFactory()->markdown($value, $this->tree), ['br']);
1140
                    } else {
1141
                        $value = str_replace("\n", "<br>", $value);
1142
                        //$value = strip_tags(Registry::markdownFactory()->autolink($value, $this->tree), ['br']);
1143
                    }
1144
                    $value = strtr($value, [MarkdownFactory::BREAK => ' ']);
1145
                }
1146
1147
                if (isset($attrs['lcfirst'])) {
1148
                    $value = lcfirst($value);
1149
                    $value = str_replace(["Å","Ä","Ö"], ["å","ä","ö"], $value);
1150
                }
1151
1152
                if (!empty($attrs['truncate'])) {
1153
                    $value = strip_tags($value);
1154
                    if ((int) $attrs['truncate'] > 0) {
1155
                        $value = Str::limit($value, (int) $attrs['truncate'], I18N::translate('…'));
1156
                    }
1157
                }
1158
                $this->current_element->addText($value);
1159
            }
1160
        }
1161
    }
1162
1163
    /**
1164
     * Handle <repeatTag>
1165
     *
1166
     * @param array<string> $attrs
1167
     *
1168
     * @return void
1169
     */
1170
    protected function repeatTagStartHandler(array $attrs): void
1171
    {
1172
        $this->process_repeats++;
1173
        if ($this->process_repeats > 1) {
1174
            return;
1175
        }
1176
1177
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1178
        $this->repeats         = [];
1179
        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1180
1181
        $tag = $attrs['tag'] ?? '';
1182
        if (!empty($tag)) {
1183
            if ($tag === '@desc') {
1184
                $value = $this->desc;
1185
                $value = trim($value);
1186
                $this->current_element->addText($value);
1187
            } else {
1188
                $tag   = str_replace('@fact', $this->fact, $tag);
1189
                $tags  = explode(':', $tag);
1190
                $level = (int) explode(' ', trim($this->gedrec))[0];
1191
                if ($level === 0) {
1192
                    $level++;
1193
                }
1194
                $subrec = $this->gedrec;
1195
                $t      = $tag;
1196
                $count  = count($tags);
1197
                $i      = 0;
1198
                while ($i < $count) {
1199
                    $t = $tags[$i];
1200
                    if (!empty($t)) {
1201
                        if ($i < ($count - 1)) {
1202
                            $subrec = self::getSubRecord($level, "$level $t", $subrec);
1203
                            if (empty($subrec)) {
1204
                                $level--;
1205
                                $subrec = self::getSubRecord($level, "@ $t", $this->gedrec);
1206
                                if (empty($subrec)) {
1207
                                    return;
1208
                                }
1209
                            }
1210
                        }
1211
                        $level++;
1212
                    }
1213
                    $i++;
1214
                }
1215
                $level--;
1216
                $count = preg_match_all("/$level $t(.*)/", $subrec, $match, PREG_SET_ORDER);
1217
                $i     = 0;
1218
                while ($i < $count) {
1219
                    $i++;
1220
                    // Privacy check - is this a link, and are we allowed to view the linked object?
1221
                    $subrecord = self::getSubRecord($level, "$level $t", $subrec, $i);
1222
                    if (preg_match('/^\d ' . Gedcom::REGEX_TAG . ' @(' . Gedcom::REGEX_XREF . ')@/', $subrecord, $xref_match)) {
1223
                        $linked_object = Registry::gedcomRecordFactory()->make($xref_match[1], $this->tree);
1224
                        if ($linked_object && !$linked_object->canShow()) {
1225
                            //continue;
1226
                        }
1227
                    }
1228
                    $this->repeats[] = $subrecord;
1229
                }
1230
            }
1231
        }
1232
    }
1233
1234
    /**
1235
     * Handle </repeatTag>
1236
     *
1237
     * @var mixed $rep
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];
1258
                $lineoffset -= 1;
1259
            }
1260
            while (!str_contains($lines[$lineoffset + $this->repeat_bytes], '<RepeatTag')) {
1261
                $lineoffset--;
1262
            }
1263
            $lineoffset++;
1264
            $reportxml = "<tempdoc>\n";
1265
            $line_nr   = $lineoffset + $this->repeat_bytes;
1266
            $lnnn = $line_nr;
0 ignored issues
show
Unused Code introduced by
The assignment to $lnnn is dead and can be removed.
Loading history...
1267
            // RepeatTag Level counter
1268
            $count = 1;
1269
            while (0 < $count) {
1270
                if (str_contains($lines[$line_nr], '<RepeatTag')) {
1271
                    $count++;
1272
                } elseif (str_contains($lines[$line_nr], '</RepeatTag')) {
1273
                    $count--;
1274
                }
1275
                if (0 < $count) {
1276
                    $reportxml .= $lines[$line_nr];
1277
                }
1278
                $line_nr++;
1279
            }
1280
            // No need to drag this
1281
            unset($lines);
1282
            $reportxml .= "</tempdoc>\n";
1283
            // Save original values
1284
            $this->parser_stack[] = $this->parser;
1285
            $oldgedrec            = $this->gedrec;
1286
            foreach ($this->repeats as $gedrec) {
1287
                $this->gedrec  = $gedrec;
1288
                $repeat_parser = xml_parser_create();
1289
                $this->parser  = $repeat_parser;
1290
                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
1291
1292
                xml_set_element_handler(
1293
                    $repeat_parser,
1294
                    function ($parser, string $name, array $attrs): void {
1295
                        $this->startElement($parser, $name, $attrs);
1296
                    },
1297
                    function ($parser, string $name): void {
1298
                        $this->endElement($parser, $name);
1299
                    }
1300
                );
1301
1302
                xml_set_character_data_handler(
1303
                    $repeat_parser,
1304
                    function ($parser, string $data): void {
1305
                        $this->characterData($parser, $data);
1306
                    }
1307
                );
1308
1309
                if (!xml_parse($repeat_parser, $reportxml, true)) {
1310
                    throw new DomainException(sprintf(
1311
                        'RepeatTagEHandler XML error: %s at line %d',
1312
                        xml_error_string(xml_get_error_code($repeat_parser)),
1313
                        xml_get_current_line_number($repeat_parser)
1314
                    ));
1315
                }
1316
                xml_parser_free($repeat_parser);
1317
            }
1318
            // Restore original values
1319
            $this->gedrec = $oldgedrec;
1320
            $this->parser = array_pop($this->parser_stack);
1321
        }
1322
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1323
    }
1324
1325
    /**
1326
     * Variable lookup
1327
     * Retrieve predefined variables :
1328
     * @ desc GEDCOM fact description, example:
1329
     *        1 EVEN This is a description
1330
     * @ fact GEDCOM fact tag, such as BIRT, DEAT etc.
1331
     * $ I18N::translate('....')
1332
     * $ language_settings[]
1333
     *
1334
     * @param array<string> $attrs an array of key value pairs for the attributes
1335
     *
1336
     * @return void
1337
     */
1338
    protected function varStartHandler(array $attrs): void
1339
    {
1340
        if (!isset($attrs['var'])) {
1341
            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));
1342
        }
1343
1344
        $var = $attrs['var'];
1345
        // SetVar element preset variables
1346
        if (!empty($this->vars[$var]['id'])) {
1347
            $var = $this->vars[$var]['id'];
1348
        } else {
1349
            $tfact = $this->fact;
1350
            if (($this->fact === 'EVEN' || $this->fact === 'FACT') && $this->type !== '') {
1351
                // Use :
1352
                // n TYPE This text if string
1353
                $tfact = $this->type;
1354
            } else {
1355
                foreach ([Individual::RECORD_TYPE, Family::RECORD_TYPE] as $record_type) {
1356
                    $element = Registry::elementFactory()->make($record_type . ':' . $this->fact);
1357
1358
                    if (!$element instanceof UnknownElement) {
1359
                        $tfact = $element->label();
1360
                        break;
1361
                    }
1362
                }
1363
            }
1364
1365
            $var = strtr($var, ['@desc' => $this->desc, '@fact' => $tfact]);
1366
1367
            if (preg_match('/^I18N::number\((.+)\)$/', $var, $match)) {
1368
                $var = I18N::number((int) $match[1]);
1369
            } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $var, $match)) {
1370
                $var = I18N::translate($match[1]);
1371
            } elseif (preg_match('/^I18N::translate\(\$(.+)\)$/', $var, $match)) {
1372
                $var = I18N::translate($this->vars[$match[1]]['id']);
1373
            } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $var, $match)) {
1374
                $var = I18N::translateContext($match[1], $match[2]);
1375
            }
1376
        }
1377
        // Check if variable is set as a date and reformat the date
1378
        if (isset($attrs['date'])) {
1379
            if ($attrs['date'] === '1') {
1380
                $g   = new Date($var);
1381
                $var = $g->display();
1382
            }
1383
        }
1384
        if (isset($attrs['amp'])) {
1385
            $var = str_replace("%26", '&', $var);
1386
        }
1387
        if (isset($attrs['cut'])) {
1388
            $cut = (int) $attrs['cut'];
1389
            $var = $cut > 0 ? substr($var, 0, $cut) : substr($var, $cut);
1390
            if ($cut == 0) {
1391
                $var = "";
1392
            }
1393
        }
1394
        if (isset($attrs['lcfirst'])) {
1395
            $var = lcfirst($var);
1396
        }
1397
        $this->current_element->addText($var);
1398
        $this->text = $var; // Used for title/description
1399
    }
1400
1401
    /**
1402
     * Handle <facts>
1403
     *
1404
     * @param array<string> $attrs
1405
     *
1406
     * @return void
1407
     */
1408
    protected function factsStartHandler(array $attrs): void
1409
    {
1410
        $this->process_repeats++;
1411
        if ($this->process_repeats > 1) {
1412
            return;
1413
        }
1414
1415
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
1416
        $this->repeats         = [];
1417
        $this->repeat_bytes    = xml_get_current_line_number($this->parser);
1418
1419
        $id    = '';
1420
        $match = [];
1421
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1422
            $id = $match[1];
1423
        }
1424
        $tag = '';
1425
        if (isset($attrs['ignore'])) {
1426
            $tag .= $attrs['ignore'];
1427
        }
1428
        if (preg_match('/\$(.+)/', $tag, $match)) {
1429
            $tag = $this->vars[$match[1]]['id'];
1430
        }
1431
1432
        $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1433
        if (empty($attrs['diff']) && !empty($id)) {
1434
            $facts = $record->facts([], true);
1435
            $this->repeats = [];
1436
            $nonfacts      = explode(',', $tag);
1437
            foreach ($facts as $fact) {
1438
                $tag = explode(':', $fact->tag())[1];
1439
1440
                if (!in_array($tag, $nonfacts, true)) {
1441
                    $this->repeats[] = $fact->gedcom();
1442
                }
1443
            }
1444
        } else {
1445
            foreach ($record->facts() as $fact) {
1446
                if (($fact->isPendingAddition() || $fact->isPendingDeletion()) && !str_ends_with($fact->tag(), ':CHAN')) {
1447
                    $this->repeats[] = $fact->gedcom();
1448
                }
1449
            }
1450
        }
1451
1452
        if (!isset($jdarr)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $jdarr seems to never exist and therefore isset should always be false.
Loading history...
1453
            $jdarr = [];
1454
        }
1455
        // Add fact/event for FAM:DIV and for death of spouse
1456
        foreach ($this->repeats as $key => $fact) {
1457
            $jdarr[$key] = 0;
1458
            if (preg_match('/1 FAMS @(.+)@/', $fact, $match)) {
1459
                $famid = $match[1];
1460
                $fam = Registry::familyFactory()->make($match[1], $this->tree);
1461
                if ($fam === null) {
1462
                    continue;
1463
                }
1464
                $dt = $this->getGedcomValue("MARR:DATE", 0, $fam->gedcom());
1465
                if ($dt == "") {
1466
                    $dt = $this->getGedcomValue("ENGA:DATE", 0, $fam->gedcom());
1467
                }
1468
                if ($dt == "" && $this->getGedcomValue("EVEN:TYPE", 0, $fam->gedcom()) == "Sambo") {
1469
                    $dt = $this->getGedcomValue("EVEN:DATE", 0, $fam->gedcom());
1470
                }
1471
                $date = new Date($dt);
1472
                $jd = $date->julianDay();
1473
                $jdarr[$key] = $jd;
1474
                // Divorce
1475
                $dt = $this->getGedcomValue("DIV:DATE", 0, $fam->gedcom());
1476
                if ($dt != "") {
1477
                    $this->repeats[] = "1 DIV\n2 DATE " . $dt . "\n";
1478
                }
1479
                // Separation // Doesn't work!! getGedComValue only reports the first event!! I.e. no match here
1480
                if ($this->getGedcomValue("EVEN:TYPE", 0, $fam->gedcom()) == "Separation") {
1481
                    $dt = $this->getGedcomValue("EVEN:DATE", 0, $fam->gedcom());
1482
                    if ($dt != "") {
1483
                        $this->repeats[] = "1 EVEN\n2 TYPE Separation\n2 DATE " . $dt . "\n";
1484
                    }
1485
                }
1486
                // death of husband / wife
1487
                $husb = $fam->husband();
1488
                $wife = $fam->wife();
1489
                if ($this->getGedcomValue("SEX", 0, $this->gedrec) == "M") {
1490
                    $spouse = $wife;
1491
                } else {
1492
                    $spouse = $husb;
1493
                }
1494
                if ($spouse) {
1495
                    $dt = $this->getGedcomValue("DEAT:DATE", 0, $spouse->gedcom());
1496
                } else {
1497
                    $dt = "";
1498
                }
1499
                if ($dt != "") {
1500
                    $this->repeats[] = "1 _SP_DEAT\n2 DATE " . $dt . "\n2 _O_FAM " . $famid . "\n";
1501
                }
1502
            }
1503
        }
1504
        // Find the dates for the facts that are found
1505
        foreach ($this->repeats as $key => $fact) {
1506
            if (preg_match('/[234] DATE ([^\n]+)/', $fact, $match)) {
1507
                $date = new Date($match[1]);
1508
                $jd = $date->julianDay();
1509
                $jdarr[$key] = $jd;
1510
            }
1511
        }
1512
1513
        // Sort facts in chronological order, if possible
1514
        $m = count($this->repeats) - 1;
1515
        $prevd = 0;
1516
        for ($i = 0; $i <= $m; $i++) { // keep undated events after previous dated event
1517
            if ($jdarr[$i] === 0) {
1518
                $jdarr[$i] = $prevd;
1519
            } else {
1520
                $prevd = $jdarr[$i];
1521
            }
1522
        }
1523
1524
        while ($m > 1) {
1525
            $n = count($this->repeats);
1526
            while ($n > 1) {
1527
                if ($jdarr[$n - 2] > $jdarr[$n - 1] && $jdarr[$n - 1] !== 0) {
1528
                    $s = $this->repeats[$n - 1];
1529
                    $this->repeats[$n - 1] = $this->repeats[$n - 2];
1530
                    $this->repeats[$n - 2] = $s;
1531
                    $s = $jdarr[$n - 1];
1532
                    $jdarr[$n - 1] = $jdarr[$n - 2];
1533
                    $jdarr[$n - 2] = $s;
1534
                }
1535
                $n -= 1;
1536
            }
1537
            $m -= 1;
1538
        }
1539
1540
        // Remove spouse deaths that are too late: after new marriage or own death
1541
        $currfam = "";
1542
        for ($i = 0; $i <= count($this->repeats) - 1; $i++) {
1543
            if (preg_match('/[1234] FAMS @(.+)@/', $this->repeats[$i], $match)) {
1544
                $currfam = $match[1];
1545
            }
1546
            if (preg_match('/_SP_DEAT.*\n2 DATE (.*)\n.*_O_FAM (.+)\n/', $this->repeats[$i], $match)) {
1547
                if ($currfam != $match[2] || $i == count($this->repeats) - 1) {
1548
                    $this->repeats[$i] = "1 _XXX\n";
1549
                } // ignore fact
1550
            }
1551
        }
1552
    }
1553
1554
    /**
1555
     * Handle </facts>
1556
     *
1557
     * @return void
1558
     */
1559
    protected function factsEndHandler(): void
1560
    {
1561
        $this->process_repeats--;
1562
        if ($this->process_repeats > 0) {
1563
            return;
1564
        }
1565
1566
        // Check if there is anything to repeat
1567
        if (count($this->repeats) > 0) {
1568
            $line       = xml_get_current_line_number($this->parser) - 1;
1569
            $lineoffset = 0;
1570
            foreach ($this->repeats_stack as $rep) {
1571
                $lineoffset = $lineoffset + $rep[1] - 1;
1572
            }
1573
1574
            //-- read the xml from the file
1575
            $lines = file($this->report);
1576
            while ($lineoffset + $this->repeat_bytes > 0 && !str_contains($lines[$lineoffset + $this->repeat_bytes], '<Facts ')) {
1577
                $lineoffset--;
1578
            }
1579
            $lineoffset++;
1580
            $reportxml = "<tempdoc>\n";
1581
            $i         = $line + $lineoffset;
1582
            $line_nr   = $this->repeat_bytes + $lineoffset;
1583
            while ($line_nr < $i) {
1584
                $reportxml .= $lines[$line_nr];
1585
                $line_nr++;
1586
            }
1587
            // No need to drag this
1588
            unset($lines);
1589
            $reportxml .= "</tempdoc>\n";
1590
            // Save original values
1591
            $this->parser_stack[] = $this->parser;
1592
            $oldgedrec = $this->gedrec;
1593
            $count = count($this->repeats);
1594
            $i = 0;
1595
            while ($i < $count) {
1596
                if (!isset($this->repeats[$i])) {
1597
                    $i++;
1598
                    continue; // this fact has been removed above, occured too late
1599
                }
1600
                $this->gedrec = $this->repeats[$i];
1601
                $this->fact = '';
1602
                $this->desc = '';
1603
                if (preg_match('/1 (\w+)(.*)/', $this->gedrec, $match)) {
1604
                    $this->fact = $match[1];
1605
                    if ($this->fact === 'EVEN' || $this->fact === 'FACT') {
1606
                        $tmatch = [];
1607
                        if (preg_match('/2 TYPE (.+)/', $this->gedrec, $tmatch)) {
1608
                            $this->type = trim($tmatch[1]);
1609
                        } else {
1610
                            $this->type = ' ';
1611
                        }
1612
                    }
1613
                    $this->desc = trim($match[2]);
1614
                    $this->desc .= self::getCont(2, $this->gedrec);
1615
                }
1616
                $repeat_parser = xml_parser_create();
1617
                $this->parser  = $repeat_parser;
1618
                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
1619
1620
                xml_set_element_handler(
1621
                    $repeat_parser,
1622
                    function ($parser, string $name, array $attrs): void {
1623
                        $this->startElement($parser, $name, $attrs);
1624
                    },
1625
                    function ($parser, string $name): void {
1626
                        $this->endElement($parser, $name);
1627
                    }
1628
                );
1629
1630
                xml_set_character_data_handler(
1631
                    $repeat_parser,
1632
                    function ($parser, string $data): void {
1633
                        $this->characterData($parser, $data);
1634
                    }
1635
                );
1636
1637
                if (!xml_parse($repeat_parser, $reportxml, true)) {
1638
                    throw new DomainException(sprintf(
1639
                        'FactsEHandler XML error: %s at line %d',
1640
                        xml_error_string(xml_get_error_code($repeat_parser)),
1641
                        xml_get_current_line_number($repeat_parser)
1642
                    ));
1643
                }
1644
                xml_parser_free($repeat_parser);
1645
                $i++;
1646
            }
1647
            // Restore original values
1648
            $this->parser = array_pop($this->parser_stack);
1649
            $this->gedrec = $oldgedrec;
1650
        }
1651
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
1652
    }
1653
1654
    /**
1655
     * Setting upp or changing variables in the XML
1656
     * The XML variable name and value is stored in $this->vars
1657
     *
1658
     * @param array<string> $attrs an array of key value pairs for the attributes
1659
     *
1660
     * @return void
1661
     */
1662
    protected function setVarStartHandler(array $attrs): void
1663
    {
1664
        if (empty($attrs['name'])) {
1665
            throw new DomainException('REPORT ERROR var: The attribute "name" is missing or not set in the XML file');
1666
        }
1667
1668
        $name  = $attrs['name'];
1669
        $value = $attrs['value'];
1670
        if (isset($attrs['dumpvar'])) {
1671
            $dumpvar = $attrs['dumpvar'];
1672
        } else {
1673
            $dumpvar = "";
1674
        }
1675
        $curr_id = "";
1676
        $match = [];
1677
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1678
            $curr_id = $match[1];
1679
        }
1680
        $match = [];
1681
        // Current GEDCOM record strings
1682
        if ($value === '@ID') {
1683
            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1684
                $value = $match[1];
1685
            }
1686
        } elseif ($value === '@fact') {
1687
            $value = $this->fact;
1688
        } elseif ($value === '@desc') {
1689
            $value = $this->desc;
1690
        } elseif ($value === '@format') {
1691
            if (isset($_GET["format"])) {
1692
                $value = $_GET["format"];
1693
            } else {
1694
                $value = "";
1695
            }
1696
        } elseif ($value === '@generation') {
1697
            $value = (string) $this->generation;
1698
        } elseif ($value === '@base_url') {
1699
            $value = "";
1700
            if (array_key_exists("route", $_GET)) {
1701
                $value = $_GET["route"];
1702
            }
1703
            $i = strpos($value, "%2Freport");
1704
            if ($i === false) {
1705
                $i = strpos($value, "/report");
1706
            }
1707
            if ($i !== false) {
1708
                $value = substr($value, 0, $i);
1709
            }
1710
            $value = "index.php?route=" . $value;
1711
        } elseif ($value === '@relation') {
1712
            if (isset($this->mfrelation[$curr_id]) && $curr_id != "") {
1713
                $value = (string) $this->mfrelation[$curr_id];
1714
            } else {
1715
                $value = "";
1716
            }
1717
        } elseif (preg_match("/@(\w+)/", $value, $match)) {
1718
            $gmatch = [];
1719
            if (preg_match("/\d $match[1] (.+)/", $this->gedrec, $gmatch)) {
1720
                $value = str_replace('@', '', trim($gmatch[1]));
1721
            }
1722
        } elseif (preg_match("/@\\$(\w+)/", $value, $match)) {
1723
            if ($match[1] == "dump" && $this->vars['dval']['id'] > 0) {
1724
                // if ($this->vars[ 'dval' ]['id'] == 1001)
1725
                if ($dumpvar == "gedrec") {
1726
                    error_log("\n---- setvar start  " . date("Y-m-d H:i:s") . " RPG " . __LINE__ . "  " . $name . "  gedcom=\n" . $this->gedrec . "\n", 3, "my-errors.log");
1727
                } elseif ($dumpvar != "") {
1728
                    error_log("var: " . $dumpvar . " = " . $this->vars[$dumpvar]['id'] . "\n", 3, "my-errors.log");
1729
                } else {
1730
                    if (array_key_exists('dval', $this->vars)) {
1731
                        $nnn = $this->vars['dval']['id'];
1732
                    } else {
1733
                        $nnn = 0;
1734
                    }
1735
                    error_log("\n---- setvar start  " . date("Y-m-d H:i:s") . " RPG " . __LINE__ . "  " . $name . "  -----\n", 3, "my-errors.log");
1736
                    foreach ($this->vars as $key => $val) {
1737
                        if ($nnn-- < 0) {
1738
                            error_log($key . "='" . $val['id'] . "'\n", 3, "my-errors.log");
1739
                        }
1740
                    }
1741
                }
1742
            }
1743
            $value = $this->vars[$match[1]]['id'];
1744
            if (isset($this->vars[$value]['id'])) {
1745
                $value = '$' . $this->vars[$match[1]]['id'];
1746
            } else {
1747
                $value = "0";
1748
            }
1749
        }
1750
        if (isset($attrs['trim'])) {
1751
            $value = str_replace($attrs['trim'], '', $value);
1752
        }
1753
        if (preg_match("/\\$(\w+)/", $name, $match)) {
1754
            $name = $this->vars["'" . $match[1] . "'"]['id'];
1755
        }
1756
        $count = preg_match_all("/\\$(\w+)/", $value, $match, PREG_SET_ORDER);
1757
        $i     = 0;
1758
        while ($i < $count) {
1759
            $t     = $this->vars[$match[$i][1]]['id'];
1760
            $value = preg_replace('/\$' . $match[$i][1] . '/', $t, $value, 1);
1761
            $i++;
1762
        }
1763
        if (preg_match('/^I18N::number\((.+)\)$/', $value, $match)) {
1764
            $value = I18N::number((int) $match[1]);
1765
        } elseif (preg_match('/^I18N::translate\(\'(.+)\'\)$/', $value, $match)) {
1766
            $value = I18N::translate($match[1]);
1767
        } elseif (preg_match('/^I18N::translateContext\(\'(.+)\', *\'(.+)\'\)$/', $value, $match)) {
1768
            $value = I18N::translateContext($match[1], $match[2]);
1769
        }
1770
        if (isset($attrs['lcfirst'])) { // set 1st char to lower case
1771
            $value = lcfirst($value);
1772
        }
1773
1774
        // Arithmetic functions
1775
        if (preg_match("/(\d+)\s*([-+*\/])\s*(\d+)/", $value, $match)) {
1776
            // Create an expression language with the functions used by our reports.
1777
            $expression_provider  = new ReportExpressionLanguageProvider();
1778
            $expression_cache     = new NullAdapter();
1779
            $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1780
1781
            $value = (string) $expression_language->evaluate($value);
1782
        }
1783
1784
        if (str_contains($value, '@')) {
1785
            $value = '';
1786
        }
1787
        $this->vars[$name]['id'] = $value;
1788
        if ($name == 'title') {
1789
            $this->wt_report->title = $value;
1790
        }
1791
    }
1792
1793
    /**
1794
     * Handle <if>
1795
     *
1796
     * @param array<string> $attrs
1797
     *
1798
     * @return void
1799
     */
1800
    protected function ifStartHandler(array $attrs): void
1801
    {
1802
        if ($this->process_ifs > 0) {
1803
            $this->process_ifs++;
1804
1805
            return;
1806
        }
1807
1808
        $condition = $attrs['condition'];
1809
        $condition = $this->substituteVars($condition, true);
1810
        $condition = str_replace([
1811
            ' LT ',
1812
            ' GT ',
1813
        ], [
1814
            '<',
1815
            '>',
1816
        ], $condition);
1817
        // Replace the first occurrence only once of @fact:DATE or in any other combinations to the current fact, such as BIRT
1818
        $condition = str_replace('@fact:', $this->fact . ':', $condition);
1819
        $match     = [];
1820
        $count     = preg_match_all("/@([\w:.]+)/", $condition, $match, PREG_SET_ORDER);
1821
        $i         = 0;
1822
        while ($i < $count) {
1823
            $id    = $match[$i][1];
1824
            $value = '""';
1825
            if ($id === 'ID') {
1826
                if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1827
                    $value = "'" . $match[1] . "'";
1828
                }
1829
            } elseif ($id === 'fact') {
1830
                $value = '"' . $this->fact . '"';
1831
            } elseif ($id === 'desc') {
1832
                $value = '"' . addslashes($this->desc) . '"';
1833
            } elseif ($id === 'generation') {
1834
                $value = '"' . $this->generation . '"';
1835
            } else {
1836
                $level = (int) explode(' ', trim($this->gedrec))[0];
1837
                if ($level === 0) {
1838
                    $level++;
1839
                }
1840
                $value = $this->getGedcomValue($id, $level, $this->gedrec);
1841
                if (empty($value)) {
1842
                    $level++;
1843
                    $value = $this->getGedcomValue($id, $level, $this->gedrec);
1844
                }
1845
                $value = preg_replace('/^@(' . Gedcom::REGEX_XREF . ')@$/', '$1', $value);
1846
                $value = '"' . addslashes($value) . '"';
1847
            }
1848
            $condition = str_replace("@$id", $value, $condition);
1849
            $i++;
1850
        }
1851
1852
        // Create an expression language with the functions used by our reports.
1853
        $expression_provider  = new ReportExpressionLanguageProvider();
1854
        $expression_cache     = new NullAdapter();
1855
        $expression_language  = new ExpressionLanguage($expression_cache, [$expression_provider]);
1856
1857
        $ret = $expression_language->evaluate($condition);
1858
1859
        if (!$ret) {
1860
            $this->process_ifs++;
1861
        }
1862
    }
1863
1864
    /**
1865
     * Handle </if>
1866
     *
1867
     * @return void
1868
     */
1869
    protected function ifEndHandler(): void
1870
    {
1871
        if ($this->process_ifs > 0) {
1872
            $this->process_ifs--;
1873
        }
1874
    }
1875
1876
    /**
1877
     * Handle <footnote>
1878
     * Collect the Footnote links
1879
     * GEDCOM Records that are protected by Privacy setting will be ignored
1880
     *
1881
     * @param array<string> $attrs
1882
     *
1883
     * @return void
1884
     */
1885
    protected function footnoteStartHandler(array $attrs): void
1886
    {
1887
        $id = '';
1888
        if (preg_match('/[0-9] (.+) @(.+)@/', $this->gedrec, $match)) {
1889
            $id = $match[2];
1890
        }
1891
        $record = Registry::gedcomRecordFactory()->make($id, $this->tree);
1892
        if ($record && $record->canShow()) {
1893
            $this->print_data_stack[] = $this->print_data;
1894
            $this->print_data         = true;
1895
            $style                    = '';
1896
            if (!empty($attrs['style'])) {
1897
                $style = $attrs['style'];
1898
            }
1899
            $this->footnote_element = $this->current_element;
1900
            $this->current_element  = $this->report_root->createFootnote($style);
1901
        } else {
1902
            $this->print_data       = false;
1903
            $this->process_footnote = false;
1904
        }
1905
    }
1906
1907
    /**
1908
     * Handle </footnote>
1909
     * Print the collected Footnote data
1910
     *
1911
     * @return void
1912
     */
1913
    protected function footnoteEndHandler(): void
1914
    {
1915
        if ($this->process_footnote) {
1916
            $this->print_data = array_pop($this->print_data_stack);
1917
            $temp             = trim($this->current_element->getValue());
1918
            if (strlen($temp) > 3) {
1919
                $this->wt_report->addElement($this->current_element);
1920
            }
1921
            $this->current_element = $this->footnote_element;
1922
        } else {
1923
            $this->process_footnote = true;
1924
        }
1925
    }
1926
1927
    /**
1928
     * Handle <footnoteTexts />
1929
     *
1930
     * @return void
1931
     */
1932
    protected function footnoteTextsStartHandler(): void
1933
    {
1934
        $temp = 'footnotetexts';
1935
        $this->wt_report->addElement($temp);
1936
    }
1937
1938
    /**
1939
     * XML element Forced line break handler - HTML code
1940
     *
1941
     * @return void
1942
     */
1943
    protected function brStartHandler(): void
1944
    {
1945
        if ($this->print_data && $this->process_gedcoms === 0) {
1946
            $this->current_element->addText('<br>');
1947
        }
1948
    }
1949
1950
    /**
1951
     * Handle <sp />
1952
     * Forced space
1953
     *
1954
     * @return void
1955
     */
1956
    protected function spStartHandler(): void
1957
    {
1958
        if ($this->print_data && $this->process_gedcoms === 0) {
1959
            $this->current_element->addText(' ');
1960
        }
1961
    }
1962
1963
    /**
1964
     * Handle <highlightedImage />
1965
     *
1966
     * @param array<string> $attrs
1967
     *
1968
     * @return void
1969
     */
1970
    protected function highlightedImageStartHandler(array $attrs): void
1971
    {
1972
        $id = '';
1973
        if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
1974
            $id = $match[1];
1975
        }
1976
1977
        // Position the top corner of this box on the page
1978
        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
1979
1980
        // Position the left corner of this box on the page
1981
        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
1982
1983
        // string Align the image in left, center, right (or empty to use x/y position).
1984
        $align = $attrs['align'] ?? '';
1985
1986
        // string Next Line should be T:next to the image, N:next line
1987
        $ln = $attrs['ln'] ?? 'T';
1988
1989
        // Width, height (or both).
1990
        $width  = (float) ($attrs['width'] ?? 0.0);
1991
        $height = (float) ($attrs['height'] ?? 0.0);
1992
1993
        $person     = Registry::individualFactory()->make($id, $this->tree);
1994
        $media_file = $person->findHighlightedMediaFile();
1995
1996
        if ($media_file instanceof MediaFile && $media_file->fileExists()) {
1997
            $image      = imagecreatefromstring($media_file->fileContents());
1998
            $attributes = [imagesx($image), imagesy($image)];
1999
2000
            if ($width > 0 && $height == 0) {
2001
                $perc   = $width / $attributes[0];
2002
                $height = round($attributes[1] * $perc);
2003
            } elseif ($height > 0 && $width == 0) {
2004
                $perc  = $height / $attributes[1];
2005
                $width = round($attributes[0] * $perc);
2006
            } else {
2007
                $width  = (float) $attributes[0];
2008
                $height = (float) $attributes[1];
2009
            }
2010
            $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
2011
            $this->wt_report->addElement($image);
2012
        }
2013
    }
2014
2015
    /**
2016
     * Handle <image/>
2017
     *
2018
     * @param array<string> $attrs
2019
     *
2020
     * @return void
2021
     */
2022
    protected function imageStartHandler(array $attrs): void
2023
    {
2024
        // Position the top corner of this box on the page. the default is the current position
2025
        $top = (float) ($attrs['top'] ?? ReportBaseElement::CURRENT_POSITION);
2026
2027
        // mixed Position the left corner of this box on the page. the default is the current position
2028
        $left = (float) ($attrs['left'] ?? ReportBaseElement::CURRENT_POSITION);
2029
2030
        // string Align the image in left, center, right (or empty to use x/y position).
2031
        $align = $attrs['align'] ?? '';
2032
2033
        // string Next Line should be T:next to the image, N:next line
2034
        $ln = $attrs['ln'] ?? 'T';
2035
2036
        // Width, height (or both).
2037
        $width  = (float) ($attrs['width'] ?? 0.0);
2038
        $height = (float) ($attrs['height'] ?? 0.0);
2039
2040
        $file = $attrs['file'] ?? '';
2041
2042
        if ($file === '@FILE') {
2043
            $match = [];
2044
            if (preg_match("/\d OBJE @(.+)@/", $this->gedrec, $match)) {
2045
                $mediaobject = Registry::mediaFactory()->make($match[1], $this->tree);
2046
                $media_file  = $mediaobject->firstImageFile();
2047
2048
                if ($media_file instanceof MediaFile && $media_file->fileExists()) {
2049
                    $image      = imagecreatefromstring($media_file->fileContents());
2050
                    $attributes = [imagesx($image), imagesy($image)];
2051
2052
                    if ($width > 0 && $height == 0) {
2053
                        $perc   = $width / $attributes[0];
2054
                        $height = round($attributes[1] * $perc);
2055
                    } elseif ($height > 0 && $width == 0) {
2056
                        $perc  = $height / $attributes[1];
2057
                        $width = round($attributes[0] * $perc);
2058
                    } else {
2059
                        $width  = (float) $attributes[0];
2060
                        $height = (float) $attributes[1];
2061
                    }
2062
                    $image = $this->report_root->createImageFromObject($media_file, $left, $top, $width, $height, $align, $ln);
2063
                    $this->wt_report->addElement($image);
2064
                }
2065
            }
2066
        } else {
2067
            if (file_exists($file) && preg_match('/(jpg|jpeg|png|gif)$/i', $file)) {
2068
                $size = getimagesize($file);
2069
                if ($width > 0 && $height == 0) {
2070
                    $perc   = $width / $size[0];
2071
                    $height = round($size[1] * $perc);
2072
                } elseif ($height > 0 && $width == 0) {
2073
                    $perc  = $height / $size[1];
2074
                    $width = round($size[0] * $perc);
2075
                } else {
2076
                    $width  = $size[0];
2077
                    $height = $size[1];
2078
                }
2079
                $image = $this->report_root->createImage($file, $left, $top, $width, $height, $align, $ln);
2080
                $this->wt_report->addElement($image);
2081
            }
2082
        }
2083
    }
2084
2085
    /**
2086
     * Handle <line>
2087
     *
2088
     * @param array<string> $attrs
2089
     *
2090
     * @return void
2091
     */
2092
    protected function lineStartHandler(array $attrs): void
2093
    {
2094
        // Start horizontal position, current position (default)
2095
        $x1 = ReportBaseElement::CURRENT_POSITION;
2096
        if (isset($attrs['x1'])) {
2097
            if ($attrs['x1'] === '0') {
2098
                $x1 = 0;
2099
            } elseif ($attrs['x1'] === '.') {
2100
                $x1 = ReportBaseElement::CURRENT_POSITION;
2101
            } elseif (!empty($attrs['x1'])) {
2102
                $x1 = (float) $attrs['x1'];
2103
            }
2104
        }
2105
        // Start vertical position, current position (default)
2106
        $y1 = ReportBaseElement::CURRENT_POSITION;
2107
        if (isset($attrs['y1'])) {
2108
            if ($attrs['y1'] === '0') {
2109
                $y1 = 0;
2110
            } elseif ($attrs['y1'] === '.') {
2111
                $y1 = ReportBaseElement::CURRENT_POSITION;
2112
            } elseif (!empty($attrs['y1'])) {
2113
                $y1 = (float) $attrs['y1'];
2114
            }
2115
        }
2116
        // End horizontal position, maximum width (default)
2117
        $x2 = ReportBaseElement::CURRENT_POSITION;
2118
        if (isset($attrs['x2'])) {
2119
            if ($attrs['x2'] === '0') {
2120
                $x2 = 0;
2121
            } elseif ($attrs['x2'] === '.') {
2122
                $x2 = ReportBaseElement::CURRENT_POSITION;
2123
            } elseif (!empty($attrs['x2'])) {
2124
                $x2 = (float) $attrs['x2'];
2125
            }
2126
        }
2127
        // End vertical position
2128
        $y2 = ReportBaseElement::CURRENT_POSITION;
2129
        if (isset($attrs['y2'])) {
2130
            if ($attrs['y2'] === '0') {
2131
                $y2 = 0;
2132
            } elseif ($attrs['y2'] === '.') {
2133
                $y2 = ReportBaseElement::CURRENT_POSITION;
2134
            } elseif (!empty($attrs['y2'])) {
2135
                $y2 = (float) $attrs['y2'];
2136
            }
2137
        }
2138
2139
        $line = $this->report_root->createLine($x1, $y1, $x2, $y2);
2140
        $this->wt_report->addElement($line);
2141
    }
2142
2143
    /**
2144
     * Handle <list>
2145
     *
2146
     * @param array<string> $attrs
2147
     *
2148
     * @return void
2149
     */
2150
    protected function listStartHandler(array $attrs): void
2151
    {
2152
        $this->process_repeats++;
2153
        if ($this->process_repeats > 1) {
2154
            return;
2155
        }
2156
2157
        $match = [];
2158
        if (isset($attrs['sortby'])) {
2159
            $sortby = $attrs['sortby'];
2160
            if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2161
                $sortby = $this->vars[$match[1]]['id'];
2162
                $sortby = trim($sortby);
2163
            }
2164
        } else {
2165
            $sortby = 'NAME';
2166
        }
2167
2168
        $listname = $attrs['list'] ?? 'individual';
2169
2170
        // Some filters/sorts can be applied using SQL, while others require PHP
2171
        switch ($listname) {
2172
            case 'pending':
2173
                $this->list = DB::table('change')
2174
                    ->whereIn('change_id', function (Builder $query): void {
2175
                        $query->select([new Expression('MAX(change_id)')])
2176
                            ->from('change')
2177
                            ->where('gedcom_id', '=', $this->tree->id())
2178
                            ->where('status', '=', 'pending')
2179
                            ->groupBy(['xref']);
2180
                    })
2181
                    ->get()
2182
                    ->map(fn (object $row): ?GedcomRecord => Registry::gedcomRecordFactory()->make($row->xref, $this->tree, $row->new_gedcom ?: $row->old_gedcom))
2183
                    ->filter()
2184
                    ->all();
2185
                break;
2186
2187
            case 'individual':
2188
                $query = DB::table('individuals')
2189
                    ->where('i_file', '=', $this->tree->id())
2190
                    ->select(['i_id AS xref', 'i_gedcom AS gedcom'])
2191
                    ->distinct();
2192
2193
                foreach ($attrs as $attr => $value) {
2194
                    if (str_starts_with($attr, 'filter') && $value !== '') {
2195
                        $value = $this->substituteVars($value, false);
2196
                        // Convert the various filters into SQL
2197
                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
2198
                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2199
                                $join
2200
                                    ->on($attr . '.d_gid', '=', 'i_id')
2201
                                    ->on($attr . '.d_file', '=', 'i_file');
2202
                            });
2203
2204
                            $query->where($attr . '.d_fact', '=', $match[1]);
2205
2206
                            $date = new Date($match[3]);
2207
2208
                            if ($match[2] === 'LTE') {
2209
                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
2210
                            } else {
2211
                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
2212
                            }
2213
2214
                            // This filter has been fully processed
2215
                            unset($attrs[$attr]);
2216
                        } elseif (preg_match('/^NAME CONTAINS (.+)$/', $value, $match)) {
2217
                            $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2218
                                $join
2219
                                    ->on($attr . '.n_id', '=', 'i_id')
2220
                                    ->on($attr . '.n_file', '=', 'i_file');
2221
                            });
2222
                            // Search the DB only if there is any name supplied
2223
                            $names = explode(' ', $match[1]);
2224
                            foreach ($names as $name) {
2225
                                $query->where($attr . '.n_full', 'LIKE', '%' . addcslashes($name, '\\%_') . '%');
2226
                            }
2227
2228
                            // This filter has been fully processed
2229
                            unset($attrs[$attr]);
2230
                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
2231
                            // Convert newline escape sequences to actual new lines
2232
                            $match[1] = str_replace('\n', "\n", $match[1]);
2233
2234
                            $query->where('i_gedcom', 'LIKE', $match[1]);
2235
2236
                            // This filter has been fully processed
2237
                            unset($attrs[$attr]);
2238
                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
2239
                            // Don't unset this filter. This is just initial filtering for performance
2240
                            $query
2241
                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
2242
                                    $join
2243
                                        ->on($attr . 'a.pl_file', '=', 'i_file')
2244
                                        ->on($attr . 'a.pl_gid', '=', 'i_id');
2245
                                })
2246
                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
2247
                                    $join
2248
                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
2249
                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
2250
                                })
2251
                                ->where($attr . 'b.p_place', 'LIKE', '%' . addcslashes($match[1], '\\%_') . '%');
2252
                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
2253
                            // Don't unset this filter. This is just initial filtering for performance
2254
                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2255
                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
2256
                            $query->where('i_gedcom', 'LIKE', $like);
2257
                        } elseif (preg_match('/^(\w+) CONTAINS (.*)$/', $value, $match)) {
2258
                            // Don't unset this filter. This is just initial filtering for performance
2259
                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2260
                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
2261
                            $query->where('i_gedcom', 'LIKE', $like);
2262
                        }
2263
                    }
2264
                }
2265
2266
                $this->list = [];
2267
2268
                foreach ($query->get() as $row) {
2269
                    $this->list[$row->xref] = Registry::individualFactory()->make($row->xref, $this->tree, $row->gedcom);
2270
                }
2271
                break;
2272
2273
            case 'family':
2274
                $query = DB::table('families')
2275
                    ->where('f_file', '=', $this->tree->id())
2276
                    ->select(['f_id AS xref', 'f_gedcom AS gedcom'])
2277
                    ->distinct();
2278
2279
                foreach ($attrs as $attr => $value) {
2280
                    if (str_starts_with($attr, 'filter') && $value !== '') {
2281
                        $value = $this->substituteVars($value, false);
2282
                        // Convert the various filters into SQL
2283
                        if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
2284
                            $query->join('dates AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2285
                                $join
2286
                                    ->on($attr . '.d_gid', '=', 'f_id')
2287
                                    ->on($attr . '.d_file', '=', 'f_file');
2288
                            });
2289
2290
                            $query->where($attr . '.d_fact', '=', $match[1]);
2291
2292
                            $date = new Date($match[3]);
2293
2294
                            if ($match[2] === 'LTE') {
2295
                                $query->where($attr . '.d_julianday2', '<=', $date->maximumJulianDay());
2296
                            } else {
2297
                                $query->where($attr . '.d_julianday1', '>=', $date->minimumJulianDay());
2298
                            }
2299
2300
                            // This filter has been fully processed
2301
                            unset($attrs[$attr]);
2302
                        } elseif (preg_match('/^LIKE \/(.+)\/$/', $value, $match)) {
2303
                            // Convert newline escape sequences to actual new lines
2304
                            $match[1] = str_replace('\n', "\n", $match[1]);
2305
2306
                            $query->where('f_gedcom', 'LIKE', $match[1]);
2307
2308
                            // This filter has been fully processed
2309
                            unset($attrs[$attr]);
2310
                        } elseif (preg_match('/^NAME CONTAINS (.*)$/', $value, $match)) {
2311
                            if ($sortby === 'NAME' || $match[1] !== '') {
2312
                                $query->join('name AS ' . $attr, static function (JoinClause $join) use ($attr): void {
2313
                                    $join
2314
                                        ->on($attr . '.n_file', '=', 'f_file')
2315
                                        ->where(static function (Builder $query): void {
2316
                                            $query
2317
                                                ->whereColumn('n_id', '=', 'f_husb')
2318
                                                ->orWhereColumn('n_id', '=', 'f_wife');
2319
                                        });
2320
                                });
2321
                                // Search the DB only if there is any name supplied
2322
                                if ($match[1] != '') {
2323
                                    $names = explode(' ', $match[1]);
2324
                                    foreach ($names as $name) {
2325
                                        $query->where($attr . '.n_full', 'LIKE', '%' . addcslashes($name, '\\%_') . '%');
2326
                                    }
2327
                                }
2328
                            }
2329
2330
                            // This filter has been fully processed
2331
                            unset($attrs[$attr]);
2332
                        } elseif (preg_match('/^(?:\w*):PLAC CONTAINS (.+)$/', $value, $match)) {
2333
                            // Don't unset this filter. This is just initial filtering for performance
2334
                            $query
2335
                                ->join('placelinks AS ' . $attr . 'a', static function (JoinClause $join) use ($attr): void {
2336
                                    $join
2337
                                        ->on($attr . 'a.pl_file', '=', 'f_file')
2338
                                        ->on($attr . 'a.pl_gid', '=', 'f_id');
2339
                                })
2340
                                ->join('places AS ' . $attr . 'b', static function (JoinClause $join) use ($attr): void {
2341
                                    $join
2342
                                        ->on($attr . 'b.p_file', '=', $attr . 'a.pl_file')
2343
                                        ->on($attr . 'b.p_id', '=', $attr . 'a.pl_p_id');
2344
                                })
2345
                                ->where($attr . 'b.p_place', 'LIKE', '%' . addcslashes($match[1], '\\%_') . '%');
2346
                        } elseif (preg_match('/^(\w*):(\w+) CONTAINS (.+)$/', $value, $match)) {
2347
                            // Don't unset this filter. This is just initial filtering for performance
2348
                            $match[3] = strtr($match[3], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2349
                            $like = "%\n1 " . $match[1] . "%\n2 " . $match[2] . '%' . $match[3] . '%';
2350
                            $query->where('f_gedcom', 'LIKE', $like);
2351
                        } elseif (preg_match('/^(\w+) CONTAINS (.+)$/', $value, $match)) {
2352
                            // Don't unset this filter. This is just initial filtering for performance
2353
                            $match[2] = strtr($match[2], ['\\' => '\\\\', '%'  => '\\%', '_'  => '\\_', ' ' => '%']);
2354
                            $like = "%\n1 " . $match[1] . '%' . $match[2] . '%';
2355
                            $query->where('f_gedcom', 'LIKE', $like);
2356
                        }
2357
                    }
2358
                }
2359
2360
                $this->list = [];
2361
2362
                foreach ($query->get() as $row) {
2363
                    $this->list[$row->xref] = Registry::familyFactory()->make($row->xref, $this->tree, $row->gedcom);
2364
                }
2365
                break;
2366
2367
            default:
2368
                throw new DomainException('Invalid list name: ' . $listname);
2369
        }
2370
2371
        $filters  = [];
2372
        $filters2 = [];
2373
        if (isset($attrs['filter1']) && count($this->list) > 0) {
2374
            foreach ($attrs as $key => $value) {
2375
                if (preg_match("/filter(\d)/", $key)) {
2376
                    $condition = $value;
2377
                    if (preg_match("/@(\w+)/", $condition, $match)) {
2378
                        $id    = $match[1];
2379
                        $value = "''";
2380
                        if ($id === 'ID') {
2381
                            if (preg_match('/0 @(.+)@/', $this->gedrec, $match)) {
2382
                                $value = "'" . $match[1] . "'";
2383
                            }
2384
                        } elseif ($id === 'fact') {
2385
                            $value = "'" . $this->fact . "'";
2386
                        } elseif ($id === 'desc') {
2387
                            $value = "'" . $this->desc . "'";
2388
                        } else {
2389
                            if (preg_match("/\d $id (.+)/", $this->gedrec, $match)) {
2390
                                $value = "'" . str_replace('@', '', trim($match[1])) . "'";
2391
                            }
2392
                        }
2393
                        $condition = preg_replace("/@$id/", $value, $condition);
2394
                    }
2395
                    //-- handle regular expressions
2396
                    if (preg_match("/([A-Z:]+)\s*([^\s]+)\s*(.+)/", $condition, $match)) {
2397
                        $tag  = trim($match[1]);
2398
                        $expr = trim($match[2]);
2399
                        $val  = trim($match[3]);
2400
                        if (preg_match("/\\$(\w+)/", $val, $match)) {
2401
                            $val = $this->vars[$match[1]]['id'];
2402
                            $val = trim($val);
2403
                        }
2404
                        if ($val !== '') {
2405
                            $searchstr = '';
2406
                            $tags      = explode(':', $tag);
2407
                            //-- only limit to a level number if we are specifically looking at a level
2408
                            if (count($tags) > 1) {
2409
                                $level = 1;
2410
                                $t = 'XXXX';
2411
                                foreach ($tags as $t) {
2412
                                    if (!empty($searchstr)) {
2413
                                        $searchstr .= "[^\n]*(\n[2-9][^\n]*)*\n";
2414
                                    }
2415
                                    //-- search for both EMAIL and _EMAIL... silly double gedcom standard
2416
                                    if ($t === 'EMAIL' || $t === '_EMAIL') {
2417
                                        $t = '_?EMAIL';
2418
                                    }
2419
                                    $searchstr .= $level . ' ' . $t;
2420
                                    $level++;
2421
                                }
2422
                            } else {
2423
                                if ($tag === 'EMAIL' || $tag === '_EMAIL') {
2424
                                    $tag = '_?EMAIL';
2425
                                }
2426
                                $t         = $tag;
2427
                                $searchstr = '1 ' . $tag;
2428
                            }
2429
                            switch ($expr) {
2430
                                case 'CONTAINS':
2431
                                    if ($t === 'PLAC') {
2432
                                        $searchstr .= "[^\n]*[, ]*" . $val;
2433
                                    } else {
2434
                                        $searchstr .= "[^\n]*" . $val;
2435
                                    }
2436
                                    $filters[] = $searchstr;
2437
                                    break;
2438
                                default:
2439
                                    $filters2[] = [
2440
                                        'tag'  => $tag,
2441
                                        'expr' => $expr,
2442
                                        'val'  => $val,
2443
                                    ];
2444
                                    break;
2445
                            }
2446
                        }
2447
                    }
2448
                }
2449
            }
2450
        }
2451
        //-- apply other filters to the list that could not be added to the search string
2452
        if ($filters !== []) {
2453
            foreach ($this->list as $key => $record) {
2454
                foreach ($filters as $filter) {
2455
                    if (!preg_match('/' . $filter . '/i', $record->privatizeGedcom(Auth::accessLevel($this->tree)))) {
2456
                        unset($this->list[$key]);
2457
                        break;
2458
                    }
2459
                }
2460
            }
2461
        }
2462
        if ($filters2 !== []) {
2463
            $mylist = [];
2464
            foreach ($this->list as $indi) {
2465
                $key  = $indi->xref();
2466
                $grec = $indi->privatizeGedcom(Auth::accessLevel($this->tree));
2467
                $keep = true;
2468
                foreach ($filters2 as $filter) {
2469
                    if ($keep) {
2470
                        $tag  = $filter['tag'];
2471
                        $expr = $filter['expr'];
2472
                        $val  = $filter['val'];
2473
                        if ($val === "''") {
2474
                            $val = '';
2475
                        }
2476
                        $tags = explode(':', $tag);
2477
                        $t    = end($tags);
2478
                        $v    = $this->getGedcomValue($tag, 1, $grec);
2479
                        //-- check for EMAIL and _EMAIL (silly double gedcom standard :P)
2480
                        if ($t === 'EMAIL' && empty($v)) {
2481
                            $tag  = str_replace('EMAIL', '_EMAIL', $tag);
2482
                            $tags = explode(':', $tag);
2483
                            $t    = end($tags);
2484
                            $v    = self::getSubRecord(1, $tag, $grec);
2485
                        }
2486
2487
                        switch ($expr) {
2488
                            case 'GTE':
2489
                                if ($t === 'DATE') {
2490
                                    $date1 = new Date($v);
2491
                                    $date2 = new Date($val);
2492
                                    $keep  = (Date::compare($date1, $date2) >= 0);
2493
                                } elseif ($val >= $v) {
2494
                                    $keep = true;
2495
                                }
2496
                                break;
2497
                            case 'LTE':
2498
                                if ($t === 'DATE') {
2499
                                    $date1 = new Date($v);
2500
                                    $date2 = new Date($val);
2501
                                    $keep  = (Date::compare($date1, $date2) <= 0);
2502
                                } elseif ($val >= $v) {
2503
                                    $keep = true;
2504
                                }
2505
                                break;
2506
                            default:
2507
                                if ($v == $val) {
2508
                                    $keep = true;
2509
                                } else {
2510
                                    $keep = false;
2511
                                }
2512
                                break;
2513
                        }
2514
                    }
2515
                }
2516
                if ($keep) {
2517
                    $mylist[$key] = $indi;
2518
                }
2519
            }
2520
            $this->list = $mylist;
2521
        }
2522
2523
        switch ($sortby) {
2524
            case 'NAME':
2525
                uasort($this->list, GedcomRecord::nameComparator());
2526
                break;
2527
            case 'CHAN':
2528
                uasort($this->list, GedcomRecord::lastChangeComparator());
2529
                break;
2530
            case 'BIRT:DATE':
2531
                uasort($this->list, Individual::birthDateComparator());
2532
                break;
2533
            case 'DEAT:DATE':
2534
                uasort($this->list, Individual::deathDateComparator());
2535
                break;
2536
            case 'MARR:DATE':
2537
                uasort($this->list, Family::marriageDateComparator());
2538
                break;
2539
            default:
2540
                // unsorted or already sorted by SQL
2541
                break;
2542
        }
2543
2544
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2545
        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2546
    }
2547
2548
    /**
2549
     * Handle </list>
2550
     *
2551
     * @return void
2552
     */
2553
    protected function listEndHandler(): void
2554
    {
2555
        $this->process_repeats--;
2556
        if ($this->process_repeats > 0) {
2557
            return;
2558
        }
2559
2560
        // Check if there is any list
2561
        if (count($this->list) > 0) {
2562
            $lineoffset = 0;
2563
            foreach ($this->repeats_stack as $rep) {
2564
                $lineoffset = $lineoffset + $rep[1] - 1;
2565
            }
2566
            //-- read the xml from the file
2567
            $lines = file($this->report);
2568
            while ((!str_contains($lines[$lineoffset + $this->repeat_bytes], '<List')) && (($lineoffset + $this->repeat_bytes) > 0)) {
2569
                $lineoffset--;
2570
            }
2571
            $lineoffset++;
2572
            $reportxml = "<tempdoc>\n";
2573
            $line_nr   = $lineoffset + $this->repeat_bytes;
2574
            // List Level counter
2575
            $count = 1;
2576
            while (0 < $count) {
2577
                if (str_contains($lines[$line_nr], '<List')) {
2578
                    $count++;
2579
                } elseif (str_contains($lines[$line_nr], '</List')) {
2580
                    $count--;
2581
                }
2582
                if (0 < $count) {
2583
                    $reportxml .= $lines[$line_nr];
2584
                }
2585
                $line_nr++;
2586
            }
2587
            // No need to drag this
2588
            unset($lines);
2589
            $reportxml .= '</tempdoc>';
2590
            // Save original values
2591
            $this->parser_stack[] = $this->parser;
2592
            $oldgedrec            = $this->gedrec;
2593
2594
            $this->list_total   = count($this->list);
2595
            $this->list_private = 0;
2596
            foreach ($this->list as $record) {
2597
                if ($record->canShow()) {
2598
                    $this->gedrec = $record->privatizeGedcom(Auth::accessLevel($record->tree()));
2599
                    //-- start the sax parser
2600
                    $repeat_parser = xml_parser_create();
2601
                    $this->parser  = $repeat_parser;
2602
                    xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
2603
2604
                    xml_set_element_handler(
2605
                        $repeat_parser,
2606
                        function ($parser, string $name, array $attrs): void {
2607
                            $this->startElement($parser, $name, $attrs);
2608
                        },
2609
                        function ($parser, string $name): void {
2610
                            $this->endElement($parser, $name);
2611
                        }
2612
                    );
2613
2614
                    xml_set_character_data_handler(
2615
                        $repeat_parser,
2616
                        function ($parser, string $data): void {
2617
                            $this->characterData($parser, $data);
2618
                        }
2619
                    );
2620
2621
                    if (!xml_parse($repeat_parser, $reportxml, true)) {
2622
                        throw new DomainException(sprintf(
2623
                            'ListEHandler XML error: %s at line %d',
2624
                            xml_error_string(xml_get_error_code($repeat_parser)),
2625
                            xml_get_current_line_number($repeat_parser)
2626
                        ));
2627
                    }
2628
                    xml_parser_free($repeat_parser);
2629
                } else {
2630
                    $this->list_private++;
2631
                }
2632
            }
2633
            $this->list   = [];
2634
            $this->parser = array_pop($this->parser_stack);
2635
            $this->gedrec = $oldgedrec;
2636
        }
2637
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2638
    }
2639
2640
    /**
2641
     * Handle <listTotal>
2642
     * Prints the total number of records in a list
2643
     * The total number is collected from <list> and <relatives>
2644
     *
2645
     * @return void
2646
     */
2647
    protected function listTotalStartHandler(): void
2648
    {
2649
        if ($this->list_private == 0) {
2650
            $this->current_element->addText((string) $this->list_total);
2651
        } else {
2652
            $this->current_element->addText(($this->list_total - $this->list_private) . ' / ' . $this->list_total);
2653
        }
2654
    }
2655
2656
    /**
2657
     * Handle <relatives>
2658
     *
2659
     * @param array<string> $attrs
2660
     *
2661
     * @return void
2662
     */
2663
    protected function relativesStartHandler(array $attrs): void
2664
    {
2665
        $this->process_repeats++;
2666
        if ($this->process_repeats > 1) {
2667
            return;
2668
        }
2669
2670
        $sortby = $attrs['sortby'] ?? 'NAME';
2671
2672
        $match = [];
2673
        if (preg_match("/\\$(\w+)/", $sortby, $match)) {
2674
            $sortby = $this->vars[$match[1]]['id'];
2675
            $sortby = trim($sortby);
2676
        }
2677
2678
        $maxgen = -1;
2679
        if (isset($attrs['maxgen'])) {
2680
            $maxgen = (int) $attrs['maxgen'];
2681
        }
2682
2683
        $group = $attrs['group'] ?? 'child-family';
2684
2685
        if (preg_match("/\\$(\w+)/", $group, $match)) {
2686
            $group = $this->vars[$match[1]]['id'];
2687
            $group = trim($group);
2688
        }
2689
2690
        $id = $attrs['id'] ?? '';
2691
2692
        if (preg_match("/\\$(\w+)/", $id, $match)) {
2693
            $id = $this->vars[$match[1]]['id'];
2694
            $id = trim($id);
2695
        }
2696
2697
        $this->list = [];
2698
        $person     = Registry::individualFactory()->make($id, $this->tree);
2699
        if ($person instanceof Individual) {
2700
            $this->list[$id] = $person;
2701
            $this->mfrelation[$id] = "";
2702
            $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...
2703
            switch ($group) {
2704
                case 'child-family':
2705
                    foreach ($person->childFamilies() as $family) {
2706
                        foreach ($family->spouses() as $spouse) {
2707
                            $this->list[$spouse->xref()] = $spouse;
2708
                        }
2709
2710
                        foreach ($family->children() as $child) {
2711
                            $this->list[$child->xref()] = $child;
2712
                        }
2713
                    }
2714
                    break;
2715
                case 'spouse-family':
2716
                    foreach ($person->spouseFamilies() as $family) {
2717
                        foreach ($family->spouses() as $spouse) {
2718
                            $this->list[$spouse->xref()] = $spouse;
2719
                        }
2720
2721
                        foreach ($family->children() as $child) {
2722
                            $this->list[$child->xref()] = $child;
2723
                        }
2724
                    }
2725
                    break;
2726
                case 'direct-ancestors':
2727
                    $this->addAncestors($this->list, $id, false, $maxgen);
2728
                    break;
2729
                case 'ancestors':
2730
                    $this->addAncestors($this->list, $id, true, $maxgen);
2731
                    break;
2732
                case 'descendants':
2733
                    $this->list[$id]->generation = 1;
2734
                    $this->addDescendancy($this->list, $id, false, $maxgen);
2735
                    break;
2736
                case 'all':
2737
                    $this->addAncestors($this->list, $id, true, $maxgen);
2738
                    $this->addDescendancy($this->list, $id, true, $maxgen);
2739
                    break;
2740
            }
2741
        }
2742
2743
        switch ($sortby) {
2744
            case 'NAME':
2745
                uasort($this->list, GedcomRecord::nameComparator());
2746
                break;
2747
            case 'BIRT:DATE':
2748
                uasort($this->list, Individual::birthDateComparator());
2749
                break;
2750
            case 'DEAT:DATE':
2751
                uasort($this->list, Individual::deathDateComparator());
2752
                break;
2753
            case 'generation':
2754
                $newarray = [];
2755
                reset($this->list);
2756
                $genCounter = 1;
2757
                while (count($newarray) < count($this->list)) {
2758
                    foreach ($this->list as $key => $value) {
2759
                        if ($value->generation < 0) {
2760
                            // indication of husband or wife
2761
                            $this->generation = -$value->generation;
2762
                        } else {
2763
                            $this->generation = $value->generation;
2764
                        }
2765
                        if ($this->generation == $genCounter) {
2766
                            $newarray[$key] = (object) ['generation' => $this->generation];
2767
                        }
2768
                    }
2769
                    $genCounter++;
2770
                }
2771
                $this->list = $newarray;
2772
                break;
2773
            default:
2774
                // unsorted
2775
                break;
2776
        }
2777
        $this->repeats_stack[] = [$this->repeats, $this->repeat_bytes];
2778
        $this->repeat_bytes    = xml_get_current_line_number($this->parser) + 1;
2779
    }
2780
2781
    /**
2782
     * Handle </relatives>
2783
     *
2784
     * @return void
2785
     */
2786
    protected function relativesEndHandler(): void
2787
    {
2788
        $this->process_repeats--;
2789
        if ($this->process_repeats > 0) {
2790
            return;
2791
        }
2792
2793
        // Check if there is any relatives
2794
        if (count($this->list) > 0) {
2795
            $lineoffset = 0;
2796
            foreach ($this->repeats_stack as $rep) {
2797
                $lineoffset = $lineoffset + $rep[1] - 1;
2798
            }
2799
            //-- read the xml from the file
2800
            $lines = file($this->report);
2801
            while (!str_contains($lines[$lineoffset + $this->repeat_bytes], '<Relatives') && $lineoffset + $this->repeat_bytes > 0) {
2802
                $lineoffset--;
2803
            }
2804
            $lineoffset++;
2805
            $reportxml = "<tempdoc>\n";
2806
            $line_nr   = $lineoffset + $this->repeat_bytes;
2807
            // Relatives Level counter
2808
            $count = 1;
2809
            while (0 < $count) {
2810
                if (str_contains($lines[$line_nr], '<Relatives')) {
2811
                    $count++;
2812
                } elseif (str_contains($lines[$line_nr], '</Relatives')) {
2813
                    $count--;
2814
                }
2815
                if (0 < $count) {
2816
                    $reportxml .= $lines[$line_nr];
2817
                }
2818
                $line_nr++;
2819
            }
2820
            // No need to drag this
2821
            unset($lines);
2822
            $reportxml .= "</tempdoc>\n";
2823
            // Save original values
2824
            $this->parser_stack[] = $this->parser;
2825
            $oldgedrec            = $this->gedrec;
2826
2827
            $this->list_total   = count($this->list);
2828
            $this->list_private = 0;
2829
            foreach ($this->list as $key => $value) {
2830
                if (isset($value->generation)) {
2831
                    $this->generation = $value->generation;
2832
                }
2833
                $xref = $key;
2834
                $this->vars["dupl"]["id"] = "no";
2835
                if (substr($key, 0, 2) == "D_") {
2836
                    $xref = substr($key, strrpos($key, "_") + 1);
2837
                    $this->vars["dupl"]["id"] = "yes";
2838
                }
2839
                $tmp          = Registry::gedcomRecordFactory()->make((string) $xref, $this->tree);
2840
                $this->gedrec = $tmp->privatizeGedcom(Auth::accessLevel($this->tree));
2841
2842
                $repeat_parser = xml_parser_create();
2843
                $this->parser  = $repeat_parser;
2844
                xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, 0);
2845
2846
                xml_set_element_handler(
2847
                    $repeat_parser,
2848
                    function ($parser, string $name, array $attrs): void {
2849
                        $this->startElement($parser, $name, $attrs);
2850
                    },
2851
                    function ($parser, string $name): void {
2852
                        $this->endElement($parser, $name);
2853
                    }
2854
                );
2855
2856
                xml_set_character_data_handler(
2857
                    $repeat_parser,
2858
                    function ($parser, string $data): void {
2859
                        $this->characterData($parser, $data);
2860
                    }
2861
                );
2862
2863
                if (!xml_parse($repeat_parser, $reportxml, true)) {
2864
                    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)));
2865
                }
2866
                xml_parser_free($repeat_parser);
2867
            }
2868
            // Clean up the list array
2869
            $this->list   = [];
2870
            $this->parser = array_pop($this->parser_stack);
2871
            $this->gedrec = $oldgedrec;
2872
        }
2873
        [$this->repeats, $this->repeat_bytes] = array_pop($this->repeats_stack);
2874
    }
2875
2876
    /**
2877
     * Handle <generation />
2878
     * Prints the number of generations
2879
     *
2880
     * @return void
2881
     */
2882
    protected function generationStartHandler(): void
2883
    {
2884
        $this->current_element->addText((string) $this->generation);
2885
    }
2886
2887
    /**
2888
     * Handle <newPage />
2889
     * Has to be placed in an element (header, body or footer)
2890
     *
2891
     * @return void
2892
     */
2893
    protected function newPageStartHandler(): void
2894
    {
2895
        $temp = 'addpage';
2896
        $this->wt_report->addElement($temp);
2897
    }
2898
2899
    /**
2900
     * Handle </title>
2901
     *
2902
     * @return void
2903
     */
2904
    protected function titleEndHandler(): void
2905
    {
2906
        $this->report_root->addTitle($this->text);
2907
    }
2908
2909
    /**
2910
     * Handle </description>
2911
     *
2912
     * @return void
2913
     */
2914
    protected function descriptionEndHandler(): void
2915
    {
2916
        $this->report_root->addDescription($this->text);
2917
    }
2918
2919
    /**
2920
     * Create a list of all descendants.
2921
     *
2922
     * @param array<Individual> $list
2923
     * @param string            $pid
2924
     * @param bool              $parents
2925
     * @param int               $generations
2926
     *
2927
     * @return void
2928
     */
2929
    private function addDescendancy(&$list, $pid, $parents = false, $generations = -1): void
2930
    {
2931
        $person = Registry::individualFactory()->make($pid, $this->tree);
2932
        if ($person === null) {
2933
            return;
2934
        }
2935
2936
        static $focusperson = true;
2937
        static $dupl = 1;
2938
        $sx = $person->sex();
2939
        $rl = "x"; // unknown
2940
        if ($sx == "M") {
2941
            $rl = "s";
2942
        } // son
2943
        if ($sx == "F") {
2944
            $rl = "d";
0 ignored issues
show
Unused Code introduced by
The assignment to $rl is dead and can be removed.
Loading history...
2945
        } // daughter
2946
        if ($focusperson) {
2947
            $this->mfrelation[$pid] = "";
2948
        }
2949
        $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...
2950
2951
        $newpid = $pid;
2952
        if (!isset($list[$pid])) {
2953
            $list[$pid] = $person;
2954
        } elseif (!$focusperson) {
2955
            $newpid = "D_" . $dupl . "_" . $pid;
2956
            $list[$newpid] = $person;
2957
        }
2958
        if (!isset($list[$newpid]->generation)) {
2959
            $list[$newpid]->generation = 0;
2960
        }
2961
        $focusperson = false;
2962
        foreach ($person->spouseFamilies() as $family) {
2963
            if ($parents) {
2964
                $husband = $family->husband();
2965
                $wife    = $family->wife();
2966
                if ($husband) {
2967
                    $list[$husband->xref()] = $husband;
2968
                    if (isset($list[$pid]->generation)) {
2969
                        $list[$husband->xref()]->generation = $list[$pid]->generation - 1;
2970
                    } else {
2971
                        $list[$husband->xref()]->generation = 1;
2972
                    }
2973
                }
2974
                if ($wife) {
2975
                    $list[$wife->xref()] = $wife;
2976
                    if (isset($list[$pid]->generation)) {
2977
                        $list[$wife->xref()]->generation = $list[$pid]->generation - 1;
2978
                    } else {
2979
                        $list[$wife->xref()]->generation = 1;
2980
                    }
2981
                }
2982
            }
2983
            $husband = $family->husband();
2984
            $wife = $family->wife();
2985
2986
            if ($husband && $wife) {
2987
                if ($husband->xref() == $person->xref()) {
2988
                    $this->mfrelation[$wife->xref()] = $this->mfrelation[$person->xref()] . "x";
2989
                    if ($wife->canShow()) {
2990
                        $list[$wife->xref()] = $wife;
2991
                    }
2992
                    if (!isset($wife->generation)) {
2993
                        $wife->generation = $person->generation;
2994
                    }
2995
                    $nam = $wife->getAllNames()[0]['fullNN'];
2996
                } else {
2997
                    $this->mfrelation[$husband->xref()] = $this->mfrelation[$person->xref()] . "x";
2998
                    if ($husband->canShow()) {
2999
                        $list[$husband->xref()] = $husband;
3000
                    }
3001
                    if (!isset($husband->generation)) {
3002
                        $husband->generation = $person->generation;
3003
                    }
3004
                    $nam = $husband->getAllNames()[0]['fullNN'];
3005
                }
3006
            }
3007
3008
            $children = $family->children();
3009
            foreach ($children as $child) {
3010
                if ($child) {
3011
                    $sx = $child->sex();
3012
                    $rl = "x"; // unknown
3013
                    if ($sx == "M") {
3014
                        $rl = "s";
3015
                    } // son
3016
                    if ($sx == "F") {
3017
                        $rl = "d";
3018
                    } // daughter
3019
                    $rl = $this->mfrelation[$person->xref()] . $rl;
3020
                    $this->mfrelation[$child->xref()] = $rl;
3021
                    if (isset($list[$pid]->generation)) {
3022
                        $child->generation = $list[$pid]->generation + 1;
3023
                    } else {
3024
                        $child->generation = 2;
3025
                    }
3026
                }
3027
            }
3028
            if ($generations == -1 || $list[$pid]->generation < $generations) {
3029
                foreach ($children as $child) {
3030
                    if ($child->canShow()) {
3031
                        $this->addDescendancy($list, $child->xref(), $parents, $generations);
3032
                    } // recurse on the childs family
3033
                }
3034
            }
3035
        }
3036
        $focusperson = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $focusperson is dead and can be removed.
Loading history...
3037
    }
3038
3039
    /**
3040
     * Create a list of all ancestors.
3041
     *
3042
     * @param array<Individual> $list
3043
     * @param string            $pid
3044
     * @param bool              $children
3045
     * @param int               $generations
3046
     *
3047
     * @return void
3048
     */
3049
    private function addAncestors(array &$list, string $pid, bool $children = false, int $generations = -1): void
3050
    {
3051
        $genlist                = [$pid];
3052
        $list[$pid]->generation = 1;
3053
        while (count($genlist) > 0) {
3054
            $id = array_shift($genlist);
3055
            if (str_starts_with($id, 'empty')) {
3056
                continue; // id can be something like “empty7”
3057
            }
3058
            if (!isset($this->mfrelation[$id])) {
3059
                $this->mfrelation[$id] = "";
3060
            }
3061
            $person = Registry::individualFactory()->make($id, $this->tree);
3062
            foreach ($person->childFamilies() as $family) {
3063
                $husband = $family->husband();
3064
                $wife    = $family->wife();
3065
                if ($husband) {
3066
                    $list[$husband->xref()]             = $husband;
3067
                    $list[$husband->xref()]->generation = $list[$id]->generation + 1;
3068
                    $this->mfrelation[$husband->xref()] = $this->mfrelation[$id] . "f";
3069
                }
3070
                if ($wife) {
3071
                    $list[$wife->xref()]             = $wife;
3072
                    $list[$wife->xref()]->generation = $list[$id]->generation + 1;
3073
                    $this->mfrelation[$wife->xref()] = $this->mfrelation[$id] . "m";
3074
                }
3075
                if ($generations == -1 || $list[$id]->generation + 1 < $generations) {
3076
                    if ($husband) {
3077
                        $genlist[] = $husband->xref();
3078
                    }
3079
                    if ($wife) {
3080
                        $genlist[] = $wife->xref();
3081
                    }
3082
                }
3083
                if ($children && isset($person)) {
3084
                    // unnecessary test of $person to satisfy phpstan!
3085
                    foreach ($family->children() as $child) {
3086
                        $list[$child->xref()] = $child;
3087
                        $child->generation = $list[$id]->generation ?? 1;
3088
                        if ($child->xref() != $person->xref()) {
3089
                            $this->mfrelation[$child->xref()] = $this->mfrelation[$id] . "x";
3090
                        }
3091
                    }
3092
                }
3093
            }
3094
        }
3095
    }
3096
3097
    /**
3098
     * get gedcom tag value
3099
     *
3100
     * @param string $tag    The tag to find, use : to delineate subtags
3101
     * @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
3102
     * @param string $gedrec The gedcom record to get the value from
3103
     *
3104
     * @return string the value of a gedcom tag from the given gedcom record
3105
     */
3106
    private function getGedcomValue(string $tag, int $level, string $gedrec): string
3107
    {
3108
        if ($gedrec === '') {
3109
            return '';
3110
        }
3111
        $tags      = explode(':', $tag);
3112
        $origlevel = $level;
3113
        if ($level === 0) {
3114
            $level = $gedrec[0] + 1;
3115
        }
3116
3117
        $subrec = $gedrec;
3118
        $t = 'XXXX';
3119
        foreach ($tags as $t) {
3120
            $lastsubrec = $subrec;
3121
            $subrec     = self::getSubRecord($level, "$level $t", $subrec);
3122
            if (empty($subrec) && $origlevel == 0) {
3123
                $level--;
3124
                $subrec = self::getSubRecord($level, "$level $t", $lastsubrec);
3125
            }
3126
            if (empty($subrec)) {
3127
                if ($t === 'TITL') {
3128
                    $subrec = self::getSubRecord($level, "$level ABBR", $lastsubrec);
3129
                    if (!empty($subrec)) {
3130
                        $t = 'ABBR';
3131
                    }
3132
                }
3133
                if ($subrec === '') {
3134
                    if ($level > 0) {
3135
                        $level--;
3136
                    }
3137
                    $subrec = self::getSubRecord($level, "@ $t", $gedrec);
3138
                    if ($subrec === '') {
3139
                        return '';
3140
                    }
3141
                }
3142
            }
3143
            $level++;
3144
        }
3145
        $level--;
3146
        $ct = preg_match("/$level $t(.*)/", $subrec, $match);
3147
        if ($ct === 0) {
3148
            $ct = preg_match("/$level @.+@ (.+)/", $subrec, $match);
3149
        }
3150
        if ($ct === 0) {
3151
            $ct = preg_match("/@ $t (.+)/", $subrec, $match);
3152
        }
3153
        if ($ct > 0) {
3154
            $value = trim($match[1]);
3155
            if ($t === 'NOTE' && preg_match('/^@(.+)@$/', $value, $match)) {
3156
                $note = Registry::noteFactory()->make($match[1], $this->tree);
3157
                if ($note instanceof Note) {
3158
                    $value = $note->getNote();
3159
                } else {
3160
                    //-- set the value to the id without the @
3161
                    $value = $match[1];
3162
                }
3163
            }
3164
            if ($level !== 0 || $t !== 'NOTE') {
3165
                $value .= self::getCont($level + 1, $subrec);
3166
            }
3167
3168
            if ($tag === 'NAME' || $tag === '_MARNM' || $tag === '_AKA') {
3169
                return strtr($value, ['/' => '']);
3170
            }
3171
3172
            if ($tag === 'NAME' || $tag === '_MARNM' || $tag === '_AKA') {
3173
                return strtr($value, ['/' => '']);
3174
            }
3175
3176
            return $value;
3177
        }
3178
3179
        return '';
3180
    }
3181
3182
    /**
3183
     * Replace variable identifiers with their values.
3184
     *
3185
     * @param string $expression An expression such as "$foo == 123"
3186
     * @param bool   $quote      Whether to add quotation marks
3187
     *
3188
     * @return string
3189
     */
3190
    private function substituteVars($expression, $quote): string
3191
    {
3192
        return preg_replace_callback(
3193
            '/\$(\w+)/',
3194
            function (array $matches) use ($quote): string {
3195
                if (isset($this->vars[$matches[1]]['id'])) {
3196
                    if ($quote) {
3197
                        return "'" . addcslashes($this->vars[$matches[1]]['id'], "'") . "'";
3198
                    }
3199
3200
                    return $this->vars[$matches[1]]['id'];
3201
                }
3202
3203
                Log::addErrorLog(sprintf('Undefined variable $%s in report', $matches[1]));
3204
3205
                return '$' . $matches[1];
3206
            },
3207
            $expression
3208
        );
3209
    }
3210
}
3211