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