]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/HubSub.php
825d36ebd64c656367a79c9a64bb1d686b04e53f
[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     function table()
58     {
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);
68     }
69
70     static function schemaDef()
71     {
72         return array(new ColumnDef('hashkey', 'char',
73                                    /*size*/40,
74                                    /*nullable*/false,
75                                    /*key*/'PRI'),
76                      new ColumnDef('topic', 'varchar',
77                                    /*size*/255,
78                                    /*nullable*/false,
79                                    /*key*/'MUL'),
80                      new ColumnDef('callback', 'varchar',
81                                    255, false),
82                      new ColumnDef('secret', 'text',
83                                    null, true),
84                      new ColumnDef('lease', 'int',
85                                    null, true),
86                      new ColumnDef('sub_start', 'datetime',
87                                    null, true),
88                      new ColumnDef('sub_end', 'datetime',
89                                    null, true),
90                      new ColumnDef('created', 'datetime',
91                                    null, false),
92                      new ColumnDef('modified', 'datetime',
93                                    null, false));
94     }
95
96     function keys()
97     {
98         return array_keys($this->keyTypes());
99     }
100
101     function sequenceKey()
102     {
103         return array(false, false, false);
104     }
105
106     /**
107      * return key definitions for DB_DataObject
108      *
109      * DB_DataObject needs to know about keys that the table has; this function
110      * defines them.
111      *
112      * @return array key definitions
113      */
114     function keyTypes()
115     {
116         return array('hashkey' => 'K');
117     }
118
119     /**
120      * Validates a requested lease length, sets length plus
121      * subscription start & end dates.
122      *
123      * Does not save to database -- use before insert() or update().
124      *
125      * @param int $length in seconds
126      */
127     function setLease($length)
128     {
129         assert(is_int($length));
130
131         $min = 86400;
132         $max = 86400 * 30;
133
134         if ($length == 0) {
135             // We want to garbage collect dead subscriptions!
136             $length = $max;
137         } elseif( $length < $min) {
138             $length = $min;
139         } else if ($length > $max) {
140             $length = $max;
141         }
142
143         $this->lease = $length;
144         $this->start_sub = common_sql_now();
145         $this->end_sub = common_sql_date(time() + $length);
146     }
147
148     /**
149      * Schedule a future verification ping to the subscriber.
150      * If queues are disabled, will be immediate.
151      *
152      * @param string $mode 'subscribe' or 'unsubscribe'
153      * @param string $token hub.verify_token value, if provided by client
154      */
155     function scheduleVerify($mode, $token=null, $retries=null)
156     {
157         if ($retries === null) {
158             $retries = intval(common_config('ostatus', 'hub_retries'));
159         }
160         $data = array('sub' => clone($this),
161                       'mode' => $mode,
162                       'token' => $token,
163                       'retries' => $retries);
164         $qm = QueueManager::get();
165         $qm->enqueue($data, 'hubconf');
166     }
167
168     /**
169      * Send a verification ping to subscriber, and if confirmed apply the changes.
170      * This may create, update, or delete the database record.
171      *
172      * @param string $mode 'subscribe' or 'unsubscribe'
173      * @param string $token hub.verify_token value, if provided by client
174      * @throws ClientException on failure
175      */
176     function verify($mode, $token=null)
177     {
178         assert($mode == 'subscribe' || $mode == 'unsubscribe');
179
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;
186         }
187         if ($token !== null) {
188             $params['hub.verify_token'] = $token;
189         }
190
191         // Any existing query string parameters must be preserved
192         $url = $this->callback;
193         if (strpos($url, '?') !== false) {
194             $url .= '&';
195         } else {
196             $url .= '?';
197         }
198         $url .= http_build_query($params, '', '&');
199
200         $request = new HTTPClient();
201         $response = $request->get($url);
202         $status = $response->getStatus();
203
204         if ($status >= 200 && $status < 300) {
205             common_log(LOG_INFO, "Verified $mode of $this->callback:$this->topic");
206         } else {
207             // TRANS: Client exception. %s is a HTTP status code.
208             throw new ClientException(sprintf(_m('Hub subscriber verification returned HTTP %s.'),$status));
209         }
210
211         $old = HubSub::staticGet($this->topic, $this->callback);
212         if ($mode == 'subscribe') {
213             if ($old) {
214                 $this->update($old);
215             } else {
216                 $ok = $this->insert();
217             }
218         } else if ($mode == 'unsubscribe') {
219             if ($old) {
220                 $old->delete();
221             } else {
222                 // That's ok, we're already unsubscribed.
223             }
224         }
225     }
226
227     /**
228      * Insert wrapper; transparently set the hash key from topic and callback columns.
229      * @return mixed success
230      */
231     function insert()
232     {
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();
237     }
238
239     /**
240      * Update wrapper; transparently update modified column.
241      * @return boolean success
242      */
243     function update($old=null)
244     {
245         $this->modified = common_sql_now();
246         return parent::update($old);
247     }
248
249     /**
250      * Schedule delivery of a 'fat ping' to the subscriber's callback
251      * endpoint. If queues are disabled, this will run immediately.
252      *
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
255      */
256     function distribute($atom, $retries=null)
257     {
258         if ($retries === null) {
259             $retries = intval(common_config('ostatus', 'hub_retries'));
260         }
261
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);
268
269             if ($site) {
270                 if ($this->secret) {
271                     $hmac = 'sha1=' . hash_hmac('sha1', $atom, $this->secret);
272                 } else {
273                     $hmac = '';
274                 }
275
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));
282
283                 $data = array('feedsub_id' => $subId,
284                               'post' => $atom,
285                               'hmac' => $hmac);
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);
289                 return;
290             }
291         }
292
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,
299                       'atom' => $atom,
300                       'retries' => $retries);
301         common_log(LOG_INFO, "Queuing PuSH: $this->topic to $this->callback");
302         $qm = QueueManager::get();
303         $qm->enqueue($data, 'hubout');
304     }
305
306     /**
307      * Queue up a large batch of pushes to multiple subscribers
308      * for this same topic update.
309      *
310      * If queues are disabled, this will run immediately.
311      *
312      * @param string $atom well-formed Atom feed
313      * @param array $pushCallbacks list of callback URLs
314      */
315     function bulkDistribute($atom, $pushCallbacks)
316     {
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');
324     }
325
326     /**
327      * Send a 'fat ping' to the subscriber's callback endpoint
328      * containing the given Atom feed chunk.
329      *
330      * Determination of which items to send should be done at
331      * a higher level; don't just shove in a complete feed!
332      *
333      * @param string $atom well-formed Atom feed
334      * @throws Exception (HTTP or general)
335      */
336     function push($atom)
337     {
338         $headers = array('Content-Type: application/atom+xml');
339         if ($this->secret) {
340             $hmac = hash_hmac('sha1', $atom, $this->secret);
341             $headers[] = "X-Hub-Signature: sha1=$hmac";
342         } else {
343             $hmac = '(none)';
344         }
345         common_log(LOG_INFO, "About to push feed to $this->callback for $this->topic, HMAC $hmac");
346
347         $request = new HTTPClient();
348         $request->setBody($atom);
349         $response = $request->post($this->callback, $headers);
350
351         if ($response->isOk()) {
352             return true;
353         } else {
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())));
357         }
358     }
359 }