Skip to content

Commit

Permalink
fix: cleanup content before sending it to the user
Browse files Browse the repository at this point in the history
  • Loading branch information
thorsten committed Apr 11, 2023
1 parent 6ed70ee commit e7599d4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
2 changes: 2 additions & 0 deletions phpmyfaq/faq.php
Expand Up @@ -105,6 +105,8 @@
$answer = $faqHelper->renderMarkupContent($faq->faqRecord['content']);
}

$answer = $faqHelper->cleanUpContent($answer);

// Rewrite URL fragments
$currentUrl = htmlspecialchars("//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}", ENT_QUOTES, 'UTF-8');
$answer = $faqHelper->rewriteUrlFragments($answer, $currentUrl);
Expand Down
21 changes: 21 additions & 0 deletions phpmyfaq/src/phpMyFAQ/Helper/FaqHelper.php
Expand Up @@ -17,6 +17,7 @@

namespace phpMyFAQ\Helper;

use DOMDocument;
use Exception;
use ParsedownExtra;
use phpMyFAQ\Category;
Expand Down Expand Up @@ -226,4 +227,24 @@ public function createFaqUrl(FaqEntity $faqEntity, int $categoryId): string
$faqEntity->getLanguage()
);
}

/**
* Remove <script> tags, we don't need them
*
* @param string $content
* @return string
*/
public function cleanUpContent(string $content): string
{
$document = new DOMDocument();
$document->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$scriptTags = $document->getElementsByTagName('script');

for ($i = 0; $i < $scriptTags->length; $i++) {
$scriptTags->item($i)->parentNode->removeChild($scriptTags->item($i));
}

return preg_replace(['/\r/', '/\n/'], '', $document->saveHTML());
}
}
10 changes: 10 additions & 0 deletions tests/phpMyFAQ/Helper/FaqHelperTest.php
Expand Up @@ -59,4 +59,14 @@ public function testCreateFaqUrl(): void
$this->faqHelper->createFaqUrl($faqEntity, 1)
);
}

public function testCleanUpContent(): void
{
$content = '<p>Some text <script>alert("Hello, world!");</script></p>';
$expectedOutput = '<p>Some text </p>';

$actualOutput = $this->faqHelper->cleanUpContent($content);

$this->assertEquals($expectedOutput, $actualOutput);
}
}

0 comments on commit e7599d4

Please sign in to comment.