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.

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