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

ReportParserGenerate::getPersonNameStartHandler()   F

Complexity

Conditions 24
Paths 644

Size

Total Lines 75
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 24
eloc 57
c 0
b 0
f 0
nc 644
nop 1
dl 0
loc 75
rs 0.4944

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<array<string,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
                if ($ix1 = strpos($name, '<span class="starredname">')) {   // '«' and '»' mark text for underlining
1031
                    $name = substr_replace($name, '«', $ix1, 26);
1032
                    $ix1 = strpos($name, '</span>', $ix1);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type array; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

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