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.

236 lines
7.8 KiB

  1. <?php
  2. namespace p3k\XRay;
  3. use p3k\XRay\Formats;
  4. use DOMDocument, DOMXPath;
  5. class Parser {
  6. private $http;
  7. public function __construct($http) {
  8. $this->http = $http;
  9. }
  10. public function parse($http_response, $opts=[]) {
  11. $allowIframeVideo = isset($opts['allowIframeVideo']) ? $opts['allowIframeVideo'] : false;
  12. allow_iframe_video($allowIframeVideo);
  13. $document = $this->parse_document($http_response, $opts);
  14. // If a target parameter was provided, make sure a link to it exists in the parsed document
  15. if(!isset($document['error']) && !empty($opts['target'])) {
  16. if(isset($document['data']['type']) && $document['data']['type'] == 'unknown') {
  17. if(isset($document['html'])) {
  18. // Couldn't parse the page, check for the link manually assuming HTML content
  19. $found = $this->_findLinkInHTML($opts['target'], $document['html']);
  20. } else {
  21. // Ignore this check for any non-HTML documents since this will be uncommon anyway
  22. $found = false;
  23. }
  24. $error_description = 'The source document does not have a link to the target URL';
  25. } else {
  26. $found = $this->_findLinkInTree($opts['target'], $document['data']);
  27. $error_description = 'The Microformats at the source URL do not contain a link to the target URL. Check the source URL in a Microformats parser such as php.microformats.io';
  28. if(!$found && isset($document['html'])) {
  29. // If no link was found in the parsed mf2 tree, check for a link in the HTML
  30. $found = $this->_findLinkInHTML($opts['target'], $document['html']);
  31. // If there is a link, and if the HTML document has no mf2, then downgrade to a regular mention
  32. if($found) {
  33. $mf2Data = Formats\HTML::parse($this->http, $http_response, ['include-mf1'=>false]);
  34. if(isset($mf2Data['data']['type']) && $mf2Data['data']['type'] == 'unknown') {
  35. // Since the link was found in the HTML, but not in the parsed tree, it shouldn't return the parsed document
  36. $document['data'] = [
  37. 'type' => 'unknown'
  38. ];
  39. } else {
  40. // Otherwise, the document did have mf2, but the link wasn't in it (checked earlier), so set found=false
  41. $found = false;
  42. }
  43. }
  44. }
  45. }
  46. if(!$found) {
  47. return [
  48. 'error' => 'no_link_found',
  49. 'error_description' => $error_description,
  50. 'code' => isset($document['code']) ? $document['code'] : 200,
  51. 'url' => $document['url'],
  52. 'debug' => $document['data']
  53. ];
  54. }
  55. }
  56. // If the HTML parser couldn't parse the page it returns the full HTML for checking the target above,
  57. // but we don't want to return that in the output so remove it here
  58. unset($document['html']);
  59. return $document;
  60. }
  61. public function parse_document($http_response, $opts=[]) {
  62. if(isset($opts['timeout']))
  63. $this->http->set_timeout($opts['timeout']);
  64. if(isset($opts['max_redirects']))
  65. $this->http->set_max_redirects($opts['max_redirects']);
  66. // Check if the URL matches a special parser
  67. $url = $http_response['url'];
  68. if(Formats\GitHub::matches($url)) {
  69. return Formats\GitHub::parse($http_response);
  70. }
  71. if(Formats\Twitter::matches($url)) {
  72. return Formats\Twitter::parse($http_response);
  73. }
  74. if(Formats\XKCD::matches($url)) {
  75. return Formats\XKCD::parse($http_response);
  76. }
  77. if(Formats\Hackernews::matches($url)) {
  78. return Formats\Hackernews::parse($http_response);
  79. }
  80. $body = $http_response['body'];
  81. // Check if an mf2 JSON object was passed in
  82. if(is_array($body) && isset($body['items'])) {
  83. $data = Formats\Mf2::parse($http_response, $this->http, $opts);
  84. if($data == false) {
  85. $data = [
  86. 'data' => [
  87. 'type' => 'unknown',
  88. ]
  89. ];
  90. }
  91. $data['source-format'] = 'mf2+json';
  92. return $data;
  93. }
  94. // Check if an ActivityStreams JSON object was passed in
  95. if(Formats\ActivityStreams::is_as2_json($body)) {
  96. $data = Formats\ActivityStreams::parse($http_response, $this->http, $opts);
  97. $data['source-format'] = 'activity+json';
  98. return $data;
  99. }
  100. if(is_string($body) && substr($body, 0, 5) == '<?xml') {
  101. return Formats\XML::parse($http_response);
  102. }
  103. if(is_string($body)) {
  104. // Some feeds don't start with <?xml
  105. $begin = trim(substr($body, 0, 40));
  106. if(substr($begin, 0, 4) == '<rss') {
  107. return Formats\XML::parse($http_response);
  108. }
  109. }
  110. if(is_string($body) && substr($body, 0, 1) == '{') {
  111. $parsed = json_decode($body, true);
  112. if($parsed && isset($parsed['version']) && in_array($parsed['version'], ['https://jsonfeed.org/version/1','https://jsonfeed.org/version/1.1'])) {
  113. $http_response['body'] = $parsed;
  114. return Formats\JSONFeed::parse($http_response);
  115. } elseif($parsed && isset($parsed['items'][0]['type']) && isset($parsed['items'][0]['properties'])) {
  116. // Check if an mf2 JSON string was passed in
  117. $http_response['body'] = $parsed;
  118. $data = Formats\Mf2::parse($http_response, $this->http, $opts);
  119. $data['source-format'] = 'mf2+json';
  120. return $data;
  121. } elseif($parsed && Formats\ActivityStreams::is_as2_json($parsed)) {
  122. // Check if an ActivityStreams JSON string was passed in
  123. $http_response['body'] = $parsed;
  124. $data = Formats\ActivityStreams::parse($http_response, $this->http, $opts);
  125. $data['source-format'] = 'activity+json';
  126. return $data;
  127. }
  128. }
  129. // No special parsers matched, parse for Microformats now
  130. $data = Formats\HTML::parse($this->http, $http_response, $opts);
  131. if(!isset($data['source-format']) && isset($data['type']) && $data['type'] != 'unknown')
  132. $data['source-format'] = 'mf2+html';
  133. return $data;
  134. }
  135. private function _findLinkInTree($link, $document) {
  136. if(!$document)
  137. return false;
  138. if(is_string($document) || is_numeric($document)) {
  139. return $document == $link;
  140. }
  141. if(is_array($document)) {
  142. foreach($document as $key=>$value) {
  143. if($key === 'html') {
  144. $found = $this->_findLinkInHTML($link, $value);
  145. if($found) {
  146. return true;
  147. }
  148. } else {
  149. $found = $this->_findLinkInTree($link, $value);
  150. if($found) {
  151. return true;
  152. }
  153. }
  154. }
  155. return false;
  156. }
  157. throw new Exception('Unexpected value in tree');
  158. }
  159. private function _findLinkInHTML($link, $html) {
  160. $doc = new DOMDocument();
  161. @$doc->loadHTML(self::_toHtmlEntities($html));
  162. if(!$doc)
  163. return false;
  164. $xpath = new DOMXPath($doc);
  165. return self::_findLinksInDOMDocument($xpath, $link);
  166. }
  167. private static function _findLinksInDOMDocument(&$xpath, $target) {
  168. $found = [];
  169. self::_xPathFindNodeWithAttribute($xpath, 'a', 'href', function($u) use($target, &$found){
  170. if($u == $target) {
  171. $found[$u] = null;
  172. }
  173. });
  174. self::_xPathFindNodeWithAttribute($xpath, 'img', 'src', function($u) use($target, &$found){
  175. if($u == $target) {
  176. $found[$u] = null;
  177. }
  178. });
  179. self::_xPathFindNodeWithAttribute($xpath, 'video', 'src', function($u) use($target, &$found){
  180. if($u == $target) {
  181. $found[$u] = null;
  182. }
  183. });
  184. self::_xPathFindNodeWithAttribute($xpath, 'audio', 'src', function($u) use($target, &$found){
  185. if($u == $target) {
  186. $found[$u] = null;
  187. }
  188. });
  189. return $found;
  190. }
  191. private static function _xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  192. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  193. $v = $el->getAttribute($attr);
  194. $callback($v);
  195. }
  196. }
  197. private static function _toHtmlEntities($input) {
  198. return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
  199. }
  200. }