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.

334 lines
10 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. // Check for known services
  96. $host = parse_url($result['url'], PHP_URL_HOST);
  97. if(in_array($host, ['www.instagram.com','instagram.com'])) {
  98. list($data, $parsed) = Formats\Instagram::parse($result['body'], $result['url'], $this->http);
  99. if($request->get('include_original'))
  100. $data['original'] = $parsed;
  101. $data['url'] = $result['url'];
  102. $data['code'] = $result['code'];
  103. return $this->respond($response, 200, $data);
  104. }
  105. if($host == 'xkcd.com' && parse_url($url, PHP_URL_PATH) != '/') {
  106. $data = Formats\XKCD::parse($result['body'], $url);
  107. $data['url'] = $result['url'];
  108. $data['code'] = $result['code'];
  109. return $this->respond($response, 200, $data);
  110. }
  111. // attempt to parse the page as HTML
  112. $doc = new DOMDocument();
  113. @$doc->loadHTML(self::toHtmlEntities($result['body']));
  114. if(!$doc) {
  115. return $this->respond($response, 200, [
  116. 'error' => 'invalid_content',
  117. 'error_description' => 'The document could not be parsed as HTML'
  118. ]);
  119. }
  120. $xpath = new DOMXPath($doc);
  121. // Check for meta http equiv and replace the status code if present
  122. foreach($xpath->query('//meta[translate(@http-equiv,\'STATUS\',\'status\')=\'status\']') as $el) {
  123. $equivStatus = ''.$el->getAttribute('content');
  124. if($equivStatus && is_string($equivStatus)) {
  125. if(preg_match('/^(\d+)/', $equivStatus, $match)) {
  126. $result['code'] = (int)$match[1];
  127. }
  128. }
  129. }
  130. // If a target parameter was provided, make sure a link to it exists on the page
  131. if($target=$request->get('target')) {
  132. $found = [];
  133. if($target) {
  134. self::xPathFindNodeWithAttribute($xpath, 'a', 'href', function($u) use($target, &$found){
  135. if($u == $target) {
  136. $found[$u] = null;
  137. }
  138. });
  139. self::xPathFindNodeWithAttribute($xpath, 'img', 'src', function($u) use($target, &$found){
  140. if($u == $target) {
  141. $found[$u] = null;
  142. }
  143. });
  144. self::xPathFindNodeWithAttribute($xpath, 'video', 'src', function($u) use($target, &$found){
  145. if($u == $target) {
  146. $found[$u] = null;
  147. }
  148. });
  149. self::xPathFindNodeWithAttribute($xpath, 'audio', 'src', function($u) use($target, &$found){
  150. if($u == $target) {
  151. $found[$u] = null;
  152. }
  153. });
  154. }
  155. if(!$found) {
  156. return $this->respond($response, 200, [
  157. 'error' => 'no_link_found',
  158. 'error_description' => 'The source document does not have a link to the target URL',
  159. 'url' => $result['url'],
  160. 'code' => $result['code'],
  161. ]);
  162. }
  163. }
  164. // If the URL has a fragment ID, find the DOM starting at that node and parse it instead
  165. $html = $result['body'];
  166. $fragment = parse_url($url, PHP_URL_FRAGMENT);
  167. if($fragment) {
  168. $fragElement = self::xPathGetElementById($xpath, $fragment);
  169. if($fragElement) {
  170. $html = $doc->saveHTML($fragElement);
  171. $foundFragment = true;
  172. } else {
  173. $foundFragment = false;
  174. }
  175. }
  176. // Now start pulling in the data from the page. Start by looking for microformats2
  177. $mf2 = mf2\Parse($html, $result['url']);
  178. if($mf2 && count($mf2['items']) > 0) {
  179. $data = Formats\Mf2::parse($mf2, $result['url'], $this->http);
  180. if($data) {
  181. if($fragment) {
  182. $data['info'] = [
  183. 'found_fragment' => $foundFragment
  184. ];
  185. }
  186. if($request->get('include_original'))
  187. $data['original'] = $html;
  188. $data['url'] = $result['url']; // this will be the effective URL after following redirects
  189. $data['code'] = $result['code'];
  190. return $this->respond($response, 200, $data);
  191. }
  192. }
  193. // TODO: look for other content like OEmbed or other known services later
  194. return $this->respond($response, 200, [
  195. 'data' => [
  196. 'type' => 'unknown',
  197. ],
  198. 'url' => $result['url'],
  199. 'code' => $result['code']
  200. ]);
  201. }
  202. private static function xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  203. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  204. $v = $el->getAttribute($attr);
  205. $callback($v);
  206. }
  207. }
  208. private static function xPathGetElementById($xpath, $id) {
  209. $element = null;
  210. foreach($xpath->query("//*[@id='$id']") as $el) {
  211. $element = $el;
  212. }
  213. return $element;
  214. }
  215. private function parseTwitterURL(&$request, &$response, $url, $match) {
  216. $fields = ['twitter_api_key','twitter_api_secret','twitter_access_token','twitter_access_token_secret'];
  217. $creds = [];
  218. foreach($fields as $f) {
  219. if($v=$request->get($f))
  220. $creds[$f] = $v;
  221. }
  222. $data = false;
  223. if(count($creds) == 4) {
  224. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], $creds);
  225. } elseif(count($creds) > 0) {
  226. // If only some Twitter credentials were present, return an error
  227. return $this->respond($response, 400, [
  228. 'error' => 'missing_parameters',
  229. 'error_description' => 'All 4 Twitter credentials must be included in the request'
  230. ]);
  231. } else {
  232. // Accept Tweet JSON and parse that if provided
  233. $json = $request->get('json');
  234. if($json) {
  235. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], null, $json);
  236. }
  237. // Skip parsing from the Twitter API if they didn't include credentials
  238. }
  239. if($data) {
  240. if($request->get('include_original'))
  241. $data['original'] = $parsed;
  242. $data['url'] = $url;
  243. $data['code'] = 200;
  244. return $this->respond($response, 200, $data);
  245. } else {
  246. return $this->respond($response, 200, [
  247. 'data' => [
  248. 'type' => 'unknown'
  249. ],
  250. 'url' => $url,
  251. 'code' => 0
  252. ]);
  253. }
  254. }
  255. private function parseGitHubURL(&$request, &$response, $url) {
  256. $fields = ['github_access_token'];
  257. $creds = [];
  258. foreach($fields as $f) {
  259. if($v=$request->get($f))
  260. $creds[$f] = $v;
  261. }
  262. $data = false;
  263. $json = $request->get('json');
  264. if($json) {
  265. // Accept GitHub JSON and parse that if provided
  266. list($data, $json, $code) = Formats\GitHub::parse($this->http, $url, null, $json);
  267. } else {
  268. // Otherwise fetch the post unauthenticated or with the provided access token
  269. list($data, $json, $code) = Formats\GitHub::parse($this->http, $url, $creds);
  270. }
  271. if($data) {
  272. if($request->get('include_original'))
  273. $data['original'] = $json;
  274. $data['url'] = $url;
  275. $data['code'] = $code;
  276. return $this->respond($response, 200, $data);
  277. } else {
  278. return $this->respond($response, 200, [
  279. 'data' => [
  280. 'type' => 'unknown'
  281. ],
  282. 'url' => $url,
  283. 'code' => $code
  284. ]);
  285. }
  286. }
  287. }