htmlsanitizer.class.inc.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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'),
  132. 'p' => array('style'),
  133. 'br' => array(),
  134. 'span' => array('style'),
  135. 'div' => array('style'),
  136. 'b' => array(),
  137. 'i' => array(),
  138. 'em' => array(),
  139. 'strong' => array(),
  140. 'img' => array('src','style'),
  141. 'ul' => array('style'),
  142. 'ol' => array('style'),
  143. 'li' => array('style'),
  144. 'h1' => array('style'),
  145. 'h2' => array('style'),
  146. 'h3' => array('style'),
  147. 'h4' => array('style'),
  148. 'nav' => array('style'),
  149. 'section' => array('style'),
  150. 'code' => array('style'),
  151. 'table' => array('style', 'width'),
  152. 'thead' => array('style'),
  153. 'tbody' => array('style'),
  154. 'tr' => array('style'),
  155. 'td' => array('style', 'colspan'),
  156. 'th' => array('style'),
  157. 'fieldset' => array('style'),
  158. 'legend' => array('style'),
  159. 'font' => array('face', 'color', 'style', 'size'),
  160. 'big' => array(),
  161. 'small' => array(),
  162. 'tt' => array(),
  163. 'code' => array(),
  164. 'kbd' => array(),
  165. 'samp' => array(),
  166. 'var' => array(),
  167. 'del' => array(),
  168. 's' => array(), // strikethrough
  169. 'ins' => array(),
  170. 'cite' => array(),
  171. 'q' => array(),
  172. 'hr' => array('style'),
  173. 'pre' => array(),
  174. 'center' => array(),
  175. );
  176. protected static $aAttrsWhiteList = array(
  177. 'href' => '/^(http:|https:)/i',
  178. 'src' => '/^(http:|https:|data:)/i',
  179. );
  180. protected static $aStylesWhiteList = array(
  181. 'background-color', 'color', 'font', 'font-style', 'font-size', 'font-family', 'padding', 'margin', 'border', 'cellpadding', 'cellspacing', 'bordercolor', 'border-collapse', 'width', 'height',
  182. );
  183. public function DoSanitize($sHTML)
  184. {
  185. $this->oDoc = new DOMDocument();
  186. $this->oDoc->preserveWhitespace = true;
  187. @$this->oDoc->loadHTML('<?xml encoding="UTF-8"?>'.$sHTML); // For loading HTML chunks where the character set is not specified
  188. $this->CleanNode($this->oDoc);
  189. $oXPath = new DOMXPath($this->oDoc);
  190. $sXPath = "//body";
  191. $oNodesList = $oXPath->query($sXPath);
  192. if ($oNodesList->length == 0)
  193. {
  194. // No body, save the whole document
  195. $sCleanHtml = $this->oDoc->saveHTML();
  196. }
  197. else
  198. {
  199. // Export only the content of the body tag
  200. $sCleanHtml = $this->oDoc->saveHTML($oNodesList->item(0));
  201. // remove the body tag itself
  202. $sCleanHtml = str_replace( array('<body>', '</body>'), '', $sCleanHtml);
  203. }
  204. return $sCleanHtml;
  205. }
  206. protected function CleanNode(DOMNode $oElement)
  207. {
  208. $aAttrToRemove = array();
  209. // Gather the attributes to remove
  210. if ($oElement->hasAttributes())
  211. {
  212. foreach($oElement->attributes as $oAttr)
  213. {
  214. $sAttr = strtolower($oAttr->name);
  215. if (!in_array($sAttr, self::$aTagsWhiteList[strtolower($oElement->tagName)]))
  216. {
  217. // Forbidden (or unknown) attribute
  218. $aAttrToRemove[] = $oAttr->name;
  219. }
  220. else if (!$this->IsValidAttributeContent($sAttr, $oAttr->value))
  221. {
  222. // Invalid content
  223. $aAttrToRemove[] = $oAttr->name;
  224. }
  225. else if ($sAttr == 'style')
  226. {
  227. // Special processing for style tags
  228. $sCleanStyle = $this->CleanStyle($oAttr->value);
  229. if ($sCleanStyle == '')
  230. {
  231. // Invalid content
  232. $aAttrToRemove[] = $oAttr->name;
  233. }
  234. else
  235. {
  236. $oElement->setAttribute($oAttr->name, $sCleanStyle);
  237. }
  238. }
  239. }
  240. // Now remove them
  241. foreach($aAttrToRemove as $sName)
  242. {
  243. $oElement->removeAttribute($sName);
  244. }
  245. }
  246. if ($oElement->hasChildNodes())
  247. {
  248. $aChildElementsToRemove = array();
  249. // Gather the child noes to remove
  250. foreach($oElement->childNodes as $oNode)
  251. {
  252. if (($oNode instanceof DOMElement) && (!array_key_exists(strtolower($oNode->tagName), self::$aTagsWhiteList)))
  253. {
  254. $aChildElementsToRemove[] = $oNode;
  255. }
  256. else if ($oNode instanceof DOMComment)
  257. {
  258. $aChildElementsToRemove[] = $oNode;
  259. }
  260. else
  261. {
  262. // Recurse
  263. $this->CleanNode($oNode);
  264. if (($oNode instanceof DOMElement) && (strtolower($oNode->tagName) == 'img'))
  265. {
  266. $this->ProcessImage($oNode);
  267. }
  268. }
  269. }
  270. // Now remove them
  271. foreach($aChildElementsToRemove as $oDomElement)
  272. {
  273. $oElement->removeChild($oDomElement);
  274. }
  275. }
  276. }
  277. /**
  278. * Add an extra attribute data-img-id for images which are based on an actual InlineImage
  279. * so that we can later reconstruct the full "src" URL when needed
  280. * @param DOMNode $oElement
  281. */
  282. protected function ProcessImage(DOMNode $oElement)
  283. {
  284. $sSrc = $oElement->getAttribute('src');
  285. $sDownloadUrl = str_replace(array('.', '?'), array('\.', '\?'), INLINEIMAGE_DOWNLOAD_URL); // Escape . and ?
  286. $sUrlPattern = '|'.$sDownloadUrl.'([0-9]+)&s=([0-9a-f]+)|';
  287. if (preg_match($sUrlPattern, $sSrc, $aMatches))
  288. {
  289. $oElement->setAttribute('data-img-id', $aMatches[1]);
  290. $oElement->setAttribute('data-img-secret', $aMatches[2]);
  291. }
  292. }
  293. protected function CleanStyle($sStyle)
  294. {
  295. $aAllowedStyles = array();
  296. $aItems = explode(';', $sStyle);
  297. {
  298. foreach($aItems as $sItem)
  299. {
  300. $aElements = explode(':', trim($sItem));
  301. if (in_array(trim(strtolower($aElements[0])), static::$aStylesWhiteList))
  302. {
  303. $aAllowedStyles[] = trim($sItem);
  304. }
  305. }
  306. }
  307. return implode(';', $aAllowedStyles);
  308. }
  309. protected function IsValidAttributeContent($sAttributeName, $sValue)
  310. {
  311. if (array_key_exists($sAttributeName, self::$aAttrsWhiteList))
  312. {
  313. return preg_match(self::$aAttrsWhiteList[$sAttributeName], $sValue);
  314. }
  315. return true;
  316. }
  317. }