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.

297 lines
9.4 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. return $this->respond($response, 200, $data);
  105. } else {
  106. return $this->respond($response, 200, [
  107. 'data' => [
  108. 'type' => 'unknown'
  109. ]
  110. ]);
  111. }
  112. }
  113. // Now fetch the URL and check for any curl errors
  114. // Don't cache the response if a token is used to fetch it
  115. if($this->mc && !$request->get('token')) {
  116. $cacheKey = 'xray-'.md5($url);
  117. if($cached=$this->mc->get($cacheKey)) {
  118. $result = json_decode($cached, true);
  119. self::debug('using HTML from cache', 'X-Cache-Debug');
  120. } else {
  121. $result = $this->http->get($url);
  122. $cacheData = json_encode($result);
  123. // App Engine limits the size of cached items, so don't cache ones larger than that
  124. if(strlen($cacheData) < 1000000)
  125. $this->mc->set($cacheKey, $cacheData, MEMCACHE_COMPRESSED, $this->_cacheTime);
  126. }
  127. } else {
  128. $headers = [];
  129. if($request->get('token')) {
  130. $headers[] = 'Authorization: Bearer ' . $request->get('token');
  131. }
  132. $result = $this->http->get($url, $headers);
  133. }
  134. if($result['error']) {
  135. return $this->respond($response, 200, [
  136. 'error' => $result['error'],
  137. 'error_description' => $result['error_description']
  138. ]);
  139. }
  140. if(trim($result['body']) == '') {
  141. return $this->respond($response, 200, [
  142. 'error' => 'no_content',
  143. 'error_description' => 'We did not get a response body when fetching the URL'
  144. ]);
  145. }
  146. // Check for HTTP 401/403
  147. if($result['code'] == 401) {
  148. return $this->respond($response, 200, [
  149. 'error' => 'unauthorized',
  150. 'error_description' => 'The URL returned "HTTP 401 Unauthorized"',
  151. ]);
  152. }
  153. if($result['code'] == 403) {
  154. return $this->respond($response, 200, [
  155. 'error' => 'forbidden',
  156. 'error_description' => 'The URL returned "HTTP 403 Forbidden"',
  157. ]);
  158. }
  159. }
  160. // Check for known services
  161. $host = parse_url($result['url'], PHP_URL_HOST);
  162. if(in_array($host, ['www.instagram.com','instagram.com'])) {
  163. list($data, $parsed) = Formats\Instagram::parse($result['body'], $result['url'], $this->http);
  164. if($request->get('include_original'))
  165. $data['original'] = $parsed;
  166. return $this->respond($response, 200, $data);
  167. }
  168. // attempt to parse the page as HTML
  169. $doc = new DOMDocument();
  170. @$doc->loadHTML(self::toHtmlEntities($result['body']));
  171. if(!$doc) {
  172. return $this->respond($response, 200, [
  173. 'error' => 'invalid_content',
  174. 'error_description' => 'The document could not be parsed as HTML'
  175. ]);
  176. }
  177. $xpath = new DOMXPath($doc);
  178. // If a target parameter was provided, make sure a link to it exists on the page
  179. if($target=$request->get('target')) {
  180. $found = [];
  181. if($target) {
  182. self::xPathFindNodeWithAttribute($xpath, 'a', 'href', function($u) use($target, &$found){
  183. if($u == $target) {
  184. $found[$u] = null;
  185. }
  186. });
  187. self::xPathFindNodeWithAttribute($xpath, 'img', 'src', function($u) use($target, &$found){
  188. if($u == $target) {
  189. $found[$u] = null;
  190. }
  191. });
  192. self::xPathFindNodeWithAttribute($xpath, 'video', 'src', function($u) use($target, &$found){
  193. if($u == $target) {
  194. $found[$u] = null;
  195. }
  196. });
  197. self::xPathFindNodeWithAttribute($xpath, 'audio', 'src', function($u) use($target, &$found){
  198. if($u == $target) {
  199. $found[$u] = null;
  200. }
  201. });
  202. }
  203. if(!$found) {
  204. return $this->respond($response, 200, [
  205. 'error' => 'no_link_found',
  206. 'error_description' => 'The source document does not have a link to the target URL'
  207. ]);
  208. }
  209. }
  210. // If the URL has a fragment ID, find the DOM starting at that node and parse it instead
  211. $html = $result['body'];
  212. $fragment = parse_url($url, PHP_URL_FRAGMENT);
  213. if($fragment) {
  214. $fragElement = self::xPathGetElementById($xpath, $fragment);
  215. if($fragElement) {
  216. $html = $doc->saveHTML($fragElement);
  217. $foundFragment = true;
  218. } else {
  219. $foundFragment = false;
  220. }
  221. }
  222. // Now start pulling in the data from the page. Start by looking for microformats2
  223. $mf2 = mf2\Parse($html, $result['url']);
  224. if($mf2 && count($mf2['items']) > 0) {
  225. $data = Formats\Mf2::parse($mf2, $result['url'], $this->http);
  226. if($data) {
  227. if($fragment) {
  228. $data['info'] = [
  229. 'found_fragment' => $foundFragment
  230. ];
  231. }
  232. if($request->get('include_original'))
  233. $data['original'] = $html;
  234. return $this->respond($response, 200, $data);
  235. }
  236. }
  237. // TODO: look for other content like OEmbed or other known services later
  238. return $this->respond($response, 200, [
  239. 'data' => [
  240. 'type' => 'unknown',
  241. ]
  242. ]);
  243. }
  244. private static function xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  245. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  246. $v = $el->getAttribute($attr);
  247. $callback($v);
  248. }
  249. }
  250. private static function xPathGetElementById($xpath, $id) {
  251. $element = null;
  252. foreach($xpath->query("//*[@id='$id']") as $el) {
  253. $element = $el;
  254. }
  255. return $element;
  256. }
  257. }