xref: /webtrees/app/Report/HtmlRenderer.php (revision ac71572d8462e396ed5a307f05b29381e49f9e6e)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Report;
21
22use Fisharebest\Webtrees\I18N;
23use Fisharebest\Webtrees\MediaFile;
24use Fisharebest\Webtrees\Webtrees;
25
26use function array_map;
27use function ceil;
28use function count;
29use function explode;
30use function implode;
31use function preg_match;
32use function str_replace;
33use function stripos;
34use function strrpos;
35use function substr;
36use function substr_count;
37
38/**
39 * Class HtmlRenderer
40 */
41class HtmlRenderer extends AbstractRenderer
42{
43    // Cell padding
44    public float $cPadding = 2;
45
46    // Cell height ratio
47    public float $cellHeightRatio = 1.8;
48
49    // Current horizontal position
50    public float $X = 0.0;
51
52    // Current vertical position
53    public float $Y = 0.0;
54
55    // Page number counter
56    public int $pageN = 1;
57
58    // Store the page width without left and right margins
59    // Only needed for PDF reports
60    public float $noMarginWidth = 0.0;
61
62    // Last cell height
63    public float $lastCellHeight = 0.0;
64
65    // LTR or RTL alignement; "left" on LTR, "right" on RTL
66    // Used in <div>
67    public string $alignRTL = 'left';
68
69    // LTR or RTL entity
70    public string $entityRTL = '&lrm;';
71
72    // Largest Font Height is used by TextBox etc.
73    //
74    // Use this to calculate a the text height.
75    // This makes sure that the text fits into the cell/box when different font sizes are used
76    public float $largestFontHeight = 0;
77
78    // Keep track of the highest Y position
79    // Used with Header div / Body div / Footer div / "addpage" / The bottom of the last image etc.
80    public float $maxY = 0;
81
82    /**
83     * @var ReportHtmlFootnote[] Array of elements in the footer notes
84     */
85    public array $printedfootnotes = [];
86
87    /**
88     * HTML Setup - ReportHtml
89     *
90     * @return void
91     */
92    public function setup(): void
93    {
94        parent::setup();
95
96        // Setting up the correct dimensions if Portrait (default) or Landscape
97        if ($this->orientation === 'landscape') {
98            $tmpw              = $this->page_width;
99            $this->page_width  = $this->page_height;
100            $this->page_height = $tmpw;
101        }
102        // Store the pagewidth without margins
103        $this->noMarginWidth = $this->page_width - $this->left_margin - $this->right_margin;
104        // If RTL
105        if ($this->rtl) {
106            $this->alignRTL  = 'right';
107            $this->entityRTL = '&rlm;';
108        }
109        // Change the default HTML font name
110        $this->default_font = 'Arial';
111
112        if ($this->show_generated_by) {
113            // The default style name for Generated by.... is 'genby'
114            $element = new ReportHtmlCell(0.0, 10.0, '', 'C', '', 'genby', 1, ReportBaseElement::CURRENT_POSITION, ReportBaseElement::CURRENT_POSITION, 0, 0, '', '', true);
115            $element->addText($this->generated_by);
116            $element->setUrl(Webtrees::URL);
117            $this->footerElements[] = $element;
118        }
119    }
120
121    /**
122     * Generate footnotes
123     *
124     * @return void
125     */
126    public function footnotes(): void
127    {
128        $this->currentStyle = '';
129        if (!empty($this->printedfootnotes)) {
130            foreach ($this->printedfootnotes as $element) {
131                $element->renderFootnote($this);
132            }
133        }
134    }
135
136    /**
137     * Run the report.
138     *
139     * @return void
140     */
141    public function run(): void
142    {
143        // Setting up the styles
144        echo '<style>';
145        echo '#bodydiv { font: 10px sans-serif;}';
146        foreach ($this->styles as $class => $style) {
147            echo '.', $class, ' { ';
148            if ($style['font'] === 'dejavusans') {
149                $style['font'] = $this->default_font;
150            }
151            echo 'font-family: ', $style['font'], '; ';
152            echo 'font-size: ', $style['size'], 'pt; ';
153            // Case-insensitive
154            if (stripos($style['style'], 'B') !== false) {
155                echo 'font-weight: bold; ';
156            }
157            if (stripos($style['style'], 'I') !== false) {
158                echo 'font-style: italic; ';
159            }
160            if (stripos($style['style'], 'U') !== false) {
161                echo 'text-decoration: underline; ';
162            }
163            if (stripos($style['style'], 'D') !== false) {
164                echo 'text-decoration: line-through; ';
165            }
166            echo '}', PHP_EOL;
167        }
168
169        //-- header divider
170        echo '</style>', PHP_EOL;
171        echo '<div id="headermargin" style="position: relative; top: auto; height: ', $this->header_margin, 'pt; width: ', $this->noMarginWidth, 'pt;"></div>';
172        echo '<div id="headerdiv" style="position: relative; top: auto; width: ', $this->noMarginWidth, 'pt;">';
173        foreach ($this->headerElements as $element) {
174            if ($element instanceof ReportBaseElement) {
175                $element->render($this);
176            } elseif ($element === 'footnotetexts') {
177                $this->footnotes();
178            } elseif ($element === 'addpage') {
179                $this->addPage();
180            }
181        }
182        //-- body
183        echo '</div>';
184        echo '<script>document.getElementById("headerdiv").style.height="', $this->top_margin - $this->header_margin - 6, 'pt";</script>';
185        echo '<div id="bodydiv" style="position: relative; top: auto; width: ', $this->noMarginWidth, 'pt; height: 100%;">';
186        $this->Y    = 0;
187        $this->maxY = 0;
188        foreach ($this->bodyElements as $element) {
189            if ($element instanceof ReportBaseElement) {
190                $element->render($this);
191            } elseif ($element === 'footnotetexts') {
192                $this->footnotes();
193            } elseif ($element === 'addpage') {
194                $this->addPage();
195            }
196        }
197        //-- footer
198        echo '</div>';
199        echo '<script>document.getElementById("bodydiv").style.height="', $this->maxY, 'pt";</script>';
200        echo '<div id="bottommargin" style="position: relative; top: auto; height: ', $this->bottom_margin - $this->footer_margin, 'pt;width:', $this->noMarginWidth, 'pt;"></div>';
201        echo '<div id="footerdiv" style="position: relative; top: auto; width: ', $this->noMarginWidth, 'pt;height:auto;">';
202        $this->Y    = 0;
203        $this->X    = 0;
204        $this->maxY = 0;
205        foreach ($this->footerElements as $element) {
206            if ($element instanceof ReportBaseElement) {
207                $element->render($this);
208            } elseif ($element === 'footnotetexts') {
209                $this->footnotes();
210            } elseif ($element === 'addpage') {
211                $this->addPage();
212            }
213        }
214        echo '</div>';
215        echo '<script>document.getElementById("footerdiv").style.height="', $this->maxY, 'pt";</script>';
216        echo '<div id="footermargin" style="position: relative; top: auto; height: ', $this->footer_margin, 'pt;width:', $this->noMarginWidth, 'pt;"></div>';
217    }
218
219    /**
220     * Create a new Cell object.
221     *
222     * @param float  $width   cell width (expressed in points)
223     * @param float  $height  cell height (expressed in points)
224     * @param string $border  Border style
225     * @param string $align   Text alignement
226     * @param string $bgcolor Background color code
227     * @param string $style   The name of the text style
228     * @param int    $ln      Indicates where the current position should go after the call
229     * @param mixed  $top     Y-position
230     * @param mixed  $left    X-position
231     * @param int    $fill    Indicates if the cell background must be painted (1) or transparent (0). Default value: 1
232     * @param int    $stretch Stretch character mode
233     * @param string $bocolor Border color
234     * @param string $tcolor  Text color
235     * @param bool   $reseth
236     *
237     * @return ReportBaseCell
238     */
239    public function createCell(float $width, float $height, string $border, string $align, string $bgcolor, string $style, int $ln, $top, $left, int $fill, int $stretch, string $bocolor, string $tcolor, bool $reseth): ReportBaseCell
240    {
241        return new ReportHtmlCell($width, $height, $border, $align, $bgcolor, $style, $ln, $top, $left, $fill, $stretch, $bocolor, $tcolor, $reseth);
242    }
243
244    /**
245     * Create a new TextBox object.
246     *
247     * @param float  $width   Text box width
248     * @param float  $height  Text box height
249     * @param bool   $border
250     * @param string $bgcolor Background color code in HTML
251     * @param bool   $newline
252     * @param float  $left
253     * @param float  $top
254     * @param bool   $pagecheck
255     * @param string $style
256     * @param bool   $fill
257     * @param bool   $padding
258     * @param bool   $reseth
259     *
260     * @return ReportBaseTextbox
261     */
262    public function createTextBox(
263        float $width,
264        float $height,
265        bool $border,
266        string $bgcolor,
267        bool $newline,
268        float $left,
269        float $top,
270        bool $pagecheck,
271        string $style,
272        bool $fill,
273        bool $padding,
274        bool $reseth
275    ): ReportBaseTextbox {
276        return new ReportHtmlTextbox($width, $height, $border, $bgcolor, $newline, $left, $top, $pagecheck, $style, $fill, $padding, $reseth);
277    }
278
279    /**
280     * Create a text element.
281     *
282     * @param string $style
283     * @param string $color
284     *
285     * @return ReportBaseText
286     */
287    public function createText(string $style, string $color): ReportBaseText
288    {
289        return new ReportHtmlText($style, $color);
290    }
291
292    /**
293     * Create a new Footnote object.
294     *
295     * @param string $style Style name
296     *
297     * @return ReportBaseFootnote
298     */
299    public function createFootnote(string $style): ReportBaseFootnote
300    {
301        return new ReportHtmlFootnote($style);
302    }
303
304    /**
305     * Create a new image object.
306     *
307     * @param string $file  Filename
308     * @param float  $x
309     * @param float  $y
310     * @param float  $w     Image width
311     * @param float  $h     Image height
312     * @param string $align L:left, C:center, R:right or empty to use x/y
313     * @param string $ln    T:same line, N:next line
314     *
315     * @return ReportBaseImage
316     */
317    public function createImage(string $file, float $x, float $y, float $w, float $h, string $align, string $ln): ReportBaseImage
318    {
319        return new ReportHtmlImage($file, $x, $y, $w, $h, $align, $ln);
320    }
321
322    /**
323     * Create a new image object from Media Object.
324     *
325     * @param MediaFile $media_file
326     * @param float     $x
327     * @param float     $y
328     * @param float     $w     Image width
329     * @param float     $h     Image height
330     * @param string    $align L:left, C:center, R:right or empty to use x/y
331     * @param string    $ln    T:same line, N:next line
332     *
333     * @return ReportBaseImage
334     */
335    public function createImageFromObject(
336        MediaFile $media_file,
337        float $x,
338        float $y,
339        float $w,
340        float $h,
341        string $align,
342        string $ln
343    ): ReportBaseImage {
344        return new ReportHtmlImage($media_file->imageUrl((int) $w, (int) $h, 'crop'), $x, $y, $w, $h, $align, $ln);
345    }
346
347    /**
348     * Create a line.
349     *
350     * @param float $x1
351     * @param float $y1
352     * @param float $x2
353     * @param float $y2
354     *
355     * @return ReportBaseLine
356     */
357    public function createLine(float $x1, float $y1, float $x2, float $y2): ReportBaseLine
358    {
359        return new ReportHtmlLine($x1, $y1, $x2, $y2);
360    }
361
362    /**
363     * Clear the Header
364     *
365     * @return void
366     */
367    public function clearHeader(): void
368    {
369        $this->headerElements = [];
370    }
371
372    /**
373     * Update the Page Number and set a new Y if max Y is larger - ReportHtml
374     *
375     * @return void
376     */
377    public function addPage(): void
378    {
379        $this->pageN++;
380
381        // Add a little margin to max Y "between pages"
382        $this->maxY += 10;
383
384        // If Y is still heigher by any reason...
385        if ($this->maxY < $this->Y) {
386            // ... update max Y
387            $this->maxY = $this->Y;
388        } else {
389            // else update Y so that nothing will be overwritten, like images or cells...
390            $this->Y = $this->maxY;
391        }
392    }
393
394    /**
395     * Uppdate max Y to keep track it incase of a pagebreak - ReportHtml
396     *
397     * @param float $y
398     *
399     * @return void
400     */
401    public function addMaxY(float $y): void
402    {
403        if ($this->maxY < $y) {
404            $this->maxY = $y;
405        }
406    }
407
408    /**
409     * Checks the Footnote and numbers them - ReportHtml
410     *
411     * @param ReportHtmlFootnote $footnote
412     *
413     * @return ReportHtmlFootnote|bool object if already numbered, false otherwise
414     */
415    public function checkFootnote(ReportHtmlFootnote $footnote)
416    {
417        $ct  = count($this->printedfootnotes);
418        $i   = 0;
419        $val = $footnote->getValue();
420        while ($i < $ct) {
421            if ($this->printedfootnotes[$i]->getValue() === $val) {
422                // If this footnote already exist then set up the numbers for this object
423                $footnote->setNum($i + 1);
424                $footnote->setAddlink((string) ($i + 1));
425
426                return $this->printedfootnotes[$i];
427            }
428            $i++;
429        }
430        // If this Footnote has not been set up yet
431        $footnote->setNum($ct + 1);
432        $footnote->setAddlink((string) ($ct + 1));
433        $this->printedfootnotes[] = $footnote;
434
435        return false;
436    }
437
438    /**
439     * Count the number of lines - ReportHtml
440     *
441     * @param string $str
442     *
443     * @return int Number of lines. 0 if empty line
444     */
445    public function countLines(string $str): int
446    {
447        if ($str === '') {
448            return 0;
449        }
450
451        return substr_count($str, "\n") + 1;
452    }
453
454    /**
455     * Get the current style.
456     *
457     * @return string
458     */
459    public function getCurrentStyle(): string
460    {
461        return $this->currentStyle;
462    }
463
464    /**
465     * Get the current style height.
466     *
467     * @return float
468     */
469    public function getCurrentStyleHeight(): float
470    {
471        if (empty($this->currentStyle)) {
472            return $this->default_font_size;
473        }
474        $style = $this->getStyle($this->currentStyle);
475
476        return (float) $style['size'];
477    }
478
479    /**
480     * Get the current footnotes height.
481     *
482     * @param float $cellWidth
483     *
484     * @return float
485     */
486    public function getFootnotesHeight(float $cellWidth): float
487    {
488        $h = 0;
489        foreach ($this->printedfootnotes as $element) {
490            $h += $element->getFootnoteHeight($this, $cellWidth);
491        }
492
493        return $h;
494    }
495
496    /**
497     * Get the maximum width from current position to the margin - ReportHtml
498     *
499     * @return float
500     */
501    public function getRemainingWidth(): float
502    {
503        return $this->noMarginWidth - $this->X;
504    }
505
506    /**
507     * Get the page height.
508     *
509     * @return float
510     */
511    public function getPageHeight(): float
512    {
513        return $this->page_height - $this->top_margin;
514    }
515
516    /**
517     * Get the width of a string.
518     *
519     * @param string $text
520     *
521     * @return float
522     */
523    public function getStringWidth(string $text): float
524    {
525        $style = $this->getStyle($this->currentStyle);
526
527        return mb_strlen($text) * ($style['size'] / 2);
528    }
529
530    /**
531     * Get a text height in points - ReportHtml
532     *
533     * @param string $str
534     *
535     * @return float
536     */
537    public function getTextCellHeight(string $str): float
538    {
539        // Count the number of lines to calculate the height
540        $nl = $this->countLines($str);
541
542        // Calculate the cell height
543        return ceil($this->getCurrentStyleHeight() * $this->cellHeightRatio * $nl);
544    }
545
546    /**
547     * Get the current X position - ReportHtml
548     *
549     * @return float
550     */
551    public function getX(): float
552    {
553        return $this->X;
554    }
555
556    /**
557     * Get the current Y position - ReportHtml
558     *
559     * @return float
560     */
561    public function getY(): float
562    {
563        return $this->Y;
564    }
565
566    /**
567     * Get the current page number - ReportHtml
568     *
569     * @return int
570     */
571    public function pageNo(): int
572    {
573        return $this->pageN;
574    }
575
576    /**
577     * Set the current style.
578     *
579     * @param string $s
580     *
581     * @void
582     */
583    public function setCurrentStyle(string $s): void
584    {
585        $this->currentStyle = $s;
586    }
587
588    /**
589     * Set the X position - ReportHtml
590     *
591     * @param float $x
592     *
593     * @return void
594     */
595    public function setX(float $x): void
596    {
597        $this->X = $x;
598    }
599
600    /**
601     * Set the Y position - ReportHtml
602     *
603     * Also updates Max Y position
604     *
605     * @param float $y
606     *
607     * @return void
608     */
609    public function setY(float $y): void
610    {
611        $this->Y = $y;
612        if ($this->maxY < $y) {
613            $this->maxY = $y;
614        }
615    }
616
617    /**
618     * Set the X and Y position - ReportHtml
619     *
620     * Also updates Max Y position
621     *
622     * @param float $x
623     * @param float $y
624     *
625     * @return void
626     */
627    public function setXy(float $x, float $y): void
628    {
629        $this->setX($x);
630        $this->setY($y);
631    }
632
633    /**
634     * Wrap text - ReportHtml
635     *
636     * @param string $str   Text to wrap
637     * @param float  $width Width in points the text has to fit into
638     *
639     * @return string
640     */
641    public function textWrap(string $str, float $width): string
642    {
643        $line_width = (int) ($width / ($this->getCurrentStyleHeight() / 2));
644
645        $lines = explode("\n", $str);
646
647        $lines = array_map(fn (string $string): string => $this->utf8WordWrap($string, $line_width), $lines);
648
649        return implode("\n", $lines);
650    }
651
652    /**
653     * Wrap text, similar to the PHP wordwrap() function.
654     *
655     * @param string $string
656     * @param int    $width
657     *
658     * @return string
659     */
660    private function utf8WordWrap(string $string, int $width): string
661    {
662        $out = '';
663        while ($string) {
664            if (mb_strlen($string) <= $width) {
665                // Do not wrap any text that is less than the output area.
666                $out .= $string;
667                $string = '';
668            } else {
669                $sub1 = mb_substr($string, 0, $width + 1);
670                if (mb_substr($string, mb_strlen($sub1) - 1, 1) === ' ') {
671                    // include words that end by a space immediately after the area.
672                    $sub = $sub1;
673                } else {
674                    $sub = mb_substr($string, 0, $width);
675                }
676                $spacepos = strrpos($sub, ' ');
677                if ($spacepos === false) {
678                    // No space on line?
679                    $out .= $sub . "\n";
680                    $string = mb_substr($string, mb_strlen($sub));
681                } else {
682                    // Split at space;
683                    $out .= substr($string, 0, $spacepos) . "\n";
684                    $string = substr($string, $spacepos + 1);
685                }
686            }
687        }
688
689        return $out;
690    }
691
692    /**
693     * Write text - ReportHtml
694     *
695     * @param string $text  Text to print
696     * @param string $color HTML RGB color code (Ex: #001122)
697     * @param bool   $useclass
698     *
699     * @return void
700     */
701    public function write(string $text, string $color = '', bool $useclass = true): void
702    {
703        $style    = $this->getStyle($this->getCurrentStyle());
704        $htmlcode = '<span dir="' . I18N::direction() . '"';
705        if ($useclass) {
706            $htmlcode .= ' class="' . $style['name'] . '"';
707        }
708        // Check if Text Color is set and if it’s valid HTML color
709        if (preg_match('/#?(..)(..)(..)/', $color)) {
710            $htmlcode .= ' style="color:' . $color . ';"';
711        }
712
713        $htmlcode .= '>' . $text . '</span>';
714        $htmlcode = str_replace([
715            "\n",
716            '> ',
717            ' <',
718        ], [
719            '<br>',
720            '>&nbsp;',
721            '&nbsp;<',
722        ], $htmlcode);
723        echo $htmlcode;
724    }
725}
726