]> BookStack Code Mirror - bookstack/blob - app/Services/ExportService.php
05ba85dd1143f7a9c2aafdfcba28c1ff6feb0af2
[bookstack] / app / Services / ExportService.php
1 <?php namespace BookStack\Services;
2
3
4 use BookStack\Page;
5
6 class ExportService
7 {
8
9
10     /**
11      * Convert a page to a self-contained HTML file.
12      * Includes required CSS & image content. Images are base64 encoded into the HTML.
13      * @param Page $page
14      * @return mixed|string
15      */
16     public function pageToContainedHtml(Page $page)
17     {
18         $cssContent = file_get_contents(public_path('/css/export-styles.css'));
19         $pageHtml = view('pages/pdf', ['page' => $page, 'css' => $cssContent])->render();
20
21         $imageTagsOutput = [];
22         preg_match_all("/\<img.*src\=(\'|\")(.*?)(\'|\").*?\>/i", $pageHtml, $imageTagsOutput);
23
24         // Replace image src with base64 encoded image strings
25         if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) {
26             foreach ($imageTagsOutput[0] as $index => $imgMatch) {
27                 $oldImgString = $imgMatch;
28                 $srcString = $imageTagsOutput[2][$index];
29                 if (strpos(trim($srcString), 'http') !== 0) {
30                     $pathString = public_path($srcString);
31                 } else {
32                     $pathString = $srcString;
33                 }
34                 $imageContent = file_get_contents($pathString);
35                 $imageEncoded = 'data:image/' . pathinfo($pathString, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageContent);
36                 $newImageString = str_replace($srcString, $imageEncoded, $oldImgString);
37                 $pageHtml = str_replace($oldImgString, $newImageString, $pageHtml);
38             }
39         }
40
41         $linksOutput = [];
42         preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $pageHtml, $linksOutput);
43
44         // Replace image src with base64 encoded image strings
45         if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) {
46             foreach ($linksOutput[0] as $index => $linkMatch) {
47                 $oldLinkString = $linkMatch;
48                 $srcString = $linksOutput[2][$index];
49                 if (strpos(trim($srcString), 'http') !== 0) {
50                     $newSrcString = url($srcString);
51                     $newLinkString = str_replace($srcString, $newSrcString, $oldLinkString);
52                     $pageHtml = str_replace($oldLinkString, $newLinkString, $pageHtml);
53                 }
54             }
55         }
56
57         // Replace any relative links with system domain
58         return $pageHtml;
59     }
60
61 }