3 namespace BookStack\Util;
11 * Filter to ensure HTML input for description content remains simple and
12 * to a limited allow-list of elements and attributes.
13 * More for consistency and to prevent nuisance rather than for security
14 * (which would be done via a separate content filter and CSP).
16 class HtmlDescriptionFilter
19 * @var array<string, string[]>
21 protected static array $allowedAttrsByElements = [
23 'a' => ['href', 'title', 'target'],
32 public static function filterFromString(string $html): string
34 if (empty(trim($html))) {
38 $doc = new HtmlDocument($html);
40 $topLevel = [...$doc->getBodyChildren()];
41 foreach ($topLevel as $child) {
42 /** @var DOMNode $child */
43 if ($child instanceof DOMElement) {
44 static::filterElement($child);
46 $child->parentNode->removeChild($child);
50 return $doc->getBodyInnerHtml();
53 protected static function filterElement(DOMElement $element): void
55 $elType = strtolower($element->tagName);
56 $allowedAttrs = static::$allowedAttrsByElements[$elType] ?? null;
57 if (is_null($allowedAttrs)) {
62 /** @var DOMNamedNodeMap $attrs */
63 $attrs = $element->attributes;
64 for ($i = $attrs->length - 1; $i >= 0; $i--) {
65 /** @var DOMAttr $attr */
66 $attr = $attrs->item($i);
67 $name = strtolower($attr->name);
68 if (!in_array($name, $allowedAttrs)) {
69 $element->removeAttribute($attr->name);
73 foreach ($element->childNodes as $child) {
74 if ($child instanceof DOMElement) {
75 static::filterElement($child);