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.

317 lines
9.6 KiB

  1. <?php
  2. use Symfony\Component\HttpFoundation\Request;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use p3k\XRay\Formats;
  5. class Parse {
  6. public $http;
  7. public $mc;
  8. private $_cacheTime = 120;
  9. private $_pretty = false;
  10. public static function useragent() {
  11. return 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36 XRay/1.0.0 ('.\Config::$base.')';
  12. }
  13. public function __construct() {
  14. $this->http = new p3k\HTTP(self::useragent());
  15. if(Config::$cache && class_exists('Memcache')) {
  16. $this->mc = new Memcache();
  17. $this->mc->addServer('127.0.0.1');
  18. }
  19. }
  20. public static function debug($msg, $header='X-Parse-Debug') {
  21. syslog(LOG_INFO, $msg);
  22. if(array_key_exists('REMOTE_ADDR', $_SERVER))
  23. header($header . ": " . $msg);
  24. }
  25. private function respond(Response $response, $code, $params, $headers=[]) {
  26. $response->setStatusCode($code);
  27. foreach($headers as $k=>$v) {
  28. $response->headers->set($k, $v);
  29. }
  30. $response->headers->set('Content-Type', 'application/json');
  31. $opts = JSON_UNESCAPED_SLASHES;
  32. if($this->_pretty) $opts += JSON_PRETTY_PRINT;
  33. $response->setContent(json_encode($params, $opts)."\n");
  34. return $response;
  35. }
  36. private static function toHtmlEntities($input) {
  37. return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
  38. }
  39. public function parse(Request $request, Response $response) {
  40. $opts = [];
  41. if($request->get('timeout')) {
  42. // We might make 2 HTTP requests, so each request gets half the desired timeout
  43. $opts['timeout'] = $request->get('timeout') / 2;
  44. }
  45. if($request->get('max_redirects') !== null) {
  46. $opts['max_redirects'] = (int)$request->get('max_redirects');
  47. }
  48. if($request->get('pretty')) {
  49. $this->_pretty = true;
  50. }
  51. $url = $request->get('url');
  52. $html = $request->get('html');
  53. if(!$url && !$html) {
  54. return $this->respond($response, 400, [
  55. 'error' => 'missing_url',
  56. 'error_description' => 'Provide a URL or HTML to fetch'
  57. ]);
  58. }
  59. if($html) {
  60. // If HTML is provided in the request, parse that, and use the URL provided as the base URL for mf2 resolving
  61. $result['body'] = $html;
  62. $result['url'] = $url;
  63. $result['code'] = null;
  64. } else {
  65. $fetch = new p3k\XRay\Fetch($this->http);
  66. $fields = [
  67. 'twitter_api_key','twitter_api_secret','twitter_access_token','twitter_access_token_secret',
  68. 'github_access_token',
  69. 'token'
  70. ];
  71. foreach($fields as $f) {
  72. if($v=$request->get($f))
  73. $opts[$f] = $v;
  74. }
  75. $result = $fetch->fetch($url, $opts);
  76. if(!empty($result['error'])) {
  77. $error_code = isset($result['error_code']) ? $result['error_code'] : 200;
  78. unset($result['error_code']);
  79. return $this->respond($response, $error_code, $result);
  80. }
  81. }
  82. // Check for known services
  83. $host = parse_url($result['url'], PHP_URL_HOST);
  84. if(in_array($host, ['www.instagram.com','instagram.com'])) {
  85. list($data, $parsed) = Formats\Instagram::parse($result['body'], $result['url'], $this->http);
  86. if($request->get('include_original'))
  87. $data['original'] = $parsed;
  88. $data['url'] = $result['url'];
  89. $data['code'] = $result['code'];
  90. return $this->respond($response, 200, $data);
  91. }
  92. if($host == 'xkcd.com' && parse_url($url, PHP_URL_PATH) != '/') {
  93. $data = Formats\XKCD::parse($result['body'], $url);
  94. $data['url'] = $result['url'];
  95. $data['code'] = $result['code'];
  96. return $this->respond($response, 200, $data);
  97. }
  98. // attempt to parse the page as HTML
  99. $doc = new DOMDocument();
  100. @$doc->loadHTML(self::toHtmlEntities($result['body']));
  101. if(!$doc) {
  102. return $this->respond($response, 200, [
  103. 'error' => 'invalid_content',
  104. 'error_description' => 'The document could not be parsed as HTML'
  105. ]);
  106. }
  107. $xpath = new DOMXPath($doc);
  108. // Check for meta http equiv and replace the status code if present
  109. foreach($xpath->query('//meta[translate(@http-equiv,\'STATUS\',\'status\')=\'status\']') as $el) {
  110. $equivStatus = ''.$el->getAttribute('content');
  111. if($equivStatus && is_string($equivStatus)) {
  112. if(preg_match('/^(\d+)/', $equivStatus, $match)) {
  113. $result['code'] = (int)$match[1];
  114. }
  115. }
  116. }
  117. // If a target parameter was provided, make sure a link to it exists on the page
  118. if($target=$request->get('target')) {
  119. $found = [];
  120. if($target) {
  121. self::xPathFindNodeWithAttribute($xpath, 'a', 'href', function($u) use($target, &$found){
  122. if($u == $target) {
  123. $found[$u] = null;
  124. }
  125. });
  126. self::xPathFindNodeWithAttribute($xpath, 'img', 'src', function($u) use($target, &$found){
  127. if($u == $target) {
  128. $found[$u] = null;
  129. }
  130. });
  131. self::xPathFindNodeWithAttribute($xpath, 'video', 'src', function($u) use($target, &$found){
  132. if($u == $target) {
  133. $found[$u] = null;
  134. }
  135. });
  136. self::xPathFindNodeWithAttribute($xpath, 'audio', 'src', function($u) use($target, &$found){
  137. if($u == $target) {
  138. $found[$u] = null;
  139. }
  140. });
  141. }
  142. if(!$found) {
  143. return $this->respond($response, 200, [
  144. 'error' => 'no_link_found',
  145. 'error_description' => 'The source document does not have a link to the target URL',
  146. 'url' => $result['url'],
  147. 'code' => $result['code'],
  148. ]);
  149. }
  150. }
  151. // If the URL has a fragment ID, find the DOM starting at that node and parse it instead
  152. $html = $result['body'];
  153. $fragment = parse_url($url, PHP_URL_FRAGMENT);
  154. if($fragment) {
  155. $fragElement = self::xPathGetElementById($xpath, $fragment);
  156. if($fragElement) {
  157. $html = $doc->saveHTML($fragElement);
  158. $foundFragment = true;
  159. } else {
  160. $foundFragment = false;
  161. }
  162. }
  163. // Now start pulling in the data from the page. Start by looking for microformats2
  164. $mf2 = mf2\Parse($html, $result['url']);
  165. if($mf2 && count($mf2['items']) > 0) {
  166. $data = Formats\Mf2::parse($mf2, $result['url'], $this->http);
  167. if($data) {
  168. if($fragment) {
  169. $data['info'] = [
  170. 'found_fragment' => $foundFragment
  171. ];
  172. }
  173. if($request->get('include_original'))
  174. $data['original'] = $html;
  175. $data['url'] = $result['url']; // this will be the effective URL after following redirects
  176. $data['code'] = $result['code'];
  177. return $this->respond($response, 200, $data);
  178. }
  179. }
  180. // TODO: look for other content like OEmbed or other known services later
  181. return $this->respond($response, 200, [
  182. 'data' => [
  183. 'type' => 'unknown',
  184. ],
  185. 'url' => $result['url'],
  186. 'code' => $result['code']
  187. ]);
  188. }
  189. private static function xPathFindNodeWithAttribute($xpath, $node, $attr, $callback) {
  190. foreach($xpath->query('//'.$node.'[@'.$attr.']') as $el) {
  191. $v = $el->getAttribute($attr);
  192. $callback($v);
  193. }
  194. }
  195. private static function xPathGetElementById($xpath, $id) {
  196. $element = null;
  197. foreach($xpath->query("//*[@id='$id']") as $el) {
  198. $element = $el;
  199. }
  200. return $element;
  201. }
  202. private function parseTwitterURL(&$request, &$response, $url, $match) {
  203. $fields = ['twitter_api_key','twitter_api_secret','twitter_access_token','twitter_access_token_secret'];
  204. $creds = [];
  205. foreach($fields as $f) {
  206. if($v=$request->get($f))
  207. $creds[$f] = $v;
  208. }
  209. $data = false;
  210. if(count($creds) == 4) {
  211. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], $creds);
  212. } elseif(count($creds) > 0) {
  213. // If only some Twitter credentials were present, return an error
  214. return $this->respond($response, 400, [
  215. 'error' => 'missing_parameters',
  216. 'error_description' => 'All 4 Twitter credentials must be included in the request'
  217. ]);
  218. } else {
  219. // Accept Tweet JSON and parse that if provided
  220. $json = $request->get('json');
  221. if($json) {
  222. list($data, $parsed) = Formats\Twitter::parse($url, $match[1], null, $json);
  223. }
  224. // Skip parsing from the Twitter API if they didn't include credentials
  225. }
  226. if($data) {
  227. if($request->get('include_original'))
  228. $data['original'] = $parsed;
  229. $data['url'] = $url;
  230. $data['code'] = 200;
  231. return $this->respond($response, 200, $data);
  232. } else {
  233. return $this->respond($response, 200, [
  234. 'data' => [
  235. 'type' => 'unknown'
  236. ],
  237. 'url' => $url,
  238. 'code' => 0
  239. ]);
  240. }
  241. }
  242. private function parseGitHubURL(&$request, &$response, $url) {
  243. $fields = ['github_access_token'];
  244. $creds = [];
  245. foreach($fields as $f) {
  246. if($v=$request->get($f))
  247. $creds[$f] = $v;
  248. }
  249. $data = false;
  250. $json = $request->get('json');
  251. if($json) {
  252. // Accept GitHub JSON and parse that if provided
  253. list($data, $json, $code) = Formats\GitHub::parse($this->http, $url, null, $json);
  254. } else {
  255. // Otherwise fetch the post unauthenticated or with the provided access token
  256. list($data, $json, $code) = Formats\GitHub::parse($this->http, $url, $creds);
  257. }
  258. if($data) {
  259. if($request->get('include_original'))
  260. $data['original'] = $json;
  261. $data['url'] = $url;
  262. $data['code'] = $code;
  263. return $this->respond($response, 200, $data);
  264. } else {
  265. return $this->respond($response, 200, [
  266. 'data' => [
  267. 'type' => 'unknown'
  268. ],
  269. 'url' => $url,
  270. 'code' => $code
  271. ]);
  272. }
  273. }
  274. }