]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/ExportFormatter.php
Started work on details/summary blocks
[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         ])->render();
96
97         return $this->htmlToPdf($html);
98     }
99
100     /**
101      * Convert a chapter to a PDF file.
102      *
103      * @throws Throwable
104      */
105     public function chapterToPdf(Chapter $chapter)
106     {
107         $pages = $chapter->getVisiblePages();
108         $pages->each(function ($page) {
109             $page->html = (new PageContent($page))->render();
110         });
111
112         $html = view('chapters.export', [
113             'chapter' => $chapter,
114             'pages'   => $pages,
115             'format'  => 'pdf',
116         ])->render();
117
118         return $this->htmlToPdf($html);
119     }
120
121     /**
122      * Convert a book to a PDF file.
123      *
124      * @throws Throwable
125      */
126     public function bookToPdf(Book $book)
127     {
128         $bookTree = (new BookContents($book))->getTree(false, true);
129         $html = view('books.export', [
130             'book'         => $book,
131             'bookChildren' => $bookTree,
132             'format'       => 'pdf',
133         ])->render();
134
135         return $this->htmlToPdf($html);
136     }
137
138     /**
139      * Convert normal web-page HTML to a PDF.
140      *
141      * @throws Exception
142      */
143     protected function htmlToPdf(string $html): string
144     {
145         $html = $this->containHtml($html);
146         $html = $this->replaceIframesWithLinks($html);
147
148         return $this->pdfGenerator->fromHtml($html);
149     }
150
151     /**
152      * Within the given HTML content, replace any iframe elements
153      * with anchor links within paragraph blocks.
154      */
155     protected function replaceIframesWithLinks(string $html): string
156     {
157         libxml_use_internal_errors(true);
158
159         $doc = new DOMDocument();
160         $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
161         $xPath = new DOMXPath($doc);
162
163         $iframes = $xPath->query('//iframe');
164         /** @var DOMElement $iframe */
165         foreach ($iframes as $iframe) {
166             $link = $iframe->getAttribute('src');
167             if (strpos($link, '//') === 0) {
168                 $link = 'https:' . $link;
169             }
170
171             $anchor = $doc->createElement('a', $link);
172             $anchor->setAttribute('href', $link);
173             $paragraph = $doc->createElement('p');
174             $paragraph->appendChild($anchor);
175             $iframe->parentNode->replaceChild($paragraph, $iframe);
176         }
177
178         return $doc->saveHTML();
179     }
180
181     /**
182      * Bundle of the contents of a html file to be self-contained.
183      *
184      * @throws Exception
185      */
186     protected function containHtml(string $htmlContent): string
187     {
188         $imageTagsOutput = [];
189         preg_match_all("/\<img.*?src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput);
190
191         // Replace image src with base64 encoded image strings
192         if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) {
193             foreach ($imageTagsOutput[0] as $index => $imgMatch) {
194                 $oldImgTagString = $imgMatch;
195                 $srcString = $imageTagsOutput[2][$index];
196                 $imageEncoded = $this->imageService->imageUriToBase64($srcString);
197                 if ($imageEncoded === null) {
198                     $imageEncoded = $srcString;
199                 }
200                 $newImgTagString = str_replace($srcString, $imageEncoded, $oldImgTagString);
201                 $htmlContent = str_replace($oldImgTagString, $newImgTagString, $htmlContent);
202             }
203         }
204
205         $linksOutput = [];
206         preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $linksOutput);
207
208         // Replace image src with base64 encoded image strings
209         if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) {
210             foreach ($linksOutput[0] as $index => $linkMatch) {
211                 $oldLinkString = $linkMatch;
212                 $srcString = $linksOutput[2][$index];
213                 if (strpos(trim($srcString), 'http') !== 0) {
214                     $newSrcString = url($srcString);
215                     $newLinkString = str_replace($srcString, $newSrcString, $oldLinkString);
216                     $htmlContent = str_replace($oldLinkString, $newLinkString, $htmlContent);
217                 }
218             }
219         }
220
221         // Replace any relative links with system domain
222         return $htmlContent;
223     }
224
225     /**
226      * Converts the page contents into simple plain text.
227      * This method filters any bad looking content to provide a nice final output.
228      */
229     public function pageToPlainText(Page $page): string
230     {
231         $html = (new PageContent($page))->render();
232         $text = strip_tags($html);
233         // Replace multiple spaces with single spaces
234         $text = preg_replace('/\ {2,}/', ' ', $text);
235         // Reduce multiple horrid whitespace characters.
236         $text = preg_replace('/(\x0A|\xA0|\x0A|\r|\n){2,}/su', "\n\n", $text);
237         $text = html_entity_decode($text);
238         // Add title
239         $text = $page->name . "\n\n" . $text;
240
241         return $text;
242     }
243
244     /**
245      * Convert a chapter into a plain text string.
246      */
247     public function chapterToPlainText(Chapter $chapter): string
248     {
249         $text = $chapter->name . "\n\n";
250         $text .= $chapter->description . "\n\n";
251         foreach ($chapter->getVisiblePages() as $page) {
252             $text .= $this->pageToPlainText($page);
253         }
254
255         return $text;
256     }
257
258     /**
259      * Convert a book into a plain text string.
260      */
261     public function bookToPlainText(Book $book): string
262     {
263         $bookTree = (new BookContents($book))->getTree(false, false);
264         $text = $book->name . "\n\n";
265         foreach ($bookTree as $bookChild) {
266             if ($bookChild->isA('chapter')) {
267                 $text .= $this->chapterToPlainText($bookChild);
268             } else {
269                 $text .= $this->pageToPlainText($bookChild);
270             }
271         }
272
273         return $text;
274     }
275
276     /**
277      * Convert a page to a Markdown file.
278      */
279     public function pageToMarkdown(Page $page): string
280     {
281         if ($page->markdown) {
282             return '# ' . $page->name . "\n\n" . $page->markdown;
283         }
284
285         return '# ' . $page->name . "\n\n" . (new HtmlToMarkdown($page->html))->convert();
286     }
287
288     /**
289      * Convert a chapter to a Markdown file.
290      */
291     public function chapterToMarkdown(Chapter $chapter): string
292     {
293         $text = '# ' . $chapter->name . "\n\n";
294         $text .= $chapter->description . "\n\n";
295         foreach ($chapter->pages as $page) {
296             $text .= $this->pageToMarkdown($page) . "\n\n";
297         }
298
299         return $text;
300     }
301
302     /**
303      * Convert a book into a plain text string.
304      */
305     public function bookToMarkdown(Book $book): string
306     {
307         $bookTree = (new BookContents($book))->getTree(false, true);
308         $text = '# ' . $book->name . "\n\n";
309         foreach ($bookTree as $bookChild) {
310             if ($bookChild instanceof Chapter) {
311                 $text .= $this->chapterToMarkdown($bookChild);
312             } else {
313                 $text .= $this->pageToMarkdown($bookChild);
314             }
315         }
316
317         return $text;
318     }
319 }