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.

316 lines
9.5 KiB

  1. <?php
  2. use Symfony\Component\HttpFoundation\Request;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use p3k\XRay\Formats;
  5. class Parse {
  6. public $http;
  7. public $mc;
  8. private $_cacheTime = 120;
  9. private $_pretty = false;
  10. public static function useragent() {
  11. return 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36 XRay/1.0.0 ('.\Config::$base.')';
  12. }
  13. public function __construct() {
  14. $this->http = new p3k\HTTP(self::useragent());
  15. if(Config::$cache && class_exists('Memcache')) {
  16. $this->mc = new Memcache();
  17. $this->mc->addServer('127.0.0.1');
  18. }
  19. }
  20. public static function debug($msg, $header='X-Parse-Debug') {
  21. syslog(LOG_INFO, $msg);
  22. if(array_key_exists('REMOTE_ADDR', $_SERVER))
  23. header($header . ": " . $msg);
  24. }
  25. private function respond(Response $response, $code, $params, $headers=[]) {
  26. $response->setStatusCode($code);
  27. foreach($headers as $k=>$v) {
  28. $response->headers->set($k, $v);
  29. }
  30. $response->headers->set('Content-Type', 'application/json');
  31. $opts = JSON_UNESCAPED_SLASHES;
  32. if($this->_pretty) $opts += JSON_PRETTY_PRINT;
  33. $response->setContent(json_encode($params, $opts)."\n");
  34. return $response;
  35. }
  36. private static function toHtmlEntities($input) {
  37. return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
  38. }
  39. public function parse(Request $request, Response $response) {
  40. $opts = [];
  41. if($request->get('timeout')) {
  42. // We might make 2 HTTP requests, so each request gets half the desired timeout
  43. $opts['timeout'] = $request->get('timeout') / 2;
  44. }
  45. if($request->get('max_redirects') !== null) {
  46. $opts['max_redirects'] = (int)$request->get('max_redirects');
  47. }
  48. if($request->get('pretty')) {
  49. $this->_pretty = true;
  50. }
  51. $url = $request->get('url');
  52. $html = $request->get('html');
  53. if(!$url && !$html) {
  54. return $this->respond($response, 400, [
  55. 'error' => 'missing_url',
  56. 'error_description' => 'Provide a URL or HTML to fetch'
  57. ]);
  58. }
  59. if($html) {
  60. // If HTML is provided in the request, parse that, and use the URL provided as the base URL for mf2 resolving
  61. $result['body'] = $html;
  62. $result['url'] = $url;
  63. $result['code'] = null;
  64. } else {
  65. $fetcher = new p3k\XRay\Fetcher($this->http);
  66. $fields = [
  67. 'twitter_api_key','twitter_api_secret','twitter_access_token','twitter_access_token_secret',
  68. 'github_access_token',
  69. 'token'
  70. ];
  71. foreach($fields as $f) {
  72. if($v=$request->get($f))
  73. $opts[$f] = $v;
  74. }
  75. $result = $fetcher->fetch($url, $opts);
  76. if(!empty($result['error'])) {
  77. $error_code = isset($result['error_code']) ? $result['error_code'] : 200;
  78. unset($result['error_code']);
  79. return $this->respond($response, $error_code, $result);
  80. }
  81. }
  82. $parser = new p3k\XRay\Parser($this->http);
  83. $parsed = $parser->parse($result['body'], $result['url'], $opts);
  84. // Allow the parser to override the HTTP response code, e.g. a meta-equiv tag
  85. if(isset($parsed['code']))
  86. $result['code'] = $parsed['code'];
  87. $data = [
  88. 'data' => $parsed['data'],
  89. 'url' => $result['url'],
  90. 'code' => $result['code']
  91. ];
  92. if($request->get('include_original') && isset($parsed['original']))
  93. $data['original'] = $parsed['original'];
  94. return $this->respond($response, 200, $data);
  95. // attempt to parse the page as HTML
  96. $doc = new DOMDocument();
  97. @$doc->loadHTML(self::toHtmlEntities($result['body']));
  98. if(!$doc) {
  99. return $this->respond($response, 200, [
  100. 'error' => 'invalid_content',
  101. 'error_description' => 'The document could not be parsed as HTML'
  102. ]);
  103. }
  104. $xpath = new DOMXPath($doc);
  105. // Check for meta http equiv and replace the status code if present
  106. foreach($xpath->query('//meta[translate(@http-equiv,\'STATUS\',\'status\')=\'status\']') as $el) {
  107. $equivStatus = ''.$el->getAttribute('content');
  108. if($equivStatus && is_string($equivStatus)) {
  109. if(preg_match('/^(\d+)/', $equivStatus, $match)) {
  110. $result['code'] = (int)$match[1];
  111. }
  112. }
  113. }
  114. // If a target parameter was provided, make sure a link to it exists on the page
  115. if($target=$request->get('target')) {
  116. $found = [];
  117. if($target) {
  118. self::xPathFindNodeWithAttribute($xpath, 'a', 'href', function($u) use($target, &$found){
  119. if($u == $target) {
  120. $found[$u] = null;
  121. }
  122. });
  123. self::xPathFindNodeWithAttribute($xpath, 'img', 'src', function($u) use($target, &$found){
  124. if($u == $target) {
  125. $found[$u] = null;
  126. }
  127. });
  128. self::xPathFindNodeWithAttribute($xpath, 'video', 'src', function($u) use($target, &$found){
  129. if($u == $target) {
  130. $found[$u] = null;
  131. }
  132. });
  133. self::xPathFindNodeWithAttribute($xpath, 'audio', 'src', function($u) use($target, &$found){
  134. if($u == $target) {
  135. $found[$u] = null;
  136. }
  137. });
  138. }
  139. if(!$found) {
  140. return $this->respond($response, 200, [
  141. 'error' => 'no_link_found',
  142. 'error_description' => 'The source document does not have a link to the target URL',
  143. 'url' => $result['url'],
  144. 'code' => $result['code'],
  145. ]);
  146. }
  147. }
  148. // If the URL has a fragment ID, find the DOM starting at that node and parse it instead
  149. $html = $result['body'];
  150. $fragment = parse_url($url, PHP_URL_FRAGMENT);
  151. if($fragment) {
  152. $fragElement = self::xPathGetElementById($xpath, $fragment);
  153. if($fragElement) {
  154. $html = $doc->saveHTML($fragElement);
  155. $foundFragment = true;
  156. } else {
  157. $foundFragment = false;
  158. }
  159. }
  160. // Now start pulling in the data from the page. Start by looking for microformats2
  161. $mf2 = mf2\Parse($html, $result['url']);
  162. if($mf2 && count($mf2['items']) > 0) {
  163. $data = Formats\Mf2::parse($mf2, $result['url'], $this->http);
  164. if($data) {
  165. if($fragment) {
  166. $data['info'] = [
  167. 'found_fragment' => $foundFragment
  168. ];
  169. }
  170. if($request->get('include_original'))
  171. $data['original'] = $html;
  172. $data['url'] = $result['url']; // this will be the effective URL after following redirects
  173. $data['code'] = $result['code'];
  174. return $this->respond($response, 200, $data);
  175. }
  176. }
  177. // TODO: look for other content like OEmbed or other known services later
  178. return $this->respond($response, 200, [
  179. 'data' => [
  180. 'type' => 'unknown',
  181. ],
  182. 'url' => $result['url'],
  183. 'code' => $result['code']
  184. ]);
  185. }
  186. private static function xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  187. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  188. $v = $el->getAttribute($attr);
  189. $callback($v);
  190. }
  191. }
  192. private static function xPathGetElementById($xpath, $id) {
  193. $element = null;
  194. foreach($xpath->query("//*[@id='$id']") as $el) {
  195. $element = $el;
  196. }
  197. return $element;
  198. }
  199. private function parseTwitterURL(&$request, &$response, $url, $match) {
  200. $fields = ['twitter_api_key','twitter_api_secret','twitter_access_token','twitter_access_token_secret'];
  201. $creds = [];
  202. foreach($fields as $f) {
  203. if($v=$request->get($f))
  204. $creds[$f] = $v;
  205. }
  206. $data = false;
  207. if(count($creds) == 4) {
  208. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], $creds);
  209. } elseif(count($creds) > 0) {
  210. // If only some Twitter credentials were present, return an error
  211. return $this->respond($response, 400, [
  212. 'error' => 'missing_parameters',
  213. 'error_description' => 'All 4 Twitter credentials must be included in the request'
  214. ]);
  215. } else {
  216. // Accept Tweet JSON and parse that if provided
  217. $json = $request->get('json');
  218. if($json) {
  219. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], null, $json);
  220. }
  221. // Skip parsing from the Twitter API if they didn't include credentials
  222. }
  223. if($data) {
  224. if($request->get('include_original'))
  225. $data['original'] = $parsed;
  226. $data['url'] = $url;
  227. $data['code'] = 200;
  228. return $this->respond($response, 200, $data);
  229. } else {
  230. return $this->respond($response, 200, [
  231. 'data' => [
  232. 'type' => 'unknown'
  233. ],
  234. 'url' => $url,
  235. 'code' => 0
  236. ]);
  237. }
  238. }
  239. private function parseGitHubURL(&$request, &$response, $url) {
  240. $fields = ['github_access_token'];
  241. $creds = [];
  242. foreach($fields as $f) {
  243. if($v=$request->get($f))
  244. $creds[$f] = $v;
  245. }
  246. $data = false;
  247. $json = $request->get('json');
  248. if($json) {
  249. // Accept GitHub JSON and parse that if provided
  250. list($data, $json, $code) = Formats\GitHub::parse($this->http, $url, null, $json);
  251. } else {
  252. // Otherwise fetch the post unauthenticated or with the provided access token
  253. list($data, $json, $code) = Formats\GitHub::parse($this->http, $url, $creds);
  254. }
  255. if($data) {
  256. if($request->get('include_original'))
  257. $data['original'] = $json;
  258. $data['url'] = $url;
  259. $data['code'] = $code;
  260. return $this->respond($response, 200, $data);
  261. } else {
  262. return $this->respond($response, 200, [
  263. 'data' => [
  264. 'type' => 'unknown'
  265. ],
  266. 'url' => $url,
  267. 'code' => $code
  268. ]);
  269. }
  270. }
  271. }