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.

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