]> BookStack Code Mirror - bookstack/blob - app/Entities/ExportService.php
Refactored the code for ExportService to use DomDocument.
[bookstack] / app / Entities / ExportService.php
1 <?php namespace BookStack\Entities;
2
3 use BookStack\Entities\Repos\EntityRepo;
4 use BookStack\Uploads\ImageService;
5 use BookStack\Exceptions\ExportException;
6
7 class ExportService
8 {
9     protected $contentMatching = [
10         'video' => ["www.youtube.com", "player.vimeo.com", "www.dailymotion.com"],
11         'map' => ['maps.google.com']
12     ];
13
14     protected $entityRepo;
15     protected $imageService;
16
17     /**
18      * ExportService constructor.
19      * @param EntityRepo $entityRepo
20      * @param ImageService $imageService
21      */
22     public function __construct(EntityRepo $entityRepo, ImageService $imageService)
23     {
24         $this->entityRepo = $entityRepo;
25         $this->imageService = $imageService;
26     }
27
28     /**
29      * Convert a page to a self-contained HTML file.
30      * Includes required CSS & image content. Images are base64 encoded into the HTML.
31      * @param \BookStack\Entities\Page $page
32      * @return mixed|string
33      * @throws \Throwable
34      */
35     public function pageToContainedHtml(Page $page)
36     {
37         $this->entityRepo->renderPage($page);
38         $pageHtml = view('pages/export', [
39             'page' => $page
40         ])->render();
41         return $this->containHtml($pageHtml);
42     }
43
44     /**
45      * Convert a chapter to a self-contained HTML file.
46      * @param \BookStack\Entities\Chapter $chapter
47      * @return mixed|string
48      * @throws \Throwable
49      */
50     public function chapterToContainedHtml(Chapter $chapter)
51     {
52         $pages = $this->entityRepo->getChapterChildren($chapter);
53         $pages->each(function ($page) {
54             $page->html = $this->entityRepo->renderPage($page);
55         });
56         $html = view('chapters/export', [
57             'chapter' => $chapter,
58             'pages' => $pages
59         ])->render();
60         return $this->containHtml($html);
61     }
62
63     /**
64      * Convert a book to a self-contained HTML file.
65      * @param Book $book
66      * @return mixed|string
67      * @throws \Throwable
68      */
69     public function bookToContainedHtml(Book $book)
70     {
71         $bookTree = $this->entityRepo->getBookChildren($book, true, true);
72         $html = view('books/export', [
73             'book' => $book,
74             'bookChildren' => $bookTree
75         ])->render();
76         return $this->containHtml($html);
77     }
78
79     /**
80      * Convert a page to a PDF file.
81      * @param Page $page
82      * @param bool $isTesting
83      * @return mixed|string
84      * @throws \Throwable
85      */
86     public function pageToPdf(Page $page, bool $isTesting = false)
87     {
88         $this->entityRepo->renderPage($page);
89         $html = view('pages/pdf', [
90             'page' => $page
91         ])->render();
92         return $this->htmlToPdf($html, $isTesting);
93     }
94
95     /**
96      * Convert a chapter to a PDF file.
97      * @param \BookStack\Entities\Chapter $chapter
98      * @return mixed|string
99      * @throws \Throwable
100      */
101     public function chapterToPdf(Chapter $chapter)
102     {
103         $pages = $this->entityRepo->getChapterChildren($chapter);
104         $pages->each(function ($page) {
105             $page->html = $this->entityRepo->renderPage($page);
106         });
107         $html = view('chapters/export', [
108             'chapter' => $chapter,
109             'pages' => $pages
110         ])->render();
111         return $this->htmlToPdf($html);
112     }
113
114     /**
115      * Convert a book to a PDF file
116      * @param \BookStack\Entities\Book $book
117      * @return string
118      * @throws \Throwable
119      */
120     public function bookToPdf(Book $book)
121     {
122         $bookTree = $this->entityRepo->getBookChildren($book, true, true);
123         $html = view('books/export', [
124             'book' => $book,
125             'bookChildren' => $bookTree
126         ])->render();
127         return $this->htmlToPdf($html);
128     }
129
130     /**
131      * Convert normal webpage HTML to a PDF.
132      * @param $html
133      * @param $isTesting
134      * @return string
135      * @throws \Exception
136      */
137     protected function htmlToPdf($html, $isTesting = false)
138     {
139         $containedHtml = $this->containHtml($html, true);
140         if ($isTesting) {
141             return $containedHtml;
142         }
143         $useWKHTML = config('snappy.pdf.binary') !== false;
144         if ($useWKHTML) {
145             $pdf = \SnappyPDF::loadHTML($containedHtml);
146             $pdf->setOption('print-media-type', true);
147         } else {
148             $pdf = \DomPDF::loadHTML($containedHtml);
149         }
150         return $pdf->output();
151     }
152
153     /**
154      * Bundle of the contents of a html file to be self-contained.
155      * @param $htmlContent
156      * @param bool $isPDF
157      * @return mixed|string
158      * @throws \BookStack\Exceptions\ExportException
159      */
160     protected function containHtml(string $htmlContent, bool $isPDF = false) : string
161     {
162         $dom = $this->getDOM($htmlContent);
163         if ($dom === false) {
164             throw new ExportException(trans('errors.dom_parse_error'));
165         }
166
167         // replace image src with base64 encoded image strings
168         $images = $dom->getElementsByTagName('img');
169         foreach ($images as $img) {
170             $base64String = $this->imageService->imageUriToBase64($img->getAttribute('src'));
171             if ($base64String !== null) {
172                 $img->setAttribute('src', $base64String);
173                 $dom->saveHTML($img);
174             }
175         }
176
177         // replace all relative hrefs.
178         $links = $dom->getElementsByTagName('a');
179         foreach ($links as $link) {
180             $href = $link->getAttribute('href');
181             if (strpos(trim($href), 'http') !== 0) {
182                 $newHref = url($href);
183                 $link->setAttribute('href', $newHref);
184                 $dom->saveHTML($link);
185             }
186         }
187
188         // replace all src in video, audio and iframe tags
189         $xmlDoc = new \DOMXPath($dom);
190         $srcElements = $xmlDoc->query('//video | //audio | //iframe');
191         foreach ($srcElements as $element) {
192             $element = $this->fixRelativeSrc($element);
193             $dom->saveHTML($element);
194
195             if ($isPDF) {
196                 $src = $element->getAttribute('src');
197                 $label = $this->getContentLabel($src);
198
199                 $div = $dom->createElement('div');
200                 $textNode = $dom->createTextNode($label);
201
202                 $anchor = $dom->createElement('a');
203                 $anchor->setAttribute('href', $src);
204                 $anchor->textContent = $src;
205
206                 $div->appendChild($textNode);
207                 $div->appendChild($anchor);
208
209                 $element->parentNode->replaceChild($div, $element);
210             }
211         }
212
213         return $dom->saveHTML();
214     }
215
216     /**
217      * Converts the page contents into simple plain text.
218      * This method filters any bad looking content to provide a nice final output.
219      * @param Page $page
220      * @return mixed
221      * @throws \BookStack\Exceptions\ExportException
222      */
223     public function pageToPlainText(Page $page)
224     {
225         $html = $this->entityRepo->renderPage($page);
226         $dom = $this->getDom($html);
227
228         if ($dom === false) {
229             throw new ExportException(trans('errors.dom_parse_error'));
230         }
231
232         // handle anchor tags.
233         $links = $dom->getElementsByTagName('a');
234         foreach ($links as $link) {
235             $href = $link->getAttribute('href');
236             if (strpos(trim($href), 'http') !== 0) {
237                 $newHref = url($href);
238                 $link->setAttribute('href', $newHref);
239             }
240
241             $link->textContent = trim($link->textContent . " ($href)");
242             $dom->saveHTML();
243         }
244
245         $xmlDoc = new \DOMXPath($dom);
246         $srcElements = $xmlDoc->query('//video | //audio | //iframe | //img');
247         foreach ($srcElements as $element) {
248             $element = $this->fixRelativeSrc($element);
249             $fixedSrc = $element->getAttribute('src');
250             $label = $this->getContentLabel($fixedSrc);
251             $finalLabel = "\n\n$label $fixedSrc\n\n";
252
253             $textNode = $dom->createTextNode($finalLabel);
254             $element->parentNode->replaceChild($textNode, $element);
255         }
256
257         $text = strip_tags($dom->saveHTML());
258         // Replace multiple spaces with single spaces
259         $text = preg_replace('/\ {2,}/', ' ', $text);
260         // Reduce multiple horrid whitespace characters.
261         $text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text);
262         $text = html_entity_decode($text);
263         // Add title
264         $text = $page->name . "\n\n" . $text;
265         return $text;
266     }
267
268     /**
269      * Convert a chapter into a plain text string.
270      * @param \BookStack\Entities\Chapter $chapter
271      * @return string
272      */
273     public function chapterToPlainText(Chapter $chapter)
274     {
275         $text = $chapter->name . "\n\n";
276         $text .= $chapter->description . "\n\n";
277         foreach ($chapter->pages as $page) {
278             $text .= $this->pageToPlainText($page);
279         }
280         return $text;
281     }
282
283     /**
284      * Convert a book into a plain text string.
285      * @param Book $book
286      * @return string
287      */
288     public function bookToPlainText(Book $book)
289     {
290         $bookTree = $this->entityRepo->getBookChildren($book, true, true);
291         $text = $book->name . "\n\n";
292         foreach ($bookTree as $bookChild) {
293             if ($bookChild->isA('chapter')) {
294                 $text .= $this->chapterToPlainText($bookChild);
295             } else {
296                 $text .= $this->pageToPlainText($bookChild);
297             }
298         }
299         return $text;
300     }
301
302     protected function getDom(string $htmlContent) : \DOMDocument
303     {
304         // See - https://stackoverflow.com/a/17559716/903324
305         $dom = new \DOMDocument();
306         libxml_use_internal_errors(true);
307         $dom->loadHTML($htmlContent);
308         libxml_clear_errors();
309         return $dom;
310     }
311
312     protected function fixRelativeSrc(\DOMElement $element): \DOMElement
313     {
314         $src = $element->getAttribute('src');
315         if (strpos(trim($src), 'http') !== 0) {
316             $newSrc = 'https:' . $src;
317             $element->setAttribute('src', $newSrc);
318         }
319         return $element;
320     }
321
322
323     protected function getContentLabel(string $src) : string
324     {
325         foreach ($this->contentMatching as $key => $possibleValues) {
326             foreach ($possibleValues as $value) {
327                 if (strpos($src, $value)) {
328                     return trans("entities.$key");
329                 }
330             }
331         }
332         return trans('entities.embedded_content');
333     }
334 }