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.

397 lines
13 KiB

8 years ago
  1. <?php
  2. use Symfony\Component\HttpFoundation\Request;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use 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. if($request->get('timeout')) {
  41. // We might make 2 HTTP requests, so each request gets half the desired timeout
  42. $this->http->set_timeout($request->get('timeout') / 2);
  43. }
  44. if($request->get('max_redirects') !== null) {
  45. $this->http->set_max_redirects((int)$request->get('max_redirects'));
  46. }
  47. if($request->get('pretty')) {
  48. $this->_pretty = true;
  49. }
  50. $url = $request->get('url');
  51. $html = $request->get('html');
  52. if(!$url && !$html) {
  53. return $this->respond($response, 400, [
  54. 'error' => 'missing_url',
  55. 'error_description' => 'Provide a URL or HTML to fetch'
  56. ]);
  57. }
  58. if($html) {
  59. // If HTML is provided in the request, parse that, and use the URL provided as the base URL for mf2 resolving
  60. $result['body'] = $html;
  61. $result['url'] = $url;
  62. } else {
  63. // Attempt some basic URL validation
  64. $scheme = parse_url($url, PHP_URL_SCHEME);
  65. if(!in_array($scheme, ['http','https'])) {
  66. return $this->respond($response, 400, [
  67. 'error' => 'invalid_url',
  68. 'error_description' => 'Only http and https URLs are supported'
  69. ]);
  70. }
  71. $host = parse_url($url, PHP_URL_HOST);
  72. if(!$host) {
  73. return $this->respond($response, 400, [
  74. 'error' => 'invalid_url',
  75. 'error_description' => 'The URL provided was not valid'
  76. ]);
  77. }
  78. $url = \normalize_url($url);
  79. // Check if this is a Twitter URL and if they've provided API credentials, use the API
  80. if(preg_match('/https?:\/\/(?:mobile\.twitter\.com|twitter\.com|twtr\.io)\/(?:[a-z0-9_\/!#]+statuse?s?\/([0-9]+)|([a-zA-Z0-9_]+))/i', $url, $match)) {
  81. return $this->parseTwitterURL($request, $response, $url, $match);
  82. }
  83. if($host == 'github.com') {
  84. return $this->parseGitHubURL($request, $response, $url);
  85. }
  86. if(!should_follow_redirects($url))
  87. $this->http->set_transport(new p3k\HTTP\Stream());
  88. else
  89. $this->http->set_transport(new p3k\HTTP\Curl());
  90. // Now fetch the URL and check for any curl errors
  91. // Don't cache the response if a token is used to fetch it
  92. if($this->mc && !$request->get('token')) {
  93. $cacheKey = 'xray-'.md5($url);
  94. if($cached=$this->mc->get($cacheKey)) {
  95. $result = json_decode($cached, true);
  96. self::debug('using HTML from cache', 'X-Cache-Debug');
  97. } else {
  98. $result = $this->http->get($url);
  99. $cacheData = json_encode($result);
  100. // App Engine limits the size of cached items, so don't cache ones larger than that
  101. if(strlen($cacheData) < 1000000)
  102. $this->mc->set($cacheKey, $cacheData, MEMCACHE_COMPRESSED, $this->_cacheTime);
  103. }
  104. } else {
  105. $headers = [];
  106. if($request->get('token')) {
  107. $headers[] = 'Authorization: Bearer ' . $request->get('token');
  108. }
  109. $result = $this->http->get($url, $headers);
  110. }
  111. if($result['error']) {
  112. return $this->respond($response, 200, [
  113. 'error' => $result['error'],
  114. 'error_description' => $result['error_description'],
  115. 'url' => $result['url'],
  116. 'code' => $result['code']
  117. ]);
  118. }
  119. if(trim($result['body']) == '') {
  120. if($result['code'] == 410) {
  121. // 410 Gone responses are valid and should not return an error
  122. return $this->respond($response, 200, [
  123. 'data' => [
  124. 'type' => 'unknown'
  125. ],
  126. 'url' => $result['url'],
  127. 'code' => $result['code']
  128. ]);
  129. }
  130. return $this->respond($response, 200, [
  131. 'error' => 'no_content',
  132. 'error_description' => 'We did not get a response body when fetching the URL',
  133. 'url' => $result['url'],
  134. 'code' => $result['code']
  135. ]);
  136. }
  137. // Check for HTTP 401/403
  138. if($result['code'] == 401) {
  139. return $this->respond($response, 200, [
  140. 'error' => 'unauthorized',
  141. 'error_description' => 'The URL returned "HTTP 401 Unauthorized"',
  142. 'url' => $result['url'],
  143. 'code' => 401
  144. ]);
  145. }
  146. if($result['code'] == 403) {
  147. return $this->respond($response, 200, [
  148. 'error' => 'forbidden',
  149. 'error_description' => 'The URL returned "HTTP 403 Forbidden"',
  150. 'url' => $result['url'],
  151. 'code' => 403
  152. ]);
  153. }
  154. }
  155. // Check for known services
  156. $host = parse_url($result['url'], PHP_URL_HOST);
  157. if(in_array($host, ['www.instagram.com','instagram.com'])) {
  158. list($data, $parsed) = Formats\Instagram::parse($result['body'], $result['url'], $this->http);
  159. if($request->get('include_original'))
  160. $data['original'] = $parsed;
  161. $data['url'] = $result['url'];
  162. $data['code'] = $result['code'];
  163. return $this->respond($response, 200, $data);
  164. }
  165. if($host == 'xkcd.com' && parse_url($url, PHP_URL_PATH) != '/') {
  166. $data = Formats\XKCD::parse($result['body'], $url);
  167. $data['url'] = $result['url'];
  168. $data['code'] = $result['code'];
  169. return $this->respond($response, 200, $data);
  170. }
  171. // attempt to parse the page as HTML
  172. $doc = new DOMDocument();
  173. @$doc->loadHTML(self::toHtmlEntities($result['body']));
  174. if(!$doc) {
  175. return $this->respond($response, 200, [
  176. 'error' => 'invalid_content',
  177. 'error_description' => 'The document could not be parsed as HTML'
  178. ]);
  179. }
  180. $xpath = new DOMXPath($doc);
  181. // Check for meta http equiv and replace the status code if present
  182. foreach($xpath->query('//meta[translate(@http-equiv,\'STATUS\',\'status\')=\'status\']') as $el) {
  183. $equivStatus = ''.$el->getAttribute('content');
  184. if($equivStatus && is_string($equivStatus)) {
  185. if(preg_match('/^(\d+)/', $equivStatus, $match)) {
  186. $result['code'] = (int)$match[1];
  187. }
  188. }
  189. }
  190. // If a target parameter was provided, make sure a link to it exists on the page
  191. if($target=$request->get('target')) {
  192. $found = [];
  193. if($target) {
  194. self::xPathFindNodeWithAttribute($xpath, 'a', 'href', function($u) use($target, &$found){
  195. if($u == $target) {
  196. $found[$u] = null;
  197. }
  198. });
  199. self::xPathFindNodeWithAttribute($xpath, 'img', 'src', function($u) use($target, &$found){
  200. if($u == $target) {
  201. $found[$u] = null;
  202. }
  203. });
  204. self::xPathFindNodeWithAttribute($xpath, 'video', 'src', function($u) use($target, &$found){
  205. if($u == $target) {
  206. $found[$u] = null;
  207. }
  208. });
  209. self::xPathFindNodeWithAttribute($xpath, 'audio', 'src', function($u) use($target, &$found){
  210. if($u == $target) {
  211. $found[$u] = null;
  212. }
  213. });
  214. }
  215. if(!$found) {
  216. return $this->respond($response, 200, [
  217. 'error' => 'no_link_found',
  218. 'error_description' => 'The source document does not have a link to the target URL',
  219. 'url' => $result['url'],
  220. 'code' => $result['code'],
  221. ]);
  222. }
  223. }
  224. // If the URL has a fragment ID, find the DOM starting at that node and parse it instead
  225. $html = $result['body'];
  226. $fragment = parse_url($url, PHP_URL_FRAGMENT);
  227. if($fragment) {
  228. $fragElement = self::xPathGetElementById($xpath, $fragment);
  229. if($fragElement) {
  230. $html = $doc->saveHTML($fragElement);
  231. $foundFragment = true;
  232. } else {
  233. $foundFragment = false;
  234. }
  235. }
  236. // Now start pulling in the data from the page. Start by looking for microformats2
  237. $mf2 = mf2\Parse($html, $result['url']);
  238. if($mf2 && count($mf2['items']) > 0) {
  239. $data = Formats\Mf2::parse($mf2, $result['url'], $this->http);
  240. if($data) {
  241. if($fragment) {
  242. $data['info'] = [
  243. 'found_fragment' => $foundFragment
  244. ];
  245. }
  246. if($request->get('include_original'))
  247. $data['original'] = $html;
  248. $data['url'] = $result['url']; // this will be the effective URL after following redirects
  249. $data['code'] = $result['code'];
  250. return $this->respond($response, 200, $data);
  251. }
  252. }
  253. // TODO: look for other content like OEmbed or other known services later
  254. return $this->respond($response, 200, [
  255. 'data' => [
  256. 'type' => 'unknown',
  257. ],
  258. 'url' => $result['url'],
  259. 'code' => $result['code']
  260. ]);
  261. }
  262. private static function xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  263. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  264. $v = $el->getAttribute($attr);
  265. $callback($v);
  266. }
  267. }
  268. private static function xPathGetElementById($xpath, $id) {
  269. $element = null;
  270. foreach($xpath->query("//*[@id='$id']") as $el) {
  271. $element = $el;
  272. }
  273. return $element;
  274. }
  275. private function parseTwitterURL(&$request, &$response, $url, $match) {
  276. $fields = ['twitter_api_key','twitter_api_secret','twitter_access_token','twitter_access_token_secret'];
  277. $creds = [];
  278. foreach($fields as $f) {
  279. if($v=$request->get($f))
  280. $creds[$f] = $v;
  281. }
  282. $data = false;
  283. if(count($creds) == 4) {
  284. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], $creds);
  285. } elseif(count($creds) > 0) {
  286. // If only some Twitter credentials were present, return an error
  287. return $this->respond($response, 400, [
  288. 'error' => 'missing_parameters',
  289. 'error_description' => 'All 4 Twitter credentials must be included in the request'
  290. ]);
  291. } else {
  292. // Accept Tweet JSON and parse that if provided
  293. $json = $request->get('json');
  294. if($json) {
  295. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], null, $json);
  296. }
  297. // Skip parsing from the Twitter API if they didn't include credentials
  298. }
  299. if($data) {
  300. if($request->get('include_original'))
  301. $data['original'] = $parsed;
  302. $data['url'] = $url;
  303. $data['code'] = 200;
  304. return $this->respond($response, 200, $data);
  305. } else {
  306. return $this->respond($response, 200, [
  307. 'data' => [
  308. 'type' => 'unknown'
  309. ],
  310. 'url' => $url,
  311. 'code' => 0
  312. ]);
  313. }
  314. }
  315. private function parseGitHubURL(&$request, &$response, $url) {
  316. $fields = ['github_access_token'];
  317. $creds = [];
  318. foreach($fields as $f) {
  319. if($v=$request->get($f))
  320. $creds[$f] = $v;
  321. }
  322. $data = false;
  323. $json = $request->get('json');
  324. if($json) {
  325. // Accept GitHub JSON and parse that if provided
  326. list($data, $json, $code) = Formats\GitHub::parse($this->http, $url, null, $json);
  327. } else {
  328. // Otherwise fetch the post unauthenticated or with the provided access token
  329. list($data, $json, $code) = Formats\GitHub::parse($this->http, $url, $creds);
  330. }
  331. if($data) {
  332. if($request->get('include_original'))
  333. $data['original'] = $json;
  334. $data['url'] = $url;
  335. $data['code'] = $code;
  336. return $this->respond($response, 200, $data);
  337. } else {
  338. return $this->respond($response, 200, [
  339. 'data' => [
  340. 'type' => 'unknown'
  341. ],
  342. 'url' => $url,
  343. 'code' => $code
  344. ]);
  345. }
  346. }
  347. }