]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/FeedSub.php
Merge remote-tracking branch 'upstream/master' into social-master
[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;    // varchar(191)   not 255 because utf8mb4 takes more space
66
67     // PuSH subscription data
68     public $huburi;
69     public $secret;
70     public $sub_state; // subscribe, active, unsubscribe, inactive, nohub
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' => 191, '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","nohub")', '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', '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 NoUriException($this);
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      * If huburi is empty, then doublecheck that we are not using
116      * a fallback hub. If there is a fallback hub, it is only if the
117      * sub_state is "nohub" that we assume it's not a PuSH feed.
118      */
119     public function isPuSH()
120     {
121         if (empty($this->huburi)
122                 && (!common_config('feedsub', 'fallback_hub')
123                     || $this->sub_state === 'nohub')) {
124                 // Here we have no huburi set. Also, either there is no 
125                 // fallback hub configured or sub_state is "nohub".
126             return false;
127         }
128         return true;
129     }
130
131     /**
132      * Fetch the StatusNet-side profile for this feed
133      * @return Profile
134      */
135     public function localProfile()
136     {
137         if ($this->profile_id) {
138             return Profile::getKV('id', $this->profile_id);
139         }
140         return null;
141     }
142
143     /**
144      * Fetch the StatusNet-side profile for this feed
145      * @return Profile
146      */
147     public function localGroup()
148     {
149         if ($this->group_id) {
150             return User_group::getKV('id', $this->group_id);
151         }
152         return null;
153     }
154
155     /**
156      * @param string $feeduri
157      * @return FeedSub
158      * @throws FeedSubException if feed is invalid or lacks PuSH setup
159      */
160     public static function ensureFeed($feeduri)
161     {
162         $current = self::getKV('uri', $feeduri);
163         if ($current instanceof FeedSub) {
164             return $current;
165         }
166
167         $discover = new FeedDiscovery();
168         $discover->discoverFromFeedURL($feeduri);
169
170         $huburi = $discover->getHubLink();
171         if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
172             throw new FeedSubNoHubException();
173         }
174
175         $feedsub = new FeedSub();
176         $feedsub->uri = $feeduri;
177         $feedsub->huburi = $huburi;
178         $feedsub->sub_state = 'inactive';
179
180         $feedsub->created = common_sql_now();
181         $feedsub->modified = common_sql_now();
182
183         $result = $feedsub->insert();
184         if ($result === false) {
185             throw new FeedDBException($feedsub);
186         }
187
188         return $feedsub;
189     }
190
191     /**
192      * Send a subscription request to the hub for this feed.
193      * The hub will later send us a confirmation POST to /main/push/callback.
194      *
195      * @return void
196      * @throws ServerException if feed state is not valid
197      */
198     public function subscribe()
199     {
200         if ($this->sub_state && $this->sub_state != 'inactive') {
201             common_log(LOG_WARNING, sprintf('Attempting to (re)start PuSH subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
202         }
203
204         if (!Event::handle('FeedSubscribe', array($this))) {
205             // A plugin handled it
206             return;
207         }
208
209         if (empty($this->huburi)) {
210             if (common_config('feedsub', 'fallback_hub')) {
211                 // No native hub on this feed?
212                 // Use our fallback hub, which handles polling on our behalf.
213             } else if (common_config('feedsub', 'nohub')) {
214                 // For this to actually work, we'll need some polling mechanism.
215                 // The FeedPoller plugin should take care of it.
216                 return;
217             } else {
218                 // TRANS: Server exception.
219                 throw new ServerException(_m('Attempting to start PuSH subscription for feed with no hub.'));
220             }
221         }
222
223         $this->doSubscribe('subscribe');
224     }
225
226     /**
227      * Send a PuSH unsubscription request to the hub for this feed.
228      * The hub will later send us a confirmation POST to /main/push/callback.
229      * Warning: this will cancel the subscription even if someone else in
230      * the system is using it. Most callers will want garbageCollect() instead,
231      * which confirms there's no uses left.
232      *
233      * @throws ServerException if feed state is not valid
234      */
235     public function unsubscribe() {
236         if ($this->sub_state != 'active') {
237             common_log(LOG_WARNING, sprintf('Attempting to (re)end PuSH subscription to %s in unexpected state %s', $this->getUri(), $this->sub_state));
238         }
239
240         if (!Event::handle('FeedUnsubscribe', array($this))) {
241             // A plugin handled it
242             return;
243         }
244
245         if (empty($this->huburi)) {
246             if (common_config('feedsub', 'fallback_hub')) {
247                 // No native hub on this feed?
248                 // Use our fallback hub, which handles polling on our behalf.
249             } else if (common_config('feedsub', 'nohub')) {
250                 // We need a feedpolling plugin (like FeedPoller) active so it will
251                 // set the 'nohub' state to 'inactive' for us.
252                 return;
253             } else {
254                 // TRANS: Server exception.
255                 throw new ServerException(_m('Attempting to end PuSH subscription for feed with no hub.'));
256             }
257         }
258
259         $this->doSubscribe('unsubscribe');
260     }
261
262     /**
263      * Check if there are any active local uses of this feed, and if not then
264      * make sure it's inactive, unsubscribing if necessary.
265      *
266      * @return boolean true if the subscription is now inactive, false if still active.
267      * @throws NoProfileException in FeedSubSubscriberCount for missing Profile entries
268      * @throws Exception if something goes wrong in unsubscribe() method
269      */
270     public function garbageCollect()
271     {
272         if ($this->sub_state == '' || $this->sub_state == 'inactive') {
273             // No active PuSH subscription, we can just leave it be.
274             return true;
275         }
276
277         // PuSH subscription is either active or in an indeterminate state.
278         // Check if we're out of subscribers, and if so send an unsubscribe.
279         $count = 0;
280         Event::handle('FeedSubSubscriberCount', array($this, &$count));
281
282         if ($count > 0) {
283             common_log(LOG_INFO, __METHOD__ . ': ok, ' . $count . ' user(s) left for ' . $this->getUri());
284             return false;
285         }
286
287         common_log(LOG_INFO, __METHOD__ . ': unsubscribing, no users left for ' . $this->getUri());
288         // Unsubscribe throws various Exceptions on failure
289         $this->unsubscribe();
290
291         return true;
292     }
293
294     static public function renewalCheck()
295     {
296         $fs = new FeedSub();
297         // the "" empty string check is because we historically haven't saved unsubscribed feeds as NULL
298         $fs->whereAdd('sub_end IS NOT NULL AND sub_end!="" AND sub_end < NOW() + INTERVAL 1 day');
299         if (!$fs->find()) { // find can be both false and 0, depending on why nothing was found
300             throw new NoResultException($fs);
301         }
302         return $fs;
303     }
304
305     public function renew()
306     {
307         $this->subscribe();
308     }
309
310     /**
311      * Setting to subscribe means it is _waiting_ to become active. This
312      * cannot be done in a transaction because there is a chance that the
313      * remote script we're calling (as in the case of PuSHpress) performs
314      * the lookup _while_ we're POSTing data, which means the transaction
315      * never completes (PushcallbackAction gets an 'inactive' state).
316      *
317      * @return boolean true when everything is ok (throws Exception on fail)
318      * @throws Exception on failure, can be HTTPClient's or our own.
319      */
320     protected function doSubscribe($mode)
321     {
322         $orig = clone($this);
323         if ($mode == 'subscribe') {
324             $this->secret = common_random_hexstr(32);
325         }
326         $this->sub_state = $mode;
327         $this->update($orig);
328         unset($orig);
329
330         try {
331             $callback = common_local_url('pushcallback', array('feed' => $this->id));
332             $headers = array('Content-Type: application/x-www-form-urlencoded');
333             $post = array('hub.mode' => $mode,
334                           'hub.callback' => $callback,
335                           'hub.verify' => 'async',  // TODO: deprecated, remove when noone uses PuSH <0.4 (only 'async' method used there)
336                           'hub.verify_token' => 'Deprecated-since-PuSH-0.4', // TODO: rm!
337
338                           'hub.secret' => $this->secret,
339                           'hub.topic' => $this->getUri());
340             $client = new HTTPClient();
341             if ($this->huburi) {
342                 $hub = $this->huburi;
343             } else {
344                 if (common_config('feedsub', 'fallback_hub')) {
345                     $hub = common_config('feedsub', 'fallback_hub');
346                     if (common_config('feedsub', 'hub_user')) {
347                         $u = common_config('feedsub', 'hub_user');
348                         $p = common_config('feedsub', 'hub_pass');
349                         $client->setAuth($u, $p);
350                     }
351                 } else {
352                     throw new FeedSubException('Server could not find a usable PuSH hub.');
353                 }
354             }
355             $response = $client->post($hub, $headers, $post);
356             $status = $response->getStatus();
357             // PuSH specificed response status code
358             if ($status == 202  || $status == 204) {
359                 common_log(LOG_INFO, __METHOD__ . ': sub req ok, awaiting verification callback');
360                 return;
361             } else if ($status >= 200 && $status < 300) {
362                 common_log(LOG_ERR, __METHOD__ . ": sub req returned unexpected HTTP $status: " . $response->getBody());
363             } else {
364                 common_log(LOG_ERR, __METHOD__ . ": sub req failed with HTTP $status: " . $response->getBody());
365             }
366         } catch (Exception $e) {
367             common_log(LOG_ERR, __METHOD__ . ": error \"{$e->getMessage()}\" hitting hub {$this->huburi} subscribing to {$this->getUri()}");
368
369             // Reset the subscription state.
370             $orig = clone($this);
371             $this->sub_state = 'inactive';
372             $this->update($orig);
373
374             // Throw the Exception again.
375             throw $e;
376         }
377         throw new ServerException("{$mode} request failed.");
378     }
379
380     /**
381      * Save PuSH subscription confirmation.
382      * Sets approximate lease start and end times and finalizes state.
383      *
384      * @param int $lease_seconds provided hub.lease_seconds parameter, if given
385      */
386     public function confirmSubscribe($lease_seconds)
387     {
388         $original = clone($this);
389
390         $this->sub_state = 'active';
391         $this->sub_start = common_sql_date(time());
392         if ($lease_seconds > 0) {
393             $this->sub_end = common_sql_date(time() + $lease_seconds);
394         } else {
395             $this->sub_end = null;  // Backwards compatibility to StatusNet (PuSH <0.4 supported permanent subs)
396         }
397         $this->modified = common_sql_now();
398
399         return $this->update($original);
400     }
401
402     /**
403      * Save PuSH unsubscription confirmation.
404      * Wipes active PuSH sub info and resets state.
405      */
406     public function confirmUnsubscribe()
407     {
408         $original = clone($this);
409
410         // @fixme these should all be null, but DB_DataObject doesn't save null values...?????
411         $this->secret = '';
412         $this->sub_state = '';
413         $this->sub_start = '';
414         $this->sub_end = '';
415         $this->modified = common_sql_now();
416
417         return $this->update($original);
418     }
419
420     /**
421      * Accept updates from a PuSH feed. If validated, this object and the
422      * feed (as a DOMDocument) will be passed to the StartFeedSubHandleFeed
423      * and EndFeedSubHandleFeed events for processing.
424      *
425      * Not guaranteed to be running in an immediate POST context; may be run
426      * from a queue handler.
427      *
428      * Side effects: the feedsub record's lastupdate field will be updated
429      * to the current time (not published time) if we got a legit update.
430      *
431      * @param string $post source of Atom or RSS feed
432      * @param string $hmac X-Hub-Signature header, if present
433      */
434     public function receive($post, $hmac)
435     {
436         common_log(LOG_INFO, __METHOD__ . ": packet for \"" . $this->getUri() . "\"! $hmac $post");
437
438         if (!in_array($this->sub_state, array('active', 'nohub'))) {
439             common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH for inactive feed " . $this->getUri() . " (in state '$this->sub_state')");
440             return;
441         }
442
443         if ($post === '') {
444             common_log(LOG_ERR, __METHOD__ . ": ignoring empty post");
445             return;
446         }
447
448         if (!$this->validatePushSig($post, $hmac)) {
449             // Per spec we silently drop input with a bad sig,
450             // while reporting receipt to the server.
451             return;
452         }
453
454         $feed = new DOMDocument();
455         if (!$feed->loadXML($post)) {
456             // @fixme might help to include the err message
457             common_log(LOG_ERR, __METHOD__ . ": ignoring invalid XML");
458             return;
459         }
460
461         $orig = clone($this);
462         $this->last_update = common_sql_now();
463         $this->update($orig);
464
465         Event::handle('StartFeedSubReceive', array($this, $feed));
466         Event::handle('EndFeedSubReceive', array($this, $feed));
467     }
468
469     /**
470      * Validate the given Atom chunk and HMAC signature against our
471      * shared secret that was set up at subscription time.
472      *
473      * If we don't have a shared secret, there should be no signature.
474      * If we we do, our the calculated HMAC should match theirs.
475      *
476      * @param string $post raw XML source as POSTed to us
477      * @param string $hmac X-Hub-Signature HTTP header value, or empty
478      * @return boolean true for a match
479      */
480     protected function validatePushSig($post, $hmac)
481     {
482         if ($this->secret) {
483             if (preg_match('/^sha1=([0-9a-fA-F]{40})$/', $hmac, $matches)) {
484                 $their_hmac = strtolower($matches[1]);
485                 $our_hmac = hash_hmac('sha1', $post, $this->secret);
486                 if ($their_hmac === $our_hmac) {
487                     return true;
488                 }
489                 if (common_config('feedsub', 'debug')) {
490                     $tempfile = tempnam(common_get_temp_dir(), 'feedsub-receive');
491                     if ($tempfile) {
492                         file_put_contents($tempfile, $post);
493                     }
494                     common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac for feed " . $this->getUri() . " on $this->huburi; saved to $tempfile");
495                 } else {
496                     common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bad SHA-1 HMAC: got $their_hmac, expected $our_hmac for feed " . $this->getUri() . " on $this->huburi");
497                 }
498             } else {
499                 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with bogus HMAC '$hmac'");
500             }
501         } else {
502             if (empty($hmac)) {
503                 return true;
504             } else {
505                 common_log(LOG_ERR, __METHOD__ . ": ignoring PuSH with unexpected HMAC '$hmac'");
506             }
507         }
508         return false;
509     }
510
511     public function delete($useWhere=false)
512     {
513         try {
514             $oprofile = Ostatus_profile::getKV('feeduri', $this->getUri());
515             if ($oprofile instanceof Ostatus_profile) {
516                 // Check if there's a profile. If not, handle the NoProfileException below
517                 $profile = $oprofile->localProfile();
518             }
519         } catch (NoProfileException $e) {
520             // If the Ostatus_profile has no local Profile bound to it, let's clean it out at the same time
521             $oprofile->delete();
522         } catch (NoUriException $e) {
523             // FeedSub->getUri() can throw a NoUriException, let's just go ahead and delete it
524         }
525         return parent::delete($useWhere);
526     }
527 }