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.

214 lines
6.3 KiB

  1. <?php
  2. use Symfony\Component\HttpFoundation\Request;
  3. use Symfony\Component\HttpFoundation\Response;
  4. class API {
  5. public $http;
  6. public function __construct() {
  7. $this->http = new Telegraph\HTTP();
  8. }
  9. private function respond(Response $response, $code, $params, $headers=[]) {
  10. $response->setStatusCode($code);
  11. foreach($headers as $k=>$v) {
  12. $response->headers->set($k, $v);
  13. }
  14. $response->headers->set('Content-Type', 'application/json');
  15. $response->setContent(json_encode($params));
  16. return $response;
  17. }
  18. private static function toHtmlEntities($input) {
  19. return mb_convert_encoding($input, 'HTML-ENTITIES', mb_detect_encoding($input));
  20. }
  21. private static function generateStatusToken() {
  22. $str = dechex(date('y'));
  23. $chs = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  24. $len = strlen($chs);
  25. for($i = 0; $i < 16; $i++) {
  26. $str .= $chs[mt_rand(0, $len - 1)];
  27. }
  28. return $str;
  29. }
  30. public function webmention(Request $request, Response $response) {
  31. # Require the token parameter
  32. if(!$token=$request->get('token')) {
  33. return $this->respond($response, 401, [
  34. 'error' => 'authentication_required',
  35. 'error_description' => 'A token is required to use the API'
  36. ]);
  37. }
  38. # Require source and target or target_domain parameters
  39. $target = $target_domain = null;
  40. if((!$source=$request->get('source')) || ((!$target=$request->get('target')) && (!$target_domain=$request->get('target_domain')))) {
  41. return $this->respond($response, 400, [
  42. 'error' => 'missing_parameters',
  43. 'error_description' => 'The source or target or target_domain parameters were missing'
  44. ]);
  45. }
  46. if($target && $target_domain) {
  47. return $this->respond($response, 400, [
  48. 'error' => 'invalid_parameter',
  49. 'error_description' => 'Can\'t provide both target and target_domain together'
  50. ]);
  51. }
  52. $urlregex = '/^https?:\/\/[^ ]+\.[^ ]+$/';
  53. $domainregex = '/^[^ ]+$/';
  54. # Verify source, target, and callback are URLs
  55. $callback = $request->get('callback');
  56. if(!preg_match($urlregex, $source) ||
  57. (!preg_match($urlregex, $target) && !preg_match($domainregex, $target_domain)) ||
  58. ($callback && !preg_match($urlregex, $callback))) {
  59. return $this->respond($response, 400, [
  60. 'error' => 'invalid_parameter',
  61. 'error_description' => 'The source, target, or callback parameters were invalid'
  62. ]);
  63. }
  64. # Verify the token is valid
  65. $role = ORM::for_table('roles')->where('token', $token)->find_one();
  66. if(!$role) {
  67. return $this->respond($response, 401, [
  68. 'error' => 'invalid_token',
  69. 'error_description' => 'The token provided is not valid'
  70. ]);
  71. }
  72. # Synchronously check the source URL and verify that it actually contains
  73. # a link to the target. This way we prevent this API from sending known invalid mentions.
  74. $sourceData = $this->http->get($source);
  75. $doc = new DOMDocument();
  76. @$doc->loadHTML(self::toHtmlEntities($sourceData['body']));
  77. if(!$doc) {
  78. return $this->respond($response, 400, [
  79. 'error' => 'source_not_html',
  80. 'error_description' => 'The source document could not be parsed as HTML'
  81. ]);
  82. }
  83. $xpath = new DOMXPath($doc);
  84. $found = [];
  85. foreach($xpath->query('//a[@href]') as $href) {
  86. $url = $href->getAttribute('href');
  87. $domain = parse_url($url, PHP_URL_HOST);
  88. if($url == $target || $domain == $target_domain || str_ends_with($domain, $target_domain)) {
  89. $found[$url] = null;
  90. }
  91. }
  92. if(!$found) {
  93. return $this->respond($response, 400, [
  94. 'error' => 'no_link_found',
  95. 'error_description' => 'The source document does not have a link to the target URL or domain'
  96. ]);
  97. }
  98. # Everything checked out, so write the webmention to the log and queue a job to start sending
  99. # TODO: database transaction?
  100. $statusURLs = [];
  101. foreach($found as $url=>$_) {
  102. $w = ORM::for_table('webmentions')->create();
  103. $w->site_id = $role->site_id;
  104. $w->created_by = $role->user_id;
  105. $w->created_at = date('Y-m-d H:i:s');
  106. $w->token = self::generateStatusToken();
  107. $w->source = $source;
  108. $w->target = $url;
  109. $w->vouch = $request->get('vouch');
  110. $w->callback = $callback;
  111. $w->save();
  112. q()->queue('Telegraph\Webmention', 'send', [$w->id]);
  113. $statusURLs[] = Config::$base . 'webmention/' . $w->token;
  114. }
  115. if ($target) {
  116. $body = [
  117. 'status' => 'queued',
  118. 'location' => $statusURLs[0]
  119. ];
  120. $headers = ['Location' => $statusURLs[0]];
  121. } else {
  122. $body = [
  123. 'status' => 'queued',
  124. 'location' => $statusURLs
  125. ];
  126. $headers = [];
  127. }
  128. return $this->respond($response, 201, $body, $headers);
  129. }
  130. public function webmention_status(Request $request, Response $response, $args) {
  131. $webmention = ORM::for_table('webmentions')->where('token', $args['code'])->find_one();
  132. if(!$webmention) {
  133. return $this->respond($response, 404, [
  134. 'status' => 'not_found',
  135. ]);
  136. }
  137. $status = ORM::for_table('webmention_status')->where('webmention_id', $webmention->id)->order_by_desc('created_at')->find_one();
  138. $statusURL = Config::$base . 'webmention/' . $webmention->token;
  139. if(!$status) {
  140. $code = 'queued';
  141. } else {
  142. $code = $status->status;
  143. }
  144. $data = [
  145. 'status' => $code,
  146. ];
  147. if($webmention->webmention_endpoint) {
  148. $data['type'] = 'webmention';
  149. $data['endpoint'] = $webmention->webmention_endpoint;
  150. }
  151. if($webmention->pingback_endpoint) {
  152. $data['type'] = 'pingback';
  153. $data['endpoint'] = $webmention->pingback_endpoint;
  154. }
  155. switch($code) {
  156. case 'queued':
  157. $summary = 'The webmention is still in the processing queue';
  158. break;
  159. case 'not_supported':
  160. $summary = 'No webmention or pingback endpoint were found at the target';
  161. break;
  162. case 'accepted':
  163. $summary = 'The '.$data['type'].' request was accepted';
  164. break;
  165. default:
  166. $summary = false;
  167. }
  168. if($status && $status->http_code)
  169. $data['http_code'] = (int)$status->http_code;
  170. if($summary)
  171. $data['summary'] = $summary;
  172. if($webmention->complete == 0)
  173. $data['location'] = $statusURL;
  174. return $this->respond($response, 200, $data);
  175. }
  176. }