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.

157 lines
4.9 KiB

  1. <?php
  2. namespace p3k\XRay\Formats;
  3. use HTMLPurifier, HTMLPurifier_Config;
  4. use DOMDocument, DOMXPath;
  5. use p3k\XRay\Formats;
  6. class HTML extends Format {
  7. public static function matches_host($url) { return true; }
  8. public static function matches($url) { return true; }
  9. public static function parse($http, $html, $url, $opts=[]) {
  10. $result = [
  11. 'data' => [
  12. 'type' => 'unknown',
  13. ],
  14. 'url' => $url,
  15. ];
  16. // attempt to parse the page as HTML
  17. $doc = new DOMDocument();
  18. @$doc->loadHTML(self::toHtmlEntities($html));
  19. if(!$doc) {
  20. return [
  21. 'error' => 'invalid_content',
  22. 'error_description' => 'The document could not be parsed as HTML'
  23. ];
  24. }
  25. $xpath = new DOMXPath($doc);
  26. // Check for meta http equiv and replace the status code if present
  27. foreach($xpath->query('//meta[translate(@http-equiv,\'STATUS\',\'status\')=\'status\']') as $el) {
  28. $equivStatus = ''.$el->getAttribute('content');
  29. if($equivStatus && is_string($equivStatus)) {
  30. if(preg_match('/^(\d+)/', $equivStatus, $match)) {
  31. $result['code'] = (int)$match[1];
  32. }
  33. }
  34. }
  35. // If a target parameter was provided, make sure a link to it exists on the page
  36. if(isset($opts['target'])) {
  37. $target = $opts['target'];
  38. $found = [];
  39. if($target) {
  40. self::xPathFindNodeWithAttribute($xpath, 'a', 'href', function($u) use($target, &$found){
  41. if($u == $target) {
  42. $found[$u] = null;
  43. }
  44. });
  45. self::xPathFindNodeWithAttribute($xpath, 'img', 'src', function($u) use($target, &$found){
  46. if($u == $target) {
  47. $found[$u] = null;
  48. }
  49. });
  50. self::xPathFindNodeWithAttribute($xpath, 'video', 'src', function($u) use($target, &$found){
  51. if($u == $target) {
  52. $found[$u] = null;
  53. }
  54. });
  55. self::xPathFindNodeWithAttribute($xpath, 'audio', 'src', function($u) use($target, &$found){
  56. if($u == $target) {
  57. $found[$u] = null;
  58. }
  59. });
  60. }
  61. if(!$found) {
  62. return [
  63. 'error' => 'no_link_found',
  64. 'error_description' => 'The source document does not have a link to the target URL',
  65. 'code' => isset($result['code']) ? $result['code'] : 200,
  66. 'url' => $url
  67. ];
  68. }
  69. }
  70. // If the URL has a fragment ID, find the DOM starting at that node and parse it instead
  71. $fragment = parse_url($url, PHP_URL_FRAGMENT);
  72. if($fragment) {
  73. $fragElement = self::xPathGetElementById($xpath, $fragment);
  74. if($fragElement) {
  75. $html = $doc->saveHTML($fragElement);
  76. $foundFragment = true;
  77. } else {
  78. $foundFragment = false;
  79. }
  80. }
  81. $mf2 = \mf2\Parse($html, $url);
  82. // Check for a rel=alternate link to a Microformats JSON representation, and use that instead
  83. if(isset($mf2['rel-urls'])) {
  84. foreach($mf2['rel-urls'] as $relurl => $reltype) {
  85. if(in_array('alternate', $reltype['rels']) && $reltype['type'] == 'application/mf2+json') {
  86. // Fetch and parse the MF2 JSON link instead
  87. $jsonpage = $http->get($relurl, [
  88. 'Accept' => 'application/mf2+json,application/json'
  89. ]);
  90. // Skip and fall back to parsing the HTML if anything about this request fails
  91. if(!$jsonpage['error'] && $jsonpage['body']) {
  92. $jsondata = json_decode($jsonpage['body'],true);
  93. if($jsondata) {
  94. $data = Formats\Mf2::parse($jsondata, $url, $http, $opts);
  95. if($data && is_array($data) && isset($data['data']['type'])) {
  96. $data['url'] = $relurl;
  97. $data['source-format'] = 'mf2+json';
  98. return $data;
  99. }
  100. }
  101. }
  102. }
  103. }
  104. }
  105. // Now start pulling in the data from the page. Start by looking for microformats2
  106. if($mf2 && count($mf2['items']) > 0) {
  107. $data = Formats\Mf2::parse($mf2, $url, $http, $opts);
  108. if($data) {
  109. $result = array_merge($result, $data);
  110. if($fragment) {
  111. $result['info'] = [
  112. 'found_fragment' => $foundFragment
  113. ];
  114. }
  115. $result['original'] = $html;
  116. $result['url'] = $url; // this will be the effective URL after following redirects
  117. $result['source-format'] = 'mf2+html';
  118. }
  119. }
  120. return $result;
  121. }
  122. private static function toHtmlEntities($input) {
  123. return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
  124. }
  125. private static function xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  126. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  127. $v = $el->getAttribute($attr);
  128. $callback($v);
  129. }
  130. }
  131. private static function xPathGetElementById($xpath, $id) {
  132. $element = null;
  133. foreach($xpath->query("//*[@id='$id']") as $el) {
  134. $element = $el;
  135. }
  136. return $element;
  137. }
  138. }