You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.3 KiB

  1. <?php
  2. namespace p3k\XRay\Formats;
  3. use DOMDocument, DOMXPath;
  4. use HTMLPurifier, HTMLPurifier_Config;
  5. interface iFormat {
  6. public static function matches_host($url);
  7. public static function matches($url);
  8. }
  9. abstract class Format implements iFormat {
  10. protected static function _unknown() {
  11. return [
  12. 'data' => [
  13. 'type' => 'unknown'
  14. ]
  15. ];
  16. }
  17. protected static function _loadHTML($html) {
  18. $doc = new DOMDocument();
  19. @$doc->loadHTML($html);
  20. if(!$doc) {
  21. return [null, null];
  22. }
  23. $xpath = new DOMXPath($doc);
  24. return [$doc, $xpath];
  25. }
  26. protected static function sanitizeHTML($html, $allowImg=true, $baseURL=false) {
  27. $allowed = [
  28. 'a',
  29. 'abbr',
  30. 'b',
  31. 'br',
  32. 'code',
  33. 'del',
  34. 'em',
  35. 'i',
  36. 'q',
  37. 'strike',
  38. 'strong',
  39. 'time',
  40. 'blockquote',
  41. 'pre',
  42. 'p',
  43. 'h1',
  44. 'h2',
  45. 'h3',
  46. 'h4',
  47. 'h5',
  48. 'h6',
  49. 'ul',
  50. 'li',
  51. 'ol',
  52. 'span',
  53. ];
  54. if($allowImg)
  55. $allowed[] = 'img';
  56. $config = HTMLPurifier_Config::createDefault();
  57. $config->set('Cache.DefinitionImpl', null);
  58. $config->set('HTML.AllowedElements', $allowed);
  59. if($baseURL) {
  60. $config->set('URI.MakeAbsolute', true);
  61. $config->set('URI.Base', $baseURL);
  62. }
  63. $def = $config->getHTMLDefinition(true);
  64. $def->addElement(
  65. 'time',
  66. 'Inline',
  67. 'Inline',
  68. 'Common',
  69. [
  70. 'datetime' => 'Text'
  71. ]
  72. );
  73. // Override the allowed classes to only support Microformats2 classes
  74. $def->manager->attrTypes->set('Class', new HTMLPurifier_AttrDef_HTML_Microformats2());
  75. $purifier = new HTMLPurifier($config);
  76. $sanitized = $purifier->purify($html);
  77. $sanitized = str_replace("&#xD;","\r",$sanitized);
  78. return trim($sanitized);
  79. }
  80. // Return a plaintext version of the input HTML
  81. protected static function stripHTML($html) {
  82. $config = HTMLPurifier_Config::createDefault();
  83. $config->set('Cache.DefinitionImpl', null);
  84. $config->set('HTML.AllowedElements', ['br']);
  85. $purifier = new HTMLPurifier($config);
  86. $sanitized = $purifier->purify($html);
  87. $sanitized = str_replace("&#xD;","\r",$sanitized);
  88. $sanitized = html_entity_decode($sanitized);
  89. return trim(str_replace(['<br>','<br />'],"\n", $sanitized));
  90. }
  91. }