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
34 public $topic; // varchar(191) not 255 because utf8mb4 takes more space
35 public $callback; // varchar(191) not 255 because utf8mb4 takes more space
43 protected static function hashkey($topic, $callback)
45 return sha1($topic . '|' . $callback);
48 public static function getByHashkey($topic, $callback)
50 return self::getKV('hashkey', self::hashkey($topic, $callback));
53 public static function schemaDef()
57 'hashkey' => array('type' => 'char', 'not null' => true, 'length' => 40, 'description' => 'HubSub hashkey'),
58 'topic' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub topic'),
59 'callback' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub callback'),
60 'secret' => array('type' => 'text', 'description' => 'HubSub stored secret'),
61 'lease' => array('type' => 'int', 'description' => 'HubSub leasetime'),
62 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
63 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
64 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
65 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
67 'primary key' => array('hashkey'),
69 'hubsub_topic_idx' => array('topic'),
75 * Validates a requested lease length, sets length plus
76 * subscription start & end dates.
78 * Does not save to database -- use before insert() or update().
80 * @param int $length in seconds
82 function setLease($length)
84 assert(is_int($length));
90 // We want to garbage collect dead subscriptions!
92 } elseif( $length < $min) {
94 } else if ($length > $max) {
98 $this->lease = $length;
99 $this->start_sub = common_sql_now();
100 $this->end_sub = common_sql_date(time() + $length);
104 * Schedule a future verification ping to the subscriber.
105 * If queues are disabled, will be immediate.
107 * @param string $mode 'subscribe' or 'unsubscribe'
108 * @param string $token hub.verify_token value, if provided by client
110 function scheduleVerify($mode, $token=null, $retries=null)
112 if ($retries === null) {
113 $retries = intval(common_config('ostatus', 'hub_retries'));
115 $data = array('sub' => clone($this),
117 'token' => $token, // let's put it in there if remote uses PuSH <0.4
118 'retries' => $retries);
119 $qm = QueueManager::get();
120 $qm->enqueue($data, 'hubconf');
124 * Send a verification ping to subscriber, and if confirmed apply the changes.
125 * This may create, update, or delete the database record.
127 * @param string $mode 'subscribe' or 'unsubscribe'
128 * @param string $token hub.verify_token value, if provided by client
129 * @throws ClientException on failure
131 function verify($mode, $token=null)
133 assert($mode == 'subscribe' || $mode == 'unsubscribe');
135 $challenge = common_random_hexstr(32);
136 $params = array('hub.mode' => $mode,
137 'hub.topic' => $this->topic,
138 'hub.challenge' => $challenge);
139 if ($mode == 'subscribe') {
140 $params['hub.lease_seconds'] = $this->lease;
142 if ($token !== null) { // TODO: deprecated in PuSH 0.4
143 $params['hub.verify_token'] = $token; // let's put it in there if remote uses PuSH <0.4
146 // Any existing query string parameters must be preserved
147 $url = $this->callback;
148 if (strpos($url, '?') !== false) {
153 $url .= http_build_query($params, '', '&');
155 $request = new HTTPClient();
156 $response = $request->get($url);
157 $status = $response->getStatus();
159 if ($status >= 200 && $status < 300) {
160 common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->topic}");
162 // TRANS: Client exception. %s is a HTTP status code.
163 throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
166 $old = HubSub::getByHashkey($this->topic, $this->callback);
167 if ($mode == 'subscribe') {
168 if ($old instanceof HubSub) {
171 $ok = $this->insert();
173 } else if ($mode == 'unsubscribe') {
174 if ($old instanceof HubSub) {
177 // That's ok, we're already unsubscribed.
183 * Insert wrapper; transparently set the hash key from topic and callback columns.
184 * @return mixed success
188 $this->hashkey = self::hashkey($this->topic, $this->callback);
189 $this->created = common_sql_now();
190 $this->modified = common_sql_now();
191 return parent::insert();
195 * Schedule delivery of a 'fat ping' to the subscriber's callback
196 * endpoint. If queues are disabled, this will run immediately.
198 * @param string $atom well-formed Atom feed
199 * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
201 function distribute($atom, $retries=null)
203 if ($retries === null) {
204 $retries = intval(common_config('ostatus', 'hub_retries'));
207 // We dare not clone() as when the clone is discarded it'll
208 // destroy the result data for the parent query.
209 // @fixme use clone() again when it's safe to copy an
210 // individual item from a multi-item query again.
211 $sub = HubSub::getByHashkey($this->topic, $this->callback);
212 $data = array('sub' => $sub,
214 'retries' => $retries);
215 common_log(LOG_INFO, "Queuing PuSH: $this->topic to $this->callback");
216 $qm = QueueManager::get();
217 $qm->enqueue($data, 'hubout');
221 * Queue up a large batch of pushes to multiple subscribers
222 * for this same topic update.
224 * If queues are disabled, this will run immediately.
226 * @param string $atom well-formed Atom feed
227 * @param array $pushCallbacks list of callback URLs
229 function bulkDistribute($atom, $pushCallbacks)
231 $data = array('atom' => $atom,
232 'topic' => $this->topic,
233 'pushCallbacks' => $pushCallbacks);
234 common_log(LOG_INFO, "Queuing PuSH batch: $this->topic to " .
235 count($pushCallbacks) . " sites");
236 $qm = QueueManager::get();
237 $qm->enqueue($data, 'hubprep');
241 * Send a 'fat ping' to the subscriber's callback endpoint
242 * containing the given Atom feed chunk.
244 * Determination of which items to send should be done at
245 * a higher level; don't just shove in a complete feed!
247 * @param string $atom well-formed Atom feed
248 * @throws Exception (HTTP or general)
252 $headers = array('Content-Type: application/atom+xml');
254 $hmac = hash_hmac('sha1', $atom, $this->secret);
255 $headers[] = "X-Hub-Signature: sha1=$hmac";
259 common_log(LOG_INFO, "About to push feed to $this->callback for $this->topic, HMAC $hmac");
261 $request = new HTTPClient();
262 $request->setBody($atom);
263 $response = $request->post($this->callback, $headers);
265 if ($response->isOk()) {
268 // TRANS: Exception. %1$s is a response status code, %2$s is the body of the response.
269 throw new Exception(sprintf(_m('Callback returned status: %1$s. Body: %2$s'),
270 $response->getStatus(),trim($response->getBody())));