htmlsanitizer.class.inc.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. /**
  3. * Base class for all possible implementations of HTML Sanitization
  4. */
  5. abstract class HTMLSanitizer
  6. {
  7. public function __construct()
  8. {
  9. // Do nothing..
  10. }
  11. /**
  12. * Sanitizes the given HTML document
  13. * @param string $sHTML
  14. * @return string
  15. */
  16. abstract public function DoSanitize($sHTML);
  17. /**
  18. * Sanitize an HTML string with the configured sanitizer, falling back to HTMLDOMSanitizer in case of Exception or invalid configuration
  19. * @param string $sHTML
  20. * @return string
  21. */
  22. public static function Sanitize($sHTML)
  23. {
  24. $sSanitizerClass = MetaModel::GetConfig()->Get('html_sanitizer');
  25. if(!class_exists($sSanitizerClass))
  26. {
  27. IssueLog::Warning('The configured "html_sanitizer" class "'.$sSanitizerClass.'" is not a valid class. Will use HTMLDOMSanitizer as the default sanitizer.');
  28. $sSanitizerClass = 'HTMLDOMSanitizer';
  29. }
  30. else if(!is_subclass_of($sSanitizerClass, 'HTMLSanitizer'))
  31. {
  32. IssueLog::Warning('The configured "html_sanitizer" class "'.$sSanitizerClass.'" is not a subclass of HTMLSanitizer. Will use HTMLDOMSanitizer as the default sanitizer.');
  33. $sSanitizerClass = 'HTMLDOMSanitizer';
  34. }
  35. try
  36. {
  37. $oSanitizer = new $sSanitizerClass();
  38. $sCleanHTML = $oSanitizer->DoSanitize($sHTML);
  39. }
  40. catch(Exception $e)
  41. {
  42. if($sSanitizerClass != 'HTMLDOMSanitizer')
  43. {
  44. IssueLog::Warning('Failed to sanitize an HTML string with "'.$sSanitizerClass.'". The following exception occured: '.$e->getMessage());
  45. IssueLog::Warning('Will try to sanitize with HTMLDOMSanitizer.');
  46. // try again with the HTMLDOMSanitizer
  47. $oSanitizer = new HTMLDOMSanitizer();
  48. $sCleanHTML = $oSanitizer->DoSanitize($sHTML);
  49. }
  50. else
  51. {
  52. IssueLog::Error('Failed to sanitize an HTML string with "HTMLDOMSanitizer". The following exception occured: '.$e->getMessage());
  53. IssueLog::Error('The HTML will NOT be sanitized.');
  54. $sCleanHTML = $sHTML;
  55. }
  56. }
  57. return $sCleanHTML;
  58. }
  59. }
  60. /**
  61. * Dummy HTMLSanitizer which does nothing at all!
  62. * Can be used if HTML Sanitization is not important
  63. * (for example when importing "safe" data during an on-boarding)
  64. * and performance is at stake
  65. *
  66. */
  67. class HTMLNullSanitizer extends HTMLSanitizer
  68. {
  69. /**
  70. * (non-PHPdoc)
  71. * @see HTMLSanitizer::Sanitize()
  72. */
  73. public function DoSanitize($sHTML)
  74. {
  75. return $sHTML;
  76. }
  77. }
  78. /**
  79. * A standard-compliant HTMLSanitizer based on the HTMLPurifier library by Edward Z. Yang
  80. * Complete but quite slow
  81. * http://htmlpurifier.org
  82. */
  83. /*
  84. class HTMLPurifierSanitizer extends HTMLSanitizer
  85. {
  86. protected static $oPurifier = null;
  87. public function __construct()
  88. {
  89. if (self::$oPurifier == null)
  90. {
  91. $sLibPath = APPROOT.'lib/htmlpurifier/HTMLPurifier.auto.php';
  92. if (!file_exists($sLibPath))
  93. {
  94. throw new Exception("Missing library '$sLibPath', cannot use HTMLPurifierSanitizer.");
  95. }
  96. require_once($sLibPath);
  97. $oPurifierConfig = HTMLPurifier_Config::createDefault();
  98. $oPurifierConfig->set('Core.Encoding', 'UTF-8'); // defaults to 'UTF-8'
  99. $oPurifierConfig->set('HTML.Doctype', 'XHTML 1.0 Strict'); // defaults to 'XHTML 1.0 Transitional'
  100. $oPurifierConfig->set('URI.AllowedSchemes', array (
  101. 'http' => true,
  102. 'https' => true,
  103. 'data' => true, // This one is not present by default
  104. ));
  105. $sPurifierCache = APPROOT.'data/HTMLPurifier';
  106. if (!is_dir($sPurifierCache))
  107. {
  108. mkdir($sPurifierCache);
  109. }
  110. if (!is_dir($sPurifierCache))
  111. {
  112. throw new Exception("Could not create the cache directory '$sPurifierCache'");
  113. }
  114. $oPurifierConfig->set('Cache.SerializerPath', $sPurifierCache); // no trailing slash
  115. self::$oPurifier = new HTMLPurifier($oPurifierConfig);
  116. }
  117. }
  118. public function DoSanitize($sHTML)
  119. {
  120. $sCleanHtml = self::$oPurifier->purify($sHTML);
  121. return $sCleanHtml;
  122. }
  123. }
  124. */
  125. class HTMLDOMSanitizer extends HTMLSanitizer
  126. {
  127. protected $oDoc;
  128. protected static $aTagsWhiteList = array(
  129. 'html' => array(),
  130. 'body' => array(),
  131. 'a' => array('href', 'name', 'style', 'target'),
  132. 'p' => array('style'),
  133. 'br' => array(),
  134. 'span' => array('style'),
  135. 'div' => array('style'),
  136. 'b' => array(),
  137. 'i' => array(),
  138. 'u' => array(),
  139. 'em' => array(),
  140. 'strong' => array(),
  141. 'img' => array('src','style'),
  142. 'ul' => array('style'),
  143. 'ol' => array('style'),
  144. 'li' => array('style'),
  145. 'h1' => array('style'),
  146. 'h2' => array('style'),
  147. 'h3' => array('style'),
  148. 'h4' => array('style'),
  149. 'nav' => array('style'),
  150. 'section' => array('style'),
  151. 'code' => array('style'),
  152. 'table' => array('style', 'width', 'summary', 'align', 'border', 'cellpadding', 'cellspacing'),
  153. 'thead' => array('style'),
  154. 'tbody' => array('style'),
  155. 'tr' => array('style'),
  156. 'td' => array('style', 'colspan'),
  157. 'th' => array('style'),
  158. 'fieldset' => array('style'),
  159. 'legend' => array('style'),
  160. 'font' => array('face', 'color', 'style', 'size'),
  161. 'big' => array(),
  162. 'small' => array(),
  163. 'tt' => array(),
  164. 'code' => array(),
  165. 'kbd' => array(),
  166. 'samp' => array(),
  167. 'var' => array(),
  168. 'del' => array(),
  169. 's' => array(), // strikethrough
  170. 'ins' => array(),
  171. 'cite' => array(),
  172. 'q' => array(),
  173. 'hr' => array('style'),
  174. 'pre' => array(),
  175. 'center' => array(),
  176. 'caption' => array(),
  177. );
  178. protected static $aAttrsWhiteList = array(
  179. 'src' => '/^(http:|https:|data:)/i',
  180. );
  181. protected static $aStylesWhiteList = array(
  182. 'background-color', 'color', 'float', 'font', 'font-style', 'font-size', 'font-family', 'padding', 'margin', 'border', 'cellpadding', 'cellspacing', 'bordercolor', 'border-collapse', 'width', 'height', 'text-align',
  183. );
  184. public function __construct()
  185. {
  186. if (!array_key_exists('href', self::$aAttrsWhiteList))
  187. {
  188. $sPattern = '/'.str_replace('/', '\/', utils::GetConfig()->Get('url_validation_pattern')).'/i';
  189. self::$aAttrsWhiteList['href'] = $sPattern;
  190. }
  191. }
  192. public function DoSanitize($sHTML)
  193. {
  194. $this->oDoc = new DOMDocument();
  195. $this->oDoc->preserveWhitespace = true;
  196. @$this->oDoc->loadHTML('<?xml encoding="UTF-8"?>'.$sHTML); // For loading HTML chunks where the character set is not specified
  197. $this->CleanNode($this->oDoc);
  198. $oXPath = new DOMXPath($this->oDoc);
  199. $sXPath = "//body";
  200. $oNodesList = $oXPath->query($sXPath);
  201. if ($oNodesList->length == 0)
  202. {
  203. // No body, save the whole document
  204. $sCleanHtml = $this->oDoc->saveHTML();
  205. }
  206. else
  207. {
  208. // Export only the content of the body tag
  209. $sCleanHtml = $this->oDoc->saveHTML($oNodesList->item(0));
  210. // remove the body tag itself
  211. $sCleanHtml = str_replace( array('<body>', '</body>'), '', $sCleanHtml);
  212. }
  213. return $sCleanHtml;
  214. }
  215. protected function CleanNode(DOMNode $oElement)
  216. {
  217. $aAttrToRemove = array();
  218. // Gather the attributes to remove
  219. if ($oElement->hasAttributes())
  220. {
  221. foreach($oElement->attributes as $oAttr)
  222. {
  223. $sAttr = strtolower($oAttr->name);
  224. if (!in_array($sAttr, self::$aTagsWhiteList[strtolower($oElement->tagName)]))
  225. {
  226. // Forbidden (or unknown) attribute
  227. $aAttrToRemove[] = $oAttr->name;
  228. }
  229. else if (!$this->IsValidAttributeContent($sAttr, $oAttr->value))
  230. {
  231. // Invalid content
  232. $aAttrToRemove[] = $oAttr->name;
  233. }
  234. else if ($sAttr == 'style')
  235. {
  236. // Special processing for style tags
  237. $sCleanStyle = $this->CleanStyle($oAttr->value);
  238. if ($sCleanStyle == '')
  239. {
  240. // Invalid content
  241. $aAttrToRemove[] = $oAttr->name;
  242. }
  243. else
  244. {
  245. $oElement->setAttribute($oAttr->name, $sCleanStyle);
  246. }
  247. }
  248. }
  249. // Now remove them
  250. foreach($aAttrToRemove as $sName)
  251. {
  252. $oElement->removeAttribute($sName);
  253. }
  254. }
  255. if ($oElement->hasChildNodes())
  256. {
  257. $aChildElementsToRemove = array();
  258. // Gather the child noes to remove
  259. foreach($oElement->childNodes as $oNode)
  260. {
  261. if (($oNode instanceof DOMElement) && (!array_key_exists(strtolower($oNode->tagName), self::$aTagsWhiteList)))
  262. {
  263. $aChildElementsToRemove[] = $oNode;
  264. }
  265. else if ($oNode instanceof DOMComment)
  266. {
  267. $aChildElementsToRemove[] = $oNode;
  268. }
  269. else
  270. {
  271. // Recurse
  272. $this->CleanNode($oNode);
  273. if (($oNode instanceof DOMElement) && (strtolower($oNode->tagName) == 'img'))
  274. {
  275. $this->ProcessImage($oNode);
  276. }
  277. }
  278. }
  279. // Now remove them
  280. foreach($aChildElementsToRemove as $oDomElement)
  281. {
  282. $oElement->removeChild($oDomElement);
  283. }
  284. }
  285. }
  286. /**
  287. * Add an extra attribute data-img-id for images which are based on an actual InlineImage
  288. * so that we can later reconstruct the full "src" URL when needed
  289. * @param DOMNode $oElement
  290. */
  291. protected function ProcessImage(DOMNode $oElement)
  292. {
  293. $sSrc = $oElement->getAttribute('src');
  294. $sDownloadUrl = str_replace(array('.', '?'), array('\.', '\?'), INLINEIMAGE_DOWNLOAD_URL); // Escape . and ?
  295. $sUrlPattern = '|'.$sDownloadUrl.'([0-9]+)&s=([0-9a-f]+)|';
  296. if (preg_match($sUrlPattern, $sSrc, $aMatches))
  297. {
  298. $oElement->setAttribute('data-img-id', $aMatches[1]);
  299. $oElement->setAttribute('data-img-secret', $aMatches[2]);
  300. }
  301. }
  302. protected function CleanStyle($sStyle)
  303. {
  304. $aAllowedStyles = array();
  305. $aItems = explode(';', $sStyle);
  306. {
  307. foreach($aItems as $sItem)
  308. {
  309. $aElements = explode(':', trim($sItem));
  310. if (in_array(trim(strtolower($aElements[0])), static::$aStylesWhiteList))
  311. {
  312. $aAllowedStyles[] = trim($sItem);
  313. }
  314. }
  315. }
  316. return implode(';', $aAllowedStyles);
  317. }
  318. protected function IsValidAttributeContent($sAttributeName, $sValue)
  319. {
  320. if (array_key_exists($sAttributeName, self::$aAttrsWhiteList))
  321. {
  322. return preg_match(self::$aAttrsWhiteList[$sAttributeName], $sValue);
  323. }
  324. return true;
  325. }
  326. }