Refactored the code for ExportService to use DomDocument.

Fixes #883

Also handling more scenarios.
This commit is contained in:
abijeet 2019-01-27 15:53:51 +05:30
parent 8a2c13729e
commit cc275c0b53
6 changed files with 164 additions and 110 deletions

View File

@ -2,15 +2,14 @@
use BookStack\Entities\Repos\EntityRepo; use BookStack\Entities\Repos\EntityRepo;
use BookStack\Uploads\ImageService; use BookStack\Uploads\ImageService;
use BookStack\Exceptions\ExportException;
class ExportService class ExportService
{ {
protected $contentMatching = [
const VIDEO_REGEX = "/\<video.*?\>\<source.*?\ src\=(\")(.*?)(\").*?><\/video>/"; 'video' => ["www.youtube.com", "player.vimeo.com", "www.dailymotion.com"],
const YOUTUBE_REGEX = "/\<iframe.*src\=(\'|\")(\/\/www\.youtube\.com.*?)(\'|\").*?><\/iframe>/"; 'map' => ['maps.google.com']
const VIMEO_REGEX = "/\<iframe.*src\=(\'|\")(\/\/player\.vimeo\.com.*?)(\'|\").*?><\/iframe>/"; ];
const GOOGLE_MAP_REGEX = "/\<iframe.*src\=(\'|\")(\/\/maps\.google\.com.*?)(\'|\").*?><\/iframe>/";
const DAILYMOTION_REGEX = "/\<iframe.*src\=(\'|\")(\/\/www\.dailymotion\.com.*?)(\'|\").*?><\/iframe>/";
protected $entityRepo; protected $entityRepo;
protected $imageService; protected $imageService;
@ -80,16 +79,17 @@ class ExportService
/** /**
* Convert a page to a PDF file. * Convert a page to a PDF file.
* @param Page $page * @param Page $page
* @param bool $isTesting
* @return mixed|string * @return mixed|string
* @throws \Throwable * @throws \Throwable
*/ */
public function pageToPdf(Page $page) public function pageToPdf(Page $page, bool $isTesting = false)
{ {
$this->entityRepo->renderPage($page); $this->entityRepo->renderPage($page);
$html = view('pages/pdf', [ $html = view('pages/pdf', [
'page' => $page 'page' => $page
])->render(); ])->render();
return $this->htmlToPdf($html); return $this->htmlToPdf($html, $isTesting);
} }
/** /**
@ -130,12 +130,16 @@ class ExportService
/** /**
* Convert normal webpage HTML to a PDF. * Convert normal webpage HTML to a PDF.
* @param $html * @param $html
* @param $isTesting
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
protected function htmlToPdf($html) protected function htmlToPdf($html, $isTesting = false)
{ {
$containedHtml = $this->containHtml($html, true); $containedHtml = $this->containHtml($html, true);
if ($isTesting) {
return $containedHtml;
}
$useWKHTML = config('snappy.pdf.binary') !== false; $useWKHTML = config('snappy.pdf.binary') !== false;
if ($useWKHTML) { if ($useWKHTML) {
$pdf = \SnappyPDF::loadHTML($containedHtml); $pdf = \SnappyPDF::loadHTML($containedHtml);
@ -151,56 +155,62 @@ class ExportService
* @param $htmlContent * @param $htmlContent
* @param bool $isPDF * @param bool $isPDF
* @return mixed|string * @return mixed|string
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException * @throws \BookStack\Exceptions\ExportException
*/ */
protected function containHtml($htmlContent, $isPDF = false) protected function containHtml(string $htmlContent, bool $isPDF = false) : string
{ {
$imageTagsOutput = []; $dom = $this->getDOM($htmlContent);
preg_match_all("/\<img.*src\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $imageTagsOutput); if ($dom === false) {
throw new ExportException(trans('errors.dom_parse_error'));
}
// Replace image src with base64 encoded image strings // replace image src with base64 encoded image strings
if (isset($imageTagsOutput[0]) && count($imageTagsOutput[0]) > 0) { $images = $dom->getElementsByTagName('img');
foreach ($imageTagsOutput[0] as $index => $imgMatch) { foreach ($images as $img) {
$oldImgTagString = $imgMatch; $base64String = $this->imageService->imageUriToBase64($img->getAttribute('src'));
$srcString = $imageTagsOutput[2][$index]; if ($base64String !== null) {
$imageEncoded = $this->imageService->imageUriToBase64($srcString); $img->setAttribute('src', $base64String);
if ($imageEncoded === null) { $dom->saveHTML($img);
$imageEncoded = $srcString;
}
$newImgTagString = str_replace($srcString, $imageEncoded, $oldImgTagString);
$htmlContent = str_replace($oldImgTagString, $newImgTagString, $htmlContent);
} }
} }
$linksOutput = []; // replace all relative hrefs.
preg_match_all("/\<a.*href\=(\'|\")(.*?)(\'|\").*?\>/i", $htmlContent, $linksOutput); $links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
// Replace image src with base64 encoded image strings $href = $link->getAttribute('href');
if (isset($linksOutput[0]) && count($linksOutput[0]) > 0) { if (strpos(trim($href), 'http') !== 0) {
foreach ($linksOutput[0] as $index => $linkMatch) { $newHref = url($href);
$oldLinkString = $linkMatch; $link->setAttribute('href', $newHref);
$srcString = $linksOutput[2][$index]; $dom->saveHTML($link);
if (strpos(trim($srcString), 'http') !== 0) {
$newSrcString = url($srcString);
$newLinkString = str_replace($srcString, $newSrcString, $oldLinkString);
$htmlContent = str_replace($oldLinkString, $newLinkString, $htmlContent);
}
} }
} }
// Replace problems caused by TinyMCE removing the protocol for YouTube, Google Maps, DailyMotion and Vimeo // replace all src in video, audio and iframe tags
if ($isPDF) { $xmlDoc = new \DOMXPath($dom);
$callback = [$this, 'replaceContentPDF']; $srcElements = $xmlDoc->query('//video | //audio | //iframe');
$htmlContent = $this->replaceLinkedTags(self::VIDEO_REGEX, $htmlContent, $callback, 'Video'); foreach ($srcElements as $element) {
} else { $element = $this->fixRelativeSrc($element);
$callback = [$this, 'replaceContentHtml']; $dom->saveHTML($element);
}
$htmlContent = $this->replaceLinkedTags(self::YOUTUBE_REGEX, $htmlContent, $callback, 'Video');
$htmlContent = $this->replaceLinkedTags(self::GOOGLE_MAP_REGEX, $htmlContent, $callback, 'Map');
$htmlContent = $this->replaceLinkedTags(self::DAILYMOTION_REGEX, $htmlContent, $callback, 'Video');
$htmlContent = $this->replaceLinkedTags(self::VIMEO_REGEX, $htmlContent, $callback, 'Video');
return $htmlContent; if ($isPDF) {
$src = $element->getAttribute('src');
$label = $this->getContentLabel($src);
$div = $dom->createElement('div');
$textNode = $dom->createTextNode($label);
$anchor = $dom->createElement('a');
$anchor->setAttribute('href', $src);
$anchor->textContent = $src;
$div->appendChild($textNode);
$div->appendChild($anchor);
$element->parentNode->replaceChild($div, $element);
}
}
return $dom->saveHTML();
} }
/** /**
@ -208,21 +218,43 @@ class ExportService
* This method filters any bad looking content to provide a nice final output. * This method filters any bad looking content to provide a nice final output.
* @param Page $page * @param Page $page
* @return mixed * @return mixed
* @throws \BookStack\Exceptions\ExportException
*/ */
public function pageToPlainText(Page $page) public function pageToPlainText(Page $page)
{ {
$html = $this->entityRepo->renderPage($page); $html = $this->entityRepo->renderPage($page);
$dom = $this->getDom($html);
$callback = [$this, 'replaceContentText']; if ($dom === false) {
// Replace video tag in PDF throw new ExportException(trans('errors.dom_parse_error'));
$html = $this->replaceLinkedTags(self::VIDEO_REGEX, $html, $callback, 'Video'); }
// Replace problems caused by TinyMCE removing the protocol for YouTube, Google Maps, DailyMotion and Vimeo
$html = $this->replaceLinkedTags(self::YOUTUBE_REGEX, $html, $callback, 'Video');
$html = $this->replaceLinkedTags(self::GOOGLE_MAP_REGEX, $html, $callback, 'Map');
$html = $this->replaceLinkedTags(self::DAILYMOTION_REGEX, $html, $callback, 'Video');
$html = $this->replaceLinkedTags(self::VIMEO_REGEX, $html, $callback, 'Video');
$text = strip_tags($html); // handle anchor tags.
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
$href = $link->getAttribute('href');
if (strpos(trim($href), 'http') !== 0) {
$newHref = url($href);
$link->setAttribute('href', $newHref);
}
$link->textContent = trim($link->textContent . " ($href)");
$dom->saveHTML();
}
$xmlDoc = new \DOMXPath($dom);
$srcElements = $xmlDoc->query('//video | //audio | //iframe | //img');
foreach ($srcElements as $element) {
$element = $this->fixRelativeSrc($element);
$fixedSrc = $element->getAttribute('src');
$label = $this->getContentLabel($fixedSrc);
$finalLabel = "\n\n$label $fixedSrc\n\n";
$textNode = $dom->createTextNode($finalLabel);
$element->parentNode->replaceChild($textNode, $element);
}
$text = strip_tags($dom->saveHTML());
// Replace multiple spaces with single spaces // Replace multiple spaces with single spaces
$text = preg_replace('/\ {2,}/', ' ', $text); $text = preg_replace('/\ {2,}/', ' ', $text);
// Reduce multiple horrid whitespace characters. // Reduce multiple horrid whitespace characters.
@ -267,56 +299,36 @@ class ExportService
return $text; return $text;
} }
/** protected function getDom(string $htmlContent) : \DOMDocument
* Can be used to replace certain tags that cause problems such as the TinyMCE video tag {
* modification that have to be undone. // See - https://stackoverflow.com/a/17559716/903324
* See - https://github.com/tinymce/tinymce/blob/0f7a0f12667bde6eae9377b50b797f4479aa1ac7/src/plugins/media/main/ts/core/UrlPatterns.ts#L22 $dom = new \DOMDocument();
* @param String $regex libxml_use_internal_errors(true);
* @param String $htmlContent $dom->loadHTML($htmlContent);
* @param array $callback libxml_clear_errors();
* @param String $contentLabel return $dom;
* @return String $htmlContent - Modified html content }
*/
protected function replaceLinkedTags($regex, $htmlContent, $callback, $contentLabel = '') { protected function fixRelativeSrc(\DOMElement $element): \DOMElement
$iframeOutput = []; {
preg_match_all($regex, $htmlContent, $iframeOutput); $src = $element->getAttribute('src');
if (isset($iframeOutput[0]) && count($iframeOutput[0]) > 0) { if (strpos(trim($src), 'http') !== 0) {
foreach ($iframeOutput[0] as $index => $iframeMatch) { $newSrc = 'https:' . $src;
$htmlContent = call_user_func($callback, $htmlContent, $iframeOutput, $index, $contentLabel); $element->setAttribute('src', $newSrc);
}
return $element;
}
protected function getContentLabel(string $src) : string
{
foreach ($this->contentMatching as $key => $possibleValues) {
foreach ($possibleValues as $value) {
if (strpos($src, $value)) {
return trans("entities.$key");
}
} }
} }
return $htmlContent; return trans('entities.embedded_content');
}
protected function replaceContentHtml($htmlContent, $iframeOutput, $index, $contentLabel) {
$srcString = $iframeOutput[2][$index];
$newSrcString = $srcString;
if (strpos($srcString, 'http') !== 0) {
$newSrcString = 'https:' . $srcString;
}
$htmlContent = str_replace($srcString, $newSrcString, $htmlContent);
return $htmlContent;
}
protected function replaceContentPDF($htmlContent, $iframeOutput, $index, $contentLabel) {
$srcString = $iframeOutput[2][$index];
$newSrcString = $srcString;
if (strpos($srcString, 'http') !== 0) {
$newSrcString = 'https:' . $srcString;
}
$finalHtmlString = "$contentLabel: <a href='$newSrcString'>$newSrcString</a>";
$htmlContent = str_replace($iframeOutput[0][$index], $finalHtmlString, $htmlContent);
return $htmlContent;
}
protected function replaceContentText($htmlContent, $iframeOutput, $index, $contentLabel) {
$srcString = $iframeOutput[2][$index];
$newSrcString = $srcString;
if (strpos($srcString, 'http') !== 0) {
$newSrcString = 'https:' . $srcString;
}
$finalHtmlString = "$contentLabel: $newSrcString";
$htmlContent = str_replace($iframeOutput[0][$index], $finalHtmlString, $htmlContent);
return $htmlContent;
} }
} }

View File

@ -0,0 +1,6 @@
<?php namespace BookStack\Exceptions;
class ExportException extends PrettyException
{
}

View File

@ -495,13 +495,15 @@ class PageController extends Controller
* https://github.com/barryvdh/laravel-dompdf * https://github.com/barryvdh/laravel-dompdf
* @param string $bookSlug * @param string $bookSlug
* @param string $pageSlug * @param string $pageSlug
* @param Request $request
* @return \Illuminate\Http\Response * @return \Illuminate\Http\Response
*/ */
public function exportPdf($bookSlug, $pageSlug) public function exportPdf($bookSlug, $pageSlug, Request $request)
{ {
$isTesting = $request->query('isTesting');
$page = $this->pageRepo->getPageBySlug($pageSlug, $bookSlug); $page = $this->pageRepo->getPageBySlug($pageSlug, $bookSlug);
$page->html = $this->pageRepo->renderPage($page); $page->html = $this->pageRepo->renderPage($page);
$pdfContent = $this->exportService->pageToPdf($page); $pdfContent = $this->exportService->pageToPdf($page, !empty($isTesting));
return $this->downloadResponse($pdfContent, $pageSlug . '.pdf'); return $this->downloadResponse($pdfContent, $pageSlug . '.pdf');
} }

View File

@ -289,5 +289,11 @@ return [
// Revision // Revision
'revision_delete_confirm' => 'Are you sure you want to delete this revision?', 'revision_delete_confirm' => 'Are you sure you want to delete this revision?',
'revision_delete_success' => 'Revision deleted', 'revision_delete_success' => 'Revision deleted',
'revision_cannot_delete_latest' => 'Cannot delete the latest revision.' 'revision_cannot_delete_latest' => 'Cannot delete the latest revision.',
// PDF / Text Embeds
'video' => 'Video: ',
'map' => 'Map: ',
'embedded_content' => 'Embedded Content: '
]; ];

View File

@ -81,4 +81,7 @@ return [
'app_down' => ':appName is down right now', 'app_down' => ':appName is down right now',
'back_soon' => 'It will be back up soon.', 'back_soon' => 'It will be back up soon.',
// Export errors
'dom_parse_error' => 'There was an error while exporting the page. This maybe caused due to the HTML structure of the page.'
]; ];

View File

@ -157,4 +157,29 @@ class ExportTest extends TestCase
} }
public function test_pdf_export_no_video_iframe() {
$page = Page::first();
$page->html = '<p id="bkmrk-%C2%A0-0">&nbsp;</p>' .
'<p id="bkmrk-%C2%A0-1"><iframe src="//www.youtube.com/embed/LkFt_fp7FmE" width="560" height="314" allowfullscreen="allowfullscreen"></iframe></p>' .
'<p id="bkmrk-"><video src="//player.vimeo.com/video/276396369?title=0&amp;amp;byline=0" width="425" height="350" allowfullscreen="allowfullscreen"></video></p>' .
'<p id="bkmrk--0"><iframe style="border: 0;" src="//maps.google.com/embed?testquery=true" width="600" height="450" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p>' .
'<p id="bkmrk--1"><iframe src="//www.dailymotion.com/embed/video/x2rqgfm" width="480" height="432" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p>' .
'<p id="bkmrk-%C2%A0-2">&nbsp;</p>';
$page->save();
$this->asEditor();
$resp = $this->get($page->getUrl('/export/pdf?isTesting=true'));
$resp->assertStatus(200);
$checks = [
'</video>',
'</iframe>'
];
foreach ($checks as $check) {
$resp->assertDontSee($check);
}
}
} }