]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/ExportFormatter.php
Applied StyleCI changes, updated readme badges & roadmap
[bookstack] / app / Entities / Tools / ExportFormatter.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Entities\Tools\Markdown\HtmlToMarkdown;
9 use BookStack\Uploads\ImageService;
10 use DOMDocument;
11 use DOMElement;
12 use DOMXPath;
13 use Exception;
14 use Throwable;
15
16 class ExportFormatter
17 {
18     protected $imageService;
19     protected $pdfGenerator;
20
21     /**
22      * ExportService constructor.
23      */
24     public function __construct(ImageService $imageService, PdfGenerator $pdfGenerator)
25     {
26         $this->imageService = $imageService;
27         $this->pdfGenerator = $pdfGenerator;
28     }
29
30     /**
31      * Convert a page to a self-contained HTML file.
32      * Includes required CSS & image content. Images are base64 encoded into the HTML.
33      *
34      * @throws Throwable
35      */
36     public function pageToContainedHtml(Page $page)
37     {
38         $page->html = (new PageContent($page))->render();
39         $pageHtml = view('pages.export', [
40             'page'   => $page,
41             'format' => 'html',
42         ])->render();
43
44         return $this->containHtml($pageHtml);
45     }
46
47     /**
48      * Convert a chapter to a self-contained HTML file.
49      *
50      * @throws Throwable
51      */
52     public function chapterToContainedHtml(Chapter $chapter)
53     {
54         $pages = $chapter->getVisiblePages();
55         $pages->each(function ($page) {
56             $page->html = (new PageContent($page))->render();
57         });
58         $html = view('chapters.export', [
59             'chapter' => $chapter,
60             'pages'   => $pages,
61             'format'  => 'html',
62         ])->render();
63
64         return $this->containHtml($html);
65     }
66
67     /**
68      * Convert a book to a self-contained HTML file.
69      *
70      * @throws Throwable
71      */
72     public function bookToContainedHtml(Book $book)
73     {
74         $bookTree = (new BookContents($book))->getTree(false, true);
75         $html = view('books.export', [
76             'book'         => $book,
77             'bookChildren' => $bookTree,
78             'format'       => 'html',
79         ])->render();
80
81         return $this->containHtml($html);
82     }
83
84     /**
85      * Convert a page to a PDF file.
86      *
87      * @throws Throwable
88      */
89     public function pageToPdf(Page $page)
90     {
91         $page->html = (new PageContent($page))->render();
92         $html = view('pages.export', [
93             'page'   => $page,
94             'format' => 'pdf',
95             'engine' => $this->pdfGenerator->getActiveEngine(),
96         ])->render();
97
98         return $this->htmlToPdf($html);
99     }
100
101     /**
102      * Convert a chapter to a PDF file.
103      *
104      * @throws Throwable
105      */
106     public function chapterToPdf(Chapter $chapter)
107     {
108         $pages = $chapter->getVisiblePages();
109         $pages->each(function ($page) {
110             $page->html = (new PageContent($page))->render();
111         });
112
113         $html = view('chapters.export', [
114             'chapter' => $chapter,
115             'pages'   => $pages,
116             'format'  => 'pdf',
117             'engine'  => $this->pdfGenerator->getActiveEngine(),
118         ])->render();
119
120         return $this->htmlToPdf($html);
121     }
122
123     /**
124      * Convert a book to a PDF file.
125      *
126      * @throws Throwable
127      */
128     public function bookToPdf(Book $book)
129     {
130         $bookTree = (new BookContents($book))->getTree(false, true);
131         $html = view('books.export', [
132             'book'         => $book,
133             'bookChildren' => $bookTree,
134             'format'       => 'pdf',
135             'engine'       => $this->pdfGenerator->getActiveEngine(),
136         ])->render();
137
138         return $this->htmlToPdf($html);
139     }
140
141     /**
142      * Convert normal web-page HTML to a PDF.
143      *
144      * @throws Exception
145      */
146     protected function htmlToPdf(string $html): string
147     {
148         $html = $this->containHtml($html);
149         $html = $this->replaceIframesWithLinks($html);
150         $html = $this->openDetailElements($html);
151
152         return $this->pdfGenerator->fromHtml($html);
153     }
154
155     /**
156      * Within the given HTML content, Open any detail blocks.
157      */
158     protected function openDetailElements(string $html): string
159     {
160         libxml_use_internal_errors(true);
161
162         $doc = new DOMDocument();
163         $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
164         $xPath = new DOMXPath($doc);
165
166         $details = $xPath->query('//details');
167         /** @var DOMElement $detail */
168         foreach ($details as $detail) {
169             $detail->setAttribute('open', 'open');
170         }
171
172         return $doc->saveHTML();
173     }
174
175     /**
176      * Within the given HTML content, replace any iframe elements
177      * with anchor links within paragraph blocks.
178      */
179     protected function replaceIframesWithLinks(string $html): string
180     {
181         libxml_use_internal_errors(true);
182
183         $doc = new DOMDocument();
184         $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
185         $xPath = new DOMXPath($doc);
186
187         $iframes = $xPath->query('//iframe');
188         /** @var DOMElement $iframe */
189         foreach ($iframes as $iframe) {
190             $link = $iframe->getAttribute('src');
191             if (strpos($link, '//') === 0) {
192                 $link = 'https:' . $link;
193             }
194
195             $anchor = $doc->createElement('a', $link);
196             $anchor->setAttribute('href', $link);
197             $paragraph = $doc->createElement('p');
198             $paragraph->appendChild($anchor);
199             $iframe->parentNode->replaceChild($paragraph, $iframe);
200         }
201
202         return $doc->saveHTML();
203     }
204
205     /**
206      * Bundle of the contents of a html file to be self-contained.
207      *
208      * @throws Exception
209      */
210     protected function containHtml(string $htmlContent): string
211     {
212         $imageTagsOutput = [];
213         preg_match_all("/\<img.*?src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput);
214
215         // Replace image src with base64 encoded image strings
216         if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) {
217             foreach ($imageTagsOutput[0] as $index => $imgMatch) {
218                 $oldImgTagString = $imgMatch;
219                 $srcString = $imageTagsOutput[2][$index];
220                 $imageEncoded = $this->imageService->imageUriToBase64($srcString);
221                 if ($imageEncoded === null) {
222                     $imageEncoded = $srcString;
223                 }
224                 $newImgTagString = str_replace($srcString, $imageEncoded, $oldImgTagString);
225                 $htmlContent = str_replace($oldImgTagString, $newImgTagString, $htmlContent);
226             }
227         }
228
229         $linksOutput = [];
230         preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $linksOutput);
231
232         // Replace image src with base64 encoded image strings
233         if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) {
234             foreach ($linksOutput[0] as $index => $linkMatch) {
235                 $oldLinkString = $linkMatch;
236                 $srcString = $linksOutput[2][$index];
237                 if (strpos(trim($srcString), 'http') !== 0) {
238                     $newSrcString = url($srcString);
239                     $newLinkString = str_replace($srcString, $newSrcString, $oldLinkString);
240                     $htmlContent = str_replace($oldLinkString, $newLinkString, $htmlContent);
241                 }
242             }
243         }
244
245         // Replace any relative links with system domain
246         return $htmlContent;
247     }
248
249     /**
250      * Converts the page contents into simple plain text.
251      * This method filters any bad looking content to provide a nice final output.
252      */
253     public function pageToPlainText(Page $page): string
254     {
255         $html = (new PageContent($page))->render();
256         $text = strip_tags($html);
257         // Replace multiple spaces with single spaces
258         $text = preg_replace('/\ {2,}/', ' ', $text);
259         // Reduce multiple horrid whitespace characters.
260         $text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text);
261         $text = html_entity_decode($text);
262         // Add title
263         $text = $page->name . "\n\n" . $text;
264
265         return $text;
266     }
267
268     /**
269      * Convert a chapter into a plain text string.
270      */
271     public function chapterToPlainText(Chapter $chapter): string
272     {
273         $text = $chapter->name . "\n\n";
274         $text .= $chapter->description . "\n\n";
275         foreach ($chapter->getVisiblePages() as $page) {
276             $text .= $this->pageToPlainText($page);
277         }
278
279         return $text;
280     }
281
282     /**
283      * Convert a book into a plain text string.
284      */
285     public function bookToPlainText(Book $book): string
286     {
287         $bookTree = (new BookContents($book))->getTree(false, false);
288         $text = $book->name . "\n\n";
289         foreach ($bookTree as $bookChild) {
290             if ($bookChild->isA('chapter')) {
291                 $text .= $this->chapterToPlainText($bookChild);
292             } else {
293                 $text .= $this->pageToPlainText($bookChild);
294             }
295         }
296
297         return $text;
298     }
299
300     /**
301      * Convert a page to a Markdown file.
302      */
303     public function pageToMarkdown(Page $page): string
304     {
305         if ($page->markdown) {
306             return '# ' . $page->name . "\n\n" . $page->markdown;
307         }
308
309         return '# ' . $page->name . "\n\n" . (new HtmlToMarkdown($page->html))->convert();
310     }
311
312     /**
313      * Convert a chapter to a Markdown file.
314      */
315     public function chapterToMarkdown(Chapter $chapter): string
316     {
317         $text = '# ' . $chapter->name . "\n\n";
318         $text .= $chapter->description . "\n\n";
319         foreach ($chapter->pages as $page) {
320             $text .= $this->pageToMarkdown($page) . "\n\n";
321         }
322
323         return $text;
324     }
325
326     /**
327      * Convert a book into a plain text string.
328      */
329     public function bookToMarkdown(Book $book): string
330     {
331         $bookTree = (new BookContents($book))->getTree(false, true);
332         $text = '# ' . $book->name . "\n\n";
333         foreach ($bookTree as $bookChild) {
334             if ($bookChild instanceof Chapter) {
335                 $text .= $this->chapterToMarkdown($bookChild);
336             } else {
337                 $text .= $this->pageToMarkdown($bookChild);
338             }
339         }
340
341         return $text;
342     }
343 }