pushhub.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2010, StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * Integrated PuSH hub; lets us only ping them what need it.
  21. * @package Hub
  22. * @maintainer Brion Vibber <brion@status.net>
  23. */
  24. if (!defined('STATUSNET')) {
  25. exit(1);
  26. }
  27. /**
  28. * Things to consider...
  29. * should we purge incomplete subscriptions that never get a verification pingback?
  30. * when can we send subscription renewal checks?
  31. * - at next send time probably ok
  32. * when can we handle trimming of subscriptions?
  33. * - at next send time probably ok
  34. * should we keep a fail count?
  35. */
  36. class PushHubAction extends Action
  37. {
  38. function arg($arg, $def=null)
  39. {
  40. // PHP converts '.'s in incoming var names to '_'s.
  41. // It also merges multiple values, which'll break hub.verify and hub.topic for publishing
  42. // @fixme handle multiple args
  43. $arg = str_replace('hub.', 'hub_', $arg);
  44. return parent::arg($arg, $def);
  45. }
  46. protected function prepare(array $args=array())
  47. {
  48. GNUsocial::setApi(true); // reduce exception reports to aid in debugging
  49. return parent::prepare($args);
  50. }
  51. protected function handle()
  52. {
  53. $mode = $this->trimmed('hub.mode');
  54. switch ($mode) {
  55. case "subscribe":
  56. case "unsubscribe":
  57. $this->subunsub($mode);
  58. break;
  59. case "publish":
  60. // TRANS: Client exception.
  61. throw new ClientException(_m('Publishing outside feeds not supported.'), 400);
  62. default:
  63. // TRANS: Client exception. %s is a mode.
  64. throw new ClientException(sprintf(_m('Unrecognized mode "%s".'),$mode), 400);
  65. }
  66. }
  67. /**
  68. * Process a request for a new or modified PuSH feed subscription.
  69. * If asynchronous verification is requested, updates won't be saved immediately.
  70. *
  71. * HTTP return codes:
  72. * 202 Accepted - request saved and awaiting verification
  73. * 204 No Content - already subscribed
  74. * 400 Bad Request - rejecting this (not specifically spec'd)
  75. */
  76. function subunsub($mode)
  77. {
  78. $callback = $this->argUrl('hub.callback');
  79. common_debug('New PuSH hub request ('._ve($mode).') for callback '._ve($callback));
  80. $topic = $this->argUrl('hub.topic');
  81. if (!$this->recognizedFeed($topic)) {
  82. common_debug('PuSH hub request had unrecognized feed topic=='._ve($topic));
  83. // TRANS: Client exception. %s is a topic.
  84. throw new ClientException(sprintf(_m('Unsupported hub.topic %s this hub only serves local user and group Atom feeds.'),$topic));
  85. }
  86. $lease = $this->arg('hub.lease_seconds', null);
  87. if ($mode == 'subscribe' && $lease != '' && !preg_match('/^\d+$/', $lease)) {
  88. common_debug('PuSH hub request had invalid lease_seconds=='._ve($lease));
  89. // TRANS: Client exception. %s is the invalid lease value.
  90. throw new ClientException(sprintf(_m('Invalid hub.lease "%s". It must be empty or positive integer.'),$lease));
  91. }
  92. $secret = $this->arg('hub.secret', null);
  93. if ($secret != '' && strlen($secret) >= 200) {
  94. common_debug('PuSH hub request had invalid secret=='._ve($secret));
  95. // TRANS: Client exception. %s is the invalid hub secret.
  96. throw new ClientException(sprintf(_m('Invalid hub.secret "%s". It must be under 200 bytes.'),$secret));
  97. }
  98. $sub = HubSub::getByHashkey($topic, $callback);
  99. if (!$sub instanceof HubSub) {
  100. // Creating a new one!
  101. common_debug('PuSH creating new HubSub entry for topic=='._ve($topic).' to remote callback '._ve($callback));
  102. $sub = new HubSub();
  103. $sub->topic = $topic;
  104. $sub->callback = $callback;
  105. }
  106. if ($mode == 'subscribe') {
  107. if ($secret) {
  108. $sub->secret = $secret;
  109. }
  110. if ($lease) {
  111. $sub->setLease(intval($lease));
  112. }
  113. }
  114. common_debug('PuSH hub request is now:'._ve($sub));
  115. $verify = $this->arg('hub.verify'); // TODO: deprecated
  116. $token = $this->arg('hub.verify_token', null); // TODO: deprecated
  117. if ($verify == 'sync') { // pre-0.4 PuSH
  118. $sub->verify($mode, $token);
  119. header('HTTP/1.1 204 No Content');
  120. } else { // If $verify is not "sync", we might be using PuSH 0.4
  121. $sub->scheduleVerify($mode, $token); // If we were certain it's PuSH 0.4, token could be removed
  122. header('HTTP/1.1 202 Accepted');
  123. }
  124. }
  125. /**
  126. * Check whether the given URL represents one of our canonical
  127. * user or group Atom feeds.
  128. *
  129. * @param string $feed URL
  130. * @return boolean true if it matches, false if not a recognized local feed
  131. * @throws exception if local entity does not exist
  132. */
  133. protected function recognizedFeed($feed)
  134. {
  135. $matches = array();
  136. // Simple mapping to local ID for user or group
  137. if (preg_match('!/(\d+)\.atom$!', $feed, $matches)) {
  138. $id = $matches[1];
  139. $params = array('id' => $id, 'format' => 'atom');
  140. // Double-check against locally generated URLs
  141. switch ($feed) {
  142. case common_local_url('ApiTimelineUser', $params):
  143. $user = User::getKV('id', $id);
  144. if (!$user instanceof User) {
  145. // TRANS: Client exception. %s is a feed URL.
  146. throw new ClientException(sprintf(_m('Invalid hub.topic "%s". User does not exist.'),$feed));
  147. }
  148. return true;
  149. case common_local_url('ApiTimelineGroup', $params):
  150. $group = Local_group::getKV('group_id', $id);
  151. if (!$group instanceof Local_group) {
  152. // TRANS: Client exception. %s is a feed URL.
  153. throw new ClientException(sprintf(_m('Invalid hub.topic "%s". Local_group does not exist.'),$feed));
  154. }
  155. return true;
  156. }
  157. common_debug("Feed was not recognized by any local User or Group Atom feed URLs: {$feed}");
  158. return false;
  159. }
  160. // Profile lists are unique per user, so we need both IDs
  161. if (preg_match('!/(\d+)/lists/(\d+)/statuses\.atom$!', $feed, $matches)) {
  162. $user = $matches[1];
  163. $id = $matches[2];
  164. $params = array('user' => $user, 'id' => $id, 'format' => 'atom');
  165. // Double-check against locally generated URLs
  166. switch ($feed) {
  167. case common_local_url('ApiTimelineList', $params):
  168. $list = Profile_list::getKV('id', $id);
  169. $user = User::getKV('id', $user);
  170. if (!$list instanceof Profile_list || !$user instanceof User || $list->tagger != $user->id) {
  171. // TRANS: Client exception. %s is a feed URL.
  172. throw new ClientException(sprintf(_m('Invalid hub.topic %s; list does not exist.'),$feed));
  173. }
  174. return true;
  175. }
  176. common_debug("Feed was not recognized by any local Profile_list Atom feed URL: {$feed}");
  177. return false;
  178. }
  179. common_debug("Unknown feed URL structure, can't match against local user, group or profile_list: {$feed}");
  180. return false;
  181. }
  182. /**
  183. * Grab and validate a URL from POST parameters.
  184. * @throws ClientException for malformed or non-http/https URLs
  185. */
  186. protected function argUrl($arg)
  187. {
  188. $url = $this->arg($arg);
  189. $params = array('domain_check' => false, // otherwise breaks my local tests :P
  190. 'allowed_schemes' => array('http', 'https'));
  191. $validate = new Validate();
  192. if ($validate->uri($url, $params)) {
  193. return $url;
  194. } else {
  195. // TRANS: Client exception.
  196. // TRANS: %1$s is this argument to the method this exception occurs in, %2$s is a URL.
  197. throw new ClientException(sprintf(_m('Invalid URL passed for %1$s: "%2$s"'),$arg,$url));
  198. }
  199. }
  200. /**
  201. * Get HubSub subscription record for a given feed & subscriber.
  202. *
  203. * @param string $feed
  204. * @param string $callback
  205. * @return mixed HubSub or false
  206. */
  207. protected function getSub($feed, $callback)
  208. {
  209. return HubSub::getByHashkey($feed, $callback);
  210. }
  211. }