]> BookStack Code Mirror - bookstack/blob - app/Util/HtmlDescriptionFilter.php
Comments: Moved to tab UI, Converted tabs component to ts
[bookstack] / app / Util / HtmlDescriptionFilter.php
1 <?php
2
3 namespace BookStack\Util;
4
5 use DOMAttr;
6 use DOMElement;
7 use DOMNamedNodeMap;
8 use DOMNode;
9
10 /**
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).
15  */
16 class HtmlDescriptionFilter
17 {
18     /**
19      * @var array<string, string[]>
20      */
21     protected static array $allowedAttrsByElements = [
22         'p' => [],
23         'a' => ['href', 'title', 'target'],
24         'ol' => [],
25         'ul' => [],
26         'li' => [],
27         'strong' => [],
28         'em' => [],
29         'br' => [],
30     ];
31
32     public static function filterFromString(string $html): string
33     {
34         if (empty(trim($html))) {
35             return '';
36         }
37
38         $doc = new HtmlDocument($html);
39
40         $topLevel = [...$doc->getBodyChildren()];
41         foreach ($topLevel as $child) {
42             /** @var DOMNode $child */
43             if ($child instanceof DOMElement) {
44                 static::filterElement($child);
45             } else {
46                 $child->parentNode->removeChild($child);
47             }
48         }
49
50         return $doc->getBodyInnerHtml();
51     }
52
53     protected static function filterElement(DOMElement $element): void
54     {
55         $elType = strtolower($element->tagName);
56         $allowedAttrs = static::$allowedAttrsByElements[$elType] ?? null;
57         if (is_null($allowedAttrs)) {
58             $element->remove();
59             return;
60         }
61
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);
70             }
71         }
72
73         foreach ($element->childNodes as $child) {
74             if ($child instanceof DOMElement) {
75                 static::filterElement($child);
76             }
77         }
78     }
79 }