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.

194 lines
6.0 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. $alternates = [
  85. 'mf2' => [],
  86. 'as2' => [],
  87. ];
  88. foreach($mf2['rel-urls'] as $relurl => $reltype) {
  89. if(in_array('alternate', $reltype['rels']) && $reltype['type'] == 'application/mf2+json') {
  90. $alternates['mf2'][] = $relurl;
  91. }
  92. if(in_array('alternate', $reltype['rels']) && $reltype['type'] == 'application/activity+json') {
  93. $alternates['as2'][] = $relurl;
  94. }
  95. }
  96. if(count($alternates['mf2'])) {
  97. // Fetch and parse the MF2 JSON link
  98. $relurl = $alternates['mf2'][0];
  99. $jsonpage = $http->get($relurl, [
  100. 'Accept' => 'application/mf2+json,application/json'
  101. ]);
  102. // Skip and fall back to parsing the HTML if anything about this request fails
  103. if(!$jsonpage['error'] && $jsonpage['body']) {
  104. $jsondata = json_decode($jsonpage['body'],true);
  105. if($jsondata) {
  106. $data = Formats\Mf2::parse($jsondata, $url, $http, $opts);
  107. if($data && is_array($data) && isset($data['data']['type'])) {
  108. $data['url'] = $relurl;
  109. $data['source-format'] = 'mf2+json';
  110. return $data;
  111. }
  112. }
  113. }
  114. }
  115. if(count($alternates['as2'])) {
  116. $relurl = $alternates['as2'][0];
  117. // Fetch and parse the ActivityStreams JSON link
  118. $jsonpage = $http->get($relurl, [
  119. 'Accept' => 'application/activity+json,application/json'
  120. ]);
  121. // Skip and fall back to parsing the HTML if anything about this request fails
  122. if(!$jsonpage['error'] && $jsonpage['body']) {
  123. $jsondata = json_decode($jsonpage['body'],true);
  124. if($jsondata) {
  125. $data = Formats\ActivityStreams::parse($jsondata, $url, $http, $opts);
  126. if($data && is_array($data) && isset($data['data']['type'])) {
  127. $data['url'] = $relurl;
  128. $data['source-format'] = 'activity+json';
  129. return $data;
  130. }
  131. }
  132. }
  133. }
  134. }
  135. // Now start pulling in the data from the page. Start by looking for microformats2
  136. if($mf2 && count($mf2['items']) > 0) {
  137. $data = Formats\Mf2::parse($mf2, $url, $http, $opts);
  138. if($data) {
  139. $result = array_merge($result, $data);
  140. if($fragment) {
  141. $result['info'] = [
  142. 'found_fragment' => $foundFragment
  143. ];
  144. }
  145. $result['original'] = $html;
  146. $result['url'] = $url; // this will be the effective URL after following redirects
  147. $result['source-format'] = 'mf2+html';
  148. }
  149. }
  150. return $result;
  151. }
  152. private static function toHtmlEntities($input) {
  153. return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
  154. }
  155. private static function xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  156. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  157. $v = $el->getAttribute($attr);
  158. $callback($v);
  159. }
  160. }
  161. private static function xPathGetElementById($xpath, $id) {
  162. $element = null;
  163. foreach($xpath->query("//*[@id='$id']") as $el) {
  164. $element = $el;
  165. }
  166. return $element;
  167. }
  168. }