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.

216 lines
6.4 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 ||
  89. # subdomain check
  90. ($target_domain and substr_compare($domain, '.' . $target_domain, -(strlen($target_domain) + 1)) == 0)) {
  91. $found[$url] = null;
  92. }
  93. }
  94. if(!$found) {
  95. return $this->respond($response, 400, [
  96. 'error' => 'no_link_found',
  97. 'error_description' => 'The source document does not have a link to the target URL or domain'
  98. ]);
  99. }
  100. # Everything checked out, so write the webmention to the log and queue a job to start sending
  101. # TODO: database transaction?
  102. $statusURLs = [];
  103. foreach($found as $url=>$_) {
  104. $w = ORM::for_table('webmentions')->create();
  105. $w->site_id = $role->site_id;
  106. $w->created_by = $role->user_id;
  107. $w->created_at = date('Y-m-d H:i:s');
  108. $w->token = self::generateStatusToken();
  109. $w->source = $source;
  110. $w->target = $url;
  111. $w->vouch = $request->get('vouch');
  112. $w->callback = $callback;
  113. $w->save();
  114. q()->queue('Telegraph\Webmention', 'send', [$w->id]);
  115. $statusURLs[] = Config::$base . 'webmention/' . $w->token;
  116. }
  117. if ($target) {
  118. $body = [
  119. 'status' => 'queued',
  120. 'location' => $statusURLs[0]
  121. ];
  122. $headers = ['Location' => $statusURLs[0]];
  123. } else {
  124. $body = [
  125. 'status' => 'queued',
  126. 'location' => $statusURLs
  127. ];
  128. $headers = [];
  129. }
  130. return $this->respond($response, 201, $body, $headers);
  131. }
  132. public function webmention_status(Request $request, Response $response, $args) {
  133. $webmention = ORM::for_table('webmentions')->where('token', $args['code'])->find_one();
  134. if(!$webmention) {
  135. return $this->respond($response, 404, [
  136. 'status' => 'not_found',
  137. ]);
  138. }
  139. $status = ORM::for_table('webmention_status')->where('webmention_id', $webmention->id)->order_by_desc('created_at')->find_one();
  140. $statusURL = Config::$base . 'webmention/' . $webmention->token;
  141. if(!$status) {
  142. $code = 'queued';
  143. } else {
  144. $code = $status->status;
  145. }
  146. $data = [
  147. 'status' => $code,
  148. ];
  149. if($webmention->webmention_endpoint) {
  150. $data['type'] = 'webmention';
  151. $data['endpoint'] = $webmention->webmention_endpoint;
  152. }
  153. if($webmention->pingback_endpoint) {
  154. $data['type'] = 'pingback';
  155. $data['endpoint'] = $webmention->pingback_endpoint;
  156. }
  157. switch($code) {
  158. case 'queued':
  159. $summary = 'The webmention is still in the processing queue';
  160. break;
  161. case 'not_supported':
  162. $summary = 'No webmention or pingback endpoint were found at the target';
  163. break;
  164. case 'accepted':
  165. $summary = 'The '.$data['type'].' request was accepted';
  166. break;
  167. default:
  168. $summary = false;
  169. }
  170. if($status && $status->http_code)
  171. $data['http_code'] = (int)$status->http_code;
  172. if($summary)
  173. $data['summary'] = $summary;
  174. if($webmention->complete == 0)
  175. $data['location'] = $statusURL;
  176. return $this->respond($response, 200, $data);
  177. }
  178. }