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