]> BookStack Code Mirror - bookstack/blobdiff - app/Entities/Tools/ExportFormatter.php
Merge branch 'markdown-export' of https://github.com/nikhiljha/BookStack-1 into nikhi...
[bookstack] / app / Entities / Tools / ExportFormatter.php
index eb8f6862f23fe76b703c8f0a2514b2f5d61acae9..b462abec5671666ebb806d953ab1dd34a7c3b558 100644 (file)
@@ -7,7 +7,9 @@ use BookStack\Uploads\ImageService;
 use DomPDF;
 use Exception;
 use SnappyPDF;
+use League\HTMLToMarkdown\HtmlConverter;
 use Throwable;
+use ZipArchive;
 
 class ExportFormatter
 {
@@ -226,4 +228,72 @@ class ExportFormatter
         }
         return $text;
     }
+
+    /**
+     * Convert a page to a Markdown file.
+     * @throws Throwable
+     */
+    public function pageToMarkdown(Page $page)
+    {
+        if (property_exists($page, 'markdown') && $page->markdown != '') {
+            return "# " . $page->name . "\n\n" . $page->markdown;
+        } else {
+            $converter = new HtmlConverter();
+            return "# " . $page->name . "\n\n" . $converter->convert($page->html);
+        }
+    }
+
+    /**
+     * Convert a chapter to a Markdown file.
+     * @throws Throwable
+     */
+    public function chapterToMarkdown(Chapter $chapter)
+    {
+        $text = "# " . $chapter->name . "\n\n";
+        $text .= $chapter->description . "\n\n";
+        foreach ($chapter->pages as $page) {
+            $text .= $this->pageToMarkdown($page);
+        }
+        return $text;
+    }
+
+    /**
+     * Convert a book into a plain text string.
+     */
+    public function bookToMarkdown(Book $book): string
+    {
+        $bookTree = (new BookContents($book))->getTree(false, true);
+        $text = "# " . $book->name . "\n\n";
+        foreach ($bookTree as $bookChild) {
+            if ($bookChild->isA('chapter')) {
+                $text .= $this->chapterToMarkdown($bookChild);
+            } else {
+                $text .= $this->pageToMarkdown($bookChild);
+            }
+        }
+        return $text;
+    }
+
+    /**
+     * Convert a book into a zip file.
+     */
+    public function bookToZip(Book $book): string
+    {
+        // TODO: Is not unlinking the file a security risk?
+        $z = new ZipArchive();
+        $z->open("book.zip", \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
+        $bookTree = (new BookContents($book))->getTree(false, true);
+        foreach ($bookTree as $bookChild) {
+            if ($bookChild->isA('chapter')) {
+                $z->addEmptyDir($bookChild->name);
+                foreach ($bookChild->pages as $page) {
+                    $filename = $bookChild->name . "/" . $page->name . ".md";
+                    $z->addFromString($filename, $this->pageToMarkdown($page));
+                }
+            } else {
+                $z->addFromString($bookChild->name . ".md", $this->pageToMarkdown($bookChild));
+            }
+        }
+        return "book.zip";
+    }
 }