]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/HubSub.php
Merge branch 'delete_group_logo' into 'nightly'
[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;      // varchar(191)   not 255 because utf8mb4 takes more space
35     public $callback;   // varchar(191)   not 255 because utf8mb4 takes more space
36     public $secret;
37     public $sub_start;
38     public $sub_end;
39     public $created;
40     public $modified;
41
42     static function hashkey($topic, $callback)
43     {
44         return sha1($topic . '|' . $callback);
45     }
46
47     public static function getByHashkey($topic, $callback)
48     {
49         return self::getKV('hashkey', self::hashkey($topic, $callback));
50     }
51
52     public static function schemaDef()
53     {
54         return array(
55             'fields' => array(
56                 'hashkey' => array('type' => 'char', 'not null' => true, 'length' => 40, 'description' => 'HubSub hashkey'),
57                 'topic' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub topic'),
58                 'callback' => array('type' => 'varchar', 'not null' => true, 'length' => 191, 'description' => 'HubSub callback'),
59                 'secret' => array('type' => 'text', 'description' => 'HubSub stored secret'),
60                 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
61                 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
62                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
63                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
64             ),
65             'primary key' => array('hashkey'),
66             'indexes' => array(
67                 'hubsub_callback_idx' => array('callback'),
68                 'hubsub_topic_idx' => array('topic'),
69             ),
70         );
71     }
72
73     /**
74      * Validates a requested lease length, sets length plus
75      * subscription start & end dates.
76      *
77      * Does not save to database -- use before insert() or update().
78      *
79      * @param int $length in seconds
80      */
81     function setLease($length)
82     {
83         common_debug('PuSH hub got requested lease_seconds=='._ve($length));
84         assert(is_int($length));
85
86         $min = 86400;   // 3600*24 (one day)
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         common_debug('PuSH hub after sanitation: lease_seconds=='._ve($length));
99         $this->sub_start = common_sql_now();
100         $this->sub_end = common_sql_date(time() + $length);
101     }
102
103     function getLeaseTime()
104     {
105         if (empty($this->sub_start) || empty($this->sub_end)) {
106             return null;
107         }
108         $length = strtotime($this->sub_end) - strtotime($this->sub_start);
109         assert($length > 0);
110         return $length;
111     }
112
113     function getLeaseRemaining()
114     {
115         if (empty($this->sub_end)) {
116             return null;
117         }
118         return strtotime($this->sub_end) - time();
119     }
120
121     /**
122      * Schedule a future verification ping to the subscriber.
123      * If queues are disabled, will be immediate.
124      *
125      * @param string $mode 'subscribe' or 'unsubscribe'
126      * @param string $token hub.verify_token value, if provided by client
127      */
128     function scheduleVerify($mode, $token=null, $retries=null)
129     {
130         if ($retries === null) {
131             $retries = intval(common_config('ostatus', 'hub_retries'));
132         }
133         $data = array('sub' => clone($this),
134                       'mode' => $mode,
135                       'token' => $token,    // let's put it in there if remote uses PuSH <0.4
136                       'retries' => $retries);
137         $qm = QueueManager::get();
138         $qm->enqueue($data, 'hubconf');
139     }
140
141     public function getTopic()
142     {
143         return $this->topic;
144     }
145
146     /**
147      * Send a verification ping to subscriber, and if confirmed apply the changes.
148      * This may create, update, or delete the database record.
149      *
150      * @param string $mode 'subscribe' or 'unsubscribe'
151      * @param string $token hub.verify_token value, if provided by client
152      * @throws ClientException on failure
153      */
154     function verify($mode, $token=null)
155     {
156         assert($mode == 'subscribe' || $mode == 'unsubscribe');
157
158         $challenge = common_random_hexstr(32);
159         $params = array('hub.mode' => $mode,
160                         'hub.topic' => $this->getTopic(),
161                         'hub.challenge' => $challenge);
162         if ($mode == 'subscribe') {
163             $params['hub.lease_seconds'] = $this->getLeaseTime();
164         }
165         if ($token !== null) {  // TODO: deprecated in PuSH 0.4
166             $params['hub.verify_token'] = $token;   // let's put it in there if remote uses PuSH <0.4
167         }
168
169         // Any existing query string parameters must be preserved
170         $url = $this->callback;
171         if (strpos($url, '?') !== false) {
172             $url .= '&';
173         } else {
174             $url .= '?';
175         }
176         $url .= http_build_query($params, '', '&');
177
178         $request = new HTTPClient();
179         $response = $request->get($url);
180         $status = $response->getStatus();
181
182         if ($status >= 200 && $status < 300) {
183             common_log(LOG_INFO, "Verified {$mode} of {$this->callback}:{$this->getTopic()}");
184         } else {
185             // TRANS: Client exception. %s is a HTTP status code.
186             throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
187         }
188
189         $old = HubSub::getByHashkey($this->getTopic(), $this->callback);
190         if ($mode == 'subscribe') {
191             if ($old instanceof HubSub) {
192                 $this->update($old);
193             } else {
194                 $ok = $this->insert();
195             }
196         } else if ($mode == 'unsubscribe') {
197             if ($old instanceof HubSub) {
198                 $old->delete();
199             } else {
200                 // That's ok, we're already unsubscribed.
201             }
202         }
203     }
204
205     /**
206      * Insert wrapper; transparently set the hash key from topic and callback columns.
207      * @return mixed success
208      */
209     function insert()
210     {
211         $this->hashkey = self::hashkey($this->getTopic(), $this->callback);
212         $this->created = common_sql_now();
213         $this->modified = common_sql_now();
214         return parent::insert();
215     }
216
217     /**
218      * Schedule delivery of a 'fat ping' to the subscriber's callback
219      * endpoint. If queues are disabled, this will run immediately.
220      *
221      * @param string $atom well-formed Atom feed
222      * @param int $retries optional count of retries if POST fails; defaults to hub_retries from config or 0 if unset
223      */
224     function distribute($atom, $retries=null)
225     {
226         if ($retries === null) {
227             $retries = intval(common_config('ostatus', 'hub_retries'));
228         }
229
230         // We dare not clone() as when the clone is discarded it'll
231         // destroy the result data for the parent query.
232         // @fixme use clone() again when it's safe to copy an
233         // individual item from a multi-item query again.
234         $sub = HubSub::getByHashkey($this->getTopic(), $this->callback);
235         $data = array('sub' => $sub,
236                       'atom' => $atom,
237                       'retries' => $retries);
238         common_log(LOG_INFO, "Queuing PuSH: {$this->getTopic()} to {$this->callback}");
239         $qm = QueueManager::get();
240         $qm->enqueue($data, 'hubout');
241     }
242
243     /**
244      * Queue up a large batch of pushes to multiple subscribers
245      * for this same topic update.
246      *
247      * If queues are disabled, this will run immediately.
248      *
249      * @param string $atom well-formed Atom feed
250      * @param array $pushCallbacks list of callback URLs
251      */
252     function bulkDistribute($atom, array $pushCallbacks)
253     {
254         if (empty($pushCallbacks)) {
255             common_log(LOG_ERR, 'Callback list empty for bulkDistribute.');
256             return false;
257         }
258         $data = array('atom' => $atom,
259                       'topic' => $this->getTopic(),
260                       'pushCallbacks' => $pushCallbacks);
261         common_log(LOG_INFO, "Queuing PuSH batch: {$this->getTopic()} to ".count($pushCallbacks)." sites");
262         $qm = QueueManager::get();
263         $qm->enqueue($data, 'hubprep');
264         return true;
265     }
266
267     /**
268      * Send a 'fat ping' to the subscriber's callback endpoint
269      * containing the given Atom feed chunk.
270      *
271      * Determination of which items to send should be done at
272      * a higher level; don't just shove in a complete feed!
273      *
274      * @param string $atom well-formed Atom feed
275      * @throws Exception (HTTP or general)
276      */
277     function push($atom)
278     {
279         $headers = array('Content-Type: application/atom+xml');
280         if ($this->secret) {
281             $hmac = hash_hmac('sha1', $atom, $this->secret);
282             $headers[] = "X-Hub-Signature: sha1=$hmac";
283         } else {
284             $hmac = '(none)';
285         }
286         common_log(LOG_INFO, "About to push feed to $this->callback for {$this->getTopic()}, HMAC $hmac");
287
288         $request = new HTTPClient();
289         $request->setConfig(array('follow_redirects' => false));
290         $request->setBody($atom);
291         try {
292             $response = $request->post($this->callback, $headers);
293
294             if ($response->isOk()) {
295                 return true;
296             }
297         } catch (Exception $e) {
298             $response = null;
299
300             common_debug('PuSH callback to '._ve($this->callback).' for '._ve($this->getTopic()).' failed with exception: '._ve($e->getMessage()));
301         }
302
303         // XXX: DO NOT trust a Location header here, _especially_ from 'http' protocols,
304         // but not 'https' either at least if we don't do proper CA verification. Trust that
305         // the most common change here is simply switching 'http' to 'https' and we will
306         // solve 99% of all of these issues for now. There should be a proper mechanism
307         // if we want to change the callback URLs, preferrably just manual resubscriptions
308         // from the remote side, combined with implemented PuSH subscription timeouts.
309
310         // We failed the PuSH, but it might be that the remote site has changed their configuration to HTTPS
311         if ('http' === parse_url($this->callback, PHP_URL_SCHEME)) {
312             // Test if the feed callback for this node has migrated to HTTPS
313             $httpscallback = preg_replace('/^http/', 'https', $this->callback, 1);
314             $alreadyreplaced = self::getByHashKey($this->getTopic(), $httpscallback);
315             if ($alreadyreplaced instanceof HubSub) {
316                 $this->delete();
317                 throw new AlreadyFulfilledException('The remote side has already established an HTTPS callback, deleting the legacy HTTP entry.');
318             }
319
320             common_debug('PuSH callback to '._ve($this->callback).' for '._ve($this->getTopic()).' trying HTTPS callback: '._ve($httpscallback));
321             $response = $request->post($httpscallback, $headers);
322             if ($response->isOk()) {
323                 $orig = clone($this);
324                 $this->callback = $httpscallback;
325                 $this->hashkey = self::hashkey($this->getTopic(), $this->callback);
326                 $this->updateWithKeys($orig);
327                 return true;
328             }
329         }
330
331         // FIXME: Add 'failed' incremental count for this callback.
332
333         if (is_null($response)) {
334             // This means we got a lower-than-HTTP level error, like domain not found or maybe connection refused
335             // This should be using a more distinguishable exception class, but for now this will do.
336             throw new Exception(sprintf(_m('HTTP request failed without response to URL: %s'), _ve(isset($httpscallback) ? $httpscallback : $this->callback)));
337         }
338
339         // TRANS: Exception. %1$s is a response status code, %2$s is the body of the response.
340         throw new Exception(sprintf(_m('Callback returned status: %1$s. Body: %2$s'),
341                             $response->getStatus(),trim($response->getBody())));
342     }
343 }