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.

246 lines
7.3 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. // attempt to parse the page as HTML
  124. $doc = new DOMDocument();
  125. @$doc->loadHTML(self::toHtmlEntities($result['body']));
  126. if(!$doc) {
  127. return $this->respond($response, 200, [
  128. 'error' => 'invalid_content',
  129. 'error_description' => 'The document could not be parsed as HTML'
  130. ]);
  131. }
  132. $xpath = new DOMXPath($doc);
  133. // If a target parameter was provided, make sure a link to it exists on the page
  134. if($target=$request->get('target')) {
  135. $found = [];
  136. if($target) {
  137. self::xPathFindNodeWithAttribute($xpath, 'a', 'href', function($u) use($target, &$found){
  138. if($u == $target) {
  139. $found[$u] = null;
  140. }
  141. });
  142. self::xPathFindNodeWithAttribute($xpath, 'img', 'src', function($u) use($target, &$found){
  143. if($u == $target) {
  144. $found[$u] = null;
  145. }
  146. });
  147. self::xPathFindNodeWithAttribute($xpath, 'video', 'src', function($u) use($target, &$found){
  148. if($u == $target) {
  149. $found[$u] = null;
  150. }
  151. });
  152. self::xPathFindNodeWithAttribute($xpath, 'audio', 'src', function($u) use($target, &$found){
  153. if($u == $target) {
  154. $found[$u] = null;
  155. }
  156. });
  157. }
  158. if(!$found) {
  159. return $this->respond($response, 200, [
  160. 'error' => 'no_link_found',
  161. 'error_description' => 'The source document does not have a link to the target URL'
  162. ]);
  163. }
  164. }
  165. // If the URL has a fragment ID, find the DOM starting at that node and parse it instead
  166. $html = $result['body'];
  167. $fragment = parse_url($url, PHP_URL_FRAGMENT);
  168. if($fragment) {
  169. $fragElement = self::xPathGetElementById($xpath, $fragment);
  170. if($fragElement) {
  171. $html = $doc->saveHTML($fragElement);
  172. $foundFragment = true;
  173. } else {
  174. $foundFragment = false;
  175. }
  176. }
  177. // Now start pulling in the data from the page. Start by looking for microformats2
  178. $mf2 = mf2\Parse($html, $result['url']);
  179. if($mf2 && count($mf2['items']) > 0) {
  180. $data = Formats\Mf2::parse($mf2, $result['url'], $this->http);
  181. if($data) {
  182. if($fragment) {
  183. $data['info'] = [
  184. 'found_fragment' => $foundFragment
  185. ];
  186. }
  187. return $this->respond($response, 200, $data);
  188. }
  189. }
  190. // TODO: look for other content like OEmbed or other known services later
  191. return $this->respond($response, 200, [
  192. 'data' => [
  193. 'type' => 'unknown',
  194. ]
  195. ]);
  196. }
  197. private static function xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  198. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  199. $v = $el->getAttribute($attr);
  200. $callback($v);
  201. }
  202. }
  203. private static function xPathGetElementById($xpath, $id) {
  204. $element = null;
  205. foreach($xpath->query("//*[@id='$id']") as $el) {
  206. $element = $el;
  207. }
  208. return $element;
  209. }
  210. }