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.

192 lines
5.5 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 parameters
  39. if((!$source=$request->get('source')) || (!$target=$request->get('target'))) {
  40. return $this->respond($response, 400, [
  41. 'error' => 'missing_parameters',
  42. 'error_description' => 'The source or target parameters were missing'
  43. ]);
  44. }
  45. $urlregex = '/^https?:\/\/[^ ]+\.[^ ]+$/';
  46. # Verify source, target, and callback are URLs
  47. $callback = $request->get('callback');
  48. if(!preg_match($urlregex, $source) || !preg_match($urlregex, $target) ||
  49. ($callback && !preg_match($urlregex, $callback))) {
  50. return $this->respond($response, 400, [
  51. 'error' => 'invalid_parameter',
  52. 'error_description' => 'The source, target, or callback parameters were invalid'
  53. ]);
  54. }
  55. # Verify the token is valid
  56. $role = ORM::for_table('roles')->where('token', $token)->find_one();
  57. if(!$role) {
  58. return $this->respond($response, 401, [
  59. 'error' => 'invalid_token',
  60. 'error_description' => 'The token provided is not valid'
  61. ]);
  62. }
  63. # Synchronously check the source URL and verify that it actually contains
  64. # a link to the target. This way we prevent this API from sending known invalid mentions.
  65. $sourceData = $this->http->get($source);
  66. $doc = new DOMDocument();
  67. @$doc->loadHTML(self::toHtmlEntities($sourceData['body']));
  68. if(!$doc) {
  69. return $this->respond($response, 400, [
  70. 'error' => 'source_not_html',
  71. 'error_description' => 'The source document could not be parsed as HTML'
  72. ]);
  73. }
  74. $xpath = new DOMXPath($doc);
  75. $found = false;
  76. foreach($xpath->query('//a[@href]') as $href) {
  77. if($href->getAttribute('href') == $target) {
  78. $found = true;
  79. continue;
  80. }
  81. }
  82. if(!$found) {
  83. return $this->respond($response, 400, [
  84. 'error' => 'no_link_found',
  85. 'error_description' => 'The source document does not have a link to the target URL'
  86. ]);
  87. }
  88. # Everything checked out, so write the webmention to the log and queue a job to start sending
  89. $w = ORM::for_table('webmentions')->create();
  90. $w->site_id = $role->site_id;
  91. $w->created_by = $role->user_id;
  92. $w->created_at = date('Y-m-d H:i:s');
  93. $w->token = self::generateStatusToken();
  94. $w->source = $source;
  95. $w->target = $target;
  96. $w->vouch = $request->get('vouch');
  97. $w->callback = $callback;
  98. $w->save();
  99. q()->queue('Telegraph\Webmention', 'send', [$w->id]);
  100. $statusURL = Config::$base . 'webmention/' . $w->token;
  101. return $this->respond($response, 201, [
  102. 'status' => 'queued',
  103. 'location' => $statusURL
  104. ], [
  105. 'Location' => $statusURL
  106. ]);
  107. }
  108. public function webmention_status(Request $request, Response $response, $args) {
  109. $webmention = ORM::for_table('webmentions')->where('token', $args['code'])->find_one();
  110. if(!$webmention) {
  111. return $this->respond($response, 404, [
  112. 'status' => 'not_found',
  113. ]);
  114. }
  115. $status = ORM::for_table('webmention_status')->where('webmention_id', $webmention->id)->order_by_desc('created_at')->find_one();
  116. $statusURL = Config::$base . 'webmention/' . $webmention->token;
  117. if(!$status) {
  118. $code = 'queued';
  119. } else {
  120. $code = $status->status;
  121. }
  122. $data = [
  123. 'status' => $code,
  124. ];
  125. if($webmention->webmention_endpoint) {
  126. $data['type'] = 'webmention';
  127. $data['endpoint'] = $webmention->webmention_endpoint;
  128. }
  129. if($webmention->pingback_endpoint) {
  130. $data['type'] = 'pingback';
  131. $data['endpoint'] = $webmention->pingback_endpoint;
  132. }
  133. switch($code) {
  134. case 'queued':
  135. $summary = 'The webmention is still in the processing queue';
  136. break;
  137. case 'not_supported':
  138. $summary = 'No webmention or pingback endpoint were found at the target';
  139. break;
  140. case 'accepted':
  141. $summary = 'The '.$data['type'].' request was accepted';
  142. break;
  143. default:
  144. $summary = false;
  145. }
  146. if($status && $status->http_code)
  147. $data['http_code'] = (int)$status->http_code;
  148. if($summary)
  149. $data['summary'] = $summary;
  150. if($webmention->complete == 0)
  151. $data['location'] = $statusURL;
  152. return $this->respond($response, 200, $data);
  153. }
  154. }