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.

101 lines
2.2 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) {
  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. ];
  53. if($allowImg)
  54. $allowed[] = 'img';
  55. $config = HTMLPurifier_Config::createDefault();
  56. $config->set('Cache.DefinitionImpl', null);
  57. $config->set('HTML.AllowedElements', $allowed);
  58. $def = $config->getHTMLDefinition(true);
  59. $def->addElement(
  60. 'time',
  61. 'Inline',
  62. 'Inline',
  63. 'Common',
  64. [
  65. 'datetime' => 'Text'
  66. ]
  67. );
  68. // Override the allowed classes to only support Microformats2 classes
  69. $def->manager->attrTypes->set('Class', new HTMLPurifier_AttrDef_HTML_Microformats2());
  70. $purifier = new HTMLPurifier($config);
  71. $sanitized = $purifier->purify($html);
  72. $sanitized = str_replace("&#xD;","\r",$sanitized);
  73. return trim($sanitized);
  74. }
  75. // Return a plaintext version of the input HTML
  76. protected static function stripHTML($html) {
  77. $config = HTMLPurifier_Config::createDefault();
  78. $config->set('Cache.DefinitionImpl', null);
  79. $config->set('HTML.AllowedElements', ['br']);
  80. $purifier = new HTMLPurifier($config);
  81. $sanitized = $purifier->purify($html);
  82. $sanitized = str_replace("&#xD;","\r",$sanitized);
  83. $sanitized = html_entity_decode($sanitized);
  84. return trim(str_replace(['<br>','<br />'],"\n", $sanitized));
  85. }
  86. }