]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/HubSub.php
IMPORTANT - fixed HubSub to properly fetch primary keys
[quix0rs-gnu-social.git] / plugins / OStatus / classes / HubSub.php
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 if (!defined('STATUSNET')) {
21     exit(1);
22 }
23
24 /**
25  * PuSH feed subscription record
26  * @package Hub
27  * @author Brion Vibber <brion@status.net>
28  */
29 class HubSub extends Managed_DataObject
30 {
31     public $__table = 'hubsub';
32
33     public $hashkey; // sha1(topic . '|' . $callback); (topic, callback) key is too long for myisam in utf8
34     public $topic;
35     public $callback;
36     public $secret;
37     public $lease;
38     public $sub_start;
39     public $sub_end;
40     public $created;
41     public $modified;
42
43     protected static function hashkey($topic, $callback)
44     {
45         return sha1($topic . '|' . $callback);
46     }
47
48     public static function getByHashkey($topic, $callback)
49     {
50         return self::getKV('hashkey', self::hashkey($topic, $callback));
51     }
52
53     public static function schemaDef()
54     {
55         return array(
56             'fields' => array(
57                 'hashkey' => array('type' => 'char', 'not null' => true, 'length' => 40, 'description' => 'HubSub hashkey'),
58                 'topic' => array('type' => 'varchar', 'not null' => true, 'length' => 255, 'description' => 'HubSub topic'),
59                 'callback' => array('type' => 'varchar', 'not null' => true, 'length' => 255, 'description' => 'HubSub callback'),
60                 'secret' => array('type' => 'text', 'description' => 'HubSub stored secret'),
61                 'lease' => array('type' => 'int', 'not null' => true, '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'),
66             ),
67             'primary key' => array('hashkey'),
68             'indexes' => array(
69                 'hubsub_topic_idx' => array('topic'),
70             ),
71         );
72     }
73
74     /**
75      * Validates a requested lease length, sets length plus
76      * subscription start & end dates.
77      *
78      * Does not save to database -- use before insert() or update().
79      *
80      * @param int $length in seconds
81      */
82     function setLease($length)
83     {
84         assert(is_int($length));
85
86         $min = 86400;
87         $max = 86400 * 30;
88
89         if ($length == 0) {
90             // We want to garbage collect dead subscriptions!
91             $length = $max;
92         } elseif( $length < $min) {
93             $length = $min;
94         } else if ($length > $max) {
95             $length = $max;
96         }
97
98         $this->lease = $length;
99         $this->start_sub = common_sql_now();
100         $this->end_sub = common_sql_date(time() + $length);
101     }
102
103     /**
104      * Schedule a future verification ping to the subscriber.
105      * If queues are disabled, will be immediate.
106      *
107      * @param string $mode 'subscribe' or 'unsubscribe'
108      * @param string $token hub.verify_token value, if provided by client
109      */
110     function scheduleVerify($mode, $token=null, $retries=null)
111     {
112         if ($retries === null) {
113             $retries = intval(common_config('ostatus', 'hub_retries'));
114         }
115         $data = array('sub' => clone($this),
116                       'mode' => $mode,
117                       'token' => $token,
118                       'retries' => $retries);
119         $qm = QueueManager::get();
120         $qm->enqueue($data, 'hubconf');
121     }
122
123     /**
124      * Send a verification ping to subscriber, and if confirmed apply the changes.
125      * This may create, update, or delete the database record.
126      *
127      * @param string $mode 'subscribe' or 'unsubscribe'
128      * @param string $token hub.verify_token value, if provided by client
129      * @throws ClientException on failure
130      */
131     function verify($mode, $token=null)
132     {
133         assert($mode == 'subscribe' || $mode == 'unsubscribe');
134
135         $challenge = common_good_rand(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;
141         }
142         if ($token !== null) {
143             $params['hub.verify_token'] = $token;
144         }
145
146         // Any existing query string parameters must be preserved
147         $url = $this->callback;
148         if (strpos($url, '?') !== false) {
149             $url .= '&';
150         } else {
151             $url .= '?';
152         }
153         $url .= http_build_query($params, '', '&');
154
155         $request = new HTTPClient();
156         $response = $request->get($url);
157         $status = $response->getStatus();
158
159         if ($status >= 200 && $status < 300) {
160             common_log(LOG_INFO, "Verified $mode of $this->callback:$this->topic");
161         } else {
162             // TRANS: Client exception. %s is a HTTP status code.
163             throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
164         }
165
166         $old = HubSub::getByHashkey($this->topic, $this->callback);
167         if ($mode == 'subscribe') {
168             if ($old) {
169                 $this->update($old);
170             } else {
171                 $ok = $this->insert();
172             }
173         } else if ($mode == 'unsubscribe') {
174             if ($old) {
175                 $old->delete();
176             } else {
177                 // That's ok, we're already unsubscribed.
178             }
179         }
180     }
181
182     /**
183      * Insert wrapper; transparently set the hash key from topic and callback columns.
184      * @return mixed success
185      */
186     function insert()
187     {
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();
192     }
193
194     /**
195      * Update wrapper; transparently update modified column.
196      * @return boolean success
197      */
198     function update($old=null)
199     {
200         $this->modified = common_sql_now();
201         return parent::update($old);
202     }
203
204     /**
205      * Schedule delivery of a 'fat ping' to the subscriber's callback
206      * endpoint. If queues are disabled, this will run immediately.
207      *
208      * @param string $atom well-formed Atom feed
209      * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
210      */
211     function distribute($atom, $retries=null)
212     {
213         if ($retries === null) {
214             $retries = intval(common_config('ostatus', 'hub_retries'));
215         }
216
217         if (common_config('ostatus', 'local_push_bypass')) {
218             // If target is a local site, bypass the web server and drop the
219             // item directly into the target's input queue.
220             $url = parse_url($this->callback);
221             $wildcard = common_config('ostatus', 'local_wildcard');
222             $site = Status_network::getFromHostname($url['host'], $wildcard);
223
224             if ($site) {
225                 if ($this->secret) {
226                     $hmac = 'sha1=' . hash_hmac('sha1', $atom, $this->secret);
227                 } else {
228                     $hmac = '';
229                 }
230
231                 // Hack: at the moment we stick the subscription ID in the callback
232                 // URL so we don't have to look inside the Atom to route the subscription.
233                 // For now this means we need to extract that from the target URL
234                 // so we can include it in the data.
235                 $parts = explode('/', $url['path']);
236                 $subId = intval(array_pop($parts));
237
238                 $data = array('feedsub_id' => $subId,
239                               'post' => $atom,
240                               'hmac' => $hmac);
241                 common_log(LOG_DEBUG, "Cross-site PuSH bypass enqueueing straight to $site->nickname feed $subId");
242                 $qm = QueueManager::get();
243                 $qm->enqueue($data, 'pushin', $site->nickname);
244                 return;
245             }
246         }
247
248         // We dare not clone() as when the clone is discarded it'll
249         // destroy the result data for the parent query.
250         // @fixme use clone() again when it's safe to copy an
251         // individual item from a multi-item query again.
252         $sub = HubSub::getByHashkey($this->topic, $this->callback);
253         $data = array('sub' => $sub,
254                       'atom' => $atom,
255                       'retries' => $retries);
256         common_log(LOG_INFO, "Queuing PuSH: $this->topic to $this->callback");
257         $qm = QueueManager::get();
258         $qm->enqueue($data, 'hubout');
259     }
260
261     /**
262      * Queue up a large batch of pushes to multiple subscribers
263      * for this same topic update.
264      *
265      * If queues are disabled, this will run immediately.
266      *
267      * @param string $atom well-formed Atom feed
268      * @param array $pushCallbacks list of callback URLs
269      */
270     function bulkDistribute($atom, $pushCallbacks)
271     {
272         $data = array('atom' => $atom,
273                       'topic' => $this->topic,
274                       'pushCallbacks' => $pushCallbacks);
275         common_log(LOG_INFO, "Queuing PuSH batch: $this->topic to " .
276                              count($pushCallbacks) . " sites");
277         $qm = QueueManager::get();
278         $qm->enqueue($data, 'hubprep');
279     }
280
281     /**
282      * Send a 'fat ping' to the subscriber's callback endpoint
283      * containing the given Atom feed chunk.
284      *
285      * Determination of which items to send should be done at
286      * a higher level; don't just shove in a complete feed!
287      *
288      * @param string $atom well-formed Atom feed
289      * @throws Exception (HTTP or general)
290      */
291     function push($atom)
292     {
293         $headers = array('Content-Type: application/atom+xml');
294         if ($this->secret) {
295             $hmac = hash_hmac('sha1', $atom, $this->secret);
296             $headers[] = "X-Hub-Signature: sha1=$hmac";
297         } else {
298             $hmac = '(none)';
299         }
300         common_log(LOG_INFO, "About to push feed to $this->callback for $this->topic, HMAC $hmac");
301
302         $request = new HTTPClient();
303         $request->setBody($atom);
304         $response = $request->post($this->callback, $headers);
305
306         if ($response->isOk()) {
307             return true;
308         } else {
309             // TRANS: Exception. %1$s is a response status code, %2$s is the body of the response.
310             throw new Exception(sprintf(_m('Callback returned status: %1$s. Body: %2$s'),
311                                 $response->getStatus(),trim($response->getBody())));
312         }
313     }
314 }