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.

331 lines
10 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 function __construct() {
  11. $this->http = new p3k\HTTP();
  12. if(Config::$cache && class_exists('Memcache')) {
  13. $this->mc = new Memcache();
  14. $this->mc->addServer('127.0.0.1');
  15. }
  16. }
  17. public static function debug($msg, $header='X-Parse-Debug') {
  18. syslog(LOG_INFO, $msg);
  19. if(array_key_exists('REMOTE_ADDR', $_SERVER))
  20. header($header . ": " . $msg);
  21. }
  22. private function respond(Response $response, $code, $params, $headers=[]) {
  23. $response->setStatusCode($code);
  24. foreach($headers as $k=>$v) {
  25. $response->headers->set($k, $v);
  26. }
  27. $response->headers->set('Content-Type', 'application/json');
  28. $opts = JSON_UNESCAPED_SLASHES;
  29. if($this->_pretty) $opts += JSON_PRETTY_PRINT;
  30. $response->setContent(json_encode($params, $opts)."\n");
  31. return $response;
  32. }
  33. private static function toHtmlEntities($input) {
  34. return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
  35. }
  36. public function parse(Request $request, Response $response) {
  37. if($request->get('timeout')) {
  38. // We might make 2 HTTP requests, so each request gets half the desired timeout
  39. $this->http->timeout = $request->get('timeout') / 2;
  40. }
  41. if($request->get('max_redirects')) {
  42. $this->http->max_redirects = (int)$request->get('max_redirects');
  43. }
  44. if($request->get('pretty')) {
  45. $this->_pretty = true;
  46. }
  47. $url = $request->get('url');
  48. $html = $request->get('html');
  49. if(!$url && !$html) {
  50. return $this->respond($response, 400, [
  51. 'error' => 'missing_url',
  52. 'error_description' => 'Provide a URL or HTML to fetch'
  53. ]);
  54. }
  55. if($html) {
  56. // If HTML is provided in the request, parse that, and use the URL provided as the base URL for mf2 resolving
  57. $result['body'] = $html;
  58. $result['url'] = $url;
  59. } else {
  60. // Attempt some basic URL validation
  61. $scheme = parse_url($url, PHP_URL_SCHEME);
  62. if(!in_array($scheme, ['http','https'])) {
  63. return $this->respond($response, 400, [
  64. 'error' => 'invalid_url',
  65. 'error_description' => 'Only http and https URLs are supported'
  66. ]);
  67. }
  68. $host = parse_url($url, PHP_URL_HOST);
  69. if(!$host) {
  70. return $this->respond($response, 400, [
  71. 'error' => 'invalid_url',
  72. 'error_description' => 'The URL provided was not valid'
  73. ]);
  74. }
  75. $url = \normalize_url($url);
  76. // Check if this is a Twitter URL and if they've provided API credentials, use the API
  77. 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)) {
  78. return $this->parseTwitterURL($request, $response, $url, $match);
  79. }
  80. // Now fetch the URL and check for any curl errors
  81. // Don't cache the response if a token is used to fetch it
  82. if($this->mc && !$request->get('token')) {
  83. $cacheKey = 'xray-'.md5($url);
  84. if($cached=$this->mc->get($cacheKey)) {
  85. $result = json_decode($cached, true);
  86. self::debug('using HTML from cache', 'X-Cache-Debug');
  87. } else {
  88. $result = $this->http->get($url);
  89. $cacheData = json_encode($result);
  90. // App Engine limits the size of cached items, so don't cache ones larger than that
  91. if(strlen($cacheData) < 1000000)
  92. $this->mc->set($cacheKey, $cacheData, MEMCACHE_COMPRESSED, $this->_cacheTime);
  93. }
  94. } else {
  95. $headers = [];
  96. if($request->get('token')) {
  97. $headers[] = 'Authorization: Bearer ' . $request->get('token');
  98. }
  99. $result = $this->http->get($url, $headers);
  100. }
  101. if($result['error']) {
  102. return $this->respond($response, 200, [
  103. 'error' => $result['error'],
  104. 'error_description' => $result['error_description'],
  105. 'url' => $result['url'],
  106. 'code' => $result['code']
  107. ]);
  108. }
  109. if(trim($result['body']) == '') {
  110. if($result['code'] == 410) {
  111. // 410 Gone responses are valid and should not return an error
  112. return $this->respond($response, 200, [
  113. 'data' => [
  114. 'type' => 'unknown'
  115. ],
  116. 'url' => $result['url'],
  117. 'code' => $result['code']
  118. ]);
  119. }
  120. return $this->respond($response, 200, [
  121. 'error' => 'no_content',
  122. 'error_description' => 'We did not get a response body when fetching the URL',
  123. 'url' => $result['url'],
  124. 'code' => $result['code']
  125. ]);
  126. }
  127. // Check for HTTP 401/403
  128. if($result['code'] == 401) {
  129. return $this->respond($response, 200, [
  130. 'error' => 'unauthorized',
  131. 'error_description' => 'The URL returned "HTTP 401 Unauthorized"',
  132. 'url' => $result['url'],
  133. 'code' => 401
  134. ]);
  135. }
  136. if($result['code'] == 403) {
  137. return $this->respond($response, 200, [
  138. 'error' => 'forbidden',
  139. 'error_description' => 'The URL returned "HTTP 403 Forbidden"',
  140. 'url' => $result['url'],
  141. 'code' => 403
  142. ]);
  143. }
  144. }
  145. // Check for known services
  146. $host = parse_url($result['url'], PHP_URL_HOST);
  147. if(in_array($host, ['www.instagram.com','instagram.com'])) {
  148. list($data, $parsed) = Formats\Instagram::parse($result['body'], $result['url'], $this->http);
  149. if($request->get('include_original'))
  150. $data['original'] = $parsed;
  151. $data['url'] = $result['url'];
  152. $data['code'] = $result['code'];
  153. return $this->respond($response, 200, $data);
  154. }
  155. // attempt to parse the page as HTML
  156. $doc = new DOMDocument();
  157. @$doc->loadHTML(self::toHtmlEntities($result['body']));
  158. if(!$doc) {
  159. return $this->respond($response, 200, [
  160. 'error' => 'invalid_content',
  161. 'error_description' => 'The document could not be parsed as HTML'
  162. ]);
  163. }
  164. $xpath = new DOMXPath($doc);
  165. // If a target parameter was provided, make sure a link to it exists on the page
  166. if($target=$request->get('target')) {
  167. $found = [];
  168. if($target) {
  169. self::xPathFindNodeWithAttribute($xpath, 'a', 'href', function($u) use($target, &$found){
  170. if($u == $target) {
  171. $found[$u] = null;
  172. }
  173. });
  174. self::xPathFindNodeWithAttribute($xpath, 'img', 'src', function($u) use($target, &$found){
  175. if($u == $target) {
  176. $found[$u] = null;
  177. }
  178. });
  179. self::xPathFindNodeWithAttribute($xpath, 'video', 'src', function($u) use($target, &$found){
  180. if($u == $target) {
  181. $found[$u] = null;
  182. }
  183. });
  184. self::xPathFindNodeWithAttribute($xpath, 'audio', 'src', function($u) use($target, &$found){
  185. if($u == $target) {
  186. $found[$u] = null;
  187. }
  188. });
  189. }
  190. if(!$found) {
  191. return $this->respond($response, 200, [
  192. 'error' => 'no_link_found',
  193. 'error_description' => 'The source document does not have a link to the target URL'
  194. ]);
  195. }
  196. }
  197. // If the URL has a fragment ID, find the DOM starting at that node and parse it instead
  198. $html = $result['body'];
  199. $fragment = parse_url($url, PHP_URL_FRAGMENT);
  200. if($fragment) {
  201. $fragElement = self::xPathGetElementById($xpath, $fragment);
  202. if($fragElement) {
  203. $html = $doc->saveHTML($fragElement);
  204. $foundFragment = true;
  205. } else {
  206. $foundFragment = false;
  207. }
  208. }
  209. // Now start pulling in the data from the page. Start by looking for microformats2
  210. $mf2 = mf2\Parse($html, $result['url']);
  211. if($mf2 && count($mf2['items']) > 0) {
  212. $data = Formats\Mf2::parse($mf2, $result['url'], $this->http);
  213. if($data) {
  214. if($fragment) {
  215. $data['info'] = [
  216. 'found_fragment' => $foundFragment
  217. ];
  218. }
  219. if($request->get('include_original'))
  220. $data['original'] = $html;
  221. $data['url'] = $result['url']; // this will be the effective URL after following redirects
  222. $data['code'] = $result['code'];
  223. return $this->respond($response, 200, $data);
  224. }
  225. }
  226. // TODO: look for other content like OEmbed or other known services later
  227. return $this->respond($response, 200, [
  228. 'data' => [
  229. 'type' => 'unknown',
  230. ],
  231. 'url' => $result['url'],
  232. 'code' => $result['code']
  233. ]);
  234. }
  235. private static function xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  236. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  237. $v = $el->getAttribute($attr);
  238. $callback($v);
  239. }
  240. }
  241. private static function xPathGetElementById($xpath, $id) {
  242. $element = null;
  243. foreach($xpath->query("//*[@id='$id']") as $el) {
  244. $element = $el;
  245. }
  246. return $element;
  247. }
  248. private function parseTwitterURL(&$request, &$response, $url, $match) {
  249. $fields = ['twitter_api_key','twitter_api_secret','twitter_access_token','twitter_access_token_secret'];
  250. $creds = [];
  251. foreach($fields as $f) {
  252. if($v=$request->get($f))
  253. $creds[$f] = $v;
  254. }
  255. $data = false;
  256. if(count($creds) == 4) {
  257. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], $creds);
  258. } elseif(count($creds) > 0) {
  259. // If only some Twitter credentials were present, return an error
  260. return $this->respond($response, 400, [
  261. 'error' => 'missing_parameters',
  262. 'error_description' => 'All 4 Twitter credentials must be included in the request'
  263. ]);
  264. } else {
  265. // Accept Tweet JSON and parse that if provided
  266. $json = $request->get('json');
  267. if($json) {
  268. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], null, $json);
  269. }
  270. // Skip parsing from the Twitter API if they didn't include credentials
  271. }
  272. if($data) {
  273. if($request->get('include_original'))
  274. $data['original'] = $parsed;
  275. $data['url'] = $url;
  276. $data['code'] = 200;
  277. return $this->respond($response, 200, $data);
  278. } else {
  279. return $this->respond($response, 200, [
  280. 'data' => [
  281. 'type' => 'unknown'
  282. ],
  283. 'url' => $url,
  284. 'code' => 0
  285. ]);
  286. }
  287. }
  288. }