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.

299 lines
9.6 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));
  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 parameter
  33. if(!$token=$request->get('token')) {
  34. return $this->respond($response, 401, [
  35. 'error' => 'authentication_required',
  36. 'error_description' => 'A token is required to use the API'
  37. ]);
  38. }
  39. # Require source and target or target_domain parameters
  40. $target = $target_domain = null;
  41. if((!$source=$request->get('source')) || ((!$target=$request->get('target')) && (!$target_domain=$request->get('target_domain')))) {
  42. return $this->respond($response, 400, [
  43. 'error' => 'missing_parameters',
  44. 'error_description' => 'The source or target or target_domain parameters were missing'
  45. ]);
  46. }
  47. if($target && $target_domain) {
  48. return $this->respond($response, 400, [
  49. 'error' => 'invalid_parameter',
  50. 'error_description' => 'Can\'t provide both target and target_domain together'
  51. ]);
  52. }
  53. $urlregex = '/^https?:\/\/[^ ]+\.[^ ]+$/';
  54. $domainregex = '/^[^ ]+$/';
  55. # Verify source, target, and callback are URLs
  56. $callback = $request->get('callback');
  57. if(!preg_match($urlregex, $source) ||
  58. (!preg_match($urlregex, $target) && !preg_match($domainregex, $target_domain)) ||
  59. ($callback && !preg_match($urlregex, $callback))) {
  60. return $this->respond($response, 400, [
  61. 'error' => 'invalid_parameter',
  62. 'error_description' => 'The source, target, or callback parameters were invalid'
  63. ]);
  64. }
  65. # Don't send anything if the source domain matches the target domain
  66. # The problem is someone pushing to Superfeedr who is also subscribed, will cause a
  67. # request to be sent with the source of one of their posts, and their own target domain.
  68. # This causes a whole slew of webmentions to be queued up, almost all of which are not needed.
  69. if($target_domain) {
  70. $source_domain = parse_url($source, PHP_URL_HOST);
  71. if($target_domain == $source_domain) {
  72. # Return 200 so Superfeedr doesn't think something is broken
  73. return $this->respond($response, 200, [
  74. 'error' => 'not_supported',
  75. 'error_description' => 'You cannot use the target_domain feature to send webmentions to the same domain as the source URL'
  76. ]);
  77. }
  78. }
  79. # Verify the token is valid
  80. $role = ORM::for_table('roles')->where('token', $token)->find_one();
  81. if(!$role) {
  82. return $this->respond($response, 401, [
  83. 'error' => 'invalid_token',
  84. 'error_description' => 'The token provided is not valid'
  85. ]);
  86. }
  87. # Check the blacklist of domains that are known to not accept webmentions
  88. if($target && !Telegraph\Webmention::isProbablySupported($target)) {
  89. return $this->respond($response, 400, [
  90. 'error' => 'not_supported',
  91. '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'
  92. ]);
  93. }
  94. # Synchronously check the source URL and verify that it actually contains
  95. # a link to the target. This way we prevent this API from sending known invalid mentions.
  96. $sourceData = $this->http->get($source);
  97. $doc = new DOMDocument();
  98. libxml_use_internal_errors(true); # suppress parse errors and warnings
  99. @$doc->loadHTML(self::toHtmlEntities($sourceData['body']), LIBXML_NOWARNING|LIBXML_NOERROR);
  100. libxml_clear_errors();
  101. if(!$doc) {
  102. return $this->respond($response, 400, [
  103. 'error' => 'source_not_html',
  104. 'error_description' => 'The source document could not be parsed as HTML'
  105. ]);
  106. }
  107. $xpath = new DOMXPath($doc);
  108. $found = [];
  109. foreach($xpath->query('//a[@href]') as $href) {
  110. $url = $href->getAttribute('href');
  111. if($target) {
  112. # target parameter was provided
  113. if($url == $target) {
  114. $found[$url] = null;
  115. }
  116. } elseif($target_domain) {
  117. # target_domain parameter was provided
  118. $domain = parse_url($url, PHP_URL_HOST);
  119. if($domain && ($domain == $target_domain || str_ends_with($domain, '.' . $target_domain))) {
  120. $found[$url] = null;
  121. }
  122. }
  123. }
  124. if(!$found) {
  125. return $this->respond($response, 400, [
  126. 'error' => 'no_link_found',
  127. 'error_description' => 'The source document does not have a link to the target URL or domain'
  128. ]);
  129. }
  130. # Everything checked out, so write the webmention to the log and queue a job to start sending
  131. # TODO: database transaction?
  132. $statusURLs = [];
  133. foreach($found as $url=>$_) {
  134. $w = ORM::for_table('webmentions')->create();
  135. $w->site_id = $role->site_id;
  136. $w->created_by = $role->user_id;
  137. $w->created_at = date('Y-m-d H:i:s');
  138. $w->token = self::generateStatusToken();
  139. $w->source = $source;
  140. $w->target = $url;
  141. $w->vouch = $request->get('vouch');
  142. $w->callback = $callback;
  143. $w->save();
  144. q()->queue('Telegraph\Webmention', 'send', [$w->id]);
  145. $statusURLs[] = Config::$base . 'webmention/' . $w->token;
  146. }
  147. if ($target) {
  148. $body = [
  149. 'status' => 'queued',
  150. 'location' => $statusURLs[0]
  151. ];
  152. $headers = ['Location' => $statusURLs[0]];
  153. } else {
  154. $body = [
  155. 'status' => 'queued',
  156. 'location' => $statusURLs
  157. ];
  158. $headers = [];
  159. }
  160. return $this->respond($response, 201, $body, $headers);
  161. }
  162. public function superfeedr_tracker(Request $request, Response $response, $args) {
  163. logger()->addInfo("Got payload from superfeedr: " . $request->getContent());
  164. $input = json_decode($request->getContent(), true);
  165. # Require the code parameter
  166. if(!$token=$args['token']) {
  167. return $this->respond($response, 401, [
  168. 'error' => 'authentication_required',
  169. 'error_description' => 'A token is required to use the API'
  170. ]);
  171. }
  172. # Verify the token is valid
  173. $role = ORM::for_table('roles')->where('token', $token)->find_one();
  174. if(!$role) {
  175. return $this->respond($response, 401, [
  176. 'error' => 'invalid_token',
  177. 'error_description' => 'The token provided is not valid'
  178. ]);
  179. }
  180. $site = ORM::for_table('sites')->where('id', $role->site_id)->find_one();
  181. if(is_array($input)
  182. && array_key_exists('items', $input)
  183. && ($items = $input['items'])
  184. && is_array($items)
  185. && array_key_exists(0, $items)
  186. && ($item = $items[0])
  187. && array_key_exists('permalinkUrl', $item)) {
  188. $url = $item['permalinkUrl'];
  189. $domain = parse_url($site->url, PHP_URL_HOST);
  190. # Create a new request that looks like a request to the API with a target_domain parameter
  191. $new_request = new Request(['token' => $token, 'source' => $url, 'target_domain' => $domain]);
  192. return $this->webmention($new_request, $response);
  193. } else {
  194. return $this->respond($response, 200, [
  195. 'error' => 'invalid_request',
  196. 'error_description' => 'Could not find source URL from the superfeedr payload'
  197. ]);
  198. }
  199. }
  200. public function webmention_status(Request $request, Response $response, $args) {
  201. $webmention = ORM::for_table('webmentions')->where('token', $args['code'])->find_one();
  202. if(!$webmention) {
  203. return $this->respond($response, 404, [
  204. 'status' => 'not_found',
  205. ]);
  206. }
  207. $status = ORM::for_table('webmention_status')->where('webmention_id', $webmention->id)->order_by_desc('created_at')->find_one();
  208. $statusURL = Config::$base . 'webmention/' . $webmention->token;
  209. if(!$status) {
  210. $code = 'queued';
  211. } else {
  212. $code = $status->status;
  213. }
  214. $data = [
  215. 'source' => $webmention->source,
  216. 'target' => $webmention->target,
  217. 'status' => $code,
  218. ];
  219. if($webmention->webmention_endpoint) {
  220. $data['type'] = 'webmention';
  221. $data['endpoint'] = $webmention->webmention_endpoint;
  222. }
  223. if($webmention->pingback_endpoint) {
  224. $data['type'] = 'pingback';
  225. $data['endpoint'] = $webmention->pingback_endpoint;
  226. }
  227. switch($code) {
  228. case 'queued':
  229. $summary = 'The webmention is still in the processing queue';
  230. break;
  231. case 'not_supported':
  232. $summary = 'No webmention or pingback endpoint were found at the target';
  233. break;
  234. case 'accepted':
  235. $summary = 'The '.$data['type'].' request was accepted';
  236. break;
  237. default:
  238. $summary = false;
  239. }
  240. if($status && $status->http_code)
  241. $data['http_code'] = (int)$status->http_code;
  242. if($summary)
  243. $data['summary'] = $summary;
  244. if($webmention->complete == 0)
  245. $data['location'] = $statusURL;
  246. return $this->respond($response, 200, $data);
  247. }
  248. }