]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/FeedSub.php
Add functions to avoid direct variable access
[quix0rs-gnu-social.git] / plugins / OStatus / classes / FeedSub.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009-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  * @package OStatusPlugin
26  * @maintainer Brion Vibber <brion@status.net>
27  */
28
29 /*
30 PuSH subscription flow:
31
32     $profile->subscribe()
33         sends a sub request to the hub...
34
35     main/push/callback
36         hub sends confirmation back to us via GET
37         We verify the request, then echo back the challenge.
38         On our end, we save the time we subscribed and the lease expiration
39
40     main/push/callback
41         hub sends us updates via POST
42
43 */
44 class FeedDBException extends FeedSubException
45 {
46     public $obj;
47
48     function __construct($obj)
49     {
50         parent::__construct('Database insert failure');
51         $this->obj = $obj;
52     }
53 }
54
55 /**
56  * FeedSub handles low-level PubHubSubbub (PuSH) subscriptions.
57  * Higher-level behavior building OStatus stuff on top is handled
58  * under Ostatus_profile.
59  */
60 class FeedSub extends Managed_DataObject
61 {
62     public $__table = 'feedsub';
63
64     public $id;
65     public $uri;
66
67     // PuSH subscription data
68     public $huburi;
69     public $secret;
70     public $sub_state; // subscribe, active, unsubscribe, inactive
71     public $sub_start;
72     public $sub_end;
73     public $last_update;
74
75     public $created;
76     public $modified;
77
78     public static function schemaDef()
79     {
80         return array(
81             'fields' => array(
82                 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'FeedSub local unique id'),
83                 'uri' => array('type' => 'varchar', 'not null' => true, 'length' => 255, 'description' => 'FeedSub uri'),
84                 'huburi' => array('type' => 'text', 'description' => 'FeedSub hub-uri'),
85                 'secret' => array('type' => 'text', 'description' => 'FeedSub stored secret'),
86                 'sub_state' => array('type' => 'enum("subscribe","active","unsubscribe","inactive")', 'not null' => true, 'description' => 'subscription state'),
87                 'sub_start' => array('type' => 'datetime', 'description' => 'subscription start'),
88                 'sub_end' => array('type' => 'datetime', 'description' => 'subscription end'),
89                 'last_update' => array('type' => 'datetime', 'not null' => true, 'description' => 'when this record was last updated'),
90                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
91                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
92             ),
93             'primary key' => array('id'),
94             'unique keys' => array(
95                 'feedsub_uri_key' => array('uri'),
96             ),
97         );
98     }
99
100     /**
101      * Get the feed uri (http/https)
102      */
103     public function getUri()
104     {
105         if (empty($this->uri)) {
106             throw new ServerException('No URI for FeedSub entry');
107         }
108         return $this->uri;
109     }
110
111     /**
112      * Do we have a hub? Then we are a PuSH feed.
113      * https://en.wikipedia.org/wiki/PubSubHubbub
114      *
115      * NOTE: does not respect if we have a fallback_hub configured
116      */
117     public function isPuSH()
118     {
119         return !empty($this->huburi);
120     }
121
122     /**
123      * Fetch the StatusNet-side profile for this feed
124      * @return Profile
125      */
126     public function localProfile()
127     {
128         if ($this->profile_id) {
129             return Profile::getKV('id', $this->profile_id);
130         }
131         return null;
132     }
133
134     /**
135      * Fetch the StatusNet-side profile for this feed
136      * @return Profile
137      */
138     public function localGroup()
139     {
140         if ($this->group_id) {
141             return User_group::getKV('id', $this->group_id);
142         }
143         return null;
144     }
145
146     /**
147      * @param string $feeduri
148      * @return FeedSub
149      * @throws FeedSubException if feed is invalid or lacks PuSH setup
150      */
151     public static function ensureFeed($feeduri)
152     {
153         $current = self::getKV('uri', $feeduri);
154         if ($current instanceof FeedSub) {
155             return $current;
156         }
157
158         $discover = new FeedDiscovery();
159         $discover->discoverFromFeedURL($feeduri);
160
161         $huburi = $discover->getHubLink();
162         if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
163             throw new FeedSubNoHubException();
164         }
165
166         $feedsub = new FeedSub();
167         $feedsub->uri = $feeduri;
168         $feedsub->huburi = $huburi;
169         $feedsub->sub_state = 'inactive';
170
171         $feedsub->created = common_sql_now();
172         $feedsub->modified = common_sql_now();
173
174         $result = $feedsub->insert();
175         if ($result === false) {
176             throw new FeedDBException($feedsub);
177         }
178
179         return $feedsub;
180     }
181
182     /**
183      * Send a subscription request to the hub for this feed.
184      * The hub will later send us a confirmation POST to /main/push/callback.
185      *
186      * @return bool true on success, false on failure
187      * @throws ServerException if feed state is not valid
188      */
189     public function subscribe()
190     {
191         if ($this->sub_state && $this->sub_state != 'inactive') {
192             common_log(LOG_WARNING, "Attempting to (re)start PuSH subscription to {$this->uri} in unexpected state {$this->sub_state}");
193         }
194
195         if (!Event::handle('FeedSubscribe', array($this))) {
196             // A plugin handled it
197             return true;
198         }
199
200         if (empty($this->huburi)) {
201             if (common_config('feedsub', 'fallback_hub')) {
202                 // No native hub on this feed?
203                 // Use our fallback hub, which handles polling on our behalf.
204             } else if (common_config('feedsub', 'nohub')) {
205                 // Fake it! We're just testing remote feeds w/o hubs.
206                 // We'll never actually get updates in this mode.
207                 return true;
208             } else {
209                 // TRANS: Server exception.
210                 throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
211             }
212         }
213
214         return $this->doSubscribe('subscribe');
215     }
216
217     /**
218      * Send a PuSH unsubscription request to the hub for this feed.
219      * The hub will later send us a confirmation POST to /main/push/callback.
220      * Warning: this will cancel the subscription even if someone else in
221      * the system is using it. Most callers will want garbageCollect() instead,
222      * which confirms there's no uses left.
223      *
224      * @return bool true on success, false on failure
225      * @throws ServerException if feed state is not valid
226      */
227     public function unsubscribe() {
228         if ($this->sub_state != 'active') {
229             common_log(LOG_WARNING, "Attempting to (re)end PuSH subscription to {$this->uri} in unexpected state {$this->sub_state}");
230         }
231
232         if (!Event::handle('FeedUnsubscribe', array($this))) {
233             // A plugin handled it
234             return true;
235         }
236
237         if (empty($this->huburi)) {
238             if (common_config('feedsub', 'fallback_hub')) {
239                 // No native hub on this feed?
240                 // Use our fallback hub, which handles polling on our behalf.
241             } else if (common_config('feedsub', 'nohub')) {
242                 // Fake it! We're just testing remote feeds w/o hubs.
243                 // We'll never actually get updates in this mode.
244                 return true;
245             } else {
246                 // TRANS: Server exception.
247                 throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
248             }
249         }
250
251         return $this->doSubscribe('unsubscribe');
252     }
253
254     /**
255      * Check if there are any active local uses of this feed, and if not then
256      * make sure it's inactive, unsubscribing if necessary.
257      *
258      * @return boolean true if the subscription is now inactive, false if still active.
259      */
260     public function garbageCollect()
261     {
262         if ($this->sub_state == '' || $this->sub_state == 'inactive') {
263             // No active PuSH subscription, we can just leave it be.
264             return true;
265         } else {
266             // PuSH subscription is either active or in an indeterminate state.
267             // Check if we're out of subscribers, and if so send an unsubscribe.
268             $count = 0;
269             Event::handle('FeedSubSubscriberCount', array($this, &$count));
270
271             if ($count) {
272                 common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->uri);
273                 return false;
274             } else {
275                 common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->uri);
276                 return $this->unsubscribe();
277             }
278         }
279     }
280
281     static public function renewalCheck()
282     {
283         $fs = new FeedSub();
284         // the "" empty string check is because we historically haven't saved unsubscribed feeds as NULL
285         $fs->whereAdd('sub_end IS NOT NULL AND sub_end!="" AND sub_end < NOW() - INTERVAL 1 day');
286         if (!$fs->find()) { // find can be both false and 0, depending on why nothing was found
287             throw new NoResultException($fs);
288         }
289         return $fs;
290     }
291
292     public function renew()
293     {
294         $this->subscribe();
295     }
296
297     /**
298      * Setting to subscribe means it is _waiting_ to become active. This
299      * cannot be done in a transaction because there is a chance that the
300      * remote script we're calling (as in the case of PuSHpress) performs
301      * the lookup _while_ we're POSTing data, which means the transaction
302      * never completes (PushcallbackAction gets an 'inactive' state).
303      *
304      * @return boolean  true on successful sub/unsub, false on failure
305      */
306     protected function doSubscribe($mode)
307     {
308         $orig = clone($this);
309         if ($mode == 'subscribe') {
310             $this->secret = common_random_hexstr(32);
311         }
312         $this->sub_state = $mode;
313         $this->update($orig);
314         unset($orig);
315
316         try {
317             $callback = common_local_url('pushcallback', array('feed' => $this->id));
318             $headers = array('Content-Type: application/x-www-form-urlencoded');
319             $post = array('hub.mode' => $mode,
320                           'hub.callback' => $callback,
321                           'hub.verify' => 'async',  // TODO: deprecated, remove when noone uses PuSH <0.4 (only 'async' method used there)
322                           'hub.verify_token' => 'Deprecated-since-PuSH-0.4', // TODO: rm!
323
324                           'hub.secret' => $this->secret,
325                           'hub.topic' => $this->uri);
326             $client = new HTTPClient();
327             if ($this->huburi) {
328                 $hub = $this->huburi;
329             } else {
330                 if (common_config('feedsub', 'fallback_hub')) {
331                     $hub = common_config('feedsub', 'fallback_hub');
332                     if (common_config('feedsub', 'hub_user')) {
333                         $u = common_config('feedsub', 'hub_user');
334                         $p = common_config('feedsub', 'hub_pass');
335                         $client->setAuth($u, $p);
336                     }
337                 } else {
338                     throw new FeedSubException('WTF?');
339                 }
340             }
341             $response = $client->post($hub, $headers, $post);
342             $status = $response->getStatus();
343             if ($status == 202) {
344                 common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
345                 return true;
346             } else if ($status >= 200 && $status < 300) {
347                 common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
348             } else {
349                 common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
350             }
351         } catch (Exception $e) {
352             // wtf!
353             common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub $this->huburi subscribing to $this->uri");
354
355             $orig = clone($this);
356             $this->sub_state = 'inactive';
357             $this->update($orig);
358             unset($orig);
359         }
360         return false;
361     }
362
363     /**
364      * Save PuSH subscription confirmation.
365      * Sets approximate lease start and end times and finalizes state.
366      *
367      * @param int $lease_seconds provided hub.lease_seconds parameter, if given
368      */
369     public function confirmSubscribe($lease_seconds)
370     {
371         $original = clone($this);
372
373         $this->sub_state = 'active';
374         $this->sub_start = common_sql_date(time());
375         if ($lease_seconds > 0) {
376             $this->sub_end = common_sql_date(time() + $lease_seconds);
377         } else {
378             $this->sub_end = null;  // Backwards compatibility to StatusNet (PuSH <0.4 supported permanent subs)
379         }
380         $this->modified = common_sql_now();
381
382         return $this->update($original);
383     }
384
385     /**
386      * Save PuSH unsubscription confirmation.
387      * Wipes active PuSH sub info and resets state.
388      */
389     public function confirmUnsubscribe()
390     {
391         $original = clone($this);
392
393         // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
394         $this->secret = '';
395         $this->sub_state = '';
396         $this->sub_start = '';
397         $this->sub_end = '';
398         $this->modified = common_sql_now();
399
400         return $this->update($original);
401     }
402
403     /**
404      * Accept updates from a PuSH feed. If validated, this object and the
405      * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
406      * and EndFeedSubHandleFeed events for processing.
407      *
408      * Not guaranteed to be running in an immediate POST context; may be run
409      * from a queue handler.
410      *
411      * Side effects: the feedsub record's lastupdate field will be updated
412      * to the current time (not published time) if we got a legit update.
413      *
414      * @param string $post source of Atom or RSS feed
415      * @param string $hmac X-Hub-Signature header, if present
416      */
417     public function receive($post, $hmac)
418     {
419         common_log(LOG_INFO, __METHOD__ . ": packet for \"$this->uri\"! $hmac $post");
420
421         if ($this->sub_state != 'active') {
422             common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed $this->uri (in state '$this->sub_state')");
423             return;
424         }
425
426         if ($post === '') {
427             common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
428             return;
429         }
430
431         if (!$this->validatePushSig($post, $hmac)) {
432             // Per spec we silently drop input with a bad sig,
433             // while reporting receipt to the server.
434             return;
435         }
436
437         $feed = new DOMDocument();
438         if (!$feed->loadXML($post)) {
439             // @fixme might help to include the err message
440             common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
441             return;
442         }
443
444         $orig = clone($this);
445         $this->last_update = common_sql_now();
446         $this->update($orig);
447
448         Event::handle('StartFeedSubReceive', array($this, $feed));
449         Event::handle('EndFeedSubReceive', array($this, $feed));
450     }
451
452     /**
453      * Validate the given Atom chunk and HMAC signature against our
454      * shared secret that was set up at subscription time.
455      *
456      * If we don't have a shared secret, there should be no signature.
457      * If we we do, our the calculated HMAC should match theirs.
458      *
459      * @param string $post raw XML source as POSTed to us
460      * @param string $hmac X-Hub-Signature HTTP header value, or empty
461      * @return boolean true for a match
462      */
463     protected function validatePushSig($post, $hmac)
464     {
465         if ($this->secret) {
466             if (preg_match('/^sha1=([0-9a-fA-F]{40})$/', $hmac, $matches)) {
467                 $their_hmac = strtolower($matches[1]);
468                 $our_hmac = hash_hmac('sha1', $post, $this->secret);
469                 if ($their_hmac === $our_hmac) {
470                     return true;
471                 }
472                 if (common_config('feedsub', 'debug')) {
473                     $tempfile = tempnam(sys_get_temp_dir(), 'feedsub-receive');
474                     if ($tempfile) {
475                         file_put_contents($tempfile, $post);
476                     }
477                     common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac for feed $this->uri on $this->huburi; saved to $tempfile");
478                 } else {
479                     common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac for feed $this->uri on $this->huburi");
480                 }
481             } else {
482                 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
483             }
484         } else {
485             if (empty($hmac)) {
486                 return true;
487             } else {
488                 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");
489             }
490         }
491         return false;
492     }
493 }