3 namespace BookStack\Util;
10 class HtmlNonceApplicator
13 * Apply the given nonce to all scripts and styles in the given html.
15 public static function apply(string $html, string $nonce): string
21 $html = '<body>' . $html . '</body>';
22 libxml_use_internal_errors(true);
23 $doc = new DOMDocument();
24 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
25 $xPath = new DOMXPath($doc);
28 $scriptElems = $xPath->query('//script');
29 static::addNonceAttributes($scriptElems, $nonce);
32 $styleElems = $xPath->query('//style');
33 static::addNonceAttributes($styleElems, $nonce);
36 $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
37 foreach ($topElems as $child) {
38 $returnHtml .= $doc->saveHTML($child);
44 protected static function addNonceAttributes(DOMNodeList $nodes, string $nonce): void
46 /** @var DOMElement $node */
47 foreach ($nodes as $node) {
48 $node->setAttribute('nonce', $nonce);