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.

268 lines
8.1 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. # Verify the token is valid
  66. $role = ORM::for_table('roles')->where('token', $token)->find_one();
  67. if(!$role) {
  68. return $this->respond($response, 401, [
  69. 'error' => 'invalid_token',
  70. 'error_description' => 'The token provided is not valid'
  71. ]);
  72. }
  73. # Synchronously check the source URL and verify that it actually contains
  74. # a link to the target. This way we prevent this API from sending known invalid mentions.
  75. $sourceData = $this->http->get($source);
  76. $doc = new DOMDocument();
  77. @$doc->loadHTML(self::toHtmlEntities($sourceData['body']));
  78. if(!$doc) {
  79. return $this->respond($response, 400, [
  80. 'error' => 'source_not_html',
  81. 'error_description' => 'The source document could not be parsed as HTML'
  82. ]);
  83. }
  84. $xpath = new DOMXPath($doc);
  85. $found = [];
  86. foreach($xpath->query('//a[@href]') as $href) {
  87. $url = $href->getAttribute('href');
  88. if($target) {
  89. # target parameter was provided
  90. if($url == $target) {
  91. $found[$url] = null;
  92. }
  93. } elseif($target_domain) {
  94. # target_domain parameter was provided
  95. $domain = parse_url($url, PHP_URL_HOST);
  96. if($domain && ($domain == $target_domain || str_ends_with($domain, '.' . $target_domain))) {
  97. $found[$url] = null;
  98. }
  99. }
  100. }
  101. if(!$found) {
  102. return $this->respond($response, 400, [
  103. 'error' => 'no_link_found',
  104. 'error_description' => 'The source document does not have a link to the target URL or domain'
  105. ]);
  106. }
  107. # Everything checked out, so write the webmention to the log and queue a job to start sending
  108. # TODO: database transaction?
  109. $statusURLs = [];
  110. foreach($found as $url=>$_) {
  111. $w = ORM::for_table('webmentions')->create();
  112. $w->site_id = $role->site_id;
  113. $w->created_by = $role->user_id;
  114. $w->created_at = date('Y-m-d H:i:s');
  115. $w->token = self::generateStatusToken();
  116. $w->source = $source;
  117. $w->target = $url;
  118. $w->vouch = $request->get('vouch');
  119. $w->callback = $callback;
  120. $w->save();
  121. q()->queue('Telegraph\Webmention', 'send', [$w->id]);
  122. $statusURLs[] = Config::$base . 'webmention/' . $w->token;
  123. }
  124. if ($target) {
  125. $body = [
  126. 'status' => 'queued',
  127. 'location' => $statusURLs[0]
  128. ];
  129. $headers = ['Location' => $statusURLs[0]];
  130. } else {
  131. $body = [
  132. 'status' => 'queued',
  133. 'location' => $statusURLs
  134. ];
  135. $headers = [];
  136. }
  137. return $this->respond($response, 201, $body, $headers);
  138. }
  139. public function superfeedr_tracker(Request $request, Response $response, $args) {
  140. logger()->addInfo("Got payload from superfeedr", $request->request->all());
  141. # Require the code parameter
  142. if(!$token=$args['token']) {
  143. return $this->respond($response, 401, [
  144. 'error' => 'authentication_required',
  145. 'error_description' => 'A token is required to use the API'
  146. ]);
  147. }
  148. # Verify the token is valid
  149. $role = ORM::for_table('roles')->where('token', $token)->find_one();
  150. if(!$role) {
  151. return $this->respond($response, 401, [
  152. 'error' => 'invalid_token',
  153. 'error_description' => 'The token provided is not valid'
  154. ]);
  155. }
  156. $site = ORM::for_table('sites')->where('id', $role->site_id)->find_one();
  157. if(($items = $request->get('items'))
  158. && is_array($items)
  159. && array_key_exists(0, $items)
  160. && ($item = $items[0])
  161. && array_key_exists('permalinkUrl', $item)) {
  162. $url = $item['permalinkUrl'];
  163. $domain = parse_url($site->url, PHP_URL_HOST);
  164. # Create a new request that looks like a request to the API with a target_domain parameter
  165. $new_request = new Request(['token' => $token, 'source' => $url, 'target_domain' => $domain]);
  166. return $this->webmention($new_request, $response);
  167. } else {
  168. return $this->respond($response, 400, [
  169. 'error' => 'invalid_request',
  170. 'error_description' => 'Could not find source URL from the superfeedr payload'
  171. ]);
  172. }
  173. }
  174. public function webmention_status(Request $request, Response $response, $args) {
  175. $webmention = ORM::for_table('webmentions')->where('token', $args['code'])->find_one();
  176. if(!$webmention) {
  177. return $this->respond($response, 404, [
  178. 'status' => 'not_found',
  179. ]);
  180. }
  181. $status = ORM::for_table('webmention_status')->where('webmention_id', $webmention->id)->order_by_desc('created_at')->find_one();
  182. $statusURL = Config::$base . 'webmention/' . $webmention->token;
  183. if(!$status) {
  184. $code = 'queued';
  185. } else {
  186. $code = $status->status;
  187. }
  188. $data = [
  189. 'status' => $code,
  190. ];
  191. if($webmention->webmention_endpoint) {
  192. $data['type'] = 'webmention';
  193. $data['endpoint'] = $webmention->webmention_endpoint;
  194. }
  195. if($webmention->pingback_endpoint) {
  196. $data['type'] = 'pingback';
  197. $data['endpoint'] = $webmention->pingback_endpoint;
  198. }
  199. switch($code) {
  200. case 'queued':
  201. $summary = 'The webmention is still in the processing queue';
  202. break;
  203. case 'not_supported':
  204. $summary = 'No webmention or pingback endpoint were found at the target';
  205. break;
  206. case 'accepted':
  207. $summary = 'The '.$data['type'].' request was accepted';
  208. break;
  209. default:
  210. $summary = false;
  211. }
  212. if($status && $status->http_code)
  213. $data['http_code'] = (int)$status->http_code;
  214. if($summary)
  215. $data['summary'] = $summary;
  216. if($webmention->complete == 0)
  217. $data['location'] = $statusURL;
  218. return $this->respond($response, 200, $data);
  219. }
  220. }