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.

297 lines
9.5 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. @$doc->loadHTML(self::toHtmlEntities($sourceData['body']), LIBXML_NOWARNING|LIBXML_NOERROR);
  99. if(!$doc) {
  100. return $this->respond($response, 400, [
  101. 'error' => 'source_not_html',
  102. 'error_description' => 'The source document could not be parsed as HTML'
  103. ]);
  104. }
  105. $xpath = new DOMXPath($doc);
  106. $found = [];
  107. foreach($xpath->query('//a[@href]') as $href) {
  108. $url = $href->getAttribute('href');
  109. if($target) {
  110. # target parameter was provided
  111. if($url == $target) {
  112. $found[$url] = null;
  113. }
  114. } elseif($target_domain) {
  115. # target_domain parameter was provided
  116. $domain = parse_url($url, PHP_URL_HOST);
  117. if($domain && ($domain == $target_domain || str_ends_with($domain, '.' . $target_domain))) {
  118. $found[$url] = null;
  119. }
  120. }
  121. }
  122. if(!$found) {
  123. return $this->respond($response, 400, [
  124. 'error' => 'no_link_found',
  125. 'error_description' => 'The source document does not have a link to the target URL or domain'
  126. ]);
  127. }
  128. # Everything checked out, so write the webmention to the log and queue a job to start sending
  129. # TODO: database transaction?
  130. $statusURLs = [];
  131. foreach($found as $url=>$_) {
  132. $w = ORM::for_table('webmentions')->create();
  133. $w->site_id = $role->site_id;
  134. $w->created_by = $role->user_id;
  135. $w->created_at = date('Y-m-d H:i:s');
  136. $w->token = self::generateStatusToken();
  137. $w->source = $source;
  138. $w->target = $url;
  139. $w->vouch = $request->get('vouch');
  140. $w->callback = $callback;
  141. $w->save();
  142. q()->queue('Telegraph\Webmention', 'send', [$w->id]);
  143. $statusURLs[] = Config::$base . 'webmention/' . $w->token;
  144. }
  145. if ($target) {
  146. $body = [
  147. 'status' => 'queued',
  148. 'location' => $statusURLs[0]
  149. ];
  150. $headers = ['Location' => $statusURLs[0]];
  151. } else {
  152. $body = [
  153. 'status' => 'queued',
  154. 'location' => $statusURLs
  155. ];
  156. $headers = [];
  157. }
  158. return $this->respond($response, 201, $body, $headers);
  159. }
  160. public function superfeedr_tracker(Request $request, Response $response, $args) {
  161. logger()->addInfo("Got payload from superfeedr: " . $request->getContent());
  162. $input = json_decode($request->getContent(), true);
  163. # Require the code parameter
  164. if(!$token=$args['token']) {
  165. return $this->respond($response, 401, [
  166. 'error' => 'authentication_required',
  167. 'error_description' => 'A token is required to use the API'
  168. ]);
  169. }
  170. # Verify the token is valid
  171. $role = ORM::for_table('roles')->where('token', $token)->find_one();
  172. if(!$role) {
  173. return $this->respond($response, 401, [
  174. 'error' => 'invalid_token',
  175. 'error_description' => 'The token provided is not valid'
  176. ]);
  177. }
  178. $site = ORM::for_table('sites')->where('id', $role->site_id)->find_one();
  179. if(is_array($input)
  180. && array_key_exists('items', $input)
  181. && ($items = $input['items'])
  182. && is_array($items)
  183. && array_key_exists(0, $items)
  184. && ($item = $items[0])
  185. && array_key_exists('permalinkUrl', $item)) {
  186. $url = $item['permalinkUrl'];
  187. $domain = parse_url($site->url, PHP_URL_HOST);
  188. # Create a new request that looks like a request to the API with a target_domain parameter
  189. $new_request = new Request(['token' => $token, 'source' => $url, 'target_domain' => $domain]);
  190. return $this->webmention($new_request, $response);
  191. } else {
  192. return $this->respond($response, 200, [
  193. 'error' => 'invalid_request',
  194. 'error_description' => 'Could not find source URL from the superfeedr payload'
  195. ]);
  196. }
  197. }
  198. public function webmention_status(Request $request, Response $response, $args) {
  199. $webmention = ORM::for_table('webmentions')->where('token', $args['code'])->find_one();
  200. if(!$webmention) {
  201. return $this->respond($response, 404, [
  202. 'status' => 'not_found',
  203. ]);
  204. }
  205. $status = ORM::for_table('webmention_status')->where('webmention_id', $webmention->id)->order_by_desc('created_at')->find_one();
  206. $statusURL = Config::$base . 'webmention/' . $webmention->token;
  207. if(!$status) {
  208. $code = 'queued';
  209. } else {
  210. $code = $status->status;
  211. }
  212. $data = [
  213. 'source' => $webmention->source,
  214. 'target' => $webmention->target,
  215. 'status' => $code,
  216. ];
  217. if($webmention->webmention_endpoint) {
  218. $data['type'] = 'webmention';
  219. $data['endpoint'] = $webmention->webmention_endpoint;
  220. }
  221. if($webmention->pingback_endpoint) {
  222. $data['type'] = 'pingback';
  223. $data['endpoint'] = $webmention->pingback_endpoint;
  224. }
  225. switch($code) {
  226. case 'queued':
  227. $summary = 'The webmention is still in the processing queue';
  228. break;
  229. case 'not_supported':
  230. $summary = 'No webmention or pingback endpoint were found at the target';
  231. break;
  232. case 'accepted':
  233. $summary = 'The '.$data['type'].' request was accepted';
  234. break;
  235. default:
  236. $summary = false;
  237. }
  238. if($status && $status->http_code)
  239. $data['http_code'] = (int)$status->http_code;
  240. if($summary)
  241. $data['summary'] = $summary;
  242. if($webmention->complete == 0)
  243. $data['location'] = $statusURL;
  244. return $this->respond($response, 200, $data);
  245. }
  246. }