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