3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET')) {
25 * PuSH feed subscription record
27 * @author Brion Vibber <brion@status.net>
29 class HubSub extends Managed_DataObject
31 public $__table = 'hubsub';
33 public $hashkey; // sha1(topic . '|' . $callback); (topic, callback) key is too long for myisam in utf8
43 protected static function hashkey($topic, $callback)
45 return sha1($topic . '|' . $callback);
49 * return table definition for DB_DataObject
51 * DB_DataObject needs to know something about the table to manipulate
52 * instances. This method provides all the DB_DataObject needs to know.
54 * @return array array of column definitions
58 return array('hashkey' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
59 'topic' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
60 'callback' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
61 'secret' => DB_DATAOBJECT_STR,
62 'lease' => DB_DATAOBJECT_INT,
63 'sub_start' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
64 'sub_end' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
65 'created' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL,
66 'modified' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
69 static function schemaDef()
71 return array(new ColumnDef('hashkey', 'char',
75 new ColumnDef('topic', 'varchar',
79 new ColumnDef('callback', 'varchar',
81 new ColumnDef('secret', 'text',
83 new ColumnDef('lease', 'int',
85 new ColumnDef('sub_start', 'datetime',
87 new ColumnDef('sub_end', 'datetime',
89 new ColumnDef('created', 'datetime',
91 new ColumnDef('modified', 'datetime',
97 return array_keys($this->keyTypes());
100 function sequenceKey()
102 return array(false, false, false);
106 * return key definitions for DB_DataObject
108 * DB_DataObject needs to know about keys that the table has; this function
111 * @return array key definitions
115 return array('hashkey' => 'K');
119 * Validates a requested lease length, sets length plus
120 * subscription start & end dates.
122 * Does not save to database -- use before insert() or update().
124 * @param int $length in seconds
126 function setLease($length)
128 assert(is_int($length));
134 // We want to garbage collect dead subscriptions!
136 } elseif( $length < $min) {
138 } else if ($length > $max) {
142 $this->lease = $length;
143 $this->start_sub = common_sql_now();
144 $this->end_sub = common_sql_date(time() + $length);
148 * Schedule a future verification ping to the subscriber.
149 * If queues are disabled, will be immediate.
151 * @param string $mode 'subscribe' or 'unsubscribe'
152 * @param string $token hub.verify_token value, if provided by client
154 function scheduleVerify($mode, $token=null, $retries=null)
156 if ($retries === null) {
157 $retries = intval(common_config('ostatus', 'hub_retries'));
159 $data = array('sub' => clone($this),
162 'retries' => $retries);
163 $qm = QueueManager::get();
164 $qm->enqueue($data, 'hubconf');
168 * Send a verification ping to subscriber, and if confirmed apply the changes.
169 * This may create, update, or delete the database record.
171 * @param string $mode 'subscribe' or 'unsubscribe'
172 * @param string $token hub.verify_token value, if provided by client
173 * @throws ClientException on failure
175 function verify($mode, $token=null)
177 assert($mode == 'subscribe' || $mode == 'unsubscribe');
179 $challenge = common_good_rand(32);
180 $params = array('hub.mode' => $mode,
181 'hub.topic' => $this->topic,
182 'hub.challenge' => $challenge);
183 if ($mode == 'subscribe') {
184 $params['hub.lease_seconds'] = $this->lease;
186 if ($token !== null) {
187 $params['hub.verify_token'] = $token;
190 // Any existing query string parameters must be preserved
191 $url = $this->callback;
192 if (strpos($url, '?') !== false) {
197 $url .= http_build_query($params, '', '&');
199 $request = new HTTPClient();
200 $response = $request->get($url);
201 $status = $response->getStatus();
203 if ($status >= 200 && $status < 300) {
204 common_log(LOG_INFO, "Verified $mode of $this->callback:$this->topic");
206 // TRANS: Client exception. %s is a HTTP status code.
207 throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
210 $old = HubSub::staticGet($this->topic, $this->callback);
211 if ($mode == 'subscribe') {
215 $ok = $this->insert();
217 } else if ($mode == 'unsubscribe') {
221 // That's ok, we're already unsubscribed.
227 * Insert wrapper; transparently set the hash key from topic and callback columns.
228 * @return mixed success
232 $this->hashkey = self::hashkey($this->topic, $this->callback);
233 $this->created = common_sql_now();
234 $this->modified = common_sql_now();
235 return parent::insert();
239 * Update wrapper; transparently update modified column.
240 * @return boolean success
242 function update($old=null)
244 $this->modified = common_sql_now();
245 return parent::update($old);
249 * Schedule delivery of a 'fat ping' to the subscriber's callback
250 * endpoint. If queues are disabled, this will run immediately.
252 * @param string $atom well-formed Atom feed
253 * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
255 function distribute($atom, $retries=null)
257 if ($retries === null) {
258 $retries = intval(common_config('ostatus', 'hub_retries'));
261 if (common_config('ostatus', 'local_push_bypass')) {
262 // If target is a local site, bypass the web server and drop the
263 // item directly into the target's input queue.
264 $url = parse_url($this->callback);
265 $wildcard = common_config('ostatus', 'local_wildcard');
266 $site = Status_network::getFromHostname($url['host'], $wildcard);
270 $hmac = 'sha1=' . hash_hmac('sha1', $atom, $this->secret);
275 // Hack: at the moment we stick the subscription ID in the callback
276 // URL so we don't have to look inside the Atom to route the subscription.
277 // For now this means we need to extract that from the target URL
278 // so we can include it in the data.
279 $parts = explode('/', $url['path']);
280 $subId = intval(array_pop($parts));
282 $data = array('feedsub_id' => $subId,
285 common_log(LOG_DEBUG, "Cross-site PuSH bypass enqueueing straight to $site->nickname feed $subId");
286 $qm = QueueManager::get();
287 $qm->enqueue($data, 'pushin', $site->nickname);
292 // We dare not clone() as when the clone is discarded it'll
293 // destroy the result data for the parent query.
294 // @fixme use clone() again when it's safe to copy an
295 // individual item from a multi-item query again.
296 $sub = HubSub::staticGet($this->topic, $this->callback);
297 $data = array('sub' => $sub,
299 'retries' => $retries);
300 common_log(LOG_INFO, "Queuing PuSH: $this->topic to $this->callback");
301 $qm = QueueManager::get();
302 $qm->enqueue($data, 'hubout');
306 * Queue up a large batch of pushes to multiple subscribers
307 * for this same topic update.
309 * If queues are disabled, this will run immediately.
311 * @param string $atom well-formed Atom feed
312 * @param array $pushCallbacks list of callback URLs
314 function bulkDistribute($atom, $pushCallbacks)
316 $data = array('atom' => $atom,
317 'topic' => $this->topic,
318 'pushCallbacks' => $pushCallbacks);
319 common_log(LOG_INFO, "Queuing PuSH batch: $this->topic to " .
320 count($pushCallbacks) . " sites");
321 $qm = QueueManager::get();
322 $qm->enqueue($data, 'hubprep');
326 * Send a 'fat ping' to the subscriber's callback endpoint
327 * containing the given Atom feed chunk.
329 * Determination of which items to send should be done at
330 * a higher level; don't just shove in a complete feed!
332 * @param string $atom well-formed Atom feed
333 * @throws Exception (HTTP or general)
337 $headers = array('Content-Type: application/atom+xml');
339 $hmac = hash_hmac('sha1', $atom, $this->secret);
340 $headers[] = "X-Hub-Signature: sha1=$hmac";
344 common_log(LOG_INFO, "About to push feed to $this->callback for $this->topic, HMAC $hmac");
346 $request = new HTTPClient();
347 $request->setBody($atom);
348 $response = $request->post($this->callback, $headers);
350 if ($response->isOk()) {
353 // TRANS: Exception. %1$s is a response status code, %2$s is the body of the response.
354 throw new Exception(sprintf(_m('Callback returned status: %1$s. Body: %2$s'),
355 $response->getStatus(),trim($response->getBody())));