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.

339 lines
11 KiB

  1. <?php
  2. use Symfony\Component\HttpFoundation\Request;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use Monolog\Logger;
  5. class API {
  6. public $http;
  7. public function __construct() {
  8. $this->http = new Telegraph\HTTP();
  9. }
  10. private function respond(Response $response, $code, $params, $headers=[]) {
  11. $response->setStatusCode($code);
  12. foreach($headers as $k=>$v) {
  13. $response->headers->set($k, $v);
  14. }
  15. $response->headers->set('Content-Type', 'application/json');
  16. $response->setContent(json_encode($params, JSON_UNESCAPED_SLASHES+JSON_PRETTY_PRINT));
  17. return $response;
  18. }
  19. private static function toHtmlEntities($input) {
  20. return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
  21. }
  22. private static function generateStatusToken() {
  23. $str = dechex(date('y'));
  24. $chs = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  25. $len = strlen($chs);
  26. for($i = 0; $i < 16; $i++) {
  27. $str .= $chs[mt_rand(0, $len - 1)];
  28. }
  29. return $str;
  30. }
  31. public function webmention(Request $request, Response $response) {
  32. # Require the token or csrf parameter
  33. if($csrf=$request->get('_csrf')) {
  34. session_start();
  35. if($csrf != $_SESSION['_csrf']) {
  36. return $this->respond($response, 401, [
  37. 'error' => 'invalid_csrf_token',
  38. 'error_description' => 'An error occurred. Make sure you have only one tab open.',
  39. ]);
  40. }
  41. } else if(!$token=$request->get('token')) {
  42. return $this->respond($response, 401, [
  43. 'error' => 'authentication_required',
  44. 'error_description' => 'A token is required to use the API'
  45. ]);
  46. # Verify the token is valid
  47. $role = ORM::for_table('roles')->where('token', $token)->find_one();
  48. if(!$role) {
  49. return $this->respond($response, 401, [
  50. 'error' => 'invalid_token',
  51. 'error_description' => 'The token provided is not valid'
  52. ]);
  53. }
  54. }
  55. # Require source and target or target_domain parameters
  56. $target = $target_domain = null;
  57. if((!$source=$request->get('source')) || ((!$target=$request->get('target')) && (!$target_domain=$request->get('target_domain')))) {
  58. return $this->respond($response, 400, [
  59. 'error' => 'missing_parameters',
  60. 'error_description' => 'The source or target or target_domain parameters were missing'
  61. ]);
  62. }
  63. if($target && $target_domain) {
  64. return $this->respond($response, 400, [
  65. 'error' => 'invalid_parameter',
  66. 'error_description' => 'Can\'t provide both target and target_domain together'
  67. ]);
  68. }
  69. # Can only use source & target if no authentication(role) is set
  70. if(!isset($role)) {
  71. if($target_domain) {
  72. return $this->respond($response, 400, [
  73. 'error' => 'unauthorized',
  74. 'error_description' => 'Can only use the target_domain feature when providing a token from the API',
  75. ]);
  76. }
  77. }
  78. $urlregex = '/^https?:\/\/[^ ]+\.[^ ]+$/';
  79. $domainregex = '/^[^ ]+$/';
  80. # Verify source, target, and callback are URLs
  81. $callback = $request->get('callback');
  82. if(!preg_match($urlregex, $source) ||
  83. (!preg_match($urlregex, $target) && !preg_match($domainregex, $target_domain)) ||
  84. ($callback && !preg_match($urlregex, $callback))) {
  85. return $this->respond($response, 400, [
  86. 'error' => 'invalid_parameter',
  87. 'error_description' => 'The source, target, or callback parameters were invalid'
  88. ]);
  89. }
  90. # Don't send anything if the source domain matches the target domain
  91. # The problem is someone pushing to Superfeedr who is also subscribed, will cause a
  92. # request to be sent with the source of one of their posts, and their own target domain.
  93. # This causes a whole slew of webmentions to be queued up, almost all of which are not needed.
  94. if($target_domain) {
  95. $source_domain = parse_url($source, PHP_URL_HOST);
  96. if($target_domain == $source_domain) {
  97. # Return 200 so Superfeedr doesn't think something is broken
  98. return $this->respond($response, 200, [
  99. 'error' => 'not_supported',
  100. 'error_description' => 'You cannot use the target_domain feature to send webmentions to the same domain as the source URL'
  101. ]);
  102. }
  103. }
  104. # Check the blacklist of domains that are known to not accept webmentions
  105. if($target && !Telegraph\Webmention::isProbablySupported($target)) {
  106. return $this->respond($response, 400, [
  107. 'error' => 'not_supported',
  108. 'error_description' => 'The target domain is known to not accept webmentions. If you believe this is in error, please file an issue at https://github.com/aaronpk/Telegraph/issues'
  109. ]);
  110. }
  111. # If there is no code given,
  112. # Synchronously check the source URL and verify that it actually contains
  113. # a link to the target. This way we prevent this API from sending known invalid mentions.
  114. if($request->get('code')) {
  115. # target URL is required
  116. if(!$target) {
  117. return $this->respond($response, 400, [
  118. 'error' => 'not_supported',
  119. 'error_description' => 'The target_domain parameter is not supported for sending private webmentions'
  120. ]);
  121. }
  122. $found[$target] = null;
  123. } else {
  124. $sourceData = $this->http->get($source, ['Accept: text/html, */*']);
  125. $doc = new DOMDocument();
  126. libxml_use_internal_errors(true); # suppress parse errors and warnings
  127. @$doc->loadHTML(self::toHtmlEntities($sourceData['body']), LIBXML_NOWARNING|LIBXML_NOERROR);
  128. libxml_clear_errors();
  129. if(!$doc) {
  130. return $this->respond($response, 400, [
  131. 'error' => 'source_not_html',
  132. 'error_description' => 'The source document could not be parsed as HTML'
  133. ]);
  134. }
  135. $xpath = new DOMXPath($doc);
  136. $found = [];
  137. $links = [];
  138. foreach($xpath->query('//a[@href]') as $href) {
  139. $url = $href->getAttribute('href');
  140. if($target) {
  141. $links[] = $url;
  142. # target parameter was provided
  143. if($url == $target) {
  144. $found[$url] = null;
  145. }
  146. } elseif($target_domain) {
  147. # target_domain parameter was provided
  148. $domain = parse_url($url, PHP_URL_HOST);
  149. if($domain && ($domain == $target_domain || str_ends_with($domain, '.' . $target_domain))) {
  150. $found[$url] = null;
  151. }
  152. }
  153. }
  154. if(!$found) {
  155. return $this->respond($response, 400, [
  156. 'error' => 'no_link_found',
  157. 'error_description' => 'The source document does not have a link to the target URL or domain',
  158. 'links' => $links
  159. ]);
  160. }
  161. }
  162. # Write the webmention to the database and queue a job to start sending
  163. $statusURLs = [];
  164. foreach($found as $url=>$_) {
  165. $w = ORM::for_table('webmentions')->create();
  166. $w->site_id = isset($role) ? $role->site_id : 0;
  167. $w->created_by = isset($role) ? $role->user_id : 0;
  168. $w->created_at = date('Y-m-d H:i:s');
  169. $w->token = self::generateStatusToken();
  170. $w->source = $source;
  171. $w->target = $url;
  172. $w->vouch = $request->get('vouch');
  173. $w->code = $request->get('code');
  174. $w->realm = $request->get('realm');
  175. $w->callback = $callback;
  176. $w->save();
  177. q()->queue('Telegraph\Webmention', 'send', [$w->id]);
  178. $statusURLs[] = Config::$base . 'webmention/' . $w->token;
  179. }
  180. if($target) {
  181. $body = [
  182. 'status' => 'queued',
  183. 'location' => $statusURLs[0]
  184. ];
  185. $headers = ['Location' => $statusURLs[0]];
  186. } else {
  187. $body = [
  188. 'status' => 'queued',
  189. 'location' => $statusURLs
  190. ];
  191. $headers = [];
  192. }
  193. return $this->respond($response, 201, $body, $headers);
  194. }
  195. public function superfeedr_tracker(Request $request, Response $response, $args) {
  196. logger()->addInfo("Got payload from superfeedr: " . $request->getContent());
  197. $input = json_decode($request->getContent(), true);
  198. # Require the code parameter
  199. if(!$token=$args['token']) {
  200. return $this->respond($response, 401, [
  201. 'error' => 'authentication_required',
  202. 'error_description' => 'A token is required to use the API'
  203. ]);
  204. }
  205. # Verify the token is valid
  206. $role = ORM::for_table('roles')->where('token', $token)->find_one();
  207. if(!$role) {
  208. return $this->respond($response, 401, [
  209. 'error' => 'invalid_token',
  210. 'error_description' => 'The token provided is not valid'
  211. ]);
  212. }
  213. $site = ORM::for_table('sites')->where('id', $role->site_id)->find_one();
  214. if(is_array($input)
  215. && array_key_exists('items', $input)
  216. && ($items = $input['items'])
  217. && is_array($items)
  218. && array_key_exists(0, $items)
  219. && ($item = $items[0])
  220. && array_key_exists('permalinkUrl', $item)) {
  221. $url = $item['permalinkUrl'];
  222. $domain = parse_url($site->url, PHP_URL_HOST);
  223. # Create a new request that looks like a request to the API with a target_domain parameter
  224. $new_request = new Request(['token' => $token, 'source' => $url, 'target_domain' => $domain]);
  225. return $this->webmention($new_request, $response);
  226. } else {
  227. return $this->respond($response, 200, [
  228. 'error' => 'invalid_request',
  229. 'error_description' => 'Could not find source URL from the superfeedr payload'
  230. ]);
  231. }
  232. }
  233. public function webmention_status(Request $request, Response $response, $args) {
  234. $webmention = ORM::for_table('webmentions')->where('token', $args['code'])->find_one();
  235. if(!$webmention) {
  236. return $this->respond($response, 404, [
  237. 'status' => 'not_found',
  238. ]);
  239. }
  240. $status = ORM::for_table('webmention_status')->where('webmention_id', $webmention->id)->order_by_desc('created_at')->find_one();
  241. $statusURL = Config::$base . 'webmention/' . $webmention->token;
  242. if(!$status) {
  243. $code = 'queued';
  244. } else {
  245. $code = $status->status;
  246. }
  247. $data = [
  248. 'source' => $webmention->source,
  249. 'target' => $webmention->target,
  250. 'status' => $code,
  251. ];
  252. if($webmention->webmention_endpoint) {
  253. $data['type'] = 'webmention';
  254. $data['endpoint'] = $webmention->webmention_endpoint;
  255. }
  256. if($webmention->pingback_endpoint) {
  257. $data['type'] = 'pingback';
  258. $data['endpoint'] = $webmention->pingback_endpoint;
  259. }
  260. switch($code) {
  261. case 'queued':
  262. $summary = 'The webmention is still in the processing queue';
  263. break;
  264. case 'not_supported':
  265. $summary = 'No webmention or pingback endpoint were found at the target';
  266. break;
  267. case 'accepted':
  268. $summary = 'The '.$data['type'].' request was accepted';
  269. break;
  270. default:
  271. $summary = false;
  272. }
  273. if($status && $status->http_code)
  274. $data['http_code'] = (int)$status->http_code;
  275. if($status && $status->raw_response) {
  276. $data['http_body'] = $status->raw_response;
  277. }
  278. if($summary)
  279. $data['summary'] = $summary;
  280. if($webmention->complete == 0)
  281. $data['location'] = $statusURL;
  282. return $this->respond($response, 200, $data);
  283. }
  284. }