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.

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