pushhub.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. StatusNet::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. $topic = $this->argUrl('hub.topic');
  80. if (!$this->recognizedFeed($topic)) {
  81. // TRANS: Client exception. %s is a topic.
  82. throw new ClientException(sprintf(_m('Unsupported hub.topic %s this hub only serves local user and group Atom feeds.'),$topic));
  83. }
  84. $lease = $this->arg('hub.lease_seconds', null);
  85. if ($mode == 'subscribe' && $lease != '' && !preg_match('/^\d+$/', $lease)) {
  86. // TRANS: Client exception. %s is the invalid lease value.
  87. throw new ClientException(sprintf(_m('Invalid hub.lease "%s". It must be empty or positive integer.'),$lease));
  88. }
  89. $secret = $this->arg('hub.secret', null);
  90. if ($secret != '' && strlen($secret) >= 200) {
  91. // TRANS: Client exception. %s is the invalid hub secret.
  92. throw new ClientException(sprintf(_m('Invalid hub.secret "%s". It must be under 200 bytes.'),$secret));
  93. }
  94. $sub = HubSub::getByHashkey($topic, $callback);
  95. if (!$sub instanceof HubSub) {
  96. // Creating a new one!
  97. $sub = new HubSub();
  98. $sub->topic = $topic;
  99. $sub->callback = $callback;
  100. }
  101. if ($mode == 'subscribe') {
  102. if ($secret) {
  103. $sub->secret = $secret;
  104. }
  105. if ($lease) {
  106. $sub->setLease(intval($lease));
  107. }
  108. }
  109. $verify = $this->arg('hub.verify'); // TODO: deprecated
  110. $token = $this->arg('hub.verify_token', null); // TODO: deprecated
  111. if ($verify == 'sync') { // pre-0.4 PuSH
  112. $sub->verify($mode, $token);
  113. header('HTTP/1.1 204 No Content');
  114. } else { // If $verify is not "sync", we might be using PuSH 0.4
  115. $sub->scheduleVerify($mode, $token); // If we were certain it's PuSH 0.4, token could be removed
  116. header('HTTP/1.1 202 Accepted');
  117. }
  118. }
  119. /**
  120. * Check whether the given URL represents one of our canonical
  121. * user or group Atom feeds.
  122. *
  123. * @param string $feed URL
  124. * @return boolean true if it matches, false if not a recognized local feed
  125. * @throws exception if local entity does not exist
  126. */
  127. protected function recognizedFeed($feed)
  128. {
  129. $matches = array();
  130. // Simple mapping to local ID for user or group
  131. if (preg_match('!/(\d+)\.atom$!', $feed, $matches)) {
  132. $id = $matches[1];
  133. $params = array('id' => $id, 'format' => 'atom');
  134. // Double-check against locally generated URLs
  135. switch ($feed) {
  136. case common_local_url('ApiTimelineUser', $params):
  137. $user = User::getKV('id', $id);
  138. if (!$user instanceof User) {
  139. // TRANS: Client exception. %s is a feed URL.
  140. throw new ClientException(sprintf(_m('Invalid hub.topic "%s". User does not exist.'),$feed));
  141. }
  142. return true;
  143. case common_local_url('ApiTimelineGroup', $params):
  144. $group = Local_group::getKV('group_id', $id);
  145. if (!$group instanceof Local_group) {
  146. // TRANS: Client exception. %s is a feed URL.
  147. throw new ClientException(sprintf(_m('Invalid hub.topic "%s". Local_group does not exist.'),$feed));
  148. }
  149. return true;
  150. }
  151. common_debug("Feed was not recognized by any local User or Group Atom feed URLs: {$feed}");
  152. return false;
  153. }
  154. // Profile lists are unique per user, so we need both IDs
  155. if (preg_match('!/(\d+)/lists/(\d+)/statuses\.atom$!', $feed, $matches)) {
  156. $user = $matches[1];
  157. $id = $matches[2];
  158. $params = array('user' => $user, 'id' => $id, 'format' => 'atom');
  159. // Double-check against locally generated URLs
  160. switch ($feed) {
  161. case common_local_url('ApiTimelineList', $params):
  162. $list = Profile_list::getKV('id', $id);
  163. $user = User::getKV('id', $user);
  164. if (!$list instanceof Profile_list || !$user instanceof User || $list->tagger != $user->id) {
  165. // TRANS: Client exception. %s is a feed URL.
  166. throw new ClientException(sprintf(_m('Invalid hub.topic %s; list does not exist.'),$feed));
  167. }
  168. return true;
  169. }
  170. common_debug("Feed was not recognized by any local Profile_list Atom feed URL: {$feed}");
  171. return false;
  172. }
  173. common_debug("Unknown feed URL structure, can't match against local user, group or profile_list: {$feed}");
  174. return false;
  175. }
  176. /**
  177. * Grab and validate a URL from POST parameters.
  178. * @throws ClientException for malformed or non-http/https URLs
  179. */
  180. protected function argUrl($arg)
  181. {
  182. $url = $this->arg($arg);
  183. $params = array('domain_check' => false, // otherwise breaks my local tests :P
  184. 'allowed_schemes' => array('http', 'https'));
  185. $validate = new Validate;
  186. if ($validate->uri($url, $params)) {
  187. return $url;
  188. } else {
  189. // TRANS: Client exception.
  190. // TRANS: %1$s is this argument to the method this exception occurs in, %2$s is a URL.
  191. throw new ClientException(sprintf(_m('Invalid URL passed for %1$s: "%2$s"'),$arg,$url));
  192. }
  193. }
  194. /**
  195. * Get HubSub subscription record for a given feed & subscriber.
  196. *
  197. * @param string $feed
  198. * @param string $callback
  199. * @return mixed HubSub or false
  200. */
  201. protected function getSub($feed, $callback)
  202. {
  203. return HubSub::getByHashkey($feed, $callback);
  204. }
  205. }