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