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.

171 lines
5.0 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 = 300;
  9. private $_pretty = false;
  10. public function __construct() {
  11. $this->http = new p3k\HTTP();
  12. $this->mc = new Memcache();
  13. $this->mc->addServer('127.0.0.1');
  14. }
  15. public static function debug($msg, $header='X-Parse-Debug') {
  16. syslog(LOG_INFO, $msg);
  17. if(array_key_exists('REMOTE_ADDR', $_SERVER))
  18. header($header . ": " . $msg);
  19. }
  20. private function respond(Response $response, $code, $params, $headers=[]) {
  21. $response->setStatusCode($code);
  22. foreach($headers as $k=>$v) {
  23. $response->headers->set($k, $v);
  24. }
  25. $response->headers->set('Content-Type', 'application/json');
  26. $opts = JSON_UNESCAPED_SLASHES;
  27. if($this->_pretty) $opts += JSON_PRETTY_PRINT;
  28. $response->setContent(json_encode($params, $opts)."\n");
  29. return $response;
  30. }
  31. private static function toHtmlEntities($input) {
  32. return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
  33. }
  34. public function parse(Request $request, Response $response) {
  35. if($request->get('timeout')) {
  36. // We might make 2 HTTP requests, so each request gets half the desired timeout
  37. $this->http->timeout = $request->get('timeout') / 2;
  38. }
  39. if($request->get('max_redirects')) {
  40. $this->http->max_redirects = (int)$request->get('max_redirects');
  41. }
  42. if($request->get('pretty')) {
  43. $this->_pretty = true;
  44. }
  45. $url = $request->get('url');
  46. $html = $request->get('html');
  47. if(!$url && !$html) {
  48. return $this->respond($response, 400, [
  49. 'error' => 'missing_url',
  50. 'error_description' => 'Provide a URL or HTML to fetch'
  51. ]);
  52. }
  53. if($html) {
  54. // If HTML is provided in the request, parse that, and use the URL provided as the base URL for mf2 resolving
  55. $result['body'] = $html;
  56. } else {
  57. // Attempt some basic URL validation
  58. $scheme = parse_url($url, PHP_URL_SCHEME);
  59. if(!in_array($scheme, ['http','https'])) {
  60. return $this->respond($response, 400, [
  61. 'error' => 'invalid_url',
  62. 'error_description' => 'Only http and https URLs are supported'
  63. ]);
  64. }
  65. $host = parse_url($url, PHP_URL_HOST);
  66. if(!$host) {
  67. return $this->respond($response, 400, [
  68. 'error' => 'invalid_url',
  69. 'error_description' => 'The URL provided was not valid'
  70. ]);
  71. }
  72. $url = \normalize_url($url);
  73. // Now fetch the URL and check for any curl errors
  74. if($cached=$this->mc->get('xray-'.md5($url))) {
  75. $result = json_decode($cached, true);
  76. self::debug('using HTML from cache', 'X-Cache-Debug');
  77. } else {
  78. $result = $this->http->get($url);
  79. $cacheData = json_encode($result);
  80. if(strlen($cacheData) < 1000000) // App Engine limits the size of cached items, so don't cache ones larger than that
  81. $this->mc->set('xray-'.md5($url), $cacheData, MEMCACHE_COMPRESSED, $this->_cacheTime);
  82. }
  83. if($result['error']) {
  84. return $this->respond($response, 400, [
  85. 'error' => $result['error'],
  86. 'error_description' => $result['error_description']
  87. ]);
  88. }
  89. if(trim($result['body']) == '') {
  90. return $this->respond($response, 200, [
  91. 'error' => 'no_content',
  92. 'error_description' => 'We did not get a response body when fetching the URL'
  93. ]);
  94. }
  95. }
  96. // attempt to parse the page as HTML
  97. $doc = new DOMDocument();
  98. @$doc->loadHTML(self::toHtmlEntities($result['body']));
  99. if(!$doc) {
  100. return $this->respond($response, 400, [
  101. 'error' => 'invalid_content',
  102. 'error_description' => 'The document could not be parsed as HTML'
  103. ]);
  104. }
  105. // If a target parameter was provided, make sure a link to it exists on the page
  106. if($target=$request->get('target')) {
  107. $xpath = new DOMXPath($doc);
  108. $found = [];
  109. foreach($xpath->query('//a[@href]') as $href) {
  110. $u = $href->getAttribute('href');
  111. if($target) {
  112. # target parameter was provided
  113. if($u == $target) {
  114. $found[$u] = null;
  115. }
  116. }
  117. }
  118. if(!$found) {
  119. return $this->respond($response, 400, [
  120. 'error' => 'no_link_found',
  121. 'error_description' => 'The source document does not have a link to the target URL'
  122. ]);
  123. }
  124. }
  125. // Now start pulling in the data from the page. Start by looking for microformats2
  126. $mf2 = mf2\Parse($result['body'], $result['url']);
  127. if($mf2 && count($mf2['items']) > 0) {
  128. $data = Formats\Mf2::parse($mf2, $result['url'], $this->http);
  129. if($data) {
  130. return $this->respond($response, 200, $data);
  131. }
  132. }
  133. // TODO: look for other content like OEmbed or other known services later
  134. return $this->respond($response, 200, [
  135. 'data' => [
  136. 'type' => 'unknown',
  137. ]
  138. ]);
  139. }
  140. }