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/>.
21 * PuSH feed subscription record
23 * @author Brion Vibber <brion@status.net>
25 class HubSub extends Memcached_DataObject
27 public $__table = 'hubsub';
29 public $hashkey; // sha1(topic . '|' . $callback); (topic, callback) key is too long for myisam in utf8
39 public /*static*/ function staticGet($topic, $callback)
41 return parent::staticGet(__CLASS__, 'hashkey', self::hashkey($topic, $callback));
44 protected static function hashkey($topic, $callback)
46 return sha1($topic . '|' . $callback);
50 * return table definition for DB_DataObject
52 * DB_DataObject needs to know something about the table to manipulate
53 * instances. This method provides all the DB_DataObject needs to know.
55 * @return array array of column definitions
59 return array('hashkey' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
60 'topic' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
61 'callback' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
62 'secret' => DB_DATAOBJECT_STR,
63 'lease' => DB_DATAOBJECT_INT,
64 'sub_start' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
65 'sub_end' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME,
66 'created' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL,
67 'modified' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
70 static function schemaDef()
72 return array(new ColumnDef('hashkey', 'char',
76 new ColumnDef('topic', 'varchar',
80 new ColumnDef('callback', 'varchar',
82 new ColumnDef('secret', 'text',
84 new ColumnDef('lease', 'int',
86 new ColumnDef('sub_start', 'datetime',
88 new ColumnDef('sub_end', 'datetime',
90 new ColumnDef('created', 'datetime',
92 new ColumnDef('modified', 'datetime',
98 return array_keys($this->keyTypes());
101 function sequenceKey()
103 return array(false, false, false);
107 * return key definitions for DB_DataObject
109 * DB_DataObject needs to know about keys that the table has; this function
112 * @return array key definitions
116 return array('hashkey' => 'K');
120 * Validates a requested lease length, sets length plus
121 * subscription start & end dates.
123 * Does not save to database -- use before insert() or update().
125 * @param int $length in seconds
127 function setLease($length)
129 assert(is_int($length));
135 // We want to garbage collect dead subscriptions!
137 } elseif( $length < $min) {
139 } else if ($length > $max) {
143 $this->lease = $length;
144 $this->start_sub = common_sql_now();
145 $this->end_sub = common_sql_date(time() + $length);
149 * Schedule a future verification ping to the subscriber.
150 * If queues are disabled, will be immediate.
152 * @param string $mode 'subscribe' or 'unsubscribe'
153 * @param string $token hub.verify_token value, if provided by client
155 function scheduleVerify($mode, $token=null, $retries=null)
157 if ($retries === null) {
158 $retries = intval(common_config('ostatus', 'hub_retries'));
160 $data = array('sub' => clone($this),
163 'retries' => $retries);
164 $qm = QueueManager::get();
165 $qm->enqueue($data, 'hubconf');
169 * Send a verification ping to subscriber, and if confirmed apply the changes.
170 * This may create, update, or delete the database record.
172 * @param string $mode 'subscribe' or 'unsubscribe'
173 * @param string $token hub.verify_token value, if provided by client
174 * @throws ClientException on failure
176 function verify($mode, $token=null)
178 assert($mode == 'subscribe' || $mode == 'unsubscribe');
180 $challenge = common_good_rand(32);
181 $params = array('hub.mode' => $mode,
182 'hub.topic' => $this->topic,
183 'hub.challenge' => $challenge);
184 if ($mode == 'subscribe') {
185 $params['hub.lease_seconds'] = $this->lease;
187 if ($token !== null) {
188 $params['hub.verify_token'] = $token;
191 // Any existing query string parameters must be preserved
192 $url = $this->callback;
193 if (strpos($url, '?') !== false) {
198 $url .= http_build_query($params, '', '&');
200 $request = new HTTPClient();
201 $response = $request->get($url);
202 $status = $response->getStatus();
204 if ($status >= 200 && $status < 300) {
205 common_log(LOG_INFO, "Verified $mode of $this->callback:$this->topic");
207 // TRANS: Client exception. %s is a HTTP status code.
208 throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
211 $old = HubSub::staticGet($this->topic, $this->callback);
212 if ($mode == 'subscribe') {
216 $ok = $this->insert();
218 } else if ($mode == 'unsubscribe') {
222 // That's ok, we're already unsubscribed.
228 * Insert wrapper; transparently set the hash key from topic and callback columns.
229 * @return mixed success
233 $this->hashkey = self::hashkey($this->topic, $this->callback);
234 $this->created = common_sql_now();
235 $this->modified = common_sql_now();
236 return parent::insert();
240 * Update wrapper; transparently update modified column.
241 * @return boolean success
243 function update($old=null)
245 $this->modified = common_sql_now();
246 return parent::update($old);
250 * Schedule delivery of a 'fat ping' to the subscriber's callback
251 * endpoint. If queues are disabled, this will run immediately.
253 * @param string $atom well-formed Atom feed
254 * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
256 function distribute($atom, $retries=null)
258 if ($retries === null) {
259 $retries = intval(common_config('ostatus', 'hub_retries'));
262 if (common_config('ostatus', 'local_push_bypass')) {
263 // If target is a local site, bypass the web server and drop the
264 // item directly into the target's input queue.
265 $url = parse_url($this->callback);
266 $wildcard = common_config('ostatus', 'local_wildcard');
267 $site = Status_network::getFromHostname($url['host'], $wildcard);
271 $hmac = 'sha1=' . hash_hmac('sha1', $atom, $this->secret);
276 // Hack: at the moment we stick the subscription ID in the callback
277 // URL so we don't have to look inside the Atom to route the subscription.
278 // For now this means we need to extract that from the target URL
279 // so we can include it in the data.
280 $parts = explode('/', $url['path']);
281 $subId = intval(array_pop($parts));
283 $data = array('feedsub_id' => $subId,
286 common_log(LOG_DEBUG, "Cross-site PuSH bypass enqueueing straight to $site->nickname feed $subId");
287 $qm = QueueManager::get();
288 $qm->enqueue($data, 'pushin', $site->nickname);
293 // We dare not clone() as when the clone is discarded it'll
294 // destroy the result data for the parent query.
295 // @fixme use clone() again when it's safe to copy an
296 // individual item from a multi-item query again.
297 $sub = HubSub::staticGet($this->topic, $this->callback);
298 $data = array('sub' => $sub,
300 'retries' => $retries);
301 common_log(LOG_INFO, "Queuing PuSH: $this->topic to $this->callback");
302 $qm = QueueManager::get();
303 $qm->enqueue($data, 'hubout');
307 * Queue up a large batch of pushes to multiple subscribers
308 * for this same topic update.
310 * If queues are disabled, this will run immediately.
312 * @param string $atom well-formed Atom feed
313 * @param array $pushCallbacks list of callback URLs
315 function bulkDistribute($atom, $pushCallbacks)
317 $data = array('atom' => $atom,
318 'topic' => $this->topic,
319 'pushCallbacks' => $pushCallbacks);
320 common_log(LOG_INFO, "Queuing PuSH batch: $this->topic to " .
321 count($pushCallbacks) . " sites");
322 $qm = QueueManager::get();
323 $qm->enqueue($data, 'hubprep');
327 * Send a 'fat ping' to the subscriber's callback endpoint
328 * containing the given Atom feed chunk.
330 * Determination of which items to send should be done at
331 * a higher level; don't just shove in a complete feed!
333 * @param string $atom well-formed Atom feed
334 * @throws Exception (HTTP or general)
338 $headers = array('Content-Type: application/atom+xml');
340 $hmac = hash_hmac('sha1', $atom, $this->secret);
341 $headers[] = "X-Hub-Signature: sha1=$hmac";
345 common_log(LOG_INFO, "About to push feed to $this->callback for $this->topic, HMAC $hmac");
347 $request = new HTTPClient();
348 $request->setBody($atom);
349 $response = $request->post($this->callback, $headers);
351 if ($response->isOk()) {
354 // TRANS: Exception. %1$s is a response status code, %2$s is the body of the response.
355 throw new Exception(sprintf(_m('Callback returned status: %1$s. Body: %2$s'),
356 $response->getStatus(),trim($response->getBody())));