]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/RSSCloud/RSSCloudRequestNotify.php
Reject subscription requests for handlers that don't support http-post
[quix0rs-gnu-social.git] / plugins / RSSCloud / RSSCloudRequestNotify.php
1 <?php
2 /**
3  * Action to let RSSCloud aggregators request update notification when
4  * user profile feeds change.
5  *
6  * PHP version 5
7  *
8  * @category Plugin
9  * @package  StatusNet
10  * @author   Zach Copley <zach@status.net>
11  * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
12  * @link     http://status.net/
13  *
14  * StatusNet - the distributed open-source microblogging tool
15  * Copyright (C) 2009, StatusNet, Inc.
16  *
17  * This program is free software: you can redistribute it and/or modify
18  * it under the terms of the GNU Affero General Public License as published by
19  * the Free Software Foundation, either version 3 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25  * GNU Affero General Public License for more details.
26  *
27  * You should have received a copy of the GNU Affero General Public License
28  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
29  */
30
31 if (!defined('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * Action class to handle RSSCloud notification (subscription) requests
37  *
38  * @category Plugin
39  * @package  StatusNet
40  * @author   Zach Copley <zach@status.net>
41  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
42  * @link     http://status.net/
43  **/
44
45 class RSSCloudRequestNotifyAction extends Action
46 {
47     /**
48      * Initialization.
49      *
50      * @param array $args Web and URL arguments
51      *
52      * @return boolean false if user doesn't exist
53      */
54
55     function prepare($args)
56     {
57         parent::prepare($args);
58
59         $this->ip        = $_SERVER['REMOTE_ADDR'];
60         $this->port      = $this->arg('port');
61         $this->path      = $this->arg('path');
62
63         if ($this->path[0] != '/') {
64             $this->path = '/' . $this->path;
65         }
66
67         $this->protocol  = $this->arg('protocol');
68         $this->procedure = $this->arg('notifyProcedure');
69         $this->domain    = $this->arg('domain');
70
71         $this->feeds     = $this->getFeeds();
72
73         return true;
74     }
75
76     /**
77      * Handle the request
78      *
79      * Checks for all the required parameters for a subscription,
80      * validates that the feed being subscribed to is real, and then
81      * saves the subsctiption.
82      *
83      * @param array $args $_REQUEST data (unused)
84      *
85      * @return void
86      */
87
88     function handle($args)
89     {
90         parent::handle($args);
91
92         if ($_SERVER['REQUEST_METHOD'] != 'POST') {
93             $this->showResult(false, 'Request must be POST.');
94             return;
95         }
96
97         $missing = array();
98
99         if (empty($this->port)) {
100             $missing[] = 'port';
101         }
102
103         if (empty($this->path)) {
104             $missing[] = 'path';
105         }
106
107         if (empty($this->protocol)) {
108             $missing[] = 'protocol';
109         } else if (strtolower($this->protocol) != 'http-post') {
110             $msg = 'Only http-post notifications are supported at this time.';
111             $this->showResult(false, $msg);
112             return;
113         }
114
115         if (!isset($this->procedure)) {
116             $missing[] = 'notifyProcedure';
117         }
118
119         if (!empty($missing)) {
120             $msg = 'The following parameters were missing from the request body: ' .
121                 implode(', ', $missing) . '.';
122             $this->showResult(false, $msg);
123             return;
124         }
125
126         if (empty($this->feeds)) {
127             $msg = 'You must provide at least one valid profile feed url (url1, url2, url3 ... urlN).';
128             $this->showResult(false, $msg);
129             return;
130         }
131
132         // We have to validate everything before saving anything.
133         // We only return one success or failure no matter how
134         // many feeds the subscriber is trying to subscribe to
135
136         foreach ($this->feeds as $feed) {
137
138             if (!$this->validateFeed($feed)) {
139                 $msg = 'Feed subscription failed - Not a valid feed.';
140                 $this->showResult(false, $msg);
141                 return;
142             }
143
144             if (!$this->testNotificationHandler($feed)) {
145                 $msg = 'Feed subscription failed - ' .
146                 'notification handler doesn\'t respond correctly.';
147                 $this->showResult(false, $msg);
148                 return;
149             }
150
151         }
152
153         foreach ($this->feeds as $feed) {
154             $this->saveSubscription($feed);
155         }
156
157         // XXX: What to do about deleting stale subscriptions?
158         // 25 hours seems harsh. WordPress doesn't ever remove
159         // subscriptions.
160
161         $msg = 'Thanks for the subscription. ' .
162           'When the feed(s) update(s) we\'ll notify you.';
163
164         $this->showResult(true, $msg);
165     }
166
167     /**
168      * Validate that the requested feed is one we serve
169      * up via RSSCloud.
170      *
171      * @param string $feed the feed in question
172      *
173      * @return void
174      */
175
176     function validateFeed($feed)
177     {
178         $user = $this->userFromFeed($feed);
179
180         if (empty($user)) {
181             return false;
182         }
183
184         return true;
185     }
186
187     /**
188      * Pull all of the urls (url1, url2, url3...urlN) that
189      * the subscriber wants to subscribe to.
190      *
191      * @return array $feeds the list of feeds
192      */
193
194     function getFeeds()
195     {
196         $feeds = array();
197
198         while (list($key, $feed) = each ($this->args)) {
199             if (preg_match('/^url\d*$/', $key)) {
200                 $feeds[] = $feed;
201             }
202         }
203
204         return $feeds;
205     }
206
207     /**
208      * Test that a notification handler is there and is reponding
209      * correctly.  This is called before adding a subscription.
210      *
211      * @param string $feed the feed to verify
212      *
213      * @return boolean success result
214      */
215
216     function testNotificationHandler($feed)
217     {
218         common_debug("RSSCloudPlugin - testNotificationHandler()");
219
220         $notifyUrl = $this->getNotifyUrl();
221
222         $notifier = new RSSCloudNotifier();
223
224         if (isset($this->domain)) {
225
226             // 'domain' param set, so we have to use GET and send a challenge
227
228             common_log(LOG_INFO, 'Testing notification handler with challenge: ' .
229                        $notifyUrl);
230             return $notifier->challenge($notifyUrl, $feed);
231
232         } else {
233             common_log(LOG_INFO, 'Testing notification handler: ' .
234                        $notifyUrl);
235
236             return $notifier->postUpdate($notifyUrl, $feed);
237         }
238     }
239
240     /**
241      * Build the URL for the notification handler based on the
242      * parameters passed in with the subscription request.
243      *
244      * @return string notification handler url
245      */
246
247     function getNotifyUrl()
248     {
249         if (isset($this->domain)) {
250             return 'http://' . $this->domain . ':' . $this->port . $this->path;
251         } else {
252             return 'http://' . $this->ip . ':' . $this->port . $this->path;
253         }
254      }
255
256     /**
257      * Uses the nickname part of the subscribed feed URL to figure out
258      * whethere there's really a user with such a feed.  Used to
259      * validate feeds before adding a subscription.
260      *
261      * @param string $feed the feed in question
262      *
263      * @return boolean success
264      */
265
266     function userFromFeed($feed)
267     {
268         // We only do profile feeds
269
270         $path = common_path('api/statuses/user_timeline/');
271         $valid = '%^' . $path . '(?<nickname>.*)\.rss$%';
272
273         if (preg_match($valid, $feed, $matches)) {
274             $user = User::staticGet('nickname', $matches['nickname']);
275             if (!empty($user)) {
276                 return $user;
277             }
278         }
279
280         return false;
281     }
282
283     /**
284      * Save an RSSCloud subscription
285      *
286      * @param $feed a valid profile feed
287      *
288      * @return boolean success result
289      */
290
291     function saveSubscription($feed)
292     {
293         $user = $this->userFromFeed($feed);
294
295         $notifyUrl = $this->getNotifyUrl();
296
297         $sub = RSSCloudSubscription::getSubscription($user->id, $notifyUrl);
298
299         if ($sub) {
300             common_debug("Already subscribed to that!");
301         } else {
302
303             $sub = new RSSCloudSubscription();
304
305             $sub->subscribed = $user->id;
306             $sub->url        = $notifyUrl;
307             $sub->created    = common_sql_now();
308
309             if (!$sub->insert()) {
310                 common_log_db_error($sub, 'INSERT', __FILE__);
311                 return false;
312             }
313
314         }
315
316         return true;
317     }
318
319     /**
320      * Show an XML message indicating the subscription
321      * was successful or failed.
322      *
323      * @param boolean $success whether it was good or bad
324      * @param string  $msg     the message to output
325      *
326      * @return boolean success result
327      */
328
329     function showResult($success, $msg)
330     {
331         $this->startXML();
332         $this->elementStart('notifyResult', array('success' => ($success) ? 'true' : 'false',
333                                                   'msg'     => $msg));
334         $this->endXML();
335     }
336
337 }
338