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.

100 lines
2.1 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. 'code',
  32. 'del',
  33. 'em',
  34. 'i',
  35. 'q',
  36. 'strike',
  37. 'strong',
  38. 'time',
  39. 'blockquote',
  40. 'pre',
  41. 'p',
  42. 'h1',
  43. 'h2',
  44. 'h3',
  45. 'h4',
  46. 'h5',
  47. 'h6',
  48. 'ul',
  49. 'li',
  50. 'ol'
  51. ];
  52. if($allowImg)
  53. $allowed[] = 'img';
  54. $config = HTMLPurifier_Config::createDefault();
  55. $config->set('Cache.DefinitionImpl', null);
  56. $config->set('HTML.AllowedElements', $allowed);
  57. $def = $config->getHTMLDefinition(true);
  58. $def->addElement(
  59. 'time',
  60. 'Inline',
  61. 'Inline',
  62. 'Common',
  63. [
  64. 'datetime' => 'Text'
  65. ]
  66. );
  67. // Override the allowed classes to only support Microformats2 classes
  68. $def->manager->attrTypes->set('Class', new HTMLPurifier_AttrDef_HTML_Microformats2());
  69. $purifier = new HTMLPurifier($config);
  70. $sanitized = $purifier->purify($html);
  71. $sanitized = str_replace("&#xD;","\r",$sanitized);
  72. return trim($sanitized);
  73. }
  74. // Return a plaintext version of the input HTML
  75. protected static function stripHTML($html) {
  76. $config = HTMLPurifier_Config::createDefault();
  77. $config->set('Cache.DefinitionImpl', null);
  78. $config->set('HTML.AllowedElements', ['br']);
  79. $purifier = new HTMLPurifier($config);
  80. $sanitized = $purifier->purify($html);
  81. $sanitized = str_replace("&#xD;","\r",$sanitized);
  82. $sanitized = html_entity_decode($sanitized);
  83. return trim(str_replace('<br>',"\n", $sanitized));
  84. }
  85. }