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.

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