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.

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